repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Workspaces/Core/Portable/Classification/SyntaxClassification/SyntacticChangeRangeComputer.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Classification { /// <summary> /// Computes a syntactic text change range that determines the range of a document that was changed by an edit. The /// portions outside this change range are guaranteed to be syntactically identical (see <see /// cref="SyntaxNode.IsIncrementallyIdenticalTo"/>). This algorithm is intended to be <em>fast</em>. It is /// technically linear in the number of nodes and tokens that may need to examined. However, in practice, it should /// operate in sub-linear time as it will bail the moment tokens don't match, and it's able to skip over matching /// nodes fully without examining the contents of those nodes. This is intended for consumers that want a /// reasonably accurate change range computer, but do not want to spend an inordinate amount of time getting the /// most accurate and minimal result possible. /// </summary> /// <remarks> /// This computation is not guaranteed to be minimal. It may return a range that includes parts that are unchanged. /// This means it is also legal for the change range to just specify the entire file was changed. The quality of /// results will depend on how well the parsers did with incremental parsing, and how much time is given to do the /// comparison. In practice, for large files (i.e. 15kloc) with standard types of edits, this generally returns /// results in around 50-100 usecs on a i7 3GHz desktop. /// <para> /// This algorithm will respect the timeout provided to the best of abilities. If any information has been computed /// when the timeout elapses, it will be returned. /// </para> /// </remarks> internal static class SyntacticChangeRangeComputer { private static readonly ObjectPool<Stack<SyntaxNodeOrToken>> s_pool = new(() => new()); public static TextChangeRange ComputeSyntacticChangeRange(SyntaxNode oldRoot, SyntaxNode newRoot, TimeSpan timeout, CancellationToken cancellationToken) { if (oldRoot == newRoot) return default; var stopwatch = SharedStopwatch.StartNew(); // We will be comparing the trees for two documents like so: // // -------------------------------------------- // old: | | // -------------------------------------------- // // --------------------------------------------------- // new: | | // --------------------------------------------------- // // (Note that `new` could be smaller or the same length as `old`, it makes no difference). // // The algorithm will sweep in from both sides, as long as the nodes and tokens it's touching on each side // are 'identical' (i.e. are the exact same green node, and were thus reused over an incremental parse.). // This will leave us with: // // -------------------------------------------- // old: | CLW | | CRW | // -------------------------------------------- // | | \ \ // --------------------------------------------------- // new: | CLW | | CRW | // --------------------------------------------------- // // Where CLW and CRW refer to the common-left-width and common-right-width respectively. The part in between // this s the change range: // // -------------------------------------------- // old: | |**********************| | // -------------------------------------------- // |**************************\ // --------------------------------------------------- // new: | |*****************************| | // --------------------------------------------------- // // The Span changed will go from `[CLW, Old_Width - CRW)`, and the NewLength will be `New_Width - CLW - CRW` var commonLeftWidth = ComputeCommonLeftWidth(); if (commonLeftWidth == null) { // The trees were effectively identical (even if the children were different). Return that there was no // text change. return default; } // Only compute the right side if we have time for it. Otherwise, assume there is nothing in common there. var commonRightWidth = 0; if (stopwatch.Elapsed < timeout) commonRightWidth = ComputeCommonRightWidth(); var oldRootWidth = oldRoot.FullWidth(); var newRootWidth = newRoot.FullWidth(); Contract.ThrowIfTrue(commonLeftWidth > oldRootWidth); Contract.ThrowIfTrue(commonLeftWidth > newRootWidth); Contract.ThrowIfTrue(commonRightWidth > oldRootWidth); Contract.ThrowIfTrue(commonRightWidth > newRootWidth); // it's possible for the common left/right to overlap. This can happen as some tokens // in the parser have a true shared underlying state, so they may get consumed both on // a leftward and rightward walk. Cap the right width so that it never overlaps hte left // width in either the old or new tree. commonRightWidth = Math.Min(commonRightWidth, oldRootWidth - commonLeftWidth.Value); commonRightWidth = Math.Min(commonRightWidth, newRootWidth - commonLeftWidth.Value); return new TextChangeRange( TextSpan.FromBounds(start: commonLeftWidth.Value, end: oldRootWidth - commonRightWidth), newRootWidth - commonLeftWidth.Value - commonRightWidth); int? ComputeCommonLeftWidth() { using var leftOldStack = s_pool.GetPooledObject(); using var leftNewStack = s_pool.GetPooledObject(); var oldStack = leftOldStack.Object; var newStack = leftNewStack.Object; oldStack.Push(oldRoot); newStack.Push(newRoot); while (oldStack.Count > 0 && newStack.Count > 0) { cancellationToken.ThrowIfCancellationRequested(); var currentOld = oldStack.Pop(); var currentNew = newStack.Pop(); Contract.ThrowIfFalse(currentOld.FullSpan.Start == currentNew.FullSpan.Start); // If the two nodes/tokens were the same just skip past them. They're part of the common left width. if (currentOld.IsIncrementallyIdenticalTo(currentNew)) continue; // if we reached a token for either of these, then we can't break things down any further, and we hit // the furthest point they are common. if (currentOld.IsToken || currentNew.IsToken) return currentOld.FullSpan.Start; // Similarly, if we've run out of time, just return what we've computed so far. It's not as accurate as // we could be. But the caller wants the results asap. if (stopwatch.Elapsed > timeout) return currentOld.FullSpan.Start; // we've got two nodes, but they weren't the same. For example, say we made an edit in a method in the // class, the class node would be new, but there might be many member nodes that were the same that we'd // want to see and skip. Crumble the node and deal with its left side. // // Reverse so that we process the leftmost child first and walk left to right. foreach (var nodeOrToken in currentOld.AsNode()!.ChildNodesAndTokens().Reverse()) oldStack.Push(nodeOrToken); foreach (var nodeOrToken in currentNew.AsNode()!.ChildNodesAndTokens().Reverse()) newStack.Push(nodeOrToken); } // If we consumed all of 'new', then the length of the new doc is what we have in common. if (oldStack.Count > 0) return newRoot.FullSpan.Length; // If we consumed all of 'old', then the length of the old doc is what we have in common. if (newStack.Count > 0) return oldRoot.FullSpan.Length; // We consumed both stacks entirely. That means the trees were identical (though the root was different). Return null to signify no change to the doc. return null; } int ComputeCommonRightWidth() { using var rightOldStack = s_pool.GetPooledObject(); using var rightNewStack = s_pool.GetPooledObject(); var oldStack = rightOldStack.Object; var newStack = rightNewStack.Object; oldStack.Push(oldRoot); newStack.Push(newRoot); while (oldStack.Count > 0 && newStack.Count > 0) { cancellationToken.ThrowIfCancellationRequested(); var currentOld = oldStack.Pop(); var currentNew = newStack.Pop(); // The width on the right we've moved past on both old/new should be the same. Contract.ThrowIfFalse((oldRoot.FullSpan.End - currentOld.FullSpan.End) == (newRoot.FullSpan.End - currentNew.FullSpan.End)); // If the two nodes/tokens were the same just skip past them. They're part of the common right width. // Critically though, we can only skip past if this wasn't already something we consumed when determining // the common left width. If this was common the left side, we can't consider it common to the right, // otherwise we could end up with overlapping regions of commonality. // // This can occur in incremental settings when the similar tokens are written successsively. // Because the parser can reuse underlying token data, it may end up with many incrementally // identical tokens in a row. if (currentOld.IsIncrementallyIdenticalTo(currentNew) && currentOld.FullSpan.Start >= commonLeftWidth && currentNew.FullSpan.Start >= commonLeftWidth) { continue; } // if we reached a token for either of these, then we can't break things down any further, and we hit // the furthest point they are common. if (currentOld.IsToken || currentNew.IsToken) return oldRoot.FullSpan.End - currentOld.FullSpan.End; // Similarly, if we've run out of time, just return what we've computed so far. It's not as accurate as // we could be. But the caller wants the results asap. if (stopwatch.Elapsed > timeout) return oldRoot.FullSpan.End - currentOld.FullSpan.End; // we've got two nodes, but they weren't the same. For example, say we made an edit in a method in the // class, the class node would be new, but there might be many member nodes following the edited node // that were the same that we'd want to see and skip. Crumble the node and deal with its right side. // // Do not reverse the children. We want to process the rightmost child first and walk right to left. foreach (var nodeOrToken in currentOld.AsNode()!.ChildNodesAndTokens()) oldStack.Push(nodeOrToken); foreach (var nodeOrToken in currentNew.AsNode()!.ChildNodesAndTokens()) newStack.Push(nodeOrToken); } // If we consumed all of 'new', then the length of the new doc is what we have in common. if (oldStack.Count > 0) return newRoot.FullSpan.Length; // If we consumed all of 'old', then the length of the old doc is what we have in common. if (newStack.Count > 0) return oldRoot.FullSpan.Length; // We consumed both stacks entirely. That means the trees were identical (though the root was // different). We should never get here. If we were the same, then walking from the left should have // consumed everything and already bailed out. throw ExceptionUtilities.Unreachable; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Classification { /// <summary> /// Computes a syntactic text change range that determines the range of a document that was changed by an edit. The /// portions outside this change range are guaranteed to be syntactically identical (see <see /// cref="SyntaxNode.IsIncrementallyIdenticalTo"/>). This algorithm is intended to be <em>fast</em>. It is /// technically linear in the number of nodes and tokens that may need to examined. However, in practice, it should /// operate in sub-linear time as it will bail the moment tokens don't match, and it's able to skip over matching /// nodes fully without examining the contents of those nodes. This is intended for consumers that want a /// reasonably accurate change range computer, but do not want to spend an inordinate amount of time getting the /// most accurate and minimal result possible. /// </summary> /// <remarks> /// This computation is not guaranteed to be minimal. It may return a range that includes parts that are unchanged. /// This means it is also legal for the change range to just specify the entire file was changed. The quality of /// results will depend on how well the parsers did with incremental parsing, and how much time is given to do the /// comparison. In practice, for large files (i.e. 15kloc) with standard types of edits, this generally returns /// results in around 50-100 usecs on a i7 3GHz desktop. /// <para> /// This algorithm will respect the timeout provided to the best of abilities. If any information has been computed /// when the timeout elapses, it will be returned. /// </para> /// </remarks> internal static class SyntacticChangeRangeComputer { private static readonly ObjectPool<Stack<SyntaxNodeOrToken>> s_pool = new(() => new()); public static TextChangeRange ComputeSyntacticChangeRange(SyntaxNode oldRoot, SyntaxNode newRoot, TimeSpan timeout, CancellationToken cancellationToken) { if (oldRoot == newRoot) return default; var stopwatch = SharedStopwatch.StartNew(); // We will be comparing the trees for two documents like so: // // -------------------------------------------- // old: | | // -------------------------------------------- // // --------------------------------------------------- // new: | | // --------------------------------------------------- // // (Note that `new` could be smaller or the same length as `old`, it makes no difference). // // The algorithm will sweep in from both sides, as long as the nodes and tokens it's touching on each side // are 'identical' (i.e. are the exact same green node, and were thus reused over an incremental parse.). // This will leave us with: // // -------------------------------------------- // old: | CLW | | CRW | // -------------------------------------------- // | | \ \ // --------------------------------------------------- // new: | CLW | | CRW | // --------------------------------------------------- // // Where CLW and CRW refer to the common-left-width and common-right-width respectively. The part in between // this s the change range: // // -------------------------------------------- // old: | |**********************| | // -------------------------------------------- // |**************************\ // --------------------------------------------------- // new: | |*****************************| | // --------------------------------------------------- // // The Span changed will go from `[CLW, Old_Width - CRW)`, and the NewLength will be `New_Width - CLW - CRW` var commonLeftWidth = ComputeCommonLeftWidth(); if (commonLeftWidth == null) { // The trees were effectively identical (even if the children were different). Return that there was no // text change. return default; } // Only compute the right side if we have time for it. Otherwise, assume there is nothing in common there. var commonRightWidth = 0; if (stopwatch.Elapsed < timeout) commonRightWidth = ComputeCommonRightWidth(); var oldRootWidth = oldRoot.FullWidth(); var newRootWidth = newRoot.FullWidth(); Contract.ThrowIfTrue(commonLeftWidth > oldRootWidth); Contract.ThrowIfTrue(commonLeftWidth > newRootWidth); Contract.ThrowIfTrue(commonRightWidth > oldRootWidth); Contract.ThrowIfTrue(commonRightWidth > newRootWidth); // it's possible for the common left/right to overlap. This can happen as some tokens // in the parser have a true shared underlying state, so they may get consumed both on // a leftward and rightward walk. Cap the right width so that it never overlaps hte left // width in either the old or new tree. commonRightWidth = Math.Min(commonRightWidth, oldRootWidth - commonLeftWidth.Value); commonRightWidth = Math.Min(commonRightWidth, newRootWidth - commonLeftWidth.Value); return new TextChangeRange( TextSpan.FromBounds(start: commonLeftWidth.Value, end: oldRootWidth - commonRightWidth), newRootWidth - commonLeftWidth.Value - commonRightWidth); int? ComputeCommonLeftWidth() { using var leftOldStack = s_pool.GetPooledObject(); using var leftNewStack = s_pool.GetPooledObject(); var oldStack = leftOldStack.Object; var newStack = leftNewStack.Object; oldStack.Push(oldRoot); newStack.Push(newRoot); while (oldStack.Count > 0 && newStack.Count > 0) { cancellationToken.ThrowIfCancellationRequested(); var currentOld = oldStack.Pop(); var currentNew = newStack.Pop(); Contract.ThrowIfFalse(currentOld.FullSpan.Start == currentNew.FullSpan.Start); // If the two nodes/tokens were the same just skip past them. They're part of the common left width. if (currentOld.IsIncrementallyIdenticalTo(currentNew)) continue; // if we reached a token for either of these, then we can't break things down any further, and we hit // the furthest point they are common. if (currentOld.IsToken || currentNew.IsToken) return currentOld.FullSpan.Start; // Similarly, if we've run out of time, just return what we've computed so far. It's not as accurate as // we could be. But the caller wants the results asap. if (stopwatch.Elapsed > timeout) return currentOld.FullSpan.Start; // we've got two nodes, but they weren't the same. For example, say we made an edit in a method in the // class, the class node would be new, but there might be many member nodes that were the same that we'd // want to see and skip. Crumble the node and deal with its left side. // // Reverse so that we process the leftmost child first and walk left to right. foreach (var nodeOrToken in currentOld.AsNode()!.ChildNodesAndTokens().Reverse()) oldStack.Push(nodeOrToken); foreach (var nodeOrToken in currentNew.AsNode()!.ChildNodesAndTokens().Reverse()) newStack.Push(nodeOrToken); } // If we consumed all of 'new', then the length of the new doc is what we have in common. if (oldStack.Count > 0) return newRoot.FullSpan.Length; // If we consumed all of 'old', then the length of the old doc is what we have in common. if (newStack.Count > 0) return oldRoot.FullSpan.Length; // We consumed both stacks entirely. That means the trees were identical (though the root was different). Return null to signify no change to the doc. return null; } int ComputeCommonRightWidth() { using var rightOldStack = s_pool.GetPooledObject(); using var rightNewStack = s_pool.GetPooledObject(); var oldStack = rightOldStack.Object; var newStack = rightNewStack.Object; oldStack.Push(oldRoot); newStack.Push(newRoot); while (oldStack.Count > 0 && newStack.Count > 0) { cancellationToken.ThrowIfCancellationRequested(); var currentOld = oldStack.Pop(); var currentNew = newStack.Pop(); // The width on the right we've moved past on both old/new should be the same. Contract.ThrowIfFalse((oldRoot.FullSpan.End - currentOld.FullSpan.End) == (newRoot.FullSpan.End - currentNew.FullSpan.End)); // If the two nodes/tokens were the same just skip past them. They're part of the common right width. // Critically though, we can only skip past if this wasn't already something we consumed when determining // the common left width. If this was common the left side, we can't consider it common to the right, // otherwise we could end up with overlapping regions of commonality. // // This can occur in incremental settings when the similar tokens are written successsively. // Because the parser can reuse underlying token data, it may end up with many incrementally // identical tokens in a row. if (currentOld.IsIncrementallyIdenticalTo(currentNew) && currentOld.FullSpan.Start >= commonLeftWidth && currentNew.FullSpan.Start >= commonLeftWidth) { continue; } // if we reached a token for either of these, then we can't break things down any further, and we hit // the furthest point they are common. if (currentOld.IsToken || currentNew.IsToken) return oldRoot.FullSpan.End - currentOld.FullSpan.End; // Similarly, if we've run out of time, just return what we've computed so far. It's not as accurate as // we could be. But the caller wants the results asap. if (stopwatch.Elapsed > timeout) return oldRoot.FullSpan.End - currentOld.FullSpan.End; // we've got two nodes, but they weren't the same. For example, say we made an edit in a method in the // class, the class node would be new, but there might be many member nodes following the edited node // that were the same that we'd want to see and skip. Crumble the node and deal with its right side. // // Do not reverse the children. We want to process the rightmost child first and walk right to left. foreach (var nodeOrToken in currentOld.AsNode()!.ChildNodesAndTokens()) oldStack.Push(nodeOrToken); foreach (var nodeOrToken in currentNew.AsNode()!.ChildNodesAndTokens()) newStack.Push(nodeOrToken); } // If we consumed all of 'new', then the length of the new doc is what we have in common. if (oldStack.Count > 0) return newRoot.FullSpan.Length; // If we consumed all of 'old', then the length of the old doc is what we have in common. if (newStack.Count > 0) return oldRoot.FullSpan.Length; // We consumed both stacks entirely. That means the trees were identical (though the root was // different). We should never get here. If we were the same, then walking from the left should have // consumed everything and already bailed out. throw ExceptionUtilities.Unreachable; } } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/VisualBasic/Portable/Symbols/NamedTypeSymbol.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.Generic Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Text Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a type other than an array, a type parameter. ''' </summary> Friend MustInherit Class NamedTypeSymbol Inherits TypeSymbol Implements INamedTypeSymbol, INamedTypeSymbolInternal ' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ' Changes to the public interface of this class should remain synchronized with the C# version. ' Do not make any changes to the public interface without making the corresponding change ' to the C# version. ' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ''' <summary> ''' Returns the arity of this type, or the number of type parameters it takes. ''' A non-generic type has zero arity. ''' </summary> Public MustOverride ReadOnly Property Arity As Integer ''' <summary> ''' Returns the type parameters that this type has. If this is a non-generic type, ''' returns an empty ImmutableArray. ''' </summary> Public MustOverride ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) ''' <summary> ''' Returns custom modifiers for the type argument that has been substituted for the type parameter. ''' The modifiers correspond to the type argument at the same ordinal within the <see cref="TypeArgumentsNoUseSiteDiagnostics"/> ''' array. ''' </summary> Public MustOverride Function GetTypeArgumentCustomModifiers(ordinal As Integer) As ImmutableArray(Of CustomModifier) Friend Function GetEmptyTypeArgumentCustomModifiers(ordinal As Integer) As ImmutableArray(Of CustomModifier) If ordinal < 0 OrElse ordinal >= Me.Arity Then Throw New IndexOutOfRangeException() End If Return ImmutableArray(Of CustomModifier).Empty End Function Friend MustOverride ReadOnly Property HasTypeArgumentsCustomModifiers As Boolean ''' <summary> ''' Returns the type arguments that have been substituted for the type parameters. ''' If nothing has been substituted for a give type parameters, ''' then the type parameter itself is consider the type argument. ''' </summary> Friend MustOverride ReadOnly Property TypeArgumentsNoUseSiteDiagnostics As ImmutableArray(Of TypeSymbol) Friend Function TypeArgumentsWithDefinitionUseSiteDiagnostics(<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As ImmutableArray(Of TypeSymbol) Dim result = TypeArgumentsNoUseSiteDiagnostics For Each typeArgument In result typeArgument.OriginalDefinition.AddUseSiteInfo(useSiteInfo) Next Return result End Function Friend Function TypeArgumentWithDefinitionUseSiteDiagnostics(index As Integer, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As TypeSymbol Dim result = TypeArgumentsNoUseSiteDiagnostics(index) result.OriginalDefinition.AddUseSiteInfo(useSiteInfo) Return result End Function ''' <summary> ''' Returns the type symbol that this type was constructed from. This type symbol ''' has the same containing type, but has type arguments that are the same ''' as the type parameters (although its containing type might not). ''' </summary> Public MustOverride ReadOnly Property ConstructedFrom As NamedTypeSymbol ''' <summary> ''' For enum types, gets the underlying type. Returns null on all other ''' kinds of types. ''' </summary> Public Overridable ReadOnly Property EnumUnderlyingType As NamedTypeSymbol Get Return Nothing End Get End Property Public Overrides ReadOnly Property ContainingType As NamedTypeSymbol Get Return TryCast(Me.ContainingSymbol, NamedTypeSymbol) End Get End Property ''' <summary> ''' For implicitly declared delegate types returns the EventSymbol that caused this ''' delegate type to be generated. ''' For all other types returns null. ''' Note, the set of possible associated symbols might be expanded in the future to ''' reflect changes in the languages. ''' </summary> Public Overridable ReadOnly Property AssociatedSymbol As Symbol Get Return Nothing End Get End Property ''' <summary> ''' Returns True for one of the types from a set of Structure types if ''' that set represents a cycle. This property is intended for flow ''' analysis only since it is only implemented for source types, ''' and only returns True for one of the types within a cycle, not all. ''' </summary> Friend Overridable ReadOnly Property KnownCircularStruct As Boolean Get Return False End Get End Property ''' <summary> ''' Is this a NoPia local type explicitly declared in source, i.e. ''' top level type with a TypeIdentifier attribute on it? ''' </summary> Friend Overridable ReadOnly Property IsExplicitDefinitionOfNoPiaLocalType As Boolean Get Return False End Get End Property ''' <summary> ''' Returns true and a string from the first GuidAttribute on the type, ''' the string might be null or an invalid guid representation. False, ''' if there is no GuidAttribute with string argument. ''' </summary> Friend Overridable Function GetGuidString(ByRef guidString As String) As Boolean Return GetGuidStringDefaultImplementation(guidString) End Function ' Named types have the arity suffix added to the metadata name. Public Overrides ReadOnly Property MetadataName As String Get ' CLR generally allows names with dots, however some APIs like IMetaDataImport ' can only return full type names combined with namespaces. ' see: http://msdn.microsoft.com/en-us/library/ms230143.aspx (IMetaDataImport::GetTypeDefProps) ' When working with such APIs, names with dots become ambiguous since metadata ' consumer cannot figure where namespace ends and actual type name starts. ' Therefore it is a good practice to avoid type names with dots. Debug.Assert(Me.IsErrorType OrElse Not (TypeOf Me Is SourceNamedTypeSymbol) OrElse Not Name.Contains("."), "type name contains dots: " + Name) Return If(MangleName, MetadataHelpers.ComposeAritySuffixedMetadataName(Name, Arity), Name) End Get End Property ''' <summary> ''' True if the type itself Is excluded from code coverage instrumentation. ''' True for source types marked with <see cref="AttributeDescription.ExcludeFromCodeCoverageAttribute"/>. ''' </summary> Friend Overridable ReadOnly Property IsDirectlyExcludedFromCodeCoverage As Boolean Get Return False End Get End Property ''' <summary> ''' Should the name returned by Name property be mangled with [`arity] suffix in order to get metadata name. ''' Must return False for a type with Arity == 0. ''' </summary> ''' <remarks> ''' Default implementation to force consideration of appropriate implementation for each new subclass ''' </remarks> Friend MustOverride ReadOnly Property MangleName As Boolean ''' <summary> ''' True if this symbol has a special name (metadata flag SpecialName is set). ''' </summary> Friend MustOverride ReadOnly Property HasSpecialName As Boolean ''' <summary> ''' True if this type is considered serializable (metadata flag Serializable is set). ''' </summary> Public MustOverride ReadOnly Property IsSerializable As Boolean Implements INamedTypeSymbol.IsSerializable ''' <summary> ''' Type layout information (ClassLayout metadata and layout kind flags). ''' </summary> Friend MustOverride ReadOnly Property Layout As TypeLayout ''' <summary> ''' The default charset used for type marshalling. ''' Can be changed via <see cref="DefaultCharSetAttribute"/> applied on the containing module. ''' </summary> Protected ReadOnly Property DefaultMarshallingCharSet As CharSet Get Return If(EffectiveDefaultMarshallingCharSet, CharSet.Ansi) End Get End Property ''' <summary> ''' Marshalling charset of string data fields within the type (string formatting flags in metadata). ''' </summary> Friend MustOverride ReadOnly Property MarshallingCharSet As CharSet ''' <summary> ''' For delegate types, gets the delegate's invoke method. Returns null on ''' all other kinds of types. Note that it is possible to have an ill-formed ''' delegate type imported from metadata which does not have an Invoke method. ''' Such a type will be classified as a delegate but its DelegateInvokeMethod ''' would be null. ''' </summary> Public Overridable ReadOnly Property DelegateInvokeMethod As MethodSymbol Get If TypeKind <> TypeKind.Delegate Then Return Nothing End If Dim methods As ImmutableArray(Of Symbol) = GetMembers(WellKnownMemberNames.DelegateInvokeName) If methods.Length <> 1 Then Return Nothing End If Dim method = TryCast(methods(0), MethodSymbol) 'EDMAURER we used to also check 'method.IsOverridable' because section 13.6 'of the CLI spec dictates that it be virtual, but real world 'working metadata has been found that contains an Invoke method that is 'marked as virtual but not newslot (both of those must be combined to 'meet the definition of virtual). Rather than weaken the check 'I've removed it, as the Dev10 C# compiler makes no check, and we don't 'stand to gain anything by having it. 'Return If(method IsNot Nothing AndAlso method.IsOverridable, method, Nothing) Return method End Get End Property ''' <summary> ''' Returns true if this type was declared as requiring a derived class; ''' i.e., declared with the "MustInherit" modifier. Always true for interfaces. ''' </summary> Public MustOverride ReadOnly Property IsMustInherit As Boolean ''' <summary> ''' Returns true if this type does not allow derived types; i.e., declared ''' with the NotInheritable modifier, or else declared as a Module, Structure, ''' Enum, or Delegate. ''' </summary> Public MustOverride ReadOnly Property IsNotInheritable As Boolean ''' <summary> ''' If this property returns false, it is certain that there are no extension ''' methods inside this type. If this property returns true, it is highly likely ''' (but not certain) that this type contains extension methods. This property allows ''' the search for extension methods to be narrowed much more quickly. ''' ''' !!! Note that this property can mutate during lifetime of the symbol !!! ''' !!! from True to False, as we learn more about the type. !!! ''' </summary> Public MustOverride ReadOnly Property MightContainExtensionMethods As Boolean Implements INamedTypeSymbol.MightContainExtensionMethods ''' <summary> ''' Returns True if the type is marked by 'Microsoft.CodeAnalysis.Embedded' attribute. ''' </summary> Friend MustOverride ReadOnly Property HasCodeAnalysisEmbeddedAttribute As Boolean ''' <summary> ''' Returns True if the type is marked by 'Microsoft.VisualBasic.Embedded' attribute. ''' </summary> Friend MustOverride ReadOnly Property HasVisualBasicEmbeddedAttribute As Boolean ''' <summary> ''' A Named type is an extensible interface if both the following are true: ''' (a) It is an interface type and ''' (b) It is either marked with 'TypeLibTypeAttribute( flags w/o TypeLibTypeFlags.FNonExtensible )' attribute OR ''' is marked with 'InterfaceTypeAttribute( flags with ComInterfaceType.InterfaceIsIDispatch )' attribute OR ''' inherits from an extensible interface type. ''' Member resolution for Extensible interfaces is late bound, i.e. members are resolved at run time by looking up the identifier on the actual run-time type of the expression. ''' </summary> Friend MustOverride ReadOnly Property IsExtensibleInterfaceNoUseSiteDiagnostics As Boolean ''' <summary> ''' This method is an entry point for the Binder to collect extension methods with the given name ''' declared within this named type. Overridden by RetargetingNamedTypeSymbol. ''' </summary> Friend Overridable Sub AppendProbableExtensionMethods(name As String, methods As ArrayBuilder(Of MethodSymbol)) If Me.MightContainExtensionMethods Then For Each member As Symbol In Me.GetMembers(name) If member.Kind = SymbolKind.Method Then Dim method = DirectCast(member, MethodSymbol) If method.MayBeReducibleExtensionMethod Then methods.Add(method) End If End If Next End If End Sub ''' <summary> ''' This method is called for a type within a namespace when we are building a map of extension methods ''' for the whole (compilation merged or module level) namespace. ''' ''' The 'appendThrough' parameter allows RetargetingNamespaceSymbol to delegate majority of the work ''' to the underlying named type symbols, but still add RetargetingMethodSymbols to the map. ''' </summary> Friend Overridable Sub BuildExtensionMethodsMap( map As Dictionary(Of String, ArrayBuilder(Of MethodSymbol)), appendThrough As NamespaceSymbol ) If Me.MightContainExtensionMethods Then Debug.Assert(False, "Possibly using inefficient implementation of AppendProbableExtensionMethods(map As Dictionary(Of String, ArrayBuilder(Of MethodSymbol)))") appendThrough.BuildExtensionMethodsMap(map, From name As String In Me.MemberNames Select New KeyValuePair(Of String, ImmutableArray(Of Symbol))(name, Me.GetMembers(name))) End If End Sub Friend Overridable Sub GetExtensionMethods( methods As ArrayBuilder(Of MethodSymbol), appendThrough As NamespaceSymbol, Name As String ) If Me.MightContainExtensionMethods Then Dim candidates = Me.GetSimpleNonTypeMembers(Name) For Each member In candidates appendThrough.AddMemberIfExtension(methods, member) Next End If End Sub ''' <summary> ''' This is an entry point for the Binder. Its purpose is to add names of viable extension methods declared ''' in this type to nameSet parameter. ''' </summary> Friend Overridable Overloads Sub AddExtensionMethodLookupSymbolsInfo(nameSet As LookupSymbolsInfo, options As LookupOptions, originalBinder As Binder) AddExtensionMethodLookupSymbolsInfo(nameSet, options, originalBinder, appendThrough:=Me) End Sub ''' <summary> ''' Add names of viable extension methods declared in this type to nameSet parameter. ''' ''' The 'appendThrough' parameter allows RetargetingNamedTypeSymbol to delegate majority of the work ''' to the underlying named type symbol, but still perform viability check on RetargetingMethodSymbol. ''' </summary> Friend Overridable Overloads Sub AddExtensionMethodLookupSymbolsInfo(nameSet As LookupSymbolsInfo, options As LookupOptions, originalBinder As Binder, appendThrough As NamedTypeSymbol) If Me.MightContainExtensionMethods Then Debug.Assert(False, "Possibly using inefficient implementation of AppendExtensionMethodNames(nameSet As HashSet(Of String), options As LookupOptions, originalBinder As Binder, appendThrough As NamespaceOrTypeSymbol)") appendThrough.AddExtensionMethodLookupSymbolsInfo(nameSet, options, originalBinder, From name As String In Me.MemberNames Select New KeyValuePair(Of String, ImmutableArray(Of Symbol))(name, Me.GetMembers(name))) End If End Sub ''' <summary> ''' Get the instance constructors for this type. ''' </summary> Public ReadOnly Property InstanceConstructors As ImmutableArray(Of MethodSymbol) Get Return GetConstructors(Of MethodSymbol)(includeInstance:=True, includeShared:=False) End Get End Property ''' <summary> ''' Get the shared constructors for this type. ''' </summary> Public ReadOnly Property SharedConstructors As ImmutableArray(Of MethodSymbol) Get Return GetConstructors(Of MethodSymbol)(includeInstance:=False, includeShared:=True) End Get End Property ''' <summary> ''' Get the instance and shared constructors for this type. ''' </summary> Public ReadOnly Property Constructors As ImmutableArray(Of MethodSymbol) Get Return GetConstructors(Of MethodSymbol)(includeInstance:=True, includeShared:=True) End Get End Property Private Function GetConstructors(Of TMethodSymbol As {IMethodSymbol, Class})(includeInstance As Boolean, includeShared As Boolean) As ImmutableArray(Of TMethodSymbol) Debug.Assert(includeInstance OrElse includeShared) Dim instanceCandidates As ImmutableArray(Of Symbol) = If(includeInstance, GetMembers(WellKnownMemberNames.InstanceConstructorName), ImmutableArray(Of Symbol).Empty) Dim sharedCandidates As ImmutableArray(Of Symbol) = If(includeShared, GetMembers(WellKnownMemberNames.StaticConstructorName), ImmutableArray(Of Symbol).Empty) If instanceCandidates.IsEmpty AndAlso sharedCandidates.IsEmpty Then Return ImmutableArray(Of TMethodSymbol).Empty End If Dim constructors As ArrayBuilder(Of TMethodSymbol) = ArrayBuilder(Of TMethodSymbol).GetInstance() For Each candidate In instanceCandidates If candidate.Kind = SymbolKind.Method Then Dim method As TMethodSymbol = TryCast(candidate, TMethodSymbol) Debug.Assert(method IsNot Nothing) Debug.Assert(method.MethodKind = MethodKind.Constructor) constructors.Add(method) End If Next For Each candidate In sharedCandidates If candidate.Kind = SymbolKind.Method Then Dim method As TMethodSymbol = TryCast(candidate, TMethodSymbol) Debug.Assert(method IsNot Nothing) Debug.Assert(method.MethodKind = MethodKind.StaticConstructor) constructors.Add(method) End If Next Return constructors.ToImmutableAndFree() End Function ''' <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 Overrides ReadOnly Property IsReferenceType As Boolean Get ' TODO: Is this correct for VB Module? Return TypeKind <> TypeKind.Enum AndAlso TypeKind <> TypeKind.Structure AndAlso TypeKind <> TypeKind.Error End Get End Property ''' <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 Overrides ReadOnly Property IsValueType As Boolean Get ' TODO: Is this correct for VB Module? Return TypeKind = TypeKind.Enum OrElse TypeKind = TypeKind.Structure End Get End Property ''' <summary> ''' Returns True if this types has Arity >= 1 and Construct can be called. This is primarily useful ''' when deal with error cases. ''' </summary> Friend MustOverride ReadOnly Property CanConstruct As Boolean ''' <summary> ''' Returns a constructed type given its type arguments. ''' </summary> Public Function Construct(ParamArray typeArguments() As TypeSymbol) As NamedTypeSymbol Return Construct(typeArguments.AsImmutableOrNull()) End Function ''' <summary> ''' Returns a constructed type given its type arguments. ''' </summary> Public Function Construct(typeArguments As IEnumerable(Of TypeSymbol)) As NamedTypeSymbol Return Construct(typeArguments.AsImmutableOrNull()) End Function ''' <summary> ''' Construct a new type from this type, substituting the given type arguments for the ''' type parameters. This method should only be called if this named type does not have ''' any substitutions applied for its own type arguments with exception of alpha-rename ''' substitution (although it's container might have substitutions applied). ''' </summary> ''' <param name="typeArguments">A set of type arguments to be applied. Must have the same length ''' as the number of type parameters that this type has.</param> Public MustOverride Function Construct(typeArguments As ImmutableArray(Of TypeSymbol)) As NamedTypeSymbol ''' <summary> Checks for validity of Construct(...) on this type with these type arguments. </summary> Protected Sub CheckCanConstructAndTypeArguments(typeArguments As ImmutableArray(Of TypeSymbol)) 'This helper is used by Public APIs to perform validation. This exception is part of the public 'contract of Construct() If Not CanConstruct OrElse Me IsNot ConstructedFrom Then Throw New InvalidOperationException() End If ' Check type arguments typeArguments.CheckTypeArguments(Me.Arity) End Sub ''' <summary> ''' Construct a new type from this type definition, substituting the given type arguments for the ''' type parameters. This method should only be called on the OriginalDefinition. Unlike previous ''' Construct method, this overload supports type parameter substitution on this type and any number ''' of its containing types. See comments for TypeSubstitution type for more information. ''' </summary> Friend Function Construct(substitution As TypeSubstitution) As NamedTypeSymbol Debug.Assert(Me.IsDefinition) Debug.Assert(Me.IsOrInGenericType()) If substitution Is Nothing Then Return Me End If Debug.Assert(substitution.IsValidToApplyTo(Me)) ' Validate the map for use of alpha-renamed type parameters. substitution.ThrowIfSubstitutingToAlphaRenamedTypeParameter() Return DirectCast(InternalSubstituteTypeParameters(substitution).AsTypeSymbolOnly(), NamedTypeSymbol) End Function ''' <summary> ''' Returns an unbound generic type of this generic named type. ''' </summary> Public Function ConstructUnboundGenericType() As NamedTypeSymbol Return Me.AsUnboundGenericType() End Function ''' <summary> ''' Returns Default property name for the type. ''' If there is no default property name, then Nothing is returned. ''' </summary> Friend MustOverride ReadOnly Property DefaultPropertyName As String ''' <summary> ''' If this is a generic type instantiation or a nested type of a generic type instantiation, ''' return TypeSubstitution for this construction. Nothing otherwise. ''' Returned TypeSubstitution should target OriginalDefinition of the symbol. ''' </summary> Friend MustOverride ReadOnly Property TypeSubstitution As TypeSubstitution ' These properties of TypeRef, NamespaceOrType, or Symbol must be overridden. ''' <summary> ''' Gets the name of this symbol. ''' </summary> Public MustOverride Overrides ReadOnly Property Name As String ''' <summary> ''' Collection of names of members declared within this type. ''' </summary> Public MustOverride ReadOnly Property MemberNames As IEnumerable(Of String) ''' <summary> ''' Returns true if the type is a Script class. ''' It might be an interactive submission class or a Script class in a csx file. ''' </summary> Public Overridable ReadOnly Property IsScriptClass As Boolean Get Return False End Get End Property ''' <summary> ''' Returns true if the type is a submission class. ''' </summary> Public ReadOnly Property IsSubmissionClass As Boolean Get Return TypeKind = TypeKind.Submission End Get End Property Friend Function GetScriptConstructor() As SynthesizedConstructorBase Debug.Assert(IsScriptClass) Return DirectCast(InstanceConstructors.Single(), SynthesizedConstructorBase) End Function Friend Function GetScriptInitializer() As SynthesizedInteractiveInitializerMethod Debug.Assert(IsScriptClass) Return DirectCast(GetMembers(SynthesizedInteractiveInitializerMethod.InitializerName).Single(), SynthesizedInteractiveInitializerMethod) End Function Friend Function GetScriptEntryPoint() As SynthesizedEntryPointSymbol Debug.Assert(IsScriptClass) Dim name = If(TypeKind = TypeKind.Submission, SynthesizedEntryPointSymbol.FactoryName, SynthesizedEntryPointSymbol.MainName) Return DirectCast(GetMembers(name).Single(), SynthesizedEntryPointSymbol) End Function ''' <summary> ''' Returns true if the type is the implicit class that holds onto invalid global members (like methods or ''' statements in a non script file). ''' </summary> Public Overridable ReadOnly Property IsImplicitClass As Boolean Get Return False End Get End Property ''' <summary> ''' Get all the members of this symbol. ''' </summary> ''' <returns>An ImmutableArray containing all the members of this symbol. If this symbol has no members, ''' returns an empty ImmutableArray. Never returns Nothing.</returns> Public MustOverride Overrides Function GetMembers() As ImmutableArray(Of Symbol) ''' <summary> ''' Get all the members of this symbol that have a particular name. ''' </summary> ''' <returns>An ImmutableArray containing all the members of this symbol with the given name. If there are ''' no members with this name, returns an empty ImmutableArray. Never returns Nothing.</returns> Public MustOverride Overrides Function GetMembers(name As String) As ImmutableArray(Of Symbol) ''' <summary> ''' Get all the members of this symbol that are types. ''' </summary> ''' <returns>An ImmutableArray containing all the types that are members of this symbol. If this symbol has no type members, ''' returns an empty ImmutableArray. Never returns Nothing.</returns> Public MustOverride Overrides Function GetTypeMembers() As ImmutableArray(Of NamedTypeSymbol) ''' <summary> ''' Get all the members of this symbol that are types that have a particular name, and any arity. ''' </summary> ''' <returns>An ImmutableArray containing all the types that are members of this symbol with the given name. ''' If this symbol has no type members with this name, ''' returns an empty ImmutableArray. Never returns Nothing.</returns> Public MustOverride Overrides Function GetTypeMembers(name As String) As ImmutableArray(Of NamedTypeSymbol) ''' <summary> ''' Get all the members of this symbol that are types that have a particular name and arity. ''' </summary> ''' <returns>An ImmutableArray containing all the types that are members of this symbol with the given name and arity. ''' If this symbol has no type members with this name and arity, ''' returns an empty ImmutableArray. Never returns Nothing.</returns> Public MustOverride Overrides Function GetTypeMembers(name As String, arity As Integer) As ImmutableArray(Of NamedTypeSymbol) ''' <summary> ''' Get this accessibility that was declared on this symbol. For symbols that do ''' not have accessibility declared on them, returns NotApplicable. ''' </summary> Public MustOverride Overrides ReadOnly Property DeclaredAccessibility As Accessibility ''' <summary> ''' Supports visitor pattern. ''' </summary> Friend Overrides Function Accept(Of TArgument, TResult)(visitor As VisualBasicSymbolVisitor(Of TArgument, TResult), arg As TArgument) As TResult Return visitor.VisitNamedType(Me, arg) End Function ' Only the compiler can created NamedTypeSymbols. Friend Sub New() End Sub ''' <summary> ''' Gets the kind of this symbol. ''' </summary> Public Overrides ReadOnly Property Kind As SymbolKind ' Cannot seal this method because of the ErrorSymbol. Get Return SymbolKind.NamedType End Get End Property ''' <summary> ''' Returns a flag indicating whether this symbol is ComImport. ''' </summary> ''' <remarks> ''' A type can me marked as a ComImport type in source by applying the <see cref="System.Runtime.InteropServices.ComImportAttribute"/> ''' </remarks> Friend MustOverride ReadOnly Property IsComImport As Boolean ''' <summary> ''' If CoClassAttribute was applied to the type returns the type symbol for the argument. ''' Type symbol may be an error type if the type was not found. Otherwise returns Nothing ''' </summary> Friend MustOverride ReadOnly Property CoClassType As TypeSymbol ''' <summary> ''' Returns a sequence of preprocessor symbols specified in <see cref="ConditionalAttribute"/> applied on this symbol, or null if there are none. ''' </summary> Friend MustOverride Function GetAppliedConditionalSymbols() As ImmutableArray(Of String) ''' <summary> ''' Returns a flag indicating whether this symbol has at least one applied conditional attribute. ''' </summary> ''' <remarks> ''' Forces binding and decoding of attributes. ''' NOTE: Conditional symbols on base type must be inherited by derived type, but the native VB compiler doesn't do so. We maintain compatibility. ''' </remarks> Friend ReadOnly Property IsConditional As Boolean Get Return Me.GetAppliedConditionalSymbols().Any() End Get End Property Friend Overridable ReadOnly Property AreMembersImplicitlyDeclared As Boolean Get Return False End Get End Property ''' <summary> ''' Gets the associated <see cref="AttributeUsageInfo"/> for an attribute type. ''' </summary> Friend MustOverride Function GetAttributeUsageInfo() As AttributeUsageInfo ''' <summary> ''' Declaration security information associated with this type, or null if there is none. ''' </summary> Friend MustOverride Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute) ''' <summary> ''' True if the type has declarative security information (HasSecurity flags). ''' </summary> Friend MustOverride ReadOnly Property HasDeclarativeSecurity As Boolean 'This represents the declared base type and base interfaces, once bound. Private _lazyDeclaredBase As NamedTypeSymbol = ErrorTypeSymbol.UnknownResultType Private _lazyDeclaredInterfaces As ImmutableArray(Of NamedTypeSymbol) = Nothing ''' <summary> ''' NamedTypeSymbol calls derived implementations of this method when declared base type ''' is needed for the first time. ''' ''' basesBeingResolved are passed if there are any types already have their bases resolved ''' so that the derived implementation could avoid infinite recursion ''' </summary> Friend MustOverride Function MakeDeclaredBase(basesBeingResolved As BasesBeingResolved, diagnostics As BindingDiagnosticBag) As NamedTypeSymbol ''' <summary> ''' NamedTypeSymbol calls derived implementations of this method when declared interfaces ''' are needed for the first time. ''' ''' basesBeingResolved are passed if there are any types already have their bases resolved ''' so that the derived implementation could avoid infinite recursion ''' </summary> Friend MustOverride Function MakeDeclaredInterfaces(basesBeingResolved As BasesBeingResolved, diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol) ''' <summary> ''' Base type as "declared". ''' Declared base type may contain circularities. ''' ''' If DeclaredBase must be accessed while other DeclaredBases are being resolved, ''' the bases that are being resolved must be specified here to prevent potential infinite recursion. ''' </summary> Friend Overridable Function GetDeclaredBase(basesBeingResolved As BasesBeingResolved) As NamedTypeSymbol If _lazyDeclaredBase Is ErrorTypeSymbol.UnknownResultType Then Dim diagnostics = BindingDiagnosticBag.GetInstance() AtomicStoreReferenceAndDiagnostics(_lazyDeclaredBase, MakeDeclaredBase(basesBeingResolved, diagnostics), diagnostics, ErrorTypeSymbol.UnknownResultType) diagnostics.Free() End If Return _lazyDeclaredBase End Function Friend Overridable Function GetSimpleNonTypeMembers(name As String) As ImmutableArray(Of Symbol) Return GetMembers(name) End Function Private Sub AtomicStoreReferenceAndDiagnostics(Of T As Class)(ByRef variable As T, value As T, diagBag As BindingDiagnosticBag, Optional comparand As T = Nothing) Debug.Assert(value IsNot comparand) If diagBag Is Nothing OrElse diagBag.IsEmpty Then Interlocked.CompareExchange(variable, value, comparand) Else Dim sourceModule = TryCast(Me.ContainingModule, SourceModuleSymbol) If sourceModule IsNot Nothing Then sourceModule.AtomicStoreReferenceAndDiagnostics(variable, value, diagBag, comparand) End If End If End Sub Friend Sub AtomicStoreArrayAndDiagnostics(Of T)(ByRef variable As ImmutableArray(Of T), value As ImmutableArray(Of T), diagBag As BindingDiagnosticBag) Debug.Assert(Not value.IsDefault) If diagBag Is Nothing OrElse diagBag.IsEmpty Then ImmutableInterlocked.InterlockedCompareExchange(variable, value, Nothing) Else Dim sourceModule = TryCast(Me.ContainingModule, SourceModuleSymbol) If sourceModule IsNot Nothing Then sourceModule.AtomicStoreArrayAndDiagnostics(variable, value, diagBag) End If End If End Sub ''' <summary> ''' Interfaces as "declared". ''' Declared interfaces may contain circularities. ''' ''' If DeclaredInterfaces must be accessed while other DeclaredInterfaces are being resolved, ''' the bases that are being resolved must be specified here to prevent potential infinite recursion. ''' </summary> Friend Overridable Function GetDeclaredInterfacesNoUseSiteDiagnostics(basesBeingResolved As BasesBeingResolved) As ImmutableArray(Of NamedTypeSymbol) If _lazyDeclaredInterfaces.IsDefault Then Dim diagnostics = BindingDiagnosticBag.GetInstance() AtomicStoreArrayAndDiagnostics(_lazyDeclaredInterfaces, MakeDeclaredInterfaces(basesBeingResolved, diagnostics), diagnostics) diagnostics.Free() End If Return _lazyDeclaredInterfaces End Function Friend Function GetDeclaredInterfacesWithDefinitionUseSiteDiagnostics(basesBeingResolved As BasesBeingResolved, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As ImmutableArray(Of NamedTypeSymbol) Dim result = GetDeclaredInterfacesNoUseSiteDiagnostics(basesBeingResolved) For Each iface In result iface.OriginalDefinition.AddUseSiteInfo(useSiteInfo) Next Return result End Function Friend Function GetDirectBaseInterfacesNoUseSiteDiagnostics(basesBeingResolved As BasesBeingResolved) As ImmutableArray(Of NamedTypeSymbol) If Me.TypeKind = TypeKind.Interface Then If basesBeingResolved.InheritsBeingResolvedOpt Is Nothing Then Return Me.InterfacesNoUseSiteDiagnostics Else Return GetDeclaredBaseInterfacesSafe(basesBeingResolved) End If Else Return ImmutableArray(Of NamedTypeSymbol).Empty End If End Function Friend Overridable Function GetDeclaredBaseInterfacesSafe(basesBeingResolved As BasesBeingResolved) As ImmutableArray(Of NamedTypeSymbol) Debug.Assert(Me.IsInterface) Debug.Assert(basesBeingResolved.InheritsBeingResolvedOpt.Any) If basesBeingResolved.InheritsBeingResolvedOpt.Contains(Me) Then Return Nothing End If Return GetDeclaredInterfacesNoUseSiteDiagnostics(basesBeingResolved.PrependInheritsBeingResolved(Me)) End Function ''' <summary> ''' NamedTypeSymbol calls derived implementations of this method when acyclic base type ''' is needed for the first time. ''' This method typically calls GetDeclaredBase, filters for ''' illegal cycles and other conditions before returning result as acyclic. ''' </summary> Friend MustOverride Function MakeAcyclicBaseType(diagnostics As BindingDiagnosticBag) As NamedTypeSymbol ''' <summary> ''' NamedTypeSymbol calls derived implementations of this method when acyclic base interfaces ''' are needed for the first time. ''' This method typically calls GetDeclaredInterfaces, filters for ''' illegal cycles and other conditions before returning result as acyclic. ''' </summary> Friend MustOverride Function MakeAcyclicInterfaces(diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol) Private _lazyBaseType As NamedTypeSymbol = ErrorTypeSymbol.UnknownResultType Private _lazyInterfaces As ImmutableArray(Of NamedTypeSymbol) ''' <summary> ''' Base type. ''' Could be Nothing for Interfaces or Object. ''' </summary> Friend NotOverridable Overrides ReadOnly Property BaseTypeNoUseSiteDiagnostics As NamedTypeSymbol Get If Me._lazyBaseType Is ErrorTypeSymbol.UnknownResultType Then ' force resolution of bases in containing type ' to make base resolution errors more deterministic If ContainingType IsNot Nothing Then Dim tmp = ContainingType.BaseTypeNoUseSiteDiagnostics End If Dim diagnostics = BindingDiagnosticBag.GetInstance Dim acyclicBase = Me.MakeAcyclicBaseType(diagnostics) AtomicStoreReferenceAndDiagnostics(Me._lazyBaseType, acyclicBase, diagnostics, ErrorTypeSymbol.UnknownResultType) diagnostics.Free() End If Return Me._lazyBaseType End Get End Property ''' <summary> ''' Interfaces that are implemented or inherited (if current type is interface itself). ''' </summary> Friend NotOverridable Overrides ReadOnly Property InterfacesNoUseSiteDiagnostics As ImmutableArray(Of NamedTypeSymbol) Get If Me._lazyInterfaces.IsDefault Then Dim diagnostics = BindingDiagnosticBag.GetInstance Dim acyclicInterfaces As ImmutableArray(Of NamedTypeSymbol) = Me.MakeAcyclicInterfaces(diagnostics) AtomicStoreArrayAndDiagnostics(Me._lazyInterfaces, acyclicInterfaces, diagnostics) diagnostics.Free() End If Return Me._lazyInterfaces End Get End Property ''' <summary> ''' Returns declared base type or actual base type if already known ''' This is only used by cycle detection code so that it can observe when cycles are broken ''' while not forcing actual Base to be realized. ''' </summary> Friend Function GetBestKnownBaseType() As NamedTypeSymbol 'NOTE: we can be at race with another thread here. ' the worst thing that can happen though, is that error on same cycle may be reported twice ' if two threads analyze the same cycle at the same time but start from different ends. ' ' For now we decided that this is something we can live with. Dim base = Me._lazyBaseType If base IsNot ErrorTypeSymbol.UnknownResultType Then Return base End If Return GetDeclaredBase(Nothing) End Function ''' <summary> ''' Returns declared interfaces or actual Interfaces if already known ''' This is only used by cycle detection code so that it can observe when cycles are broken ''' while not forcing actual Interfaces to be realized. ''' </summary> Friend Function GetBestKnownInterfacesNoUseSiteDiagnostics() As ImmutableArray(Of NamedTypeSymbol) Dim interfaces = Me._lazyInterfaces If Not interfaces.IsDefault Then Return interfaces End If Return GetDeclaredInterfacesNoUseSiteDiagnostics(Nothing) End Function ''' <summary> ''' True if and only if this type or some containing type has type parameters. ''' </summary> Public ReadOnly Property IsGenericType As Boolean Implements INamedTypeSymbol.IsGenericType Get Dim p As NamedTypeSymbol = Me Do While p IsNot Nothing If (p.Arity <> 0) Then Return True End If p = p.ContainingType Loop Return False End Get End Property ''' <summary> ''' Get the original definition of this symbol. If this symbol is derived from another ''' symbol by (say) type substitution, this gets the original symbol, as it was defined ''' in source or metadata. ''' </summary> Public Overridable Shadows ReadOnly Property OriginalDefinition As NamedTypeSymbol Get ' Default implements returns Me. Return Me End Get End Property Protected NotOverridable Overrides ReadOnly Property OriginalTypeSymbolDefinition As TypeSymbol Get Return Me.OriginalDefinition End Get End Property ''' <summary> ''' Should return full emitted namespace name for a top level type if the name ''' might be different in case from containing namespace symbol full name, Nothing otherwise. ''' </summary> Friend Overridable Function GetEmittedNamespaceName() As String Return Nothing End Function ''' <summary> ''' Does this type implement all the members of the given interface. Does not include members ''' of interfaces that iface inherits, only direct members. ''' </summary> Friend Function ImplementsAllMembersOfInterface(iface As NamedTypeSymbol) As Boolean Dim implementationMap = ExplicitInterfaceImplementationMap For Each ifaceMember In iface.GetMembersUnordered() If ifaceMember.RequiresImplementation() AndAlso Not implementationMap.ContainsKey(ifaceMember) Then Return False End If Next Return True End Function Friend Overrides Function GetUseSiteInfo() As UseSiteInfo(Of AssemblySymbol) If Me.IsDefinition Then Return New UseSiteInfo(Of AssemblySymbol)(PrimaryDependency) End If ' Doing check for constructed types here in order to share implementation across ' constructed non-error and error type symbols. ' Check definition. Dim definitionUseSiteInfo As UseSiteInfo(Of AssemblySymbol) = DeriveUseSiteInfoFromType(Me.OriginalDefinition) If definitionUseSiteInfo.DiagnosticInfo?.Code = ERRID.ERR_UnsupportedType1 Then Return definitionUseSiteInfo End If ' Check type arguments. Dim argsUseSiteInfo As UseSiteInfo(Of AssemblySymbol) = DeriveUseSiteInfoFromTypeArguments() Return MergeUseSiteInfo(definitionUseSiteInfo, argsUseSiteInfo) End Function Private Function DeriveUseSiteInfoFromTypeArguments() As UseSiteInfo(Of AssemblySymbol) Dim argsUseSiteInfo As UseSiteInfo(Of AssemblySymbol) = Nothing Dim currentType As NamedTypeSymbol = Me Do For Each arg As TypeSymbol In currentType.TypeArgumentsNoUseSiteDiagnostics If MergeUseSiteInfo(argsUseSiteInfo, DeriveUseSiteInfoFromType(arg), ERRID.ERR_UnsupportedType1) Then Return argsUseSiteInfo End If Next If currentType.HasTypeArgumentsCustomModifiers Then For i As Integer = 0 To Me.Arity - 1 If MergeUseSiteInfo(argsUseSiteInfo, DeriveUseSiteInfoFromCustomModifiers(Me.GetTypeArgumentCustomModifiers(i)), ERRID.ERR_UnsupportedType1) Then Return argsUseSiteInfo End If Next End If currentType = currentType.ContainingType Loop While currentType IsNot Nothing AndAlso Not currentType.IsDefinition Return argsUseSiteInfo End Function ''' <summary> ''' True if this is a reference to an <em>unbound</em> generic type. These occur only ''' within a <c>GetType</c> expression. A generic type is considered <em>unbound</em> ''' if all of the type argument lists in its fully qualified name are empty. ''' Note that the type arguments of an unbound generic type will be returned as error ''' types because they do not really have type arguments. An unbound generic type ''' yields null for its BaseType and an empty result for its Interfaces. ''' </summary> Public Overridable ReadOnly Property IsUnboundGenericType As Boolean Get Return False End Get End Property ''' <summary> ''' Force all declaration errors to be generated. ''' </summary> Friend MustOverride Overrides Sub GenerateDeclarationErrors(cancellationToken As CancellationToken) ''' <summary> ''' Return compiler generated nested types that are created at Declare phase, but not exposed through GetMembers and the like APIs. ''' Should return Nothing if there are no such types. ''' </summary> Friend Overridable Function GetSynthesizedNestedTypes() As IEnumerable(Of Microsoft.Cci.INestedTypeDefinition) Return Nothing End Function ''' <summary> ''' True if the type is a Windows runtime type. ''' </summary> ''' <remarks> ''' A type can me marked as a Windows runtime type in source by applying the WindowsRuntimeImportAttribute. ''' WindowsRuntimeImportAttribute is a pseudo custom attribute defined as an internal class in System.Runtime.InteropServices.WindowsRuntime namespace. ''' This is needed to mark Windows runtime types which are redefined in mscorlib.dll and System.Runtime.WindowsRuntime.dll. ''' These two assemblies are special as they implement the CLR's support for WinRT. ''' </remarks> Friend MustOverride ReadOnly Property IsWindowsRuntimeImport As Boolean ''' <summary> ''' True if the type should have its WinRT interfaces projected onto .NET types and ''' have missing .NET interface members added to the type. ''' </summary> Friend MustOverride ReadOnly Property ShouldAddWinRTMembers As Boolean ''' <summary> ''' Requires less computation than <see cref="TypeSymbol.TypeKind"/>== <see cref="TypeKind.Interface"/>. ''' </summary> ''' <remarks> ''' Metadata types need to compute their base types in order to know their TypeKinds, And that can lead ''' to cycles if base types are already being computed. ''' </remarks> ''' <returns>True if this Is an interface type.</returns> Friend MustOverride ReadOnly Property IsInterface As Boolean ''' <summary> ''' Get synthesized WithEvents overrides that aren't returned by <see cref="GetMembers"/> ''' </summary> Friend MustOverride Function GetSynthesizedWithEventsOverrides() As IEnumerable(Of PropertySymbol) #Region "INamedTypeSymbol" Private ReadOnly Property INamedTypeSymbol_Arity As Integer Implements INamedTypeSymbol.Arity Get Return Me.Arity End Get End Property Private ReadOnly Property INamedTypeSymbol_ConstructedFrom As INamedTypeSymbol Implements INamedTypeSymbol.ConstructedFrom Get Return Me.ConstructedFrom End Get End Property Private ReadOnly Property INamedTypeSymbol_DelegateInvokeMethod As IMethodSymbol Implements INamedTypeSymbol.DelegateInvokeMethod Get Return Me.DelegateInvokeMethod End Get End Property Private ReadOnly Property INamedTypeSymbol_EnumUnderlyingType As INamedTypeSymbol Implements INamedTypeSymbol.EnumUnderlyingType Get Return Me.EnumUnderlyingType End Get End Property Private ReadOnly Property INamedTypeSymbolInternal_EnumUnderlyingType As INamedTypeSymbolInternal Implements INamedTypeSymbolInternal.EnumUnderlyingType Get Return Me.EnumUnderlyingType End Get End Property Private ReadOnly Property INamedTypeSymbol_MemberNames As IEnumerable(Of String) Implements INamedTypeSymbol.MemberNames Get Return Me.MemberNames End Get End Property Private ReadOnly Property INamedTypeSymbol_IsUnboundGenericType As Boolean Implements INamedTypeSymbol.IsUnboundGenericType Get Return Me.IsUnboundGenericType End Get End Property Private ReadOnly Property INamedTypeSymbol_OriginalDefinition As INamedTypeSymbol Implements INamedTypeSymbol.OriginalDefinition Get Return Me.OriginalDefinition End Get End Property Private Function INamedTypeSymbol_GetTypeArgumentCustomModifiers(ordinal As Integer) As ImmutableArray(Of CustomModifier) Implements INamedTypeSymbol.GetTypeArgumentCustomModifiers Return GetTypeArgumentCustomModifiers(ordinal) End Function Private ReadOnly Property INamedTypeSymbol_TypeArguments As ImmutableArray(Of ITypeSymbol) Implements INamedTypeSymbol.TypeArguments Get Return StaticCast(Of ITypeSymbol).From(Me.TypeArgumentsNoUseSiteDiagnostics) End Get End Property Private ReadOnly Property TypeArgumentNullableAnnotations As ImmutableArray(Of NullableAnnotation) Implements INamedTypeSymbol.TypeArgumentNullableAnnotations Get Return Me.TypeArgumentsNoUseSiteDiagnostics.SelectAsArray(Function(t) NullableAnnotation.None) End Get End Property Private ReadOnly Property INamedTypeSymbol_TypeParameters As ImmutableArray(Of ITypeParameterSymbol) Implements INamedTypeSymbol.TypeParameters Get Return StaticCast(Of ITypeParameterSymbol).From(Me.TypeParameters) End Get End Property Private ReadOnly Property INamedTypeSymbol_IsScriptClass As Boolean Implements INamedTypeSymbol.IsScriptClass Get Return Me.IsScriptClass End Get End Property Private ReadOnly Property INamedTypeSymbol_IsImplicitClass As Boolean Implements INamedTypeSymbol.IsImplicitClass Get Return Me.IsImplicitClass End Get End Property Private Function INamedTypeSymbol_Construct(ParamArray typeArguments() As ITypeSymbol) As INamedTypeSymbol Implements INamedTypeSymbol.Construct Return Construct(ConstructTypeArguments(typeArguments)) End Function Private Function INamedTypeSymbol_Construct(typeArguments As ImmutableArray(Of ITypeSymbol), typeArgumentNullableAnnotations As ImmutableArray(Of CodeAnalysis.NullableAnnotation)) As INamedTypeSymbol Implements INamedTypeSymbol.Construct Return Construct(ConstructTypeArguments(typeArguments, typeArgumentNullableAnnotations)) End Function Private Function INamedTypeSymbol_ConstructUnboundGenericType() As INamedTypeSymbol Implements INamedTypeSymbol.ConstructUnboundGenericType Return ConstructUnboundGenericType() End Function Private ReadOnly Property INamedTypeSymbol_InstanceConstructors As ImmutableArray(Of IMethodSymbol) Implements INamedTypeSymbol.InstanceConstructors Get Return GetConstructors(Of IMethodSymbol)(includeInstance:=True, includeShared:=False) End Get End Property Private ReadOnly Property INamedTypeSymbol_StaticConstructors As ImmutableArray(Of IMethodSymbol) Implements INamedTypeSymbol.StaticConstructors Get Return GetConstructors(Of IMethodSymbol)(includeInstance:=False, includeShared:=True) End Get End Property Private ReadOnly Property INamedTypeSymbol_Constructors As ImmutableArray(Of IMethodSymbol) Implements INamedTypeSymbol.Constructors Get Return GetConstructors(Of IMethodSymbol)(includeInstance:=True, includeShared:=True) End Get End Property Private ReadOnly Property INamedTypeSymbol_AssociatedSymbol As ISymbol Implements INamedTypeSymbol.AssociatedSymbol Get Return Me.AssociatedSymbol End Get End Property Private ReadOnly Property INamedTypeSymbol_IsComImport As Boolean Implements INamedTypeSymbol.IsComImport Get Return IsComImport End Get End Property Private ReadOnly Property INamedTypeSymbol_NativeIntegerUnderlyingType As INamedTypeSymbol Implements INamedTypeSymbol.NativeIntegerUnderlyingType Get Return Nothing End Get End Property #End Region #Region "ISymbol" Protected Overrides ReadOnly Property ISymbol_IsAbstract As Boolean Get Return Me.IsMustInherit End Get End Property Protected Overrides ReadOnly Property ISymbol_IsSealed As Boolean Get Return Me.IsNotInheritable End Get End Property Private ReadOnly Property INamedTypeSymbol_TupleElements As ImmutableArray(Of IFieldSymbol) Implements INamedTypeSymbol.TupleElements Get Return StaticCast(Of IFieldSymbol).From(TupleElements) End Get End Property Private ReadOnly Property INamedTypeSymbol_TupleUnderlyingType As INamedTypeSymbol Implements INamedTypeSymbol.TupleUnderlyingType Get Return TupleUnderlyingType End Get End Property Public Overrides Sub Accept(visitor As SymbolVisitor) visitor.VisitNamedType(Me) End Sub Public Overrides Function Accept(Of TResult)(visitor As SymbolVisitor(Of TResult)) As TResult Return visitor.VisitNamedType(Me) End Function Public Overrides Sub Accept(visitor As VisualBasicSymbolVisitor) visitor.VisitNamedType(Me) End Sub Public Overrides Function Accept(Of TResult)(visitor As VisualBasicSymbolVisitor(Of TResult)) As TResult Return visitor.VisitNamedType(Me) End Function #End Region ''' <summary> ''' Verify if the given type can be used to back a tuple type ''' and return cardinality of that tuple type in <paramref name="tupleCardinality"/>. ''' </summary> ''' <param name="tupleCardinality">If method returns true, contains cardinality of the compatible tuple type.</param> ''' <returns></returns> Public NotOverridable Overrides Function IsTupleCompatible(<Out> ByRef tupleCardinality As Integer) As Boolean If IsTupleType Then tupleCardinality = 0 Return False End If ' Should this be optimized for perf (caching for VT<0> to VT<7>, etc.)? If Not IsUnboundGenericType AndAlso If(ContainingSymbol?.Kind = SymbolKind.Namespace, False) AndAlso If(ContainingNamespace.ContainingNamespace?.IsGlobalNamespace, False) AndAlso Name = TupleTypeSymbol.TupleTypeName AndAlso ContainingNamespace.Name = MetadataHelpers.SystemString Then Dim arity = Me.Arity If arity > 0 AndAlso arity < TupleTypeSymbol.RestPosition Then tupleCardinality = arity Return True ElseIf arity = TupleTypeSymbol.RestPosition AndAlso Not IsDefinition Then ' Skip through "Rest" extensions Dim typeToCheck As TypeSymbol = Me Dim levelsOfNesting As Integer = 0 Do levelsOfNesting += 1 typeToCheck = DirectCast(typeToCheck, NamedTypeSymbol).TypeArgumentsNoUseSiteDiagnostics(TupleTypeSymbol.RestPosition - 1) Loop While TypeSymbol.Equals(typeToCheck.OriginalDefinition, Me.OriginalDefinition, TypeCompareKind.ConsiderEverything) AndAlso Not typeToCheck.IsDefinition If typeToCheck.IsTupleType Then Dim underlying = typeToCheck.TupleUnderlyingType If underlying.Arity = TupleTypeSymbol.RestPosition AndAlso Not TypeSymbol.Equals(underlying.OriginalDefinition, Me.OriginalDefinition, TypeCompareKind.ConsiderEverything) Then tupleCardinality = 0 Return False End If tupleCardinality = (TupleTypeSymbol.RestPosition - 1) * levelsOfNesting + typeToCheck.TupleElementTypes.Length Return True End If arity = If(TryCast(typeToCheck, NamedTypeSymbol)?.Arity, 0) If arity > 0 AndAlso arity < TupleTypeSymbol.RestPosition AndAlso typeToCheck.IsTupleCompatible(tupleCardinality) Then Debug.Assert(tupleCardinality < TupleTypeSymbol.RestPosition) tupleCardinality += (TupleTypeSymbol.RestPosition - 1) * levelsOfNesting Return True End If End If End If tupleCardinality = 0 Return False 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.Generic Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Text Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a type other than an array, a type parameter. ''' </summary> Friend MustInherit Class NamedTypeSymbol Inherits TypeSymbol Implements INamedTypeSymbol, INamedTypeSymbolInternal ' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ' Changes to the public interface of this class should remain synchronized with the C# version. ' Do not make any changes to the public interface without making the corresponding change ' to the C# version. ' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ''' <summary> ''' Returns the arity of this type, or the number of type parameters it takes. ''' A non-generic type has zero arity. ''' </summary> Public MustOverride ReadOnly Property Arity As Integer ''' <summary> ''' Returns the type parameters that this type has. If this is a non-generic type, ''' returns an empty ImmutableArray. ''' </summary> Public MustOverride ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) ''' <summary> ''' Returns custom modifiers for the type argument that has been substituted for the type parameter. ''' The modifiers correspond to the type argument at the same ordinal within the <see cref="TypeArgumentsNoUseSiteDiagnostics"/> ''' array. ''' </summary> Public MustOverride Function GetTypeArgumentCustomModifiers(ordinal As Integer) As ImmutableArray(Of CustomModifier) Friend Function GetEmptyTypeArgumentCustomModifiers(ordinal As Integer) As ImmutableArray(Of CustomModifier) If ordinal < 0 OrElse ordinal >= Me.Arity Then Throw New IndexOutOfRangeException() End If Return ImmutableArray(Of CustomModifier).Empty End Function Friend MustOverride ReadOnly Property HasTypeArgumentsCustomModifiers As Boolean ''' <summary> ''' Returns the type arguments that have been substituted for the type parameters. ''' If nothing has been substituted for a give type parameters, ''' then the type parameter itself is consider the type argument. ''' </summary> Friend MustOverride ReadOnly Property TypeArgumentsNoUseSiteDiagnostics As ImmutableArray(Of TypeSymbol) Friend Function TypeArgumentsWithDefinitionUseSiteDiagnostics(<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As ImmutableArray(Of TypeSymbol) Dim result = TypeArgumentsNoUseSiteDiagnostics For Each typeArgument In result typeArgument.OriginalDefinition.AddUseSiteInfo(useSiteInfo) Next Return result End Function Friend Function TypeArgumentWithDefinitionUseSiteDiagnostics(index As Integer, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As TypeSymbol Dim result = TypeArgumentsNoUseSiteDiagnostics(index) result.OriginalDefinition.AddUseSiteInfo(useSiteInfo) Return result End Function ''' <summary> ''' Returns the type symbol that this type was constructed from. This type symbol ''' has the same containing type, but has type arguments that are the same ''' as the type parameters (although its containing type might not). ''' </summary> Public MustOverride ReadOnly Property ConstructedFrom As NamedTypeSymbol ''' <summary> ''' For enum types, gets the underlying type. Returns null on all other ''' kinds of types. ''' </summary> Public Overridable ReadOnly Property EnumUnderlyingType As NamedTypeSymbol Get Return Nothing End Get End Property Public Overrides ReadOnly Property ContainingType As NamedTypeSymbol Get Return TryCast(Me.ContainingSymbol, NamedTypeSymbol) End Get End Property ''' <summary> ''' For implicitly declared delegate types returns the EventSymbol that caused this ''' delegate type to be generated. ''' For all other types returns null. ''' Note, the set of possible associated symbols might be expanded in the future to ''' reflect changes in the languages. ''' </summary> Public Overridable ReadOnly Property AssociatedSymbol As Symbol Get Return Nothing End Get End Property ''' <summary> ''' Returns True for one of the types from a set of Structure types if ''' that set represents a cycle. This property is intended for flow ''' analysis only since it is only implemented for source types, ''' and only returns True for one of the types within a cycle, not all. ''' </summary> Friend Overridable ReadOnly Property KnownCircularStruct As Boolean Get Return False End Get End Property ''' <summary> ''' Is this a NoPia local type explicitly declared in source, i.e. ''' top level type with a TypeIdentifier attribute on it? ''' </summary> Friend Overridable ReadOnly Property IsExplicitDefinitionOfNoPiaLocalType As Boolean Get Return False End Get End Property ''' <summary> ''' Returns true and a string from the first GuidAttribute on the type, ''' the string might be null or an invalid guid representation. False, ''' if there is no GuidAttribute with string argument. ''' </summary> Friend Overridable Function GetGuidString(ByRef guidString As String) As Boolean Return GetGuidStringDefaultImplementation(guidString) End Function ' Named types have the arity suffix added to the metadata name. Public Overrides ReadOnly Property MetadataName As String Get ' CLR generally allows names with dots, however some APIs like IMetaDataImport ' can only return full type names combined with namespaces. ' see: http://msdn.microsoft.com/en-us/library/ms230143.aspx (IMetaDataImport::GetTypeDefProps) ' When working with such APIs, names with dots become ambiguous since metadata ' consumer cannot figure where namespace ends and actual type name starts. ' Therefore it is a good practice to avoid type names with dots. Debug.Assert(Me.IsErrorType OrElse Not (TypeOf Me Is SourceNamedTypeSymbol) OrElse Not Name.Contains("."), "type name contains dots: " + Name) Return If(MangleName, MetadataHelpers.ComposeAritySuffixedMetadataName(Name, Arity), Name) End Get End Property ''' <summary> ''' True if the type itself Is excluded from code coverage instrumentation. ''' True for source types marked with <see cref="AttributeDescription.ExcludeFromCodeCoverageAttribute"/>. ''' </summary> Friend Overridable ReadOnly Property IsDirectlyExcludedFromCodeCoverage As Boolean Get Return False End Get End Property ''' <summary> ''' Should the name returned by Name property be mangled with [`arity] suffix in order to get metadata name. ''' Must return False for a type with Arity == 0. ''' </summary> ''' <remarks> ''' Default implementation to force consideration of appropriate implementation for each new subclass ''' </remarks> Friend MustOverride ReadOnly Property MangleName As Boolean ''' <summary> ''' True if this symbol has a special name (metadata flag SpecialName is set). ''' </summary> Friend MustOverride ReadOnly Property HasSpecialName As Boolean ''' <summary> ''' True if this type is considered serializable (metadata flag Serializable is set). ''' </summary> Public MustOverride ReadOnly Property IsSerializable As Boolean Implements INamedTypeSymbol.IsSerializable ''' <summary> ''' Type layout information (ClassLayout metadata and layout kind flags). ''' </summary> Friend MustOverride ReadOnly Property Layout As TypeLayout ''' <summary> ''' The default charset used for type marshalling. ''' Can be changed via <see cref="DefaultCharSetAttribute"/> applied on the containing module. ''' </summary> Protected ReadOnly Property DefaultMarshallingCharSet As CharSet Get Return If(EffectiveDefaultMarshallingCharSet, CharSet.Ansi) End Get End Property ''' <summary> ''' Marshalling charset of string data fields within the type (string formatting flags in metadata). ''' </summary> Friend MustOverride ReadOnly Property MarshallingCharSet As CharSet ''' <summary> ''' For delegate types, gets the delegate's invoke method. Returns null on ''' all other kinds of types. Note that it is possible to have an ill-formed ''' delegate type imported from metadata which does not have an Invoke method. ''' Such a type will be classified as a delegate but its DelegateInvokeMethod ''' would be null. ''' </summary> Public Overridable ReadOnly Property DelegateInvokeMethod As MethodSymbol Get If TypeKind <> TypeKind.Delegate Then Return Nothing End If Dim methods As ImmutableArray(Of Symbol) = GetMembers(WellKnownMemberNames.DelegateInvokeName) If methods.Length <> 1 Then Return Nothing End If Dim method = TryCast(methods(0), MethodSymbol) 'EDMAURER we used to also check 'method.IsOverridable' because section 13.6 'of the CLI spec dictates that it be virtual, but real world 'working metadata has been found that contains an Invoke method that is 'marked as virtual but not newslot (both of those must be combined to 'meet the definition of virtual). Rather than weaken the check 'I've removed it, as the Dev10 C# compiler makes no check, and we don't 'stand to gain anything by having it. 'Return If(method IsNot Nothing AndAlso method.IsOverridable, method, Nothing) Return method End Get End Property ''' <summary> ''' Returns true if this type was declared as requiring a derived class; ''' i.e., declared with the "MustInherit" modifier. Always true for interfaces. ''' </summary> Public MustOverride ReadOnly Property IsMustInherit As Boolean ''' <summary> ''' Returns true if this type does not allow derived types; i.e., declared ''' with the NotInheritable modifier, or else declared as a Module, Structure, ''' Enum, or Delegate. ''' </summary> Public MustOverride ReadOnly Property IsNotInheritable As Boolean ''' <summary> ''' If this property returns false, it is certain that there are no extension ''' methods inside this type. If this property returns true, it is highly likely ''' (but not certain) that this type contains extension methods. This property allows ''' the search for extension methods to be narrowed much more quickly. ''' ''' !!! Note that this property can mutate during lifetime of the symbol !!! ''' !!! from True to False, as we learn more about the type. !!! ''' </summary> Public MustOverride ReadOnly Property MightContainExtensionMethods As Boolean Implements INamedTypeSymbol.MightContainExtensionMethods ''' <summary> ''' Returns True if the type is marked by 'Microsoft.CodeAnalysis.Embedded' attribute. ''' </summary> Friend MustOverride ReadOnly Property HasCodeAnalysisEmbeddedAttribute As Boolean ''' <summary> ''' Returns True if the type is marked by 'Microsoft.VisualBasic.Embedded' attribute. ''' </summary> Friend MustOverride ReadOnly Property HasVisualBasicEmbeddedAttribute As Boolean ''' <summary> ''' A Named type is an extensible interface if both the following are true: ''' (a) It is an interface type and ''' (b) It is either marked with 'TypeLibTypeAttribute( flags w/o TypeLibTypeFlags.FNonExtensible )' attribute OR ''' is marked with 'InterfaceTypeAttribute( flags with ComInterfaceType.InterfaceIsIDispatch )' attribute OR ''' inherits from an extensible interface type. ''' Member resolution for Extensible interfaces is late bound, i.e. members are resolved at run time by looking up the identifier on the actual run-time type of the expression. ''' </summary> Friend MustOverride ReadOnly Property IsExtensibleInterfaceNoUseSiteDiagnostics As Boolean ''' <summary> ''' This method is an entry point for the Binder to collect extension methods with the given name ''' declared within this named type. Overridden by RetargetingNamedTypeSymbol. ''' </summary> Friend Overridable Sub AppendProbableExtensionMethods(name As String, methods As ArrayBuilder(Of MethodSymbol)) If Me.MightContainExtensionMethods Then For Each member As Symbol In Me.GetMembers(name) If member.Kind = SymbolKind.Method Then Dim method = DirectCast(member, MethodSymbol) If method.MayBeReducibleExtensionMethod Then methods.Add(method) End If End If Next End If End Sub ''' <summary> ''' This method is called for a type within a namespace when we are building a map of extension methods ''' for the whole (compilation merged or module level) namespace. ''' ''' The 'appendThrough' parameter allows RetargetingNamespaceSymbol to delegate majority of the work ''' to the underlying named type symbols, but still add RetargetingMethodSymbols to the map. ''' </summary> Friend Overridable Sub BuildExtensionMethodsMap( map As Dictionary(Of String, ArrayBuilder(Of MethodSymbol)), appendThrough As NamespaceSymbol ) If Me.MightContainExtensionMethods Then Debug.Assert(False, "Possibly using inefficient implementation of AppendProbableExtensionMethods(map As Dictionary(Of String, ArrayBuilder(Of MethodSymbol)))") appendThrough.BuildExtensionMethodsMap(map, From name As String In Me.MemberNames Select New KeyValuePair(Of String, ImmutableArray(Of Symbol))(name, Me.GetMembers(name))) End If End Sub Friend Overridable Sub GetExtensionMethods( methods As ArrayBuilder(Of MethodSymbol), appendThrough As NamespaceSymbol, Name As String ) If Me.MightContainExtensionMethods Then Dim candidates = Me.GetSimpleNonTypeMembers(Name) For Each member In candidates appendThrough.AddMemberIfExtension(methods, member) Next End If End Sub ''' <summary> ''' This is an entry point for the Binder. Its purpose is to add names of viable extension methods declared ''' in this type to nameSet parameter. ''' </summary> Friend Overridable Overloads Sub AddExtensionMethodLookupSymbolsInfo(nameSet As LookupSymbolsInfo, options As LookupOptions, originalBinder As Binder) AddExtensionMethodLookupSymbolsInfo(nameSet, options, originalBinder, appendThrough:=Me) End Sub ''' <summary> ''' Add names of viable extension methods declared in this type to nameSet parameter. ''' ''' The 'appendThrough' parameter allows RetargetingNamedTypeSymbol to delegate majority of the work ''' to the underlying named type symbol, but still perform viability check on RetargetingMethodSymbol. ''' </summary> Friend Overridable Overloads Sub AddExtensionMethodLookupSymbolsInfo(nameSet As LookupSymbolsInfo, options As LookupOptions, originalBinder As Binder, appendThrough As NamedTypeSymbol) If Me.MightContainExtensionMethods Then Debug.Assert(False, "Possibly using inefficient implementation of AppendExtensionMethodNames(nameSet As HashSet(Of String), options As LookupOptions, originalBinder As Binder, appendThrough As NamespaceOrTypeSymbol)") appendThrough.AddExtensionMethodLookupSymbolsInfo(nameSet, options, originalBinder, From name As String In Me.MemberNames Select New KeyValuePair(Of String, ImmutableArray(Of Symbol))(name, Me.GetMembers(name))) End If End Sub ''' <summary> ''' Get the instance constructors for this type. ''' </summary> Public ReadOnly Property InstanceConstructors As ImmutableArray(Of MethodSymbol) Get Return GetConstructors(Of MethodSymbol)(includeInstance:=True, includeShared:=False) End Get End Property ''' <summary> ''' Get the shared constructors for this type. ''' </summary> Public ReadOnly Property SharedConstructors As ImmutableArray(Of MethodSymbol) Get Return GetConstructors(Of MethodSymbol)(includeInstance:=False, includeShared:=True) End Get End Property ''' <summary> ''' Get the instance and shared constructors for this type. ''' </summary> Public ReadOnly Property Constructors As ImmutableArray(Of MethodSymbol) Get Return GetConstructors(Of MethodSymbol)(includeInstance:=True, includeShared:=True) End Get End Property Private Function GetConstructors(Of TMethodSymbol As {IMethodSymbol, Class})(includeInstance As Boolean, includeShared As Boolean) As ImmutableArray(Of TMethodSymbol) Debug.Assert(includeInstance OrElse includeShared) Dim instanceCandidates As ImmutableArray(Of Symbol) = If(includeInstance, GetMembers(WellKnownMemberNames.InstanceConstructorName), ImmutableArray(Of Symbol).Empty) Dim sharedCandidates As ImmutableArray(Of Symbol) = If(includeShared, GetMembers(WellKnownMemberNames.StaticConstructorName), ImmutableArray(Of Symbol).Empty) If instanceCandidates.IsEmpty AndAlso sharedCandidates.IsEmpty Then Return ImmutableArray(Of TMethodSymbol).Empty End If Dim constructors As ArrayBuilder(Of TMethodSymbol) = ArrayBuilder(Of TMethodSymbol).GetInstance() For Each candidate In instanceCandidates If candidate.Kind = SymbolKind.Method Then Dim method As TMethodSymbol = TryCast(candidate, TMethodSymbol) Debug.Assert(method IsNot Nothing) Debug.Assert(method.MethodKind = MethodKind.Constructor) constructors.Add(method) End If Next For Each candidate In sharedCandidates If candidate.Kind = SymbolKind.Method Then Dim method As TMethodSymbol = TryCast(candidate, TMethodSymbol) Debug.Assert(method IsNot Nothing) Debug.Assert(method.MethodKind = MethodKind.StaticConstructor) constructors.Add(method) End If Next Return constructors.ToImmutableAndFree() End Function ''' <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 Overrides ReadOnly Property IsReferenceType As Boolean Get ' TODO: Is this correct for VB Module? Return TypeKind <> TypeKind.Enum AndAlso TypeKind <> TypeKind.Structure AndAlso TypeKind <> TypeKind.Error End Get End Property ''' <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 Overrides ReadOnly Property IsValueType As Boolean Get ' TODO: Is this correct for VB Module? Return TypeKind = TypeKind.Enum OrElse TypeKind = TypeKind.Structure End Get End Property ''' <summary> ''' Returns True if this types has Arity >= 1 and Construct can be called. This is primarily useful ''' when deal with error cases. ''' </summary> Friend MustOverride ReadOnly Property CanConstruct As Boolean ''' <summary> ''' Returns a constructed type given its type arguments. ''' </summary> Public Function Construct(ParamArray typeArguments() As TypeSymbol) As NamedTypeSymbol Return Construct(typeArguments.AsImmutableOrNull()) End Function ''' <summary> ''' Returns a constructed type given its type arguments. ''' </summary> Public Function Construct(typeArguments As IEnumerable(Of TypeSymbol)) As NamedTypeSymbol Return Construct(typeArguments.AsImmutableOrNull()) End Function ''' <summary> ''' Construct a new type from this type, substituting the given type arguments for the ''' type parameters. This method should only be called if this named type does not have ''' any substitutions applied for its own type arguments with exception of alpha-rename ''' substitution (although it's container might have substitutions applied). ''' </summary> ''' <param name="typeArguments">A set of type arguments to be applied. Must have the same length ''' as the number of type parameters that this type has.</param> Public MustOverride Function Construct(typeArguments As ImmutableArray(Of TypeSymbol)) As NamedTypeSymbol ''' <summary> Checks for validity of Construct(...) on this type with these type arguments. </summary> Protected Sub CheckCanConstructAndTypeArguments(typeArguments As ImmutableArray(Of TypeSymbol)) 'This helper is used by Public APIs to perform validation. This exception is part of the public 'contract of Construct() If Not CanConstruct OrElse Me IsNot ConstructedFrom Then Throw New InvalidOperationException() End If ' Check type arguments typeArguments.CheckTypeArguments(Me.Arity) End Sub ''' <summary> ''' Construct a new type from this type definition, substituting the given type arguments for the ''' type parameters. This method should only be called on the OriginalDefinition. Unlike previous ''' Construct method, this overload supports type parameter substitution on this type and any number ''' of its containing types. See comments for TypeSubstitution type for more information. ''' </summary> Friend Function Construct(substitution As TypeSubstitution) As NamedTypeSymbol Debug.Assert(Me.IsDefinition) Debug.Assert(Me.IsOrInGenericType()) If substitution Is Nothing Then Return Me End If Debug.Assert(substitution.IsValidToApplyTo(Me)) ' Validate the map for use of alpha-renamed type parameters. substitution.ThrowIfSubstitutingToAlphaRenamedTypeParameter() Return DirectCast(InternalSubstituteTypeParameters(substitution).AsTypeSymbolOnly(), NamedTypeSymbol) End Function ''' <summary> ''' Returns an unbound generic type of this generic named type. ''' </summary> Public Function ConstructUnboundGenericType() As NamedTypeSymbol Return Me.AsUnboundGenericType() End Function ''' <summary> ''' Returns Default property name for the type. ''' If there is no default property name, then Nothing is returned. ''' </summary> Friend MustOverride ReadOnly Property DefaultPropertyName As String ''' <summary> ''' If this is a generic type instantiation or a nested type of a generic type instantiation, ''' return TypeSubstitution for this construction. Nothing otherwise. ''' Returned TypeSubstitution should target OriginalDefinition of the symbol. ''' </summary> Friend MustOverride ReadOnly Property TypeSubstitution As TypeSubstitution ' These properties of TypeRef, NamespaceOrType, or Symbol must be overridden. ''' <summary> ''' Gets the name of this symbol. ''' </summary> Public MustOverride Overrides ReadOnly Property Name As String ''' <summary> ''' Collection of names of members declared within this type. ''' </summary> Public MustOverride ReadOnly Property MemberNames As IEnumerable(Of String) ''' <summary> ''' Returns true if the type is a Script class. ''' It might be an interactive submission class or a Script class in a csx file. ''' </summary> Public Overridable ReadOnly Property IsScriptClass As Boolean Get Return False End Get End Property ''' <summary> ''' Returns true if the type is a submission class. ''' </summary> Public ReadOnly Property IsSubmissionClass As Boolean Get Return TypeKind = TypeKind.Submission End Get End Property Friend Function GetScriptConstructor() As SynthesizedConstructorBase Debug.Assert(IsScriptClass) Return DirectCast(InstanceConstructors.Single(), SynthesizedConstructorBase) End Function Friend Function GetScriptInitializer() As SynthesizedInteractiveInitializerMethod Debug.Assert(IsScriptClass) Return DirectCast(GetMembers(SynthesizedInteractiveInitializerMethod.InitializerName).Single(), SynthesizedInteractiveInitializerMethod) End Function Friend Function GetScriptEntryPoint() As SynthesizedEntryPointSymbol Debug.Assert(IsScriptClass) Dim name = If(TypeKind = TypeKind.Submission, SynthesizedEntryPointSymbol.FactoryName, SynthesizedEntryPointSymbol.MainName) Return DirectCast(GetMembers(name).Single(), SynthesizedEntryPointSymbol) End Function ''' <summary> ''' Returns true if the type is the implicit class that holds onto invalid global members (like methods or ''' statements in a non script file). ''' </summary> Public Overridable ReadOnly Property IsImplicitClass As Boolean Get Return False End Get End Property ''' <summary> ''' Get all the members of this symbol. ''' </summary> ''' <returns>An ImmutableArray containing all the members of this symbol. If this symbol has no members, ''' returns an empty ImmutableArray. Never returns Nothing.</returns> Public MustOverride Overrides Function GetMembers() As ImmutableArray(Of Symbol) ''' <summary> ''' Get all the members of this symbol that have a particular name. ''' </summary> ''' <returns>An ImmutableArray containing all the members of this symbol with the given name. If there are ''' no members with this name, returns an empty ImmutableArray. Never returns Nothing.</returns> Public MustOverride Overrides Function GetMembers(name As String) As ImmutableArray(Of Symbol) ''' <summary> ''' Get all the members of this symbol that are types. ''' </summary> ''' <returns>An ImmutableArray containing all the types that are members of this symbol. If this symbol has no type members, ''' returns an empty ImmutableArray. Never returns Nothing.</returns> Public MustOverride Overrides Function GetTypeMembers() As ImmutableArray(Of NamedTypeSymbol) ''' <summary> ''' Get all the members of this symbol that are types that have a particular name, and any arity. ''' </summary> ''' <returns>An ImmutableArray containing all the types that are members of this symbol with the given name. ''' If this symbol has no type members with this name, ''' returns an empty ImmutableArray. Never returns Nothing.</returns> Public MustOverride Overrides Function GetTypeMembers(name As String) As ImmutableArray(Of NamedTypeSymbol) ''' <summary> ''' Get all the members of this symbol that are types that have a particular name and arity. ''' </summary> ''' <returns>An ImmutableArray containing all the types that are members of this symbol with the given name and arity. ''' If this symbol has no type members with this name and arity, ''' returns an empty ImmutableArray. Never returns Nothing.</returns> Public MustOverride Overrides Function GetTypeMembers(name As String, arity As Integer) As ImmutableArray(Of NamedTypeSymbol) ''' <summary> ''' Get this accessibility that was declared on this symbol. For symbols that do ''' not have accessibility declared on them, returns NotApplicable. ''' </summary> Public MustOverride Overrides ReadOnly Property DeclaredAccessibility As Accessibility ''' <summary> ''' Supports visitor pattern. ''' </summary> Friend Overrides Function Accept(Of TArgument, TResult)(visitor As VisualBasicSymbolVisitor(Of TArgument, TResult), arg As TArgument) As TResult Return visitor.VisitNamedType(Me, arg) End Function ' Only the compiler can created NamedTypeSymbols. Friend Sub New() End Sub ''' <summary> ''' Gets the kind of this symbol. ''' </summary> Public Overrides ReadOnly Property Kind As SymbolKind ' Cannot seal this method because of the ErrorSymbol. Get Return SymbolKind.NamedType End Get End Property ''' <summary> ''' Returns a flag indicating whether this symbol is ComImport. ''' </summary> ''' <remarks> ''' A type can me marked as a ComImport type in source by applying the <see cref="System.Runtime.InteropServices.ComImportAttribute"/> ''' </remarks> Friend MustOverride ReadOnly Property IsComImport As Boolean ''' <summary> ''' If CoClassAttribute was applied to the type returns the type symbol for the argument. ''' Type symbol may be an error type if the type was not found. Otherwise returns Nothing ''' </summary> Friend MustOverride ReadOnly Property CoClassType As TypeSymbol ''' <summary> ''' Returns a sequence of preprocessor symbols specified in <see cref="ConditionalAttribute"/> applied on this symbol, or null if there are none. ''' </summary> Friend MustOverride Function GetAppliedConditionalSymbols() As ImmutableArray(Of String) ''' <summary> ''' Returns a flag indicating whether this symbol has at least one applied conditional attribute. ''' </summary> ''' <remarks> ''' Forces binding and decoding of attributes. ''' NOTE: Conditional symbols on base type must be inherited by derived type, but the native VB compiler doesn't do so. We maintain compatibility. ''' </remarks> Friend ReadOnly Property IsConditional As Boolean Get Return Me.GetAppliedConditionalSymbols().Any() End Get End Property Friend Overridable ReadOnly Property AreMembersImplicitlyDeclared As Boolean Get Return False End Get End Property ''' <summary> ''' Gets the associated <see cref="AttributeUsageInfo"/> for an attribute type. ''' </summary> Friend MustOverride Function GetAttributeUsageInfo() As AttributeUsageInfo ''' <summary> ''' Declaration security information associated with this type, or null if there is none. ''' </summary> Friend MustOverride Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute) ''' <summary> ''' True if the type has declarative security information (HasSecurity flags). ''' </summary> Friend MustOverride ReadOnly Property HasDeclarativeSecurity As Boolean 'This represents the declared base type and base interfaces, once bound. Private _lazyDeclaredBase As NamedTypeSymbol = ErrorTypeSymbol.UnknownResultType Private _lazyDeclaredInterfaces As ImmutableArray(Of NamedTypeSymbol) = Nothing ''' <summary> ''' NamedTypeSymbol calls derived implementations of this method when declared base type ''' is needed for the first time. ''' ''' basesBeingResolved are passed if there are any types already have their bases resolved ''' so that the derived implementation could avoid infinite recursion ''' </summary> Friend MustOverride Function MakeDeclaredBase(basesBeingResolved As BasesBeingResolved, diagnostics As BindingDiagnosticBag) As NamedTypeSymbol ''' <summary> ''' NamedTypeSymbol calls derived implementations of this method when declared interfaces ''' are needed for the first time. ''' ''' basesBeingResolved are passed if there are any types already have their bases resolved ''' so that the derived implementation could avoid infinite recursion ''' </summary> Friend MustOverride Function MakeDeclaredInterfaces(basesBeingResolved As BasesBeingResolved, diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol) ''' <summary> ''' Base type as "declared". ''' Declared base type may contain circularities. ''' ''' If DeclaredBase must be accessed while other DeclaredBases are being resolved, ''' the bases that are being resolved must be specified here to prevent potential infinite recursion. ''' </summary> Friend Overridable Function GetDeclaredBase(basesBeingResolved As BasesBeingResolved) As NamedTypeSymbol If _lazyDeclaredBase Is ErrorTypeSymbol.UnknownResultType Then Dim diagnostics = BindingDiagnosticBag.GetInstance() AtomicStoreReferenceAndDiagnostics(_lazyDeclaredBase, MakeDeclaredBase(basesBeingResolved, diagnostics), diagnostics, ErrorTypeSymbol.UnknownResultType) diagnostics.Free() End If Return _lazyDeclaredBase End Function Friend Overridable Function GetSimpleNonTypeMembers(name As String) As ImmutableArray(Of Symbol) Return GetMembers(name) End Function Private Sub AtomicStoreReferenceAndDiagnostics(Of T As Class)(ByRef variable As T, value As T, diagBag As BindingDiagnosticBag, Optional comparand As T = Nothing) Debug.Assert(value IsNot comparand) If diagBag Is Nothing OrElse diagBag.IsEmpty Then Interlocked.CompareExchange(variable, value, comparand) Else Dim sourceModule = TryCast(Me.ContainingModule, SourceModuleSymbol) If sourceModule IsNot Nothing Then sourceModule.AtomicStoreReferenceAndDiagnostics(variable, value, diagBag, comparand) End If End If End Sub Friend Sub AtomicStoreArrayAndDiagnostics(Of T)(ByRef variable As ImmutableArray(Of T), value As ImmutableArray(Of T), diagBag As BindingDiagnosticBag) Debug.Assert(Not value.IsDefault) If diagBag Is Nothing OrElse diagBag.IsEmpty Then ImmutableInterlocked.InterlockedCompareExchange(variable, value, Nothing) Else Dim sourceModule = TryCast(Me.ContainingModule, SourceModuleSymbol) If sourceModule IsNot Nothing Then sourceModule.AtomicStoreArrayAndDiagnostics(variable, value, diagBag) End If End If End Sub ''' <summary> ''' Interfaces as "declared". ''' Declared interfaces may contain circularities. ''' ''' If DeclaredInterfaces must be accessed while other DeclaredInterfaces are being resolved, ''' the bases that are being resolved must be specified here to prevent potential infinite recursion. ''' </summary> Friend Overridable Function GetDeclaredInterfacesNoUseSiteDiagnostics(basesBeingResolved As BasesBeingResolved) As ImmutableArray(Of NamedTypeSymbol) If _lazyDeclaredInterfaces.IsDefault Then Dim diagnostics = BindingDiagnosticBag.GetInstance() AtomicStoreArrayAndDiagnostics(_lazyDeclaredInterfaces, MakeDeclaredInterfaces(basesBeingResolved, diagnostics), diagnostics) diagnostics.Free() End If Return _lazyDeclaredInterfaces End Function Friend Function GetDeclaredInterfacesWithDefinitionUseSiteDiagnostics(basesBeingResolved As BasesBeingResolved, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As ImmutableArray(Of NamedTypeSymbol) Dim result = GetDeclaredInterfacesNoUseSiteDiagnostics(basesBeingResolved) For Each iface In result iface.OriginalDefinition.AddUseSiteInfo(useSiteInfo) Next Return result End Function Friend Function GetDirectBaseInterfacesNoUseSiteDiagnostics(basesBeingResolved As BasesBeingResolved) As ImmutableArray(Of NamedTypeSymbol) If Me.TypeKind = TypeKind.Interface Then If basesBeingResolved.InheritsBeingResolvedOpt Is Nothing Then Return Me.InterfacesNoUseSiteDiagnostics Else Return GetDeclaredBaseInterfacesSafe(basesBeingResolved) End If Else Return ImmutableArray(Of NamedTypeSymbol).Empty End If End Function Friend Overridable Function GetDeclaredBaseInterfacesSafe(basesBeingResolved As BasesBeingResolved) As ImmutableArray(Of NamedTypeSymbol) Debug.Assert(Me.IsInterface) Debug.Assert(basesBeingResolved.InheritsBeingResolvedOpt.Any) If basesBeingResolved.InheritsBeingResolvedOpt.Contains(Me) Then Return Nothing End If Return GetDeclaredInterfacesNoUseSiteDiagnostics(basesBeingResolved.PrependInheritsBeingResolved(Me)) End Function ''' <summary> ''' NamedTypeSymbol calls derived implementations of this method when acyclic base type ''' is needed for the first time. ''' This method typically calls GetDeclaredBase, filters for ''' illegal cycles and other conditions before returning result as acyclic. ''' </summary> Friend MustOverride Function MakeAcyclicBaseType(diagnostics As BindingDiagnosticBag) As NamedTypeSymbol ''' <summary> ''' NamedTypeSymbol calls derived implementations of this method when acyclic base interfaces ''' are needed for the first time. ''' This method typically calls GetDeclaredInterfaces, filters for ''' illegal cycles and other conditions before returning result as acyclic. ''' </summary> Friend MustOverride Function MakeAcyclicInterfaces(diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol) Private _lazyBaseType As NamedTypeSymbol = ErrorTypeSymbol.UnknownResultType Private _lazyInterfaces As ImmutableArray(Of NamedTypeSymbol) ''' <summary> ''' Base type. ''' Could be Nothing for Interfaces or Object. ''' </summary> Friend NotOverridable Overrides ReadOnly Property BaseTypeNoUseSiteDiagnostics As NamedTypeSymbol Get If Me._lazyBaseType Is ErrorTypeSymbol.UnknownResultType Then ' force resolution of bases in containing type ' to make base resolution errors more deterministic If ContainingType IsNot Nothing Then Dim tmp = ContainingType.BaseTypeNoUseSiteDiagnostics End If Dim diagnostics = BindingDiagnosticBag.GetInstance Dim acyclicBase = Me.MakeAcyclicBaseType(diagnostics) AtomicStoreReferenceAndDiagnostics(Me._lazyBaseType, acyclicBase, diagnostics, ErrorTypeSymbol.UnknownResultType) diagnostics.Free() End If Return Me._lazyBaseType End Get End Property ''' <summary> ''' Interfaces that are implemented or inherited (if current type is interface itself). ''' </summary> Friend NotOverridable Overrides ReadOnly Property InterfacesNoUseSiteDiagnostics As ImmutableArray(Of NamedTypeSymbol) Get If Me._lazyInterfaces.IsDefault Then Dim diagnostics = BindingDiagnosticBag.GetInstance Dim acyclicInterfaces As ImmutableArray(Of NamedTypeSymbol) = Me.MakeAcyclicInterfaces(diagnostics) AtomicStoreArrayAndDiagnostics(Me._lazyInterfaces, acyclicInterfaces, diagnostics) diagnostics.Free() End If Return Me._lazyInterfaces End Get End Property ''' <summary> ''' Returns declared base type or actual base type if already known ''' This is only used by cycle detection code so that it can observe when cycles are broken ''' while not forcing actual Base to be realized. ''' </summary> Friend Function GetBestKnownBaseType() As NamedTypeSymbol 'NOTE: we can be at race with another thread here. ' the worst thing that can happen though, is that error on same cycle may be reported twice ' if two threads analyze the same cycle at the same time but start from different ends. ' ' For now we decided that this is something we can live with. Dim base = Me._lazyBaseType If base IsNot ErrorTypeSymbol.UnknownResultType Then Return base End If Return GetDeclaredBase(Nothing) End Function ''' <summary> ''' Returns declared interfaces or actual Interfaces if already known ''' This is only used by cycle detection code so that it can observe when cycles are broken ''' while not forcing actual Interfaces to be realized. ''' </summary> Friend Function GetBestKnownInterfacesNoUseSiteDiagnostics() As ImmutableArray(Of NamedTypeSymbol) Dim interfaces = Me._lazyInterfaces If Not interfaces.IsDefault Then Return interfaces End If Return GetDeclaredInterfacesNoUseSiteDiagnostics(Nothing) End Function ''' <summary> ''' True if and only if this type or some containing type has type parameters. ''' </summary> Public ReadOnly Property IsGenericType As Boolean Implements INamedTypeSymbol.IsGenericType Get Dim p As NamedTypeSymbol = Me Do While p IsNot Nothing If (p.Arity <> 0) Then Return True End If p = p.ContainingType Loop Return False End Get End Property ''' <summary> ''' Get the original definition of this symbol. If this symbol is derived from another ''' symbol by (say) type substitution, this gets the original symbol, as it was defined ''' in source or metadata. ''' </summary> Public Overridable Shadows ReadOnly Property OriginalDefinition As NamedTypeSymbol Get ' Default implements returns Me. Return Me End Get End Property Protected NotOverridable Overrides ReadOnly Property OriginalTypeSymbolDefinition As TypeSymbol Get Return Me.OriginalDefinition End Get End Property ''' <summary> ''' Should return full emitted namespace name for a top level type if the name ''' might be different in case from containing namespace symbol full name, Nothing otherwise. ''' </summary> Friend Overridable Function GetEmittedNamespaceName() As String Return Nothing End Function ''' <summary> ''' Does this type implement all the members of the given interface. Does not include members ''' of interfaces that iface inherits, only direct members. ''' </summary> Friend Function ImplementsAllMembersOfInterface(iface As NamedTypeSymbol) As Boolean Dim implementationMap = ExplicitInterfaceImplementationMap For Each ifaceMember In iface.GetMembersUnordered() If ifaceMember.RequiresImplementation() AndAlso Not implementationMap.ContainsKey(ifaceMember) Then Return False End If Next Return True End Function Friend Overrides Function GetUseSiteInfo() As UseSiteInfo(Of AssemblySymbol) If Me.IsDefinition Then Return New UseSiteInfo(Of AssemblySymbol)(PrimaryDependency) End If ' Doing check for constructed types here in order to share implementation across ' constructed non-error and error type symbols. ' Check definition. Dim definitionUseSiteInfo As UseSiteInfo(Of AssemblySymbol) = DeriveUseSiteInfoFromType(Me.OriginalDefinition) If definitionUseSiteInfo.DiagnosticInfo?.Code = ERRID.ERR_UnsupportedType1 Then Return definitionUseSiteInfo End If ' Check type arguments. Dim argsUseSiteInfo As UseSiteInfo(Of AssemblySymbol) = DeriveUseSiteInfoFromTypeArguments() Return MergeUseSiteInfo(definitionUseSiteInfo, argsUseSiteInfo) End Function Private Function DeriveUseSiteInfoFromTypeArguments() As UseSiteInfo(Of AssemblySymbol) Dim argsUseSiteInfo As UseSiteInfo(Of AssemblySymbol) = Nothing Dim currentType As NamedTypeSymbol = Me Do For Each arg As TypeSymbol In currentType.TypeArgumentsNoUseSiteDiagnostics If MergeUseSiteInfo(argsUseSiteInfo, DeriveUseSiteInfoFromType(arg), ERRID.ERR_UnsupportedType1) Then Return argsUseSiteInfo End If Next If currentType.HasTypeArgumentsCustomModifiers Then For i As Integer = 0 To Me.Arity - 1 If MergeUseSiteInfo(argsUseSiteInfo, DeriveUseSiteInfoFromCustomModifiers(Me.GetTypeArgumentCustomModifiers(i)), ERRID.ERR_UnsupportedType1) Then Return argsUseSiteInfo End If Next End If currentType = currentType.ContainingType Loop While currentType IsNot Nothing AndAlso Not currentType.IsDefinition Return argsUseSiteInfo End Function ''' <summary> ''' True if this is a reference to an <em>unbound</em> generic type. These occur only ''' within a <c>GetType</c> expression. A generic type is considered <em>unbound</em> ''' if all of the type argument lists in its fully qualified name are empty. ''' Note that the type arguments of an unbound generic type will be returned as error ''' types because they do not really have type arguments. An unbound generic type ''' yields null for its BaseType and an empty result for its Interfaces. ''' </summary> Public Overridable ReadOnly Property IsUnboundGenericType As Boolean Get Return False End Get End Property ''' <summary> ''' Force all declaration errors to be generated. ''' </summary> Friend MustOverride Overrides Sub GenerateDeclarationErrors(cancellationToken As CancellationToken) ''' <summary> ''' Return compiler generated nested types that are created at Declare phase, but not exposed through GetMembers and the like APIs. ''' Should return Nothing if there are no such types. ''' </summary> Friend Overridable Function GetSynthesizedNestedTypes() As IEnumerable(Of Microsoft.Cci.INestedTypeDefinition) Return Nothing End Function ''' <summary> ''' True if the type is a Windows runtime type. ''' </summary> ''' <remarks> ''' A type can me marked as a Windows runtime type in source by applying the WindowsRuntimeImportAttribute. ''' WindowsRuntimeImportAttribute is a pseudo custom attribute defined as an internal class in System.Runtime.InteropServices.WindowsRuntime namespace. ''' This is needed to mark Windows runtime types which are redefined in mscorlib.dll and System.Runtime.WindowsRuntime.dll. ''' These two assemblies are special as they implement the CLR's support for WinRT. ''' </remarks> Friend MustOverride ReadOnly Property IsWindowsRuntimeImport As Boolean ''' <summary> ''' True if the type should have its WinRT interfaces projected onto .NET types and ''' have missing .NET interface members added to the type. ''' </summary> Friend MustOverride ReadOnly Property ShouldAddWinRTMembers As Boolean ''' <summary> ''' Requires less computation than <see cref="TypeSymbol.TypeKind"/>== <see cref="TypeKind.Interface"/>. ''' </summary> ''' <remarks> ''' Metadata types need to compute their base types in order to know their TypeKinds, And that can lead ''' to cycles if base types are already being computed. ''' </remarks> ''' <returns>True if this Is an interface type.</returns> Friend MustOverride ReadOnly Property IsInterface As Boolean ''' <summary> ''' Get synthesized WithEvents overrides that aren't returned by <see cref="GetMembers"/> ''' </summary> Friend MustOverride Function GetSynthesizedWithEventsOverrides() As IEnumerable(Of PropertySymbol) #Region "INamedTypeSymbol" Private ReadOnly Property INamedTypeSymbol_Arity As Integer Implements INamedTypeSymbol.Arity Get Return Me.Arity End Get End Property Private ReadOnly Property INamedTypeSymbol_ConstructedFrom As INamedTypeSymbol Implements INamedTypeSymbol.ConstructedFrom Get Return Me.ConstructedFrom End Get End Property Private ReadOnly Property INamedTypeSymbol_DelegateInvokeMethod As IMethodSymbol Implements INamedTypeSymbol.DelegateInvokeMethod Get Return Me.DelegateInvokeMethod End Get End Property Private ReadOnly Property INamedTypeSymbol_EnumUnderlyingType As INamedTypeSymbol Implements INamedTypeSymbol.EnumUnderlyingType Get Return Me.EnumUnderlyingType End Get End Property Private ReadOnly Property INamedTypeSymbolInternal_EnumUnderlyingType As INamedTypeSymbolInternal Implements INamedTypeSymbolInternal.EnumUnderlyingType Get Return Me.EnumUnderlyingType End Get End Property Private ReadOnly Property INamedTypeSymbol_MemberNames As IEnumerable(Of String) Implements INamedTypeSymbol.MemberNames Get Return Me.MemberNames End Get End Property Private ReadOnly Property INamedTypeSymbol_IsUnboundGenericType As Boolean Implements INamedTypeSymbol.IsUnboundGenericType Get Return Me.IsUnboundGenericType End Get End Property Private ReadOnly Property INamedTypeSymbol_OriginalDefinition As INamedTypeSymbol Implements INamedTypeSymbol.OriginalDefinition Get Return Me.OriginalDefinition End Get End Property Private Function INamedTypeSymbol_GetTypeArgumentCustomModifiers(ordinal As Integer) As ImmutableArray(Of CustomModifier) Implements INamedTypeSymbol.GetTypeArgumentCustomModifiers Return GetTypeArgumentCustomModifiers(ordinal) End Function Private ReadOnly Property INamedTypeSymbol_TypeArguments As ImmutableArray(Of ITypeSymbol) Implements INamedTypeSymbol.TypeArguments Get Return StaticCast(Of ITypeSymbol).From(Me.TypeArgumentsNoUseSiteDiagnostics) End Get End Property Private ReadOnly Property TypeArgumentNullableAnnotations As ImmutableArray(Of NullableAnnotation) Implements INamedTypeSymbol.TypeArgumentNullableAnnotations Get Return Me.TypeArgumentsNoUseSiteDiagnostics.SelectAsArray(Function(t) NullableAnnotation.None) End Get End Property Private ReadOnly Property INamedTypeSymbol_TypeParameters As ImmutableArray(Of ITypeParameterSymbol) Implements INamedTypeSymbol.TypeParameters Get Return StaticCast(Of ITypeParameterSymbol).From(Me.TypeParameters) End Get End Property Private ReadOnly Property INamedTypeSymbol_IsScriptClass As Boolean Implements INamedTypeSymbol.IsScriptClass Get Return Me.IsScriptClass End Get End Property Private ReadOnly Property INamedTypeSymbol_IsImplicitClass As Boolean Implements INamedTypeSymbol.IsImplicitClass Get Return Me.IsImplicitClass End Get End Property Private Function INamedTypeSymbol_Construct(ParamArray typeArguments() As ITypeSymbol) As INamedTypeSymbol Implements INamedTypeSymbol.Construct Return Construct(ConstructTypeArguments(typeArguments)) End Function Private Function INamedTypeSymbol_Construct(typeArguments As ImmutableArray(Of ITypeSymbol), typeArgumentNullableAnnotations As ImmutableArray(Of CodeAnalysis.NullableAnnotation)) As INamedTypeSymbol Implements INamedTypeSymbol.Construct Return Construct(ConstructTypeArguments(typeArguments, typeArgumentNullableAnnotations)) End Function Private Function INamedTypeSymbol_ConstructUnboundGenericType() As INamedTypeSymbol Implements INamedTypeSymbol.ConstructUnboundGenericType Return ConstructUnboundGenericType() End Function Private ReadOnly Property INamedTypeSymbol_InstanceConstructors As ImmutableArray(Of IMethodSymbol) Implements INamedTypeSymbol.InstanceConstructors Get Return GetConstructors(Of IMethodSymbol)(includeInstance:=True, includeShared:=False) End Get End Property Private ReadOnly Property INamedTypeSymbol_StaticConstructors As ImmutableArray(Of IMethodSymbol) Implements INamedTypeSymbol.StaticConstructors Get Return GetConstructors(Of IMethodSymbol)(includeInstance:=False, includeShared:=True) End Get End Property Private ReadOnly Property INamedTypeSymbol_Constructors As ImmutableArray(Of IMethodSymbol) Implements INamedTypeSymbol.Constructors Get Return GetConstructors(Of IMethodSymbol)(includeInstance:=True, includeShared:=True) End Get End Property Private ReadOnly Property INamedTypeSymbol_AssociatedSymbol As ISymbol Implements INamedTypeSymbol.AssociatedSymbol Get Return Me.AssociatedSymbol End Get End Property Private ReadOnly Property INamedTypeSymbol_IsComImport As Boolean Implements INamedTypeSymbol.IsComImport Get Return IsComImport End Get End Property Private ReadOnly Property INamedTypeSymbol_NativeIntegerUnderlyingType As INamedTypeSymbol Implements INamedTypeSymbol.NativeIntegerUnderlyingType Get Return Nothing End Get End Property #End Region #Region "ISymbol" Protected Overrides ReadOnly Property ISymbol_IsAbstract As Boolean Get Return Me.IsMustInherit End Get End Property Protected Overrides ReadOnly Property ISymbol_IsSealed As Boolean Get Return Me.IsNotInheritable End Get End Property Private ReadOnly Property INamedTypeSymbol_TupleElements As ImmutableArray(Of IFieldSymbol) Implements INamedTypeSymbol.TupleElements Get Return StaticCast(Of IFieldSymbol).From(TupleElements) End Get End Property Private ReadOnly Property INamedTypeSymbol_TupleUnderlyingType As INamedTypeSymbol Implements INamedTypeSymbol.TupleUnderlyingType Get Return TupleUnderlyingType End Get End Property Public Overrides Sub Accept(visitor As SymbolVisitor) visitor.VisitNamedType(Me) End Sub Public Overrides Function Accept(Of TResult)(visitor As SymbolVisitor(Of TResult)) As TResult Return visitor.VisitNamedType(Me) End Function Public Overrides Sub Accept(visitor As VisualBasicSymbolVisitor) visitor.VisitNamedType(Me) End Sub Public Overrides Function Accept(Of TResult)(visitor As VisualBasicSymbolVisitor(Of TResult)) As TResult Return visitor.VisitNamedType(Me) End Function #End Region ''' <summary> ''' Verify if the given type can be used to back a tuple type ''' and return cardinality of that tuple type in <paramref name="tupleCardinality"/>. ''' </summary> ''' <param name="tupleCardinality">If method returns true, contains cardinality of the compatible tuple type.</param> ''' <returns></returns> Public NotOverridable Overrides Function IsTupleCompatible(<Out> ByRef tupleCardinality As Integer) As Boolean If IsTupleType Then tupleCardinality = 0 Return False End If ' Should this be optimized for perf (caching for VT<0> to VT<7>, etc.)? If Not IsUnboundGenericType AndAlso If(ContainingSymbol?.Kind = SymbolKind.Namespace, False) AndAlso If(ContainingNamespace.ContainingNamespace?.IsGlobalNamespace, False) AndAlso Name = TupleTypeSymbol.TupleTypeName AndAlso ContainingNamespace.Name = MetadataHelpers.SystemString Then Dim arity = Me.Arity If arity > 0 AndAlso arity < TupleTypeSymbol.RestPosition Then tupleCardinality = arity Return True ElseIf arity = TupleTypeSymbol.RestPosition AndAlso Not IsDefinition Then ' Skip through "Rest" extensions Dim typeToCheck As TypeSymbol = Me Dim levelsOfNesting As Integer = 0 Do levelsOfNesting += 1 typeToCheck = DirectCast(typeToCheck, NamedTypeSymbol).TypeArgumentsNoUseSiteDiagnostics(TupleTypeSymbol.RestPosition - 1) Loop While TypeSymbol.Equals(typeToCheck.OriginalDefinition, Me.OriginalDefinition, TypeCompareKind.ConsiderEverything) AndAlso Not typeToCheck.IsDefinition If typeToCheck.IsTupleType Then Dim underlying = typeToCheck.TupleUnderlyingType If underlying.Arity = TupleTypeSymbol.RestPosition AndAlso Not TypeSymbol.Equals(underlying.OriginalDefinition, Me.OriginalDefinition, TypeCompareKind.ConsiderEverything) Then tupleCardinality = 0 Return False End If tupleCardinality = (TupleTypeSymbol.RestPosition - 1) * levelsOfNesting + typeToCheck.TupleElementTypes.Length Return True End If arity = If(TryCast(typeToCheck, NamedTypeSymbol)?.Arity, 0) If arity > 0 AndAlso arity < TupleTypeSymbol.RestPosition AndAlso typeToCheck.IsTupleCompatible(tupleCardinality) Then Debug.Assert(tupleCardinality < TupleTypeSymbol.RestPosition) tupleCardinality += (TupleTypeSymbol.RestPosition - 1) * levelsOfNesting Return True End If End If End If tupleCardinality = 0 Return False End Function End Class End Namespace
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/VisualBasic/Test/Syntax/Syntax/ConstantExpressionEvaluatorTests.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.VisualBasic.Symbols Public Class ConstantExpressionEvaluatorTests Inherits BasicTestBase <Fact> Public Sub ConstantValueGetDiscriminatorTest01() Assert.Equal(ConstantValueTypeDiscriminator.SByte, SpecialType.System_SByte.ToConstantValueDiscriminator()) Assert.Equal(ConstantValueTypeDiscriminator.Byte, SpecialType.System_Byte.ToConstantValueDiscriminator()) Assert.Equal(ConstantValueTypeDiscriminator.Int16, SpecialType.System_Int16.ToConstantValueDiscriminator()) Assert.Equal(ConstantValueTypeDiscriminator.UInt16, SpecialType.System_UInt16.ToConstantValueDiscriminator()) Assert.Equal(ConstantValueTypeDiscriminator.Int32, SpecialType.System_Int32.ToConstantValueDiscriminator()) Assert.Equal(ConstantValueTypeDiscriminator.UInt32, SpecialType.System_UInt32.ToConstantValueDiscriminator()) Assert.Equal(ConstantValueTypeDiscriminator.Int64, SpecialType.System_Int64.ToConstantValueDiscriminator()) Assert.Equal(ConstantValueTypeDiscriminator.UInt64, SpecialType.System_UInt64.ToConstantValueDiscriminator()) Assert.Equal(ConstantValueTypeDiscriminator.Char, SpecialType.System_Char.ToConstantValueDiscriminator()) Assert.Equal(ConstantValueTypeDiscriminator.Boolean, SpecialType.System_Boolean.ToConstantValueDiscriminator()) Assert.Equal(ConstantValueTypeDiscriminator.Single, SpecialType.System_Single.ToConstantValueDiscriminator()) Assert.Equal(ConstantValueTypeDiscriminator.Double, SpecialType.System_Double.ToConstantValueDiscriminator()) Assert.Equal(ConstantValueTypeDiscriminator.Decimal, SpecialType.System_Decimal.ToConstantValueDiscriminator()) Assert.Equal(ConstantValueTypeDiscriminator.DateTime, SpecialType.System_DateTime.ToConstantValueDiscriminator()) Assert.Equal(ConstantValueTypeDiscriminator.String, SpecialType.System_String.ToConstantValueDiscriminator()) End Sub End Class
' Licensed to the .NET Foundation under one or more 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.VisualBasic.Symbols Public Class ConstantExpressionEvaluatorTests Inherits BasicTestBase <Fact> Public Sub ConstantValueGetDiscriminatorTest01() Assert.Equal(ConstantValueTypeDiscriminator.SByte, SpecialType.System_SByte.ToConstantValueDiscriminator()) Assert.Equal(ConstantValueTypeDiscriminator.Byte, SpecialType.System_Byte.ToConstantValueDiscriminator()) Assert.Equal(ConstantValueTypeDiscriminator.Int16, SpecialType.System_Int16.ToConstantValueDiscriminator()) Assert.Equal(ConstantValueTypeDiscriminator.UInt16, SpecialType.System_UInt16.ToConstantValueDiscriminator()) Assert.Equal(ConstantValueTypeDiscriminator.Int32, SpecialType.System_Int32.ToConstantValueDiscriminator()) Assert.Equal(ConstantValueTypeDiscriminator.UInt32, SpecialType.System_UInt32.ToConstantValueDiscriminator()) Assert.Equal(ConstantValueTypeDiscriminator.Int64, SpecialType.System_Int64.ToConstantValueDiscriminator()) Assert.Equal(ConstantValueTypeDiscriminator.UInt64, SpecialType.System_UInt64.ToConstantValueDiscriminator()) Assert.Equal(ConstantValueTypeDiscriminator.Char, SpecialType.System_Char.ToConstantValueDiscriminator()) Assert.Equal(ConstantValueTypeDiscriminator.Boolean, SpecialType.System_Boolean.ToConstantValueDiscriminator()) Assert.Equal(ConstantValueTypeDiscriminator.Single, SpecialType.System_Single.ToConstantValueDiscriminator()) Assert.Equal(ConstantValueTypeDiscriminator.Double, SpecialType.System_Double.ToConstantValueDiscriminator()) Assert.Equal(ConstantValueTypeDiscriminator.Decimal, SpecialType.System_Decimal.ToConstantValueDiscriminator()) Assert.Equal(ConstantValueTypeDiscriminator.DateTime, SpecialType.System_DateTime.ToConstantValueDiscriminator()) Assert.Equal(ConstantValueTypeDiscriminator.String, SpecialType.System_String.ToConstantValueDiscriminator()) End Sub End Class
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Analyzers/Core/Analyzers/FileHeaders/FileHeader.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 Microsoft.CodeAnalysis.FileHeaders { /// <summary> /// Contains the parsed file header information for a syntax tree. /// </summary> internal readonly struct FileHeader { /// <summary> /// The location in the source where the file header was expected to start. /// </summary> private readonly int _fileHeaderStart; /// <summary> /// The length of the prefix indicating the start of a comment. For example: /// <list type="bullet"> /// <item> /// <term>C#</term> /// <description>2, for the length of <c>//</c>.</description> /// </item> /// <item> /// <term>Visual Basic</term> /// <description>1, for the length of <c>'</c>.</description> /// </item> /// </list> /// </summary> private readonly int _commentPrefixLength; /// <summary> /// Initializes a new instance of the <see cref="FileHeader"/> struct. /// </summary> /// <param name="copyrightText">The copyright string, as parsed from the header.</param> /// <param name="fileHeaderStart">The offset within the file at which the header started.</param> /// <param name="fileHeaderEnd">The offset within the file at which the header ended.</param> internal FileHeader(string copyrightText, int fileHeaderStart, int fileHeaderEnd, int commentPrefixLength) : this(fileHeaderStart, isMissing: false) { // Currently unused _ = fileHeaderEnd; CopyrightText = copyrightText; _commentPrefixLength = commentPrefixLength; } /// <summary> /// Initializes a new instance of the <see cref="FileHeader"/> struct. /// </summary> /// <param name="fileHeaderStart">The offset within the file at which the header started, or was expected to start.</param> /// <param name="isMissing"><see langword="true"/> if the file header is missing; otherwise, <see langword="false"/>.</param> private FileHeader(int fileHeaderStart, bool isMissing) { _fileHeaderStart = fileHeaderStart; _commentPrefixLength = 0; IsMissing = isMissing; CopyrightText = ""; } /// <summary> /// Gets a value indicating whether the file header is missing. /// </summary> /// <value> /// <see langword="true"/> if the file header is missing; otherwise, <see langword="false"/>. /// </value> internal bool IsMissing { get; } /// <summary> /// Gets the copyright text, as parsed from the header. /// </summary> /// <value> /// The copyright text, as parsed from the header. /// </value> internal string CopyrightText { get; } /// <summary> /// Gets a <see cref="FileHeader"/> instance representing a missing file header starting at the specified /// position. /// </summary> /// <param name="fileHeaderStart">The location at which a file header was expected. This will typically be the /// start of the first line after any directive trivia (<see cref="SyntaxTrivia.IsDirective"/>) to account for /// source suppressions.</param> /// <returns> /// A <see cref="FileHeader"/> instance representing a missing file header. /// </returns> internal static FileHeader MissingFileHeader(int fileHeaderStart) => new(fileHeaderStart, isMissing: true); /// <summary> /// Gets the location representing the start of the file header. /// </summary> /// <param name="syntaxTree">The syntax tree to use for generating the location.</param> /// <returns>The location representing the start of the file header.</returns> internal Location GetLocation(SyntaxTree syntaxTree) { if (IsMissing) { return Location.Create(syntaxTree, new TextSpan(_fileHeaderStart, 0)); } return Location.Create(syntaxTree, new TextSpan(_fileHeaderStart, _commentPrefixLength)); } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.FileHeaders { /// <summary> /// Contains the parsed file header information for a syntax tree. /// </summary> internal readonly struct FileHeader { /// <summary> /// The location in the source where the file header was expected to start. /// </summary> private readonly int _fileHeaderStart; /// <summary> /// The length of the prefix indicating the start of a comment. For example: /// <list type="bullet"> /// <item> /// <term>C#</term> /// <description>2, for the length of <c>//</c>.</description> /// </item> /// <item> /// <term>Visual Basic</term> /// <description>1, for the length of <c>'</c>.</description> /// </item> /// </list> /// </summary> private readonly int _commentPrefixLength; /// <summary> /// Initializes a new instance of the <see cref="FileHeader"/> struct. /// </summary> /// <param name="copyrightText">The copyright string, as parsed from the header.</param> /// <param name="fileHeaderStart">The offset within the file at which the header started.</param> /// <param name="fileHeaderEnd">The offset within the file at which the header ended.</param> internal FileHeader(string copyrightText, int fileHeaderStart, int fileHeaderEnd, int commentPrefixLength) : this(fileHeaderStart, isMissing: false) { // Currently unused _ = fileHeaderEnd; CopyrightText = copyrightText; _commentPrefixLength = commentPrefixLength; } /// <summary> /// Initializes a new instance of the <see cref="FileHeader"/> struct. /// </summary> /// <param name="fileHeaderStart">The offset within the file at which the header started, or was expected to start.</param> /// <param name="isMissing"><see langword="true"/> if the file header is missing; otherwise, <see langword="false"/>.</param> private FileHeader(int fileHeaderStart, bool isMissing) { _fileHeaderStart = fileHeaderStart; _commentPrefixLength = 0; IsMissing = isMissing; CopyrightText = ""; } /// <summary> /// Gets a value indicating whether the file header is missing. /// </summary> /// <value> /// <see langword="true"/> if the file header is missing; otherwise, <see langword="false"/>. /// </value> internal bool IsMissing { get; } /// <summary> /// Gets the copyright text, as parsed from the header. /// </summary> /// <value> /// The copyright text, as parsed from the header. /// </value> internal string CopyrightText { get; } /// <summary> /// Gets a <see cref="FileHeader"/> instance representing a missing file header starting at the specified /// position. /// </summary> /// <param name="fileHeaderStart">The location at which a file header was expected. This will typically be the /// start of the first line after any directive trivia (<see cref="SyntaxTrivia.IsDirective"/>) to account for /// source suppressions.</param> /// <returns> /// A <see cref="FileHeader"/> instance representing a missing file header. /// </returns> internal static FileHeader MissingFileHeader(int fileHeaderStart) => new(fileHeaderStart, isMissing: true); /// <summary> /// Gets the location representing the start of the file header. /// </summary> /// <param name="syntaxTree">The syntax tree to use for generating the location.</param> /// <returns>The location representing the start of the file header.</returns> internal Location GetLocation(SyntaxTree syntaxTree) { if (IsMissing) { return Location.Create(syntaxTree, new TextSpan(_fileHeaderStart, 0)); } return Location.Create(syntaxTree, new TextSpan(_fileHeaderStart, _commentPrefixLength)); } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/Grammar/GrammarGenerator.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 // We only support grammar generation in the command line version for now which is the netcoreapp target #if NETCOREAPP using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis.CSharp; namespace CSharpSyntaxGenerator.Grammar { internal static class GrammarGenerator { public static string Run(List<TreeType> types) { // Syntax.xml refers to a special pseudo-element 'Modifier'. Synthesize that for the grammar. var modifiers = GetMembers<DeclarationModifiers>() .Select(m => m + "Keyword").Where(n => GetSyntaxKind(n) != SyntaxKind.None) .Select(n => new Kind { Name = n }).ToList(); types.Add(new Node { Name = "Modifier", Children = { new Field { Type = "SyntaxToken", Kinds = modifiers } } }); var rules = types.ToDictionary(n => n.Name, _ => new List<Production>()); foreach (var type in types) { if (type.Base != null && rules.TryGetValue(type.Base, out var productions)) productions.Add(RuleReference(type.Name)); if (type is Node && type.Children.Count > 0) { // Convert rules like `a: (x | y) ...` into: // a: x ... // | y ...; if (type.Children[0] is Field field && field.Kinds.Count > 0) { foreach (var kind in field.Kinds) { field.Kinds = new List<Kind> { kind }; rules[type.Name].Add(HandleChildren(type.Children)); } } else { rules[type.Name].Add(HandleChildren(type.Children)); } } } // The grammar will bottom out with certain lexical productions. Create rules for these. var lexicalRules = rules.Values.SelectMany(ps => ps).SelectMany(p => p.ReferencedRules) .Where(r => !rules.TryGetValue(r, out var productions) || productions.Count == 0).ToArray(); foreach (var name in lexicalRules) rules[name] = new List<Production> { new Production("/* see lexical specification */") }; var seen = new HashSet<string>(); // Define a few major sections to help keep the grammar file naturally grouped. var majorRules = ImmutableArray.Create( "CompilationUnitSyntax", "MemberDeclarationSyntax", "TypeSyntax", "StatementSyntax", "ExpressionSyntax", "XmlNodeSyntax", "StructuredTriviaSyntax"); var result = "// <auto-generated />" + Environment.NewLine + "grammar csharp;" + Environment.NewLine; // Handle each major section first and then walk any rules not hit transitively from them. foreach (var rule in majorRules.Concat(rules.Keys.OrderBy(a => a))) processRule(rule, ref result); return result; void processRule(string name, ref string result) { if (name != "CSharpSyntaxNode" && seen.Add(name)) { // Order the productions to keep us independent from whatever changes happen in Syntax.xml. var sorted = rules[name].OrderBy(v => v); result += Environment.NewLine + RuleReference(name).Text + Environment.NewLine + " : " + string.Join(Environment.NewLine + " | ", sorted) + Environment.NewLine + " ;" + Environment.NewLine; // Now proceed in depth-first fashion through the referenced rules to keep related rules // close by. Don't recurse into major-sections to help keep them separated in grammar file. foreach (var production in sorted) foreach (var referencedRule in production.ReferencedRules) if (!majorRules.Concat(lexicalRules).Contains(referencedRule)) processRule(referencedRule, ref result); } } } private static Production Join(string delim, IEnumerable<Production> productions) => new Production(string.Join(delim, productions.Where(p => p.Text.Length > 0)), productions.SelectMany(p => p.ReferencedRules)); private static Production HandleChildren(IEnumerable<TreeTypeChild> children, string delim = " ") => Join(delim, children.Select(child => child is Choice c ? HandleChildren(c.Children, delim: " | ").Parenthesize().Suffix("?", when: c.Optional) : child is Sequence s ? HandleChildren(s.Children).Parenthesize() : child is Field f ? HandleField(f).Suffix("?", when: f.IsOptional) : throw new InvalidOperationException())); private static Production HandleField(Field field) // 'bool' fields are for a few properties we generate on DirectiveTrivia. They're not // relevant to the grammar, so we just return an empty production to ignore them. => field.Type == "bool" ? new Production("") : field.Type == "CSharpSyntaxNode" ? RuleReference(field.Kinds.Single().Name + "Syntax") : field.Type.StartsWith("SeparatedSyntaxList") ? HandleSeparatedList(field, field.Type[("SeparatedSyntaxList".Length + 1)..^1]) : field.Type.StartsWith("SyntaxList") ? HandleList(field, field.Type[("SyntaxList".Length + 1)..^1]) : field.IsToken ? HandleTokenField(field) : RuleReference(field.Type); private static Production HandleSeparatedList(Field field, string elementType) => RuleReference(elementType).Suffix(" (',' " + RuleReference(elementType) + ")") .Suffix("*", when: field.MinCount < 2).Suffix("+", when: field.MinCount >= 2) .Suffix(" ','?", when: field.AllowTrailingSeparator) .Parenthesize(when: field.MinCount == 0).Suffix("?", when: field.MinCount == 0); private static Production HandleList(Field field, string elementType) => (elementType != "SyntaxToken" ? RuleReference(elementType) : field.Name == "Commas" ? new Production("','") : field.Name == "Modifiers" ? RuleReference("Modifier") : field.Name == "TextTokens" ? RuleReference(nameof(SyntaxKind.XmlTextLiteralToken)) : RuleReference(elementType)) .Suffix(field.MinCount == 0 ? "*" : "+"); private static Production HandleTokenField(Field field) => field.Kinds.Count == 0 ? HandleTokenName(field.Name) : Join(" | ", field.Kinds.Select(k => HandleTokenName(k.Name))).Parenthesize(when: field.Kinds.Count >= 2); private static Production HandleTokenName(string tokenName) => GetSyntaxKind(tokenName) is var kind && kind == SyntaxKind.None ? RuleReference("SyntaxToken") : SyntaxFacts.GetText(kind) is var text && text != "" ? new Production(text == "'" ? "'\\''" : $"'{text}'") : tokenName.StartsWith("EndOf") ? new Production("") : tokenName.StartsWith("Omitted") ? new Production("/* epsilon */") : RuleReference(tokenName); private static SyntaxKind GetSyntaxKind(string name) => GetMembers<SyntaxKind>().Where(k => k.ToString() == name).SingleOrDefault(); private static IEnumerable<TEnum> GetMembers<TEnum>() where TEnum : struct, Enum => (IEnumerable<TEnum>)Enum.GetValues(typeof(TEnum)); private static Production RuleReference(string name) => new Production( s_normalizationRegex.Replace(name.EndsWith("Syntax") ? name[..^"Syntax".Length] : name, "_").ToLower(), ImmutableArray.Create(name)); // Converts a PascalCased name into snake_cased name. private static readonly Regex s_normalizationRegex = new Regex( "(?<=[A-Z])(?=[A-Z][a-z]) | (?<=[^A-Z])(?=[A-Z]) | (?<=[A-Za-z])(?=[^A-Za-z])", RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled); } internal struct Production : IComparable<Production> { public readonly string Text; public readonly ImmutableArray<string> ReferencedRules; public Production(string text, IEnumerable<string> referencedRules = null) { Text = text; ReferencedRules = referencedRules?.ToImmutableArray() ?? ImmutableArray<string>.Empty; } public override string ToString() => Text; public int CompareTo(Production other) => StringComparer.Ordinal.Compare(this.Text, other.Text); public Production Prefix(string prefix) => new Production(prefix + this, ReferencedRules); public Production Suffix(string suffix, bool when = true) => when ? new Production(this + suffix, ReferencedRules) : this; public Production Parenthesize(bool when = true) => when ? Prefix("(").Suffix(")") : this; } } namespace Microsoft.CodeAnalysis { internal static class GreenNode { internal const int ListKind = 1; // See SyntaxKind. } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable // We only support grammar generation in the command line version for now which is the netcoreapp target #if NETCOREAPP using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis.CSharp; namespace CSharpSyntaxGenerator.Grammar { internal static class GrammarGenerator { public static string Run(List<TreeType> types) { // Syntax.xml refers to a special pseudo-element 'Modifier'. Synthesize that for the grammar. var modifiers = GetMembers<DeclarationModifiers>() .Select(m => m + "Keyword").Where(n => GetSyntaxKind(n) != SyntaxKind.None) .Select(n => new Kind { Name = n }).ToList(); types.Add(new Node { Name = "Modifier", Children = { new Field { Type = "SyntaxToken", Kinds = modifiers } } }); var rules = types.ToDictionary(n => n.Name, _ => new List<Production>()); foreach (var type in types) { if (type.Base != null && rules.TryGetValue(type.Base, out var productions)) productions.Add(RuleReference(type.Name)); if (type is Node && type.Children.Count > 0) { // Convert rules like `a: (x | y) ...` into: // a: x ... // | y ...; if (type.Children[0] is Field field && field.Kinds.Count > 0) { foreach (var kind in field.Kinds) { field.Kinds = new List<Kind> { kind }; rules[type.Name].Add(HandleChildren(type.Children)); } } else { rules[type.Name].Add(HandleChildren(type.Children)); } } } // The grammar will bottom out with certain lexical productions. Create rules for these. var lexicalRules = rules.Values.SelectMany(ps => ps).SelectMany(p => p.ReferencedRules) .Where(r => !rules.TryGetValue(r, out var productions) || productions.Count == 0).ToArray(); foreach (var name in lexicalRules) rules[name] = new List<Production> { new Production("/* see lexical specification */") }; var seen = new HashSet<string>(); // Define a few major sections to help keep the grammar file naturally grouped. var majorRules = ImmutableArray.Create( "CompilationUnitSyntax", "MemberDeclarationSyntax", "TypeSyntax", "StatementSyntax", "ExpressionSyntax", "XmlNodeSyntax", "StructuredTriviaSyntax"); var result = "// <auto-generated />" + Environment.NewLine + "grammar csharp;" + Environment.NewLine; // Handle each major section first and then walk any rules not hit transitively from them. foreach (var rule in majorRules.Concat(rules.Keys.OrderBy(a => a))) processRule(rule, ref result); return result; void processRule(string name, ref string result) { if (name != "CSharpSyntaxNode" && seen.Add(name)) { // Order the productions to keep us independent from whatever changes happen in Syntax.xml. var sorted = rules[name].OrderBy(v => v); result += Environment.NewLine + RuleReference(name).Text + Environment.NewLine + " : " + string.Join(Environment.NewLine + " | ", sorted) + Environment.NewLine + " ;" + Environment.NewLine; // Now proceed in depth-first fashion through the referenced rules to keep related rules // close by. Don't recurse into major-sections to help keep them separated in grammar file. foreach (var production in sorted) foreach (var referencedRule in production.ReferencedRules) if (!majorRules.Concat(lexicalRules).Contains(referencedRule)) processRule(referencedRule, ref result); } } } private static Production Join(string delim, IEnumerable<Production> productions) => new Production(string.Join(delim, productions.Where(p => p.Text.Length > 0)), productions.SelectMany(p => p.ReferencedRules)); private static Production HandleChildren(IEnumerable<TreeTypeChild> children, string delim = " ") => Join(delim, children.Select(child => child is Choice c ? HandleChildren(c.Children, delim: " | ").Parenthesize().Suffix("?", when: c.Optional) : child is Sequence s ? HandleChildren(s.Children).Parenthesize() : child is Field f ? HandleField(f).Suffix("?", when: f.IsOptional) : throw new InvalidOperationException())); private static Production HandleField(Field field) // 'bool' fields are for a few properties we generate on DirectiveTrivia. They're not // relevant to the grammar, so we just return an empty production to ignore them. => field.Type == "bool" ? new Production("") : field.Type == "CSharpSyntaxNode" ? RuleReference(field.Kinds.Single().Name + "Syntax") : field.Type.StartsWith("SeparatedSyntaxList") ? HandleSeparatedList(field, field.Type[("SeparatedSyntaxList".Length + 1)..^1]) : field.Type.StartsWith("SyntaxList") ? HandleList(field, field.Type[("SyntaxList".Length + 1)..^1]) : field.IsToken ? HandleTokenField(field) : RuleReference(field.Type); private static Production HandleSeparatedList(Field field, string elementType) => RuleReference(elementType).Suffix(" (',' " + RuleReference(elementType) + ")") .Suffix("*", when: field.MinCount < 2).Suffix("+", when: field.MinCount >= 2) .Suffix(" ','?", when: field.AllowTrailingSeparator) .Parenthesize(when: field.MinCount == 0).Suffix("?", when: field.MinCount == 0); private static Production HandleList(Field field, string elementType) => (elementType != "SyntaxToken" ? RuleReference(elementType) : field.Name == "Commas" ? new Production("','") : field.Name == "Modifiers" ? RuleReference("Modifier") : field.Name == "TextTokens" ? RuleReference(nameof(SyntaxKind.XmlTextLiteralToken)) : RuleReference(elementType)) .Suffix(field.MinCount == 0 ? "*" : "+"); private static Production HandleTokenField(Field field) => field.Kinds.Count == 0 ? HandleTokenName(field.Name) : Join(" | ", field.Kinds.Select(k => HandleTokenName(k.Name))).Parenthesize(when: field.Kinds.Count >= 2); private static Production HandleTokenName(string tokenName) => GetSyntaxKind(tokenName) is var kind && kind == SyntaxKind.None ? RuleReference("SyntaxToken") : SyntaxFacts.GetText(kind) is var text && text != "" ? new Production(text == "'" ? "'\\''" : $"'{text}'") : tokenName.StartsWith("EndOf") ? new Production("") : tokenName.StartsWith("Omitted") ? new Production("/* epsilon */") : RuleReference(tokenName); private static SyntaxKind GetSyntaxKind(string name) => GetMembers<SyntaxKind>().Where(k => k.ToString() == name).SingleOrDefault(); private static IEnumerable<TEnum> GetMembers<TEnum>() where TEnum : struct, Enum => (IEnumerable<TEnum>)Enum.GetValues(typeof(TEnum)); private static Production RuleReference(string name) => new Production( s_normalizationRegex.Replace(name.EndsWith("Syntax") ? name[..^"Syntax".Length] : name, "_").ToLower(), ImmutableArray.Create(name)); // Converts a PascalCased name into snake_cased name. private static readonly Regex s_normalizationRegex = new Regex( "(?<=[A-Z])(?=[A-Z][a-z]) | (?<=[^A-Z])(?=[A-Z]) | (?<=[A-Za-z])(?=[^A-Za-z])", RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled); } internal struct Production : IComparable<Production> { public readonly string Text; public readonly ImmutableArray<string> ReferencedRules; public Production(string text, IEnumerable<string> referencedRules = null) { Text = text; ReferencedRules = referencedRules?.ToImmutableArray() ?? ImmutableArray<string>.Empty; } public override string ToString() => Text; public int CompareTo(Production other) => StringComparer.Ordinal.Compare(this.Text, other.Text); public Production Prefix(string prefix) => new Production(prefix + this, ReferencedRules); public Production Suffix(string suffix, bool when = true) => when ? new Production(this + suffix, ReferencedRules) : this; public Production Parenthesize(bool when = true) => when ? Prefix("(").Suffix(")") : this; } } namespace Microsoft.CodeAnalysis { internal static class GreenNode { internal const int ListKind = 1; // See SyntaxKind. } } #endif
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/EditorFeatures/VisualBasicTest/Recommendations/Declarations/EventKeywordRecommenderTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations Public Class EventKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventInClassDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventInStructureDeclarationTest() VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "Event") End Sub <Fact> <WorkItem(544999, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544999")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventInInterfaceDeclarationTest() VerifyRecommendationsContain(<InterfaceDeclaration>|</InterfaceDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterPartialTest() VerifyRecommendationsMissing(<ClassDeclaration>Partial |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventAfterPublicTest() VerifyRecommendationsContain(<ClassDeclaration>Public |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventAfterProtectedTest() VerifyRecommendationsContain(<ClassDeclaration>Protected |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventAfterFriendTest() VerifyRecommendationsContain(<ClassDeclaration>Friend |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventAfterPrivateTest() VerifyRecommendationsContain(<ClassDeclaration>Private |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventAfterProtectedFriendTest() VerifyRecommendationsContain(<ClassDeclaration>Protected Friend |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterOverloadsTest() VerifyRecommendationsMissing(<ClassDeclaration>Overloads |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterOverridesTest() VerifyRecommendationsMissing(<ClassDeclaration>Overrides |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>Overridable |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterNotOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterMustOverrideTest() VerifyRecommendationsMissing(<ClassDeclaration>MustOverride |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterMustOverrideOverridesTest() VerifyRecommendationsMissing(<ClassDeclaration>MustOverride Overrides |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterNotOverridableOverridesTest() VerifyRecommendationsMissing(<ClassDeclaration>NotOverridable Overrides |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterConstTest() VerifyRecommendationsMissing(<ClassDeclaration>Const |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterDefaultTest() VerifyRecommendationsMissing(<ClassDeclaration>Default |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterMustInheritTest() VerifyRecommendationsMissing(<ClassDeclaration>MustInherit |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterNotInheritableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotInheritable |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterNarrowingTest() VerifyRecommendationsMissing(<ClassDeclaration>Narrowing |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterWideningTest() VerifyRecommendationsMissing(<ClassDeclaration>Widening |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterReadOnlyTest() VerifyRecommendationsMissing(<ClassDeclaration>ReadOnly |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterWriteOnlyTest() VerifyRecommendationsMissing(<ClassDeclaration>WriteOnly |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventAfterCustomTest() VerifyRecommendationsAreExactly(<ClassDeclaration>Custom |</ClassDeclaration>, {"As", "Event"}) End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterCustomTest() VerifyRecommendationsMissing(<ClassDeclaration>dim x = Custom |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventAfterSharedTest() VerifyRecommendationsContain(<ClassDeclaration>Shared |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventAfterShadowsTest() VerifyRecommendationsContain(<ClassDeclaration>Shadows |</ClassDeclaration>, "Event") End Sub <WorkItem(674791, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/674791")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterHashTest() VerifyRecommendationsMissing(<File> Imports System #| Module Module1 End Module </File>, "Event") 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. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations Public Class EventKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventInClassDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventInStructureDeclarationTest() VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "Event") End Sub <Fact> <WorkItem(544999, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544999")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventInInterfaceDeclarationTest() VerifyRecommendationsContain(<InterfaceDeclaration>|</InterfaceDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterPartialTest() VerifyRecommendationsMissing(<ClassDeclaration>Partial |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventAfterPublicTest() VerifyRecommendationsContain(<ClassDeclaration>Public |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventAfterProtectedTest() VerifyRecommendationsContain(<ClassDeclaration>Protected |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventAfterFriendTest() VerifyRecommendationsContain(<ClassDeclaration>Friend |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventAfterPrivateTest() VerifyRecommendationsContain(<ClassDeclaration>Private |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventAfterProtectedFriendTest() VerifyRecommendationsContain(<ClassDeclaration>Protected Friend |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterOverloadsTest() VerifyRecommendationsMissing(<ClassDeclaration>Overloads |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterOverridesTest() VerifyRecommendationsMissing(<ClassDeclaration>Overrides |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>Overridable |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterNotOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterMustOverrideTest() VerifyRecommendationsMissing(<ClassDeclaration>MustOverride |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterMustOverrideOverridesTest() VerifyRecommendationsMissing(<ClassDeclaration>MustOverride Overrides |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterNotOverridableOverridesTest() VerifyRecommendationsMissing(<ClassDeclaration>NotOverridable Overrides |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterConstTest() VerifyRecommendationsMissing(<ClassDeclaration>Const |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterDefaultTest() VerifyRecommendationsMissing(<ClassDeclaration>Default |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterMustInheritTest() VerifyRecommendationsMissing(<ClassDeclaration>MustInherit |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterNotInheritableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotInheritable |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterNarrowingTest() VerifyRecommendationsMissing(<ClassDeclaration>Narrowing |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterWideningTest() VerifyRecommendationsMissing(<ClassDeclaration>Widening |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterReadOnlyTest() VerifyRecommendationsMissing(<ClassDeclaration>ReadOnly |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterWriteOnlyTest() VerifyRecommendationsMissing(<ClassDeclaration>WriteOnly |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventAfterCustomTest() VerifyRecommendationsAreExactly(<ClassDeclaration>Custom |</ClassDeclaration>, {"As", "Event"}) End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventNotAfterCustomTest() VerifyRecommendationsMissing(<ClassDeclaration>dim x = Custom |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventAfterSharedTest() VerifyRecommendationsContain(<ClassDeclaration>Shared |</ClassDeclaration>, "Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub EventAfterShadowsTest() VerifyRecommendationsContain(<ClassDeclaration>Shadows |</ClassDeclaration>, "Event") End Sub <WorkItem(674791, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/674791")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterHashTest() VerifyRecommendationsMissing(<File> Imports System #| Module Module1 End Module </File>, "Event") End Sub End Class End Namespace
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/CSharp/Portable/BoundTree/BoundTreeVisitors.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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using System; using Roslyn.Utilities; using System.Linq; namespace Microsoft.CodeAnalysis.CSharp { internal abstract partial class BoundTreeVisitor<A, R> { protected BoundTreeVisitor() { } public virtual R Visit(BoundNode node, A arg) { if (node == null) { return default(R); } // this switch contains fewer than 50 of the most common node kinds switch (node.Kind) { case BoundKind.TypeExpression: return VisitTypeExpression(node as BoundTypeExpression, arg); case BoundKind.NamespaceExpression: return VisitNamespaceExpression(node as BoundNamespaceExpression, arg); case BoundKind.UnaryOperator: return VisitUnaryOperator(node as BoundUnaryOperator, arg); case BoundKind.IncrementOperator: return VisitIncrementOperator(node as BoundIncrementOperator, arg); case BoundKind.BinaryOperator: return VisitBinaryOperator(node as BoundBinaryOperator, arg); case BoundKind.CompoundAssignmentOperator: return VisitCompoundAssignmentOperator(node as BoundCompoundAssignmentOperator, arg); case BoundKind.AssignmentOperator: return VisitAssignmentOperator(node as BoundAssignmentOperator, arg); case BoundKind.NullCoalescingOperator: return VisitNullCoalescingOperator(node as BoundNullCoalescingOperator, arg); case BoundKind.ConditionalOperator: return VisitConditionalOperator(node as BoundConditionalOperator, arg); case BoundKind.ArrayAccess: return VisitArrayAccess(node as BoundArrayAccess, arg); case BoundKind.TypeOfOperator: return VisitTypeOfOperator(node as BoundTypeOfOperator, arg); case BoundKind.DefaultLiteral: return VisitDefaultLiteral(node as BoundDefaultLiteral, arg); case BoundKind.DefaultExpression: return VisitDefaultExpression(node as BoundDefaultExpression, arg); case BoundKind.IsOperator: return VisitIsOperator(node as BoundIsOperator, arg); case BoundKind.AsOperator: return VisitAsOperator(node as BoundAsOperator, arg); case BoundKind.Conversion: return VisitConversion(node as BoundConversion, arg); case BoundKind.SequencePointExpression: return VisitSequencePointExpression(node as BoundSequencePointExpression, arg); case BoundKind.SequencePoint: return VisitSequencePoint(node as BoundSequencePoint, arg); case BoundKind.SequencePointWithSpan: return VisitSequencePointWithSpan(node as BoundSequencePointWithSpan, arg); case BoundKind.Block: return VisitBlock(node as BoundBlock, arg); case BoundKind.LocalDeclaration: return VisitLocalDeclaration(node as BoundLocalDeclaration, arg); case BoundKind.MultipleLocalDeclarations: return VisitMultipleLocalDeclarations(node as BoundMultipleLocalDeclarations, arg); case BoundKind.Sequence: return VisitSequence(node as BoundSequence, arg); case BoundKind.NoOpStatement: return VisitNoOpStatement(node as BoundNoOpStatement, arg); case BoundKind.ReturnStatement: return VisitReturnStatement(node as BoundReturnStatement, arg); case BoundKind.ThrowStatement: return VisitThrowStatement(node as BoundThrowStatement, arg); case BoundKind.ExpressionStatement: return VisitExpressionStatement(node as BoundExpressionStatement, arg); case BoundKind.BreakStatement: return VisitBreakStatement(node as BoundBreakStatement, arg); case BoundKind.ContinueStatement: return VisitContinueStatement(node as BoundContinueStatement, arg); case BoundKind.IfStatement: return VisitIfStatement(node as BoundIfStatement, arg); case BoundKind.ForEachStatement: return VisitForEachStatement(node as BoundForEachStatement, arg); case BoundKind.TryStatement: return VisitTryStatement(node as BoundTryStatement, arg); case BoundKind.Literal: return VisitLiteral(node as BoundLiteral, arg); case BoundKind.ThisReference: return VisitThisReference(node as BoundThisReference, arg); case BoundKind.Local: return VisitLocal(node as BoundLocal, arg); case BoundKind.Parameter: return VisitParameter(node as BoundParameter, arg); case BoundKind.LabelStatement: return VisitLabelStatement(node as BoundLabelStatement, arg); case BoundKind.GotoStatement: return VisitGotoStatement(node as BoundGotoStatement, arg); case BoundKind.LabeledStatement: return VisitLabeledStatement(node as BoundLabeledStatement, arg); case BoundKind.StatementList: return VisitStatementList(node as BoundStatementList, arg); case BoundKind.ConditionalGoto: return VisitConditionalGoto(node as BoundConditionalGoto, arg); case BoundKind.Call: return VisitCall(node as BoundCall, arg); case BoundKind.ObjectCreationExpression: return VisitObjectCreationExpression(node as BoundObjectCreationExpression, arg); case BoundKind.DelegateCreationExpression: return VisitDelegateCreationExpression(node as BoundDelegateCreationExpression, arg); case BoundKind.FieldAccess: return VisitFieldAccess(node as BoundFieldAccess, arg); case BoundKind.PropertyAccess: return VisitPropertyAccess(node as BoundPropertyAccess, arg); case BoundKind.Lambda: return VisitLambda(node as BoundLambda, arg); case BoundKind.NameOfOperator: return VisitNameOfOperator(node as BoundNameOfOperator, arg); } return VisitInternal(node, arg); } public virtual R DefaultVisit(BoundNode node, A arg) { return default(R); } } internal abstract partial class BoundTreeVisitor { protected BoundTreeVisitor() { } [DebuggerHidden] public virtual BoundNode Visit(BoundNode node) { if (node != null) { return node.Accept(this); } return null; } [DebuggerHidden] public virtual BoundNode DefaultVisit(BoundNode node) { return null; } public class CancelledByStackGuardException : Exception { public readonly BoundNode Node; public CancelledByStackGuardException(Exception inner, BoundNode node) : base(inner.Message, inner) { Node = node; } public void AddAnError(DiagnosticBag diagnostics) { diagnostics.Add(ErrorCode.ERR_InsufficientStack, GetTooLongOrComplexExpressionErrorLocation(Node)); } public void AddAnError(BindingDiagnosticBag diagnostics) { diagnostics.Add(ErrorCode.ERR_InsufficientStack, GetTooLongOrComplexExpressionErrorLocation(Node)); } public static Location GetTooLongOrComplexExpressionErrorLocation(BoundNode node) { SyntaxNode syntax = node.Syntax; if (!(syntax is ExpressionSyntax)) { syntax = syntax.DescendantNodes(n => !(n is ExpressionSyntax)).OfType<ExpressionSyntax>().FirstOrDefault() ?? syntax; } return syntax.GetFirstToken().GetLocation(); } } /// <summary> /// Consumers must provide implementation for <see cref="VisitExpressionWithoutStackGuard"/>. /// </summary> [DebuggerStepThrough] protected BoundExpression VisitExpressionWithStackGuard(ref int recursionDepth, BoundExpression node) { BoundExpression result; recursionDepth++; #if DEBUG int saveRecursionDepth = recursionDepth; #endif if (recursionDepth > 1 || !ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException()) { EnsureSufficientExecutionStack(recursionDepth); result = VisitExpressionWithoutStackGuard(node); } else { result = VisitExpressionWithStackGuard(node); } #if DEBUG Debug.Assert(saveRecursionDepth == recursionDepth); #endif recursionDepth--; return result; } protected virtual void EnsureSufficientExecutionStack(int recursionDepth) { StackGuard.EnsureSufficientExecutionStack(recursionDepth); } protected virtual bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() { return true; } #nullable enable [DebuggerStepThrough] private BoundExpression? VisitExpressionWithStackGuard(BoundExpression node) { try { return VisitExpressionWithoutStackGuard(node); } catch (InsufficientExecutionStackException ex) { throw new CancelledByStackGuardException(ex, node); } } /// <summary> /// We should be intentional about behavior of derived classes regarding guarding against stack overflow. /// </summary> protected abstract BoundExpression? VisitExpressionWithoutStackGuard(BoundExpression node); #nullable disable } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using System; using Roslyn.Utilities; using System.Linq; namespace Microsoft.CodeAnalysis.CSharp { internal abstract partial class BoundTreeVisitor<A, R> { protected BoundTreeVisitor() { } public virtual R Visit(BoundNode node, A arg) { if (node == null) { return default(R); } // this switch contains fewer than 50 of the most common node kinds switch (node.Kind) { case BoundKind.TypeExpression: return VisitTypeExpression(node as BoundTypeExpression, arg); case BoundKind.NamespaceExpression: return VisitNamespaceExpression(node as BoundNamespaceExpression, arg); case BoundKind.UnaryOperator: return VisitUnaryOperator(node as BoundUnaryOperator, arg); case BoundKind.IncrementOperator: return VisitIncrementOperator(node as BoundIncrementOperator, arg); case BoundKind.BinaryOperator: return VisitBinaryOperator(node as BoundBinaryOperator, arg); case BoundKind.CompoundAssignmentOperator: return VisitCompoundAssignmentOperator(node as BoundCompoundAssignmentOperator, arg); case BoundKind.AssignmentOperator: return VisitAssignmentOperator(node as BoundAssignmentOperator, arg); case BoundKind.NullCoalescingOperator: return VisitNullCoalescingOperator(node as BoundNullCoalescingOperator, arg); case BoundKind.ConditionalOperator: return VisitConditionalOperator(node as BoundConditionalOperator, arg); case BoundKind.ArrayAccess: return VisitArrayAccess(node as BoundArrayAccess, arg); case BoundKind.TypeOfOperator: return VisitTypeOfOperator(node as BoundTypeOfOperator, arg); case BoundKind.DefaultLiteral: return VisitDefaultLiteral(node as BoundDefaultLiteral, arg); case BoundKind.DefaultExpression: return VisitDefaultExpression(node as BoundDefaultExpression, arg); case BoundKind.IsOperator: return VisitIsOperator(node as BoundIsOperator, arg); case BoundKind.AsOperator: return VisitAsOperator(node as BoundAsOperator, arg); case BoundKind.Conversion: return VisitConversion(node as BoundConversion, arg); case BoundKind.SequencePointExpression: return VisitSequencePointExpression(node as BoundSequencePointExpression, arg); case BoundKind.SequencePoint: return VisitSequencePoint(node as BoundSequencePoint, arg); case BoundKind.SequencePointWithSpan: return VisitSequencePointWithSpan(node as BoundSequencePointWithSpan, arg); case BoundKind.Block: return VisitBlock(node as BoundBlock, arg); case BoundKind.LocalDeclaration: return VisitLocalDeclaration(node as BoundLocalDeclaration, arg); case BoundKind.MultipleLocalDeclarations: return VisitMultipleLocalDeclarations(node as BoundMultipleLocalDeclarations, arg); case BoundKind.Sequence: return VisitSequence(node as BoundSequence, arg); case BoundKind.NoOpStatement: return VisitNoOpStatement(node as BoundNoOpStatement, arg); case BoundKind.ReturnStatement: return VisitReturnStatement(node as BoundReturnStatement, arg); case BoundKind.ThrowStatement: return VisitThrowStatement(node as BoundThrowStatement, arg); case BoundKind.ExpressionStatement: return VisitExpressionStatement(node as BoundExpressionStatement, arg); case BoundKind.BreakStatement: return VisitBreakStatement(node as BoundBreakStatement, arg); case BoundKind.ContinueStatement: return VisitContinueStatement(node as BoundContinueStatement, arg); case BoundKind.IfStatement: return VisitIfStatement(node as BoundIfStatement, arg); case BoundKind.ForEachStatement: return VisitForEachStatement(node as BoundForEachStatement, arg); case BoundKind.TryStatement: return VisitTryStatement(node as BoundTryStatement, arg); case BoundKind.Literal: return VisitLiteral(node as BoundLiteral, arg); case BoundKind.ThisReference: return VisitThisReference(node as BoundThisReference, arg); case BoundKind.Local: return VisitLocal(node as BoundLocal, arg); case BoundKind.Parameter: return VisitParameter(node as BoundParameter, arg); case BoundKind.LabelStatement: return VisitLabelStatement(node as BoundLabelStatement, arg); case BoundKind.GotoStatement: return VisitGotoStatement(node as BoundGotoStatement, arg); case BoundKind.LabeledStatement: return VisitLabeledStatement(node as BoundLabeledStatement, arg); case BoundKind.StatementList: return VisitStatementList(node as BoundStatementList, arg); case BoundKind.ConditionalGoto: return VisitConditionalGoto(node as BoundConditionalGoto, arg); case BoundKind.Call: return VisitCall(node as BoundCall, arg); case BoundKind.ObjectCreationExpression: return VisitObjectCreationExpression(node as BoundObjectCreationExpression, arg); case BoundKind.DelegateCreationExpression: return VisitDelegateCreationExpression(node as BoundDelegateCreationExpression, arg); case BoundKind.FieldAccess: return VisitFieldAccess(node as BoundFieldAccess, arg); case BoundKind.PropertyAccess: return VisitPropertyAccess(node as BoundPropertyAccess, arg); case BoundKind.Lambda: return VisitLambda(node as BoundLambda, arg); case BoundKind.NameOfOperator: return VisitNameOfOperator(node as BoundNameOfOperator, arg); } return VisitInternal(node, arg); } public virtual R DefaultVisit(BoundNode node, A arg) { return default(R); } } internal abstract partial class BoundTreeVisitor { protected BoundTreeVisitor() { } [DebuggerHidden] public virtual BoundNode Visit(BoundNode node) { if (node != null) { return node.Accept(this); } return null; } [DebuggerHidden] public virtual BoundNode DefaultVisit(BoundNode node) { return null; } public class CancelledByStackGuardException : Exception { public readonly BoundNode Node; public CancelledByStackGuardException(Exception inner, BoundNode node) : base(inner.Message, inner) { Node = node; } public void AddAnError(DiagnosticBag diagnostics) { diagnostics.Add(ErrorCode.ERR_InsufficientStack, GetTooLongOrComplexExpressionErrorLocation(Node)); } public void AddAnError(BindingDiagnosticBag diagnostics) { diagnostics.Add(ErrorCode.ERR_InsufficientStack, GetTooLongOrComplexExpressionErrorLocation(Node)); } public static Location GetTooLongOrComplexExpressionErrorLocation(BoundNode node) { SyntaxNode syntax = node.Syntax; if (!(syntax is ExpressionSyntax)) { syntax = syntax.DescendantNodes(n => !(n is ExpressionSyntax)).OfType<ExpressionSyntax>().FirstOrDefault() ?? syntax; } return syntax.GetFirstToken().GetLocation(); } } /// <summary> /// Consumers must provide implementation for <see cref="VisitExpressionWithoutStackGuard"/>. /// </summary> [DebuggerStepThrough] protected BoundExpression VisitExpressionWithStackGuard(ref int recursionDepth, BoundExpression node) { BoundExpression result; recursionDepth++; #if DEBUG int saveRecursionDepth = recursionDepth; #endif if (recursionDepth > 1 || !ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException()) { EnsureSufficientExecutionStack(recursionDepth); result = VisitExpressionWithoutStackGuard(node); } else { result = VisitExpressionWithStackGuard(node); } #if DEBUG Debug.Assert(saveRecursionDepth == recursionDepth); #endif recursionDepth--; return result; } protected virtual void EnsureSufficientExecutionStack(int recursionDepth) { StackGuard.EnsureSufficientExecutionStack(recursionDepth); } protected virtual bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() { return true; } #nullable enable [DebuggerStepThrough] private BoundExpression? VisitExpressionWithStackGuard(BoundExpression node) { try { return VisitExpressionWithoutStackGuard(node); } catch (InsufficientExecutionStackException ex) { throw new CancelledByStackGuardException(ex, node); } } /// <summary> /// We should be intentional about behavior of derived classes regarding guarding against stack overflow. /// </summary> protected abstract BoundExpression? VisitExpressionWithoutStackGuard(BoundExpression node); #nullable disable } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Workspaces/Remote/ServiceHub/Services/TodoCommentsDiscovery/RemoteTodoCommentsIncrementalAnalyzer.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.TodoComments; namespace Microsoft.CodeAnalysis.Remote { internal sealed class RemoteTodoCommentsIncrementalAnalyzer : AbstractTodoCommentsIncrementalAnalyzer { /// <summary> /// Channel back to VS to inform it of the designer attributes we discover. /// </summary> private readonly RemoteCallback<IRemoteTodoCommentsDiscoveryService.ICallback> _callback; private readonly RemoteServiceCallbackId _callbackId; public RemoteTodoCommentsIncrementalAnalyzer(RemoteCallback<IRemoteTodoCommentsDiscoveryService.ICallback> callback, RemoteServiceCallbackId callbackId) { _callback = callback; _callbackId = callbackId; } protected override async ValueTask ReportTodoCommentDataAsync(DocumentId documentId, ImmutableArray<TodoCommentData> data, CancellationToken cancellationToken) { await _callback.InvokeAsync( (callback, cancellationToken) => callback.ReportTodoCommentDataAsync(_callbackId, documentId, data, cancellationToken), cancellationToken).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. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.TodoComments; namespace Microsoft.CodeAnalysis.Remote { internal sealed class RemoteTodoCommentsIncrementalAnalyzer : AbstractTodoCommentsIncrementalAnalyzer { /// <summary> /// Channel back to VS to inform it of the designer attributes we discover. /// </summary> private readonly RemoteCallback<IRemoteTodoCommentsDiscoveryService.ICallback> _callback; private readonly RemoteServiceCallbackId _callbackId; public RemoteTodoCommentsIncrementalAnalyzer(RemoteCallback<IRemoteTodoCommentsDiscoveryService.ICallback> callback, RemoteServiceCallbackId callbackId) { _callback = callback; _callbackId = callbackId; } protected override async ValueTask ReportTodoCommentDataAsync(DocumentId documentId, ImmutableArray<TodoCommentData> data, CancellationToken cancellationToken) { await _callback.InvokeAsync( (callback, cancellationToken) => callback.ReportTodoCommentDataAsync(_callbackId, documentId, data, cancellationToken), cancellationToken).ConfigureAwait(false); } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Analyzers/VisualBasic/CodeFixes/UseConditionalExpression/VisualBasicUseConditionalExpressionForReturnCodeFixProvider.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 System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Formatting.Rules Imports Microsoft.CodeAnalysis.Operations Imports Microsoft.CodeAnalysis.UseConditionalExpression Imports Microsoft.CodeAnalysis.VisualBasic.Syntax #If CODE_STYLE Then Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.VisualBasic.Formatting #End If Namespace Microsoft.CodeAnalysis.VisualBasic.UseConditionalExpression <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.UseConditionalExpressionForReturn), [Shared]> Friend Class VisualBasicUseConditionalExpressionForReturnCodeFixProvider Inherits AbstractUseConditionalExpressionForReturnCodeFixProvider(Of StatementSyntax, MultiLineIfBlockSyntax, ExpressionSyntax, TernaryConditionalExpressionSyntax) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Protected Overrides Function ConvertToExpression(throwOperation As IThrowOperation) As ExpressionSyntax ' VB does not have throw expressions Throw ExceptionUtilities.Unreachable End Function Protected Overrides Function GetMultiLineFormattingRule() As AbstractFormattingRule Return MultiLineConditionalExpressionFormattingRule.Instance End Function Protected Overrides Function WrapWithBlockIfAppropriate(ifStatement As MultiLineIfBlockSyntax, statement As StatementSyntax) As StatementSyntax Return statement End Function #If CODE_STYLE Then Protected Overrides Function GetSyntaxFormattingService() As ISyntaxFormattingService Return VisualBasicSyntaxFormattingService.Instance End Function #End If 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 System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Formatting.Rules Imports Microsoft.CodeAnalysis.Operations Imports Microsoft.CodeAnalysis.UseConditionalExpression Imports Microsoft.CodeAnalysis.VisualBasic.Syntax #If CODE_STYLE Then Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.VisualBasic.Formatting #End If Namespace Microsoft.CodeAnalysis.VisualBasic.UseConditionalExpression <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.UseConditionalExpressionForReturn), [Shared]> Friend Class VisualBasicUseConditionalExpressionForReturnCodeFixProvider Inherits AbstractUseConditionalExpressionForReturnCodeFixProvider(Of StatementSyntax, MultiLineIfBlockSyntax, ExpressionSyntax, TernaryConditionalExpressionSyntax) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Protected Overrides Function ConvertToExpression(throwOperation As IThrowOperation) As ExpressionSyntax ' VB does not have throw expressions Throw ExceptionUtilities.Unreachable End Function Protected Overrides Function GetMultiLineFormattingRule() As AbstractFormattingRule Return MultiLineConditionalExpressionFormattingRule.Instance End Function Protected Overrides Function WrapWithBlockIfAppropriate(ifStatement As MultiLineIfBlockSyntax, statement As StatementSyntax) As StatementSyntax Return statement End Function #If CODE_STYLE Then Protected Overrides Function GetSyntaxFormattingService() As ISyntaxFormattingService Return VisualBasicSyntaxFormattingService.Instance End Function #End If End Class End Namespace
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/CSharp/Portable/Compilation/SyntaxTreeSemanticModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Allows asking semantic questions about any node in a SyntaxTree within a Compilation. /// </summary> internal partial class SyntaxTreeSemanticModel : CSharpSemanticModel { private readonly CSharpCompilation _compilation; private readonly SyntaxTree _syntaxTree; /// <summary> /// Note, the name of this field could be somewhat confusing because it is also /// used to store models for attributes and default parameter values, which are /// not members. /// </summary> private ImmutableDictionary<CSharpSyntaxNode, MemberSemanticModel> _memberModels = ImmutableDictionary<CSharpSyntaxNode, MemberSemanticModel>.Empty; private readonly BinderFactory _binderFactory; private Func<CSharpSyntaxNode, MemberSemanticModel> _createMemberModelFunction; private readonly bool _ignoresAccessibility; private ScriptLocalScopeBinder.Labels _globalStatementLabels; private static readonly Func<CSharpSyntaxNode, bool> s_isMemberDeclarationFunction = IsMemberDeclaration; #nullable enable internal SyntaxTreeSemanticModel(CSharpCompilation compilation, SyntaxTree syntaxTree, bool ignoreAccessibility = false) { _compilation = compilation; _syntaxTree = syntaxTree; _ignoresAccessibility = ignoreAccessibility; if (!this.Compilation.SyntaxTrees.Contains(syntaxTree)) { throw new ArgumentOutOfRangeException(nameof(syntaxTree), CSharpResources.TreeNotPartOfCompilation); } _binderFactory = compilation.GetBinderFactory(SyntaxTree, ignoreAccessibility); } internal SyntaxTreeSemanticModel(CSharpCompilation parentCompilation, SyntaxTree parentSyntaxTree, SyntaxTree speculatedSyntaxTree) { _compilation = parentCompilation; _syntaxTree = speculatedSyntaxTree; _binderFactory = _compilation.GetBinderFactory(parentSyntaxTree); } /// <summary> /// The compilation this object was obtained from. /// </summary> public override CSharpCompilation Compilation { get { return _compilation; } } /// <summary> /// The root node of the syntax tree that this object is associated with. /// </summary> internal override CSharpSyntaxNode Root { get { return (CSharpSyntaxNode)_syntaxTree.GetRoot(); } } /// <summary> /// The SyntaxTree that this object is associated with. /// </summary> public override SyntaxTree SyntaxTree { get { return _syntaxTree; } } /// <summary> /// Returns true if this is a SemanticModel that ignores accessibility rules when answering semantic questions. /// </summary> public override bool IgnoresAccessibility { get { return _ignoresAccessibility; } } private void VerifySpanForGetDiagnostics(TextSpan? span) { if (span.HasValue && !this.Root.FullSpan.Contains(span.Value)) { throw new ArgumentException("span"); } } public override ImmutableArray<Diagnostic> GetSyntaxDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)) { VerifySpanForGetDiagnostics(span); return Compilation.GetDiagnosticsForSyntaxTree( CompilationStage.Parse, this.SyntaxTree, span, includeEarlierStages: false, cancellationToken: cancellationToken); } public override ImmutableArray<Diagnostic> GetDeclarationDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)) { VerifySpanForGetDiagnostics(span); return Compilation.GetDiagnosticsForSyntaxTree( CompilationStage.Declare, this.SyntaxTree, span, includeEarlierStages: false, cancellationToken: cancellationToken); } public override ImmutableArray<Diagnostic> GetMethodBodyDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)) { VerifySpanForGetDiagnostics(span); return Compilation.GetDiagnosticsForSyntaxTree( CompilationStage.Compile, this.SyntaxTree, span, includeEarlierStages: false, cancellationToken: cancellationToken); } public override ImmutableArray<Diagnostic> GetDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)) { VerifySpanForGetDiagnostics(span); return Compilation.GetDiagnosticsForSyntaxTree( CompilationStage.Compile, this.SyntaxTree, span, includeEarlierStages: true, cancellationToken: cancellationToken); } #nullable disable /// <summary> /// Gets the enclosing binder associated with the node /// </summary> /// <param name="position"></param> /// <returns></returns> internal override Binder GetEnclosingBinderInternal(int position) { AssertPositionAdjusted(position); SyntaxToken token = this.Root.FindTokenIncludingCrefAndNameAttributes(position); // If we're before the start of the first token, just return // the binder for the compilation unit. if (position == 0 && position != token.SpanStart) { return _binderFactory.GetBinder(this.Root, position).WithAdditionalFlags(GetSemanticModelBinderFlags()); } MemberSemanticModel memberModel = GetMemberModel(position); if (memberModel != null) { return memberModel.GetEnclosingBinder(position); } return _binderFactory.GetBinder((CSharpSyntaxNode)token.Parent, position).WithAdditionalFlags(GetSemanticModelBinderFlags()); } internal override IOperation GetOperationWorker(CSharpSyntaxNode node, CancellationToken cancellationToken) { MemberSemanticModel model; switch (node) { case ConstructorDeclarationSyntax constructor: model = (constructor.HasAnyBody() || constructor.Initializer != null) ? GetOrAddModel(node) : null; break; case BaseMethodDeclarationSyntax method: model = method.HasAnyBody() ? GetOrAddModel(node) : null; break; case AccessorDeclarationSyntax accessor: model = (accessor.Body != null || accessor.ExpressionBody != null) ? GetOrAddModel(node) : null; break; case RecordDeclarationSyntax { ParameterList: { }, PrimaryConstructorBaseTypeIfClass: { } } recordDeclaration when TryGetSynthesizedRecordConstructor(recordDeclaration) is SynthesizedRecordConstructor: model = GetOrAddModel(recordDeclaration); break; default: model = this.GetMemberModel(node); break; } if (model != null) { return model.GetOperationWorker(node, cancellationToken); } else { return null; } } internal override SymbolInfo GetSymbolInfoWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)) { ValidateSymbolInfoOptions(options); // in case this is right side of a qualified name or member access (or part of a cref) node = SyntaxFactory.GetStandaloneNode(node); var model = this.GetMemberModel(node); SymbolInfo result; XmlNameAttributeSyntax attrSyntax; CrefSyntax crefSyntax; if (model != null) { // Expression occurs in an executable code (method body or initializer) context. Use that // model to get the information. result = model.GetSymbolInfoWorker(node, options, cancellationToken); // If we didn't get anything and were in Type/Namespace only context, let's bind normally and see // if any symbol comes out. if ((object)result.Symbol == null && result.CandidateReason == CandidateReason.None && node is ExpressionSyntax && SyntaxFacts.IsInNamespaceOrTypeContext((ExpressionSyntax)node)) { var binder = this.GetEnclosingBinder(GetAdjustedNodePosition(node)); if (binder != null) { // Wrap the binder in a LocalScopeBinder because Binder.BindExpression assumes there // will be one in the binder chain and one isn't necessarily required for the batch case. binder = new LocalScopeBinder(binder); BoundExpression bound = binder.BindExpression((ExpressionSyntax)node, BindingDiagnosticBag.Discarded); SymbolInfo info = GetSymbolInfoForNode(options, bound, bound, boundNodeForSyntacticParent: null, binderOpt: null); if ((object)info.Symbol != null) { result = new SymbolInfo(null, ImmutableArray.Create<ISymbol>(info.Symbol), CandidateReason.NotATypeOrNamespace); } else if (!info.CandidateSymbols.IsEmpty) { result = new SymbolInfo(null, info.CandidateSymbols, CandidateReason.NotATypeOrNamespace); } } } } else if (node.Parent.Kind() == SyntaxKind.XmlNameAttribute && (attrSyntax = (XmlNameAttributeSyntax)node.Parent).Identifier == node) { result = SymbolInfo.None; var binder = this.GetEnclosingBinder(GetAdjustedNodePosition(node)); if (binder != null) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var symbols = binder.BindXmlNameAttribute(attrSyntax, ref discardedUseSiteInfo); // NOTE: We don't need to call GetSymbolInfoForSymbol because the symbols // can only be parameters or type parameters. Debug.Assert(symbols.All(s => s.Kind == SymbolKind.TypeParameter || s.Kind == SymbolKind.Parameter)); switch (symbols.Length) { case 0: result = SymbolInfo.None; break; case 1: result = SymbolInfoFactory.Create(symbols, LookupResultKind.Viable, isDynamic: false); break; default: result = SymbolInfoFactory.Create(symbols, LookupResultKind.Ambiguous, isDynamic: false); break; } } } else if ((crefSyntax = node as CrefSyntax) != null) { int adjustedPosition = GetAdjustedNodePosition(crefSyntax); result = GetCrefSymbolInfo(adjustedPosition, crefSyntax, options, HasParameterList(crefSyntax)); } else { // if expression is not part of a member context then caller may really just have a // reference to a type or namespace name var symbol = GetSemanticInfoSymbolInNonMemberContext(node, bindVarAsAliasFirst: (options & SymbolInfoOptions.PreserveAliases) != 0); result = (object)symbol != null ? GetSymbolInfoForSymbol(symbol, options) : SymbolInfo.None; } return result; } internal override SymbolInfo GetCollectionInitializerSymbolInfoWorker(InitializerExpressionSyntax collectionInitializer, ExpressionSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { var model = this.GetMemberModel(collectionInitializer); if (model != null) { // Expression occurs in an executable code (method body or initializer) context. Use that // model to get the information. return model.GetCollectionInitializerSymbolInfoWorker(collectionInitializer, node, cancellationToken); } return SymbolInfo.None; } internal override CSharpTypeInfo GetTypeInfoWorker(CSharpSyntaxNode node, CancellationToken cancellationToken = default(CancellationToken)) { // in case this is right side of a qualified name or member access (or part of a cref) node = SyntaxFactory.GetStandaloneNode(node); var model = this.GetMemberModel(node); if (model != null) { // Expression occurs in an executable code (method body or initializer) context. Use that // model to get the information. return model.GetTypeInfoWorker(node, cancellationToken); } else { // if expression is not part of a member context then caller may really just have a // reference to a type or namespace name var symbol = GetSemanticInfoSymbolInNonMemberContext(node, bindVarAsAliasFirst: false); // Don't care about aliases here. return (object)symbol != null ? GetTypeInfoForSymbol(symbol) : CSharpTypeInfo.None; } } // Common helper method for GetSymbolInfoWorker and GetTypeInfoWorker, which is called when there is no member model for the given syntax node. // Even if the expression is not part of a member context, the caller may really just have a reference to a type or namespace name. // If so, the methods binds the syntax as a namespace or type or alias symbol. Otherwise, it returns null. private Symbol GetSemanticInfoSymbolInNonMemberContext(CSharpSyntaxNode node, bool bindVarAsAliasFirst) { Debug.Assert(this.GetMemberModel(node) == null); var binder = this.GetEnclosingBinder(GetAdjustedNodePosition(node)); if (binder != null) { // if expression is not part of a member context then caller may really just have a // reference to a type or namespace name var type = node as TypeSyntax; if ((object)type != null) { // determine if this type is part of a base declaration being resolved var basesBeingResolved = GetBasesBeingResolved(type); if (SyntaxFacts.IsNamespaceAliasQualifier(type)) { return binder.BindNamespaceAliasSymbol(node as IdentifierNameSyntax, BindingDiagnosticBag.Discarded); } else if (SyntaxFacts.IsInTypeOnlyContext(type)) { if (!type.IsVar) { return binder.BindTypeOrAlias(type, BindingDiagnosticBag.Discarded, basesBeingResolved).Symbol; } Symbol result = bindVarAsAliasFirst ? binder.BindTypeOrAlias(type, BindingDiagnosticBag.Discarded, basesBeingResolved).Symbol : null; // CONSIDER: we might bind "var" twice - once to see if it is an alias and again // as the type of a declared field. This should only happen for GetAliasInfo // calls on implicitly-typed fields (rare?). If it becomes a problem, then we // probably need to have the FieldSymbol retain alias info when it does its own // binding and expose it to us here. if ((object)result == null || result.Kind == SymbolKind.ErrorType) { // We might be in a field declaration with "var" keyword as the type name. // Implicitly typed field symbols are not allowed in regular C#, // but they are allowed in interactive scenario. // However, we can return fieldSymbol.Type for implicitly typed field symbols in both cases. // Note that for regular C#, fieldSymbol.Type would be an error type. var variableDecl = type.Parent as VariableDeclarationSyntax; if (variableDecl != null && variableDecl.Variables.Any()) { var fieldSymbol = GetDeclaredFieldSymbol(variableDecl.Variables.First()); if ((object)fieldSymbol != null) { result = fieldSymbol.Type; } } } return result ?? binder.BindTypeOrAlias(type, BindingDiagnosticBag.Discarded, basesBeingResolved).Symbol; } else { return binder.BindNamespaceOrTypeOrAliasSymbol(type, BindingDiagnosticBag.Discarded, basesBeingResolved, basesBeingResolved != null).Symbol; } } } return null; } internal override ImmutableArray<Symbol> GetMemberGroupWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)) { // in case this is right side of a qualified name or member access (or part of a cref) node = SyntaxFactory.GetStandaloneNode(node); var model = this.GetMemberModel(node); return model == null ? ImmutableArray<Symbol>.Empty : model.GetMemberGroupWorker(node, options, cancellationToken); } internal override ImmutableArray<IPropertySymbol> GetIndexerGroupWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)) { // in case this is right side of a qualified name or member access (or part of a cref) node = SyntaxFactory.GetStandaloneNode(node); var model = this.GetMemberModel(node); return model == null ? ImmutableArray<IPropertySymbol>.Empty : model.GetIndexerGroupWorker(node, options, cancellationToken); } internal override Optional<object> GetConstantValueWorker(CSharpSyntaxNode node, CancellationToken cancellationToken) { // in case this is right side of a qualified name or member access node = SyntaxFactory.GetStandaloneNode(node); var model = this.GetMemberModel(node); return model == null ? default(Optional<object>) : model.GetConstantValueWorker(node, cancellationToken); } public override QueryClauseInfo GetQueryClauseInfo(QueryClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(node); var model = this.GetMemberModel(node); return (model == null) ? default(QueryClauseInfo) : model.GetQueryClauseInfo(node, cancellationToken); } public override SymbolInfo GetSymbolInfo(SelectOrGroupClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(node); var model = this.GetMemberModel(node); return (model == null) ? SymbolInfo.None : model.GetSymbolInfo(node, cancellationToken); } public override TypeInfo GetTypeInfo(SelectOrGroupClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(node); var model = this.GetMemberModel(node); return (model == null) ? CSharpTypeInfo.None : model.GetTypeInfo(node, cancellationToken); } public override IPropertySymbol GetDeclaredSymbol(AnonymousObjectMemberDeclaratorSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declaratorSyntax); var model = this.GetMemberModel(declaratorSyntax); return (model == null) ? null : model.GetDeclaredSymbol(declaratorSyntax, cancellationToken); } public override INamedTypeSymbol GetDeclaredSymbol(AnonymousObjectCreationExpressionSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declaratorSyntax); var model = this.GetMemberModel(declaratorSyntax); return (model == null) ? null : model.GetDeclaredSymbol(declaratorSyntax, cancellationToken); } public override INamedTypeSymbol GetDeclaredSymbol(TupleExpressionSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declaratorSyntax); var model = this.GetMemberModel(declaratorSyntax); return (model == null) ? null : model.GetDeclaredSymbol(declaratorSyntax, cancellationToken); } public override ISymbol GetDeclaredSymbol(ArgumentSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declaratorSyntax); var model = this.GetMemberModel(declaratorSyntax); return (model == null) ? null : model.GetDeclaredSymbol(declaratorSyntax, cancellationToken); } public override IRangeVariableSymbol GetDeclaredSymbol(QueryClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(node); var model = this.GetMemberModel(node); return (model == null) ? null : model.GetDeclaredSymbol(node, cancellationToken); } public override IRangeVariableSymbol GetDeclaredSymbol(JoinIntoClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(node); var model = this.GetMemberModel(node); return (model == null) ? null : model.GetDeclaredSymbol(node, cancellationToken); } public override IRangeVariableSymbol GetDeclaredSymbol(QueryContinuationSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(node); var model = this.GetMemberModel(node); return (model == null) ? null : model.GetDeclaredSymbol(node, cancellationToken); } public override SymbolInfo GetSymbolInfo(OrderingSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(node); var model = this.GetMemberModel(node); return (model == null) ? SymbolInfo.None : model.GetSymbolInfo(node, cancellationToken); } private ConsList<TypeSymbol> GetBasesBeingResolved(TypeSyntax expression) { // if the expression is the child of a base-list node, then the expression should be // bound in the context of the containing symbols base being resolved. for (; expression != null && expression.Parent != null; expression = expression.Parent as TypeSyntax) { var parent = expression.Parent; if (parent is BaseTypeSyntax baseType && parent.Parent != null && parent.Parent.Kind() == SyntaxKind.BaseList && baseType.Type == expression) { // we have a winner var decl = (BaseTypeDeclarationSyntax)parent.Parent.Parent; var symbol = this.GetDeclaredSymbol(decl); return ConsList<TypeSymbol>.Empty.Prepend(symbol.GetSymbol().OriginalDefinition); } } return null; } public override Conversion ClassifyConversion(ExpressionSyntax expression, ITypeSymbol destination, bool isExplicitInSource = false) { TypeSymbol csdestination = destination.EnsureCSharpSymbolOrNull(nameof(destination)); if (expression.Kind() == SyntaxKind.DeclarationExpression) { // Conversion from a declaration is unspecified. return Conversion.NoConversion; } if (isExplicitInSource) { return ClassifyConversionForCast(expression, csdestination); } CheckSyntaxNode(expression); if ((object)destination == null) { throw new ArgumentNullException(nameof(destination)); } // TODO(cyrusn): Check arguments. This is a public entrypoint, so we must do appropriate // checks here. However, no other methods in this type do any checking currently. So I'm // going to hold off on this until we do a full sweep of the API. var model = this.GetMemberModel(expression); if (model == null) { // 'expression' must just be reference to a type or namespace name outside of an // expression context. Currently we bail in that case. However, is this a question // that a client would be asking and would expect sensible results for? return Conversion.NoConversion; } return model.ClassifyConversion(expression, destination); } internal override Conversion ClassifyConversionForCast(ExpressionSyntax expression, TypeSymbol destination) { CheckSyntaxNode(expression); if ((object)destination == null) { throw new ArgumentNullException(nameof(destination)); } var model = this.GetMemberModel(expression); if (model == null) { // 'expression' must just be reference to a type or namespace name outside of an // expression context. Currently we bail in that case. However, is this a question // that a client would be asking and would expect sensible results for? return Conversion.NoConversion; } return model.ClassifyConversionForCast(expression, destination); } public override bool IsSpeculativeSemanticModel { get { return false; } } public override int OriginalPositionForSpeculation { get { return 0; } } public override CSharpSemanticModel ParentModel { get { return null; } } internal override SemanticModel ContainingModelOrSelf { get { return this; } } internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, TypeSyntax type, SpeculativeBindingOption bindingOption, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var model = this.GetMemberModel(position); if (model != null) { return model.TryGetSpeculativeSemanticModelCore(parentModel, position, type, bindingOption, out speculativeModel); } Binder binder = GetSpeculativeBinder(position, type, bindingOption); if (binder != null) { speculativeModel = SpeculativeSyntaxTreeSemanticModel.Create(parentModel, type, binder, position, bindingOption); return true; } speculativeModel = null; return false; } internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, CrefSyntax crefSyntax, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); Binder binder = GetEnclosingBinder(position); if (binder?.InCref == true) { speculativeModel = SpeculativeSyntaxTreeSemanticModel.Create(parentModel, crefSyntax, binder, position); return true; } speculativeModel = null; return false; } internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, StatementSyntax statement, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var model = this.GetMemberModel(position); if (model != null) { return model.TryGetSpeculativeSemanticModelCore(parentModel, position, statement, out speculativeModel); } speculativeModel = null; return false; } internal sealed override bool TryGetSpeculativeSemanticModelForMethodBodyCore(SyntaxTreeSemanticModel parentModel, int position, BaseMethodDeclarationSyntax method, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var model = this.GetMemberModel(position); if (model != null) { return model.TryGetSpeculativeSemanticModelForMethodBodyCore(parentModel, position, method, out speculativeModel); } speculativeModel = null; return false; } internal sealed override bool TryGetSpeculativeSemanticModelForMethodBodyCore(SyntaxTreeSemanticModel parentModel, int position, AccessorDeclarationSyntax accessor, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var model = this.GetMemberModel(position); if (model != null) { return model.TryGetSpeculativeSemanticModelForMethodBodyCore(parentModel, position, accessor, out speculativeModel); } speculativeModel = null; return false; } internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, EqualsValueClauseSyntax initializer, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var model = this.GetMemberModel(position); if (model != null) { return model.TryGetSpeculativeSemanticModelCore(parentModel, position, initializer, out speculativeModel); } speculativeModel = null; return false; } internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, ArrowExpressionClauseSyntax expressionBody, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var model = this.GetMemberModel(position); if (model != null) { return model.TryGetSpeculativeSemanticModelCore(parentModel, position, expressionBody, out speculativeModel); } speculativeModel = null; return false; } internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, ConstructorInitializerSyntax constructorInitializer, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var existingConstructorInitializer = this.Root.FindToken(position).Parent.AncestorsAndSelf().OfType<ConstructorInitializerSyntax>().FirstOrDefault(); if (existingConstructorInitializer != null) { var model = this.GetMemberModel(position); if (model != null) { return model.TryGetSpeculativeSemanticModelCore(parentModel, position, constructorInitializer, out speculativeModel); } } speculativeModel = null; return false; } internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, PrimaryConstructorBaseTypeSyntax constructorInitializer, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var existingConstructorInitializer = this.Root.FindToken(position).Parent.AncestorsAndSelf().OfType<PrimaryConstructorBaseTypeSyntax>().FirstOrDefault(); if (existingConstructorInitializer != null) { var model = this.GetMemberModel(existingConstructorInitializer); if (model != null) { return model.TryGetSpeculativeSemanticModelCore(parentModel, position, constructorInitializer, out speculativeModel); } } speculativeModel = null; return false; } internal override BoundExpression GetSpeculativelyBoundExpression(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption, out Binder binder, out ImmutableArray<Symbol> crefSymbols) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } // If the given position is in a member that we can get a semantic model for, we want to defer to that implementation // of GetSpeculativelyBoundExpression so it can take nullability into account. if (bindingOption == SpeculativeBindingOption.BindAsExpression) { position = CheckAndAdjustPosition(position); var model = GetMemberModel(position); if (model is object) { return model.GetSpeculativelyBoundExpression(position, expression, bindingOption, out binder, out crefSymbols); } } return GetSpeculativelyBoundExpressionWithoutNullability(position, expression, bindingOption, out binder, out crefSymbols); } internal AttributeSemanticModel CreateSpeculativeAttributeSemanticModel(int position, AttributeSyntax attribute, Binder binder, AliasSymbol aliasOpt, NamedTypeSymbol attributeType) { var memberModel = IsNullableAnalysisEnabledAtSpeculativePosition(position, attribute) ? GetMemberModel(position) : null; return AttributeSemanticModel.CreateSpeculative(this, attribute, attributeType, aliasOpt, binder, memberModel?.GetRemappedSymbols(), position); } internal bool IsNullableAnalysisEnabledAtSpeculativePosition(int position, SyntaxNode speculativeSyntax) { Debug.Assert(speculativeSyntax.SyntaxTree != SyntaxTree); // https://github.com/dotnet/roslyn/issues/50234: CSharpSyntaxTree.IsNullableAnalysisEnabled() does not differentiate // between no '#nullable' directives and '#nullable restore' - it returns null in both cases. Since we fallback to the // directives in the original syntax tree, we're not handling '#nullable restore' correctly in the speculative text. return ((CSharpSyntaxTree)speculativeSyntax.SyntaxTree).IsNullableAnalysisEnabled(speculativeSyntax.Span) ?? Compilation.IsNullableAnalysisEnabledIn((CSharpSyntaxTree)SyntaxTree, new TextSpan(position, 0)); } private MemberSemanticModel GetMemberModel(int position) { AssertPositionAdjusted(position); CSharpSyntaxNode node = (CSharpSyntaxNode)Root.FindTokenIncludingCrefAndNameAttributes(position).Parent; CSharpSyntaxNode memberDecl = GetMemberDeclaration(node); bool outsideMemberDecl = false; if (memberDecl != null) { switch (memberDecl.Kind()) { case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: // NOTE: not UnknownAccessorDeclaration since there's no corresponding method symbol from which to build a member model. outsideMemberDecl = !LookupPosition.IsInBody(position, (AccessorDeclarationSyntax)memberDecl); break; case SyntaxKind.ConstructorDeclaration: var constructorDecl = (ConstructorDeclarationSyntax)memberDecl; outsideMemberDecl = !LookupPosition.IsInConstructorParameterScope(position, constructorDecl) && !LookupPosition.IsInParameterList(position, constructorDecl); break; case SyntaxKind.RecordDeclaration: { var recordDecl = (RecordDeclarationSyntax)memberDecl; if (recordDecl.ParameterList is null) { outsideMemberDecl = true; } else { var argumentList = recordDecl.PrimaryConstructorBaseTypeIfClass?.ArgumentList; outsideMemberDecl = argumentList is null || !LookupPosition.IsBetweenTokens(position, argumentList.OpenParenToken, argumentList.CloseParenToken); } } break; case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.MethodDeclaration: case SyntaxKind.OperatorDeclaration: var methodDecl = (BaseMethodDeclarationSyntax)memberDecl; outsideMemberDecl = !LookupPosition.IsInBody(position, methodDecl) && !LookupPosition.IsInParameterList(position, methodDecl); break; } } return outsideMemberDecl ? null : GetMemberModel(node); } // Try to get a member semantic model that encloses "node". If there is not an enclosing // member semantic model, return null. internal override MemberSemanticModel GetMemberModel(SyntaxNode node) { // Documentation comments can never legally appear within members, so there's no point // in building out the MemberSemanticModel to handle them. Instead, just say have // SyntaxTreeSemanticModel handle them, regardless of location. if (IsInDocumentationComment(node)) { return null; } var memberDecl = GetMemberDeclaration(node) ?? (node as CompilationUnitSyntax); if (memberDecl != null) { var span = node.Span; switch (memberDecl.Kind()) { case SyntaxKind.MethodDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.OperatorDeclaration: { var methodDecl = (BaseMethodDeclarationSyntax)memberDecl; var expressionBody = methodDecl.GetExpressionBodySyntax(); return (expressionBody?.FullSpan.Contains(span) == true || methodDecl.Body?.FullSpan.Contains(span) == true) ? GetOrAddModel(methodDecl) : null; } case SyntaxKind.ConstructorDeclaration: { ConstructorDeclarationSyntax constructorDecl = (ConstructorDeclarationSyntax)memberDecl; var expressionBody = constructorDecl.GetExpressionBodySyntax(); return (constructorDecl.Initializer?.FullSpan.Contains(span) == true || expressionBody?.FullSpan.Contains(span) == true || constructorDecl.Body?.FullSpan.Contains(span) == true) ? GetOrAddModel(constructorDecl) : null; } case SyntaxKind.RecordDeclaration: { var recordDecl = (RecordDeclarationSyntax)memberDecl; return recordDecl.ParameterList is object && recordDecl.PrimaryConstructorBaseTypeIfClass is PrimaryConstructorBaseTypeSyntax baseWithArguments && (node == baseWithArguments || baseWithArguments.ArgumentList.FullSpan.Contains(span)) ? GetOrAddModel(memberDecl) : null; } case SyntaxKind.DestructorDeclaration: { DestructorDeclarationSyntax destructorDecl = (DestructorDeclarationSyntax)memberDecl; var expressionBody = destructorDecl.GetExpressionBodySyntax(); return (expressionBody?.FullSpan.Contains(span) == true || destructorDecl.Body?.FullSpan.Contains(span) == true) ? GetOrAddModel(destructorDecl) : null; } case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: // NOTE: not UnknownAccessorDeclaration since there's no corresponding method symbol from which to build a member model. { var accessorDecl = (AccessorDeclarationSyntax)memberDecl; return (accessorDecl.ExpressionBody?.FullSpan.Contains(span) == true || accessorDecl.Body?.FullSpan.Contains(span) == true) ? GetOrAddModel(accessorDecl) : null; } case SyntaxKind.IndexerDeclaration: { var indexerDecl = (IndexerDeclarationSyntax)memberDecl; return GetOrAddModelIfContains(indexerDecl.ExpressionBody, span); } case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: { var fieldDecl = (BaseFieldDeclarationSyntax)memberDecl; foreach (var variableDecl in fieldDecl.Declaration.Variables) { var binding = GetOrAddModelIfContains(variableDecl.Initializer, span); if (binding != null) { return binding; } } } break; case SyntaxKind.EnumMemberDeclaration: { var enumDecl = (EnumMemberDeclarationSyntax)memberDecl; return (enumDecl.EqualsValue != null) ? GetOrAddModelIfContains(enumDecl.EqualsValue, span) : null; } case SyntaxKind.PropertyDeclaration: { var propertyDecl = (PropertyDeclarationSyntax)memberDecl; return GetOrAddModelIfContains(propertyDecl.Initializer, span) ?? GetOrAddModelIfContains(propertyDecl.ExpressionBody, span); } case SyntaxKind.GlobalStatement: if (SyntaxFacts.IsSimpleProgramTopLevelStatement((GlobalStatementSyntax)memberDecl)) { return GetOrAddModel((CompilationUnitSyntax)memberDecl.Parent); } return GetOrAddModel(memberDecl); case SyntaxKind.CompilationUnit: if (SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(Compilation, (CompilationUnitSyntax)memberDecl, fallbackToMainEntryPoint: false) is object) { return GetOrAddModel(memberDecl); } break; case SyntaxKind.Attribute: return GetOrAddModelForAttribute((AttributeSyntax)memberDecl); case SyntaxKind.Parameter: if (node != memberDecl) { return GetOrAddModelForParameter((ParameterSyntax)memberDecl, span); } else { return GetMemberModel(memberDecl.Parent); } } } return null; } /// <summary> /// Internal for test purposes only /// </summary> internal ImmutableDictionary<CSharpSyntaxNode, MemberSemanticModel> TestOnlyMemberModels => _memberModels; private MemberSemanticModel GetOrAddModelForAttribute(AttributeSyntax attribute) { MemberSemanticModel containing = attribute.Parent != null ? GetMemberModel(attribute.Parent) : null; if (containing == null) { return GetOrAddModel(attribute); } return ImmutableInterlocked.GetOrAdd(ref _memberModels, attribute, (node, binderAndModel) => CreateModelForAttribute(binderAndModel.binder, (AttributeSyntax)node, binderAndModel.model), (binder: containing.GetEnclosingBinder(attribute.SpanStart), model: containing)); } private static bool IsInDocumentationComment(SyntaxNode node) { for (SyntaxNode curr = node; curr != null; curr = curr.Parent) { if (SyntaxFacts.IsDocumentationCommentTrivia(curr.Kind())) { return true; } } return false; } // Check parameter for a default value containing span, and create an InitializerSemanticModel for binding the default value if so. // Otherwise, return model for enclosing context. private MemberSemanticModel GetOrAddModelForParameter(ParameterSyntax paramDecl, TextSpan span) { EqualsValueClauseSyntax defaultValueSyntax = paramDecl.Default; MemberSemanticModel containing = paramDecl.Parent != null ? GetMemberModel(paramDecl.Parent) : null; if (containing == null) { return GetOrAddModelIfContains(defaultValueSyntax, span); } if (defaultValueSyntax != null && defaultValueSyntax.FullSpan.Contains(span)) { var parameterSymbol = containing.GetDeclaredSymbol(paramDecl).GetSymbol<ParameterSymbol>(); if ((object)parameterSymbol != null) { return ImmutableInterlocked.GetOrAdd(ref _memberModels, defaultValueSyntax, (equalsValue, tuple) => InitializerSemanticModel.Create( this, tuple.paramDecl, tuple.parameterSymbol, tuple.containing.GetEnclosingBinder(tuple.paramDecl.SpanStart). CreateBinderForParameterDefaultValue(tuple.parameterSymbol, (EqualsValueClauseSyntax)equalsValue), tuple.containing.GetRemappedSymbols()), (compilation: this.Compilation, paramDecl, parameterSymbol, containing) ); } } return containing; } private static CSharpSyntaxNode GetMemberDeclaration(SyntaxNode node) { return node.FirstAncestorOrSelf(s_isMemberDeclarationFunction); } private MemberSemanticModel GetOrAddModelIfContains(CSharpSyntaxNode node, TextSpan span) { if (node != null && node.FullSpan.Contains(span)) { return GetOrAddModel(node); } return null; } private MemberSemanticModel GetOrAddModel(CSharpSyntaxNode node) { var createMemberModelFunction = _createMemberModelFunction ?? (_createMemberModelFunction = this.CreateMemberModel); return GetOrAddModel(node, createMemberModelFunction); } internal MemberSemanticModel GetOrAddModel(CSharpSyntaxNode node, Func<CSharpSyntaxNode, MemberSemanticModel> createMemberModelFunction) { return ImmutableInterlocked.GetOrAdd(ref _memberModels, node, createMemberModelFunction); } // Create a member model for the given declaration syntax. In certain very malformed // syntax trees, there may not be a symbol that can have a member model associated with it // (although we try to minimize such cases). In such cases, null is returned. private MemberSemanticModel CreateMemberModel(CSharpSyntaxNode node) { Binder defaultOuter() => _binderFactory.GetBinder(node).WithAdditionalFlags(this.IgnoresAccessibility ? BinderFlags.IgnoreAccessibility : BinderFlags.None); switch (node.Kind()) { case SyntaxKind.CompilationUnit: return createMethodBodySemanticModel(node, SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(Compilation, (CompilationUnitSyntax)node, fallbackToMainEntryPoint: false)); case SyntaxKind.MethodDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: { var memberDecl = (MemberDeclarationSyntax)node; var symbol = GetDeclaredSymbol(memberDecl).GetSymbol<SourceMemberMethodSymbol>(); return createMethodBodySemanticModel(memberDecl, symbol); } case SyntaxKind.RecordDeclaration: { SynthesizedRecordConstructor symbol = TryGetSynthesizedRecordConstructor((RecordDeclarationSyntax)node); if (symbol is null) { return null; } return createMethodBodySemanticModel(node, symbol); } case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: { var accessorDecl = (AccessorDeclarationSyntax)node; var symbol = GetDeclaredSymbol(accessorDecl).GetSymbol<SourceMemberMethodSymbol>(); return createMethodBodySemanticModel(accessorDecl, symbol); } case SyntaxKind.Block: // Don't throw, just use for the assert ExceptionUtilities.UnexpectedValue(node.Parent); break; case SyntaxKind.EqualsValueClause: switch (node.Parent.Kind()) { case SyntaxKind.VariableDeclarator: { var variableDecl = (VariableDeclaratorSyntax)node.Parent; FieldSymbol fieldSymbol = GetDeclaredFieldSymbol(variableDecl); return InitializerSemanticModel.Create( this, variableDecl, //pass in the entire field initializer to permit region analysis. fieldSymbol, //if we're in regular C#, then insert an extra binder to perform field initialization checks GetFieldOrPropertyInitializerBinder(fieldSymbol, defaultOuter(), variableDecl.Initializer)); } case SyntaxKind.PropertyDeclaration: { var propertyDecl = (PropertyDeclarationSyntax)node.Parent; var propertySymbol = GetDeclaredSymbol(propertyDecl).GetSymbol<SourcePropertySymbol>(); return InitializerSemanticModel.Create( this, propertyDecl, propertySymbol, GetFieldOrPropertyInitializerBinder(propertySymbol.BackingField, defaultOuter(), propertyDecl.Initializer)); } case SyntaxKind.Parameter: { // NOTE: we don't need to create a member model for lambda parameter default value // (which is bad code anyway) because lambdas only appear in code with associated // member models. ParameterSyntax parameterDecl = (ParameterSyntax)node.Parent; ParameterSymbol parameterSymbol = GetDeclaredNonLambdaParameterSymbol(parameterDecl); if ((object)parameterSymbol == null) return null; return InitializerSemanticModel.Create( this, parameterDecl, parameterSymbol, defaultOuter().CreateBinderForParameterDefaultValue(parameterSymbol, (EqualsValueClauseSyntax)node), parentRemappedSymbolsOpt: null); } case SyntaxKind.EnumMemberDeclaration: { var enumDecl = (EnumMemberDeclarationSyntax)node.Parent; var enumSymbol = GetDeclaredSymbol(enumDecl).GetSymbol<FieldSymbol>(); if ((object)enumSymbol == null) return null; return InitializerSemanticModel.Create( this, enumDecl, enumSymbol, GetFieldOrPropertyInitializerBinder(enumSymbol, defaultOuter(), enumDecl.EqualsValue)); } default: throw ExceptionUtilities.UnexpectedValue(node.Parent.Kind()); } case SyntaxKind.ArrowExpressionClause: { SourceMemberMethodSymbol symbol = null; var exprDecl = (ArrowExpressionClauseSyntax)node; if (node.Parent is BasePropertyDeclarationSyntax) { symbol = GetDeclaredSymbol(exprDecl).GetSymbol<SourceMemberMethodSymbol>(); } else { // Don't throw, just use for the assert ExceptionUtilities.UnexpectedValue(node.Parent); } ExecutableCodeBinder binder = symbol?.TryGetBodyBinder(_binderFactory, this.IgnoresAccessibility); if (binder == null) { return null; } return MethodBodySemanticModel.Create(this, symbol, new MethodBodySemanticModel.InitialState(exprDecl, binder: binder)); } case SyntaxKind.GlobalStatement: { var parent = node.Parent; // TODO (tomat): handle misplaced global statements if (parent.Kind() == SyntaxKind.CompilationUnit && !this.IsRegularCSharp && (object)_compilation.ScriptClass != null) { var scriptInitializer = _compilation.ScriptClass.GetScriptInitializer(); Debug.Assert((object)scriptInitializer != null); if ((object)scriptInitializer == null) { return null; } // Share labels across all global statements. if (_globalStatementLabels == null) { Interlocked.CompareExchange(ref _globalStatementLabels, new ScriptLocalScopeBinder.Labels(scriptInitializer, (CompilationUnitSyntax)parent), null); } return MethodBodySemanticModel.Create( this, scriptInitializer, new MethodBodySemanticModel.InitialState(node, binder: new ExecutableCodeBinder(node, scriptInitializer, new ScriptLocalScopeBinder(_globalStatementLabels, defaultOuter())))); } } break; case SyntaxKind.Attribute: return CreateModelForAttribute(defaultOuter(), (AttributeSyntax)node, containingModel: null); } return null; MemberSemanticModel createMethodBodySemanticModel(CSharpSyntaxNode memberDecl, SourceMemberMethodSymbol symbol) { ExecutableCodeBinder binder = symbol?.TryGetBodyBinder(_binderFactory, this.IgnoresAccessibility); if (binder == null) { return null; } return MethodBodySemanticModel.Create(this, symbol, new MethodBodySemanticModel.InitialState(memberDecl, binder: binder)); } } private SynthesizedRecordConstructor TryGetSynthesizedRecordConstructor(RecordDeclarationSyntax node) { NamedTypeSymbol recordType = GetDeclaredType(node); var symbol = recordType.GetMembersUnordered().OfType<SynthesizedRecordConstructor>().SingleOrDefault(); if (symbol?.SyntaxRef.SyntaxTree != node.SyntaxTree || symbol.GetSyntax() != node) { return null; } return symbol; } private AttributeSemanticModel CreateModelForAttribute(Binder enclosingBinder, AttributeSyntax attribute, MemberSemanticModel containingModel) { AliasSymbol aliasOpt; var attributeType = (NamedTypeSymbol)enclosingBinder.BindType(attribute.Name, BindingDiagnosticBag.Discarded, out aliasOpt).Type; return AttributeSemanticModel.Create( this, attribute, attributeType, aliasOpt, enclosingBinder.WithAdditionalFlags(BinderFlags.AttributeArgument), containingModel?.GetRemappedSymbols()); } private FieldSymbol GetDeclaredFieldSymbol(VariableDeclaratorSyntax variableDecl) { var declaredSymbol = GetDeclaredSymbol(variableDecl); if ((object)declaredSymbol != null) { switch (variableDecl.Parent.Parent.Kind()) { case SyntaxKind.FieldDeclaration: return declaredSymbol.GetSymbol<FieldSymbol>(); case SyntaxKind.EventFieldDeclaration: return (declaredSymbol.GetSymbol<EventSymbol>()).AssociatedField; } } return null; } private Binder GetFieldOrPropertyInitializerBinder(FieldSymbol symbol, Binder outer, EqualsValueClauseSyntax initializer) { // NOTE: checking for a containing script class is sufficient, but the regular C# test is quick and easy. outer = outer.GetFieldInitializerBinder(symbol, suppressBinderFlagsFieldInitializer: !this.IsRegularCSharp && symbol.ContainingType.IsScriptClass); if (initializer != null) { outer = new ExecutableCodeBinder(initializer, symbol, outer); } return outer; } private static bool IsMemberDeclaration(CSharpSyntaxNode node) { return (node is MemberDeclarationSyntax) || (node is AccessorDeclarationSyntax) || (node.Kind() == SyntaxKind.Attribute) || (node.Kind() == SyntaxKind.Parameter); } private bool IsRegularCSharp { get { return this.SyntaxTree.Options.Kind == SourceCodeKind.Regular; } } #region "GetDeclaredSymbol overloads for MemberDeclarationSyntax and its subtypes" /// <inheritdoc/> public override INamespaceSymbol GetDeclaredSymbol(NamespaceDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); return GetDeclaredNamespace(declarationSyntax).GetPublicSymbol(); } /// <inheritdoc/> public override INamespaceSymbol GetDeclaredSymbol(FileScopedNamespaceDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default) { CheckSyntaxNode(declarationSyntax); return GetDeclaredNamespace(declarationSyntax).GetPublicSymbol(); } private NamespaceSymbol GetDeclaredNamespace(BaseNamespaceDeclarationSyntax declarationSyntax) { Debug.Assert(declarationSyntax != null); NamespaceOrTypeSymbol container; if (declarationSyntax.Parent.Kind() == SyntaxKind.CompilationUnit) { container = _compilation.Assembly.GlobalNamespace; } else { container = GetDeclaredNamespaceOrType(declarationSyntax.Parent); } Debug.Assert((object)container != null); // We should get a namespace symbol since we match the symbol location with a namespace declaration syntax location. var symbol = (NamespaceSymbol)GetDeclaredMember(container, declarationSyntax.Span, declarationSyntax.Name); Debug.Assert((object)symbol != null); // Map to compilation-scoped namespace (Roslyn bug 9538) symbol = _compilation.GetCompilationNamespace(symbol); Debug.Assert((object)symbol != null); return symbol; } /// <summary> /// Given a type declaration, get the corresponding type symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a type.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The type symbol that was declared.</returns> /// <remarks> /// NOTE: We have no GetDeclaredSymbol overloads for subtypes of BaseTypeDeclarationSyntax as all of them return a NamedTypeSymbol. /// </remarks> public override INamedTypeSymbol GetDeclaredSymbol(BaseTypeDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); return GetDeclaredType(declarationSyntax).GetPublicSymbol(); } /// <summary> /// Given a delegate declaration, get the corresponding type symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a delegate.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The type symbol that was declared.</returns> public override INamedTypeSymbol GetDeclaredSymbol(DelegateDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); return GetDeclaredType(declarationSyntax).GetPublicSymbol(); } private NamedTypeSymbol GetDeclaredType(BaseTypeDeclarationSyntax declarationSyntax) { Debug.Assert(declarationSyntax != null); var name = declarationSyntax.Identifier.ValueText; return GetDeclaredNamedType(declarationSyntax, name); } private NamedTypeSymbol GetDeclaredType(DelegateDeclarationSyntax declarationSyntax) { Debug.Assert(declarationSyntax != null); var name = declarationSyntax.Identifier.ValueText; return GetDeclaredNamedType(declarationSyntax, name); } private NamedTypeSymbol GetDeclaredNamedType(CSharpSyntaxNode declarationSyntax, string name) { Debug.Assert(declarationSyntax != null); var container = GetDeclaredTypeMemberContainer(declarationSyntax); Debug.Assert((object)container != null); // try cast as we might get a non-type in error recovery scenarios: return GetDeclaredMember(container, declarationSyntax.Span, name) as NamedTypeSymbol; } private NamespaceOrTypeSymbol GetDeclaredNamespaceOrType(CSharpSyntaxNode declarationSyntax) { var namespaceDeclarationSyntax = declarationSyntax as BaseNamespaceDeclarationSyntax; if (namespaceDeclarationSyntax != null) { return GetDeclaredNamespace(namespaceDeclarationSyntax); } var typeDeclarationSyntax = declarationSyntax as BaseTypeDeclarationSyntax; if (typeDeclarationSyntax != null) { return GetDeclaredType(typeDeclarationSyntax); } var delegateDeclarationSyntax = declarationSyntax as DelegateDeclarationSyntax; if (delegateDeclarationSyntax != null) { return GetDeclaredType(delegateDeclarationSyntax); } return null; } /// <summary> /// Given a member declaration syntax, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a member.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> /// <remarks> /// NOTE: We have no GetDeclaredSymbol overloads for following subtypes of MemberDeclarationSyntax: /// NOTE: (1) GlobalStatementSyntax as they don't declare any symbols. /// NOTE: (2) IncompleteMemberSyntax as there are no symbols for incomplete members. /// NOTE: (3) BaseFieldDeclarationSyntax or its subtypes as these declarations can contain multiple variable declarators. /// NOTE: GetDeclaredSymbol should be called on the variable declarators directly. /// </remarks> public override ISymbol GetDeclaredSymbol(MemberDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); switch (declarationSyntax.Kind()) { // Few subtypes of MemberDeclarationSyntax don't declare any symbols or declare multiple symbols, return null for these cases. case SyntaxKind.GlobalStatement: // Global statements don't declare anything, even though they inherit from MemberDeclarationSyntax. return null; case SyntaxKind.IncompleteMember: // Incomplete members don't declare any symbols. return null; case SyntaxKind.EventFieldDeclaration: case SyntaxKind.FieldDeclaration: // these declarations can contain multiple variable declarators. GetDeclaredSymbol should be called on them directly. return null; default: return (GetDeclaredNamespaceOrType(declarationSyntax) ?? GetDeclaredMemberSymbol(declarationSyntax)).GetPublicSymbol(); } } public override IMethodSymbol GetDeclaredSymbol(CompilationUnitSyntax declarationSyntax, CancellationToken cancellationToken = default) { CheckSyntaxNode(declarationSyntax); return SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(Compilation, declarationSyntax, fallbackToMainEntryPoint: false).GetPublicSymbol(); } /// <summary> /// Given a local function declaration syntax, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a member.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override ISymbol GetDeclaredSymbol(LocalFunctionStatementSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); return this.GetMemberModel(declarationSyntax)?.GetDeclaredSymbol(declarationSyntax, cancellationToken); } /// <summary> /// Given a enum member declaration, get the corresponding field symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares an enum member.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override IFieldSymbol GetDeclaredSymbol(EnumMemberDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { return ((FieldSymbol)GetDeclaredMemberSymbol(declarationSyntax)).GetPublicSymbol(); } /// <summary> /// Given a base method declaration syntax, get the corresponding method symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a method.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> /// <remarks> /// NOTE: We have no GetDeclaredSymbol overloads for subtypes of BaseMethodDeclarationSyntax as all of them return a MethodSymbol. /// </remarks> public override IMethodSymbol GetDeclaredSymbol(BaseMethodDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { return ((MethodSymbol)GetDeclaredMemberSymbol(declarationSyntax)).GetPublicSymbol(); } #region "GetDeclaredSymbol overloads for BasePropertyDeclarationSyntax and its subtypes" /// <summary> /// Given a syntax node that declares a property, indexer or an event, get the corresponding declared symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a property, indexer or an event.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override ISymbol GetDeclaredSymbol(BasePropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { return GetDeclaredMemberSymbol(declarationSyntax).GetPublicSymbol(); } /// <summary> /// Given a syntax node that declares a property, get the corresponding declared symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a property, indexer or an event.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override IPropertySymbol GetDeclaredSymbol(PropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { return ((PropertySymbol)GetDeclaredMemberSymbol(declarationSyntax)).GetPublicSymbol(); } /// <summary> /// Given a syntax node that declares an indexer, get the corresponding declared symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares an indexer.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override IPropertySymbol GetDeclaredSymbol(IndexerDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { return ((PropertySymbol)GetDeclaredMemberSymbol(declarationSyntax)).GetPublicSymbol(); } /// <summary> /// Given a syntax node that declares a (custom) event, get the corresponding event symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a event.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override IEventSymbol GetDeclaredSymbol(EventDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { return ((EventSymbol)GetDeclaredMemberSymbol(declarationSyntax)).GetPublicSymbol(); } #endregion #endregion /// <summary> /// Given a syntax node that declares a property or member accessor, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares an accessor.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override IMethodSymbol GetDeclaredSymbol(AccessorDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); if (declarationSyntax.Kind() == SyntaxKind.UnknownAccessorDeclaration) { // this is not a real accessor, so we shouldn't return anything. return null; } var propertyOrEventDecl = declarationSyntax.Parent.Parent; switch (propertyOrEventDecl.Kind()) { case SyntaxKind.PropertyDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.EventDeclaration: case SyntaxKind.EventFieldDeclaration: // NOTE: it's an error for field-like events to have accessors, // but we want to bind them anyway for error tolerance reasons. var container = GetDeclaredTypeMemberContainer(propertyOrEventDecl); Debug.Assert((object)container != null); Debug.Assert(declarationSyntax.Keyword.Kind() != SyntaxKind.IdentifierToken); return (this.GetDeclaredMember(container, declarationSyntax.Span) as MethodSymbol).GetPublicSymbol(); default: throw ExceptionUtilities.UnexpectedValue(propertyOrEventDecl.Kind()); } } public override IMethodSymbol GetDeclaredSymbol(ArrowExpressionClauseSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); var containingMemberSyntax = declarationSyntax.Parent; NamespaceOrTypeSymbol container; switch (containingMemberSyntax.Kind()) { case SyntaxKind.PropertyDeclaration: case SyntaxKind.IndexerDeclaration: container = GetDeclaredTypeMemberContainer(containingMemberSyntax); Debug.Assert((object)container != null); // We are looking for the SourcePropertyAccessorSymbol here, // not the SourcePropertySymbol, so use declarationSyntax // to exclude the property symbol from being retrieved. return (this.GetDeclaredMember(container, declarationSyntax.Span) as MethodSymbol).GetPublicSymbol(); default: // Don't throw, use only for the assert ExceptionUtilities.UnexpectedValue(containingMemberSyntax.Kind()); return null; } } private string GetDeclarationName(CSharpSyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.MethodDeclaration: { var methodDecl = (MethodDeclarationSyntax)declaration; return GetDeclarationName(declaration, methodDecl.ExplicitInterfaceSpecifier, methodDecl.Identifier.ValueText); } case SyntaxKind.PropertyDeclaration: { var propertyDecl = (PropertyDeclarationSyntax)declaration; return GetDeclarationName(declaration, propertyDecl.ExplicitInterfaceSpecifier, propertyDecl.Identifier.ValueText); } case SyntaxKind.IndexerDeclaration: { var indexerDecl = (IndexerDeclarationSyntax)declaration; return GetDeclarationName(declaration, indexerDecl.ExplicitInterfaceSpecifier, WellKnownMemberNames.Indexer); } case SyntaxKind.EventDeclaration: { var eventDecl = (EventDeclarationSyntax)declaration; return GetDeclarationName(declaration, eventDecl.ExplicitInterfaceSpecifier, eventDecl.Identifier.ValueText); } case SyntaxKind.DelegateDeclaration: return ((DelegateDeclarationSyntax)declaration).Identifier.ValueText; case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.ClassDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.RecordDeclaration: return ((BaseTypeDeclarationSyntax)declaration).Identifier.ValueText; case SyntaxKind.VariableDeclarator: return ((VariableDeclaratorSyntax)declaration).Identifier.ValueText; case SyntaxKind.EnumMemberDeclaration: return ((EnumMemberDeclarationSyntax)declaration).Identifier.ValueText; case SyntaxKind.DestructorDeclaration: return WellKnownMemberNames.DestructorName; case SyntaxKind.ConstructorDeclaration: if (((ConstructorDeclarationSyntax)declaration).Modifiers.Any(SyntaxKind.StaticKeyword)) { return WellKnownMemberNames.StaticConstructorName; } else { return WellKnownMemberNames.InstanceConstructorName; } case SyntaxKind.OperatorDeclaration: { var operatorDecl = (OperatorDeclarationSyntax)declaration; return GetDeclarationName(declaration, operatorDecl.ExplicitInterfaceSpecifier, OperatorFacts.OperatorNameFromDeclaration(operatorDecl)); } case SyntaxKind.ConversionOperatorDeclaration: { var operatorDecl = (ConversionOperatorDeclarationSyntax)declaration; return GetDeclarationName(declaration, operatorDecl.ExplicitInterfaceSpecifier, OperatorFacts.OperatorNameFromDeclaration(operatorDecl)); } case SyntaxKind.EventFieldDeclaration: case SyntaxKind.FieldDeclaration: throw new ArgumentException(CSharpResources.InvalidGetDeclarationNameMultipleDeclarators); case SyntaxKind.IncompleteMember: // There is no name - that's why it's an incomplete member. return null; default: throw ExceptionUtilities.UnexpectedValue(declaration.Kind()); } } private string GetDeclarationName(CSharpSyntaxNode declaration, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierOpt, string memberName) { if (explicitInterfaceSpecifierOpt == null) { return memberName; } // For an explicit interface implementation, we actually have several options: // Option 1: do nothing - it will retry without the name // Option 2: detect explicit impl and return null // Option 3: get a binder and figure out the name // For now, we're going with Option 3 return ExplicitInterfaceHelpers.GetMemberName(_binderFactory.GetBinder(declaration), explicitInterfaceSpecifierOpt, memberName); } private Symbol GetDeclaredMember(NamespaceOrTypeSymbol container, TextSpan declarationSpan, NameSyntax name) { switch (name.Kind()) { case SyntaxKind.GenericName: case SyntaxKind.IdentifierName: return GetDeclaredMember(container, declarationSpan, ((SimpleNameSyntax)name).Identifier.ValueText); case SyntaxKind.QualifiedName: var qn = (QualifiedNameSyntax)name; var left = GetDeclaredMember(container, declarationSpan, qn.Left) as NamespaceOrTypeSymbol; Debug.Assert((object)left != null); return GetDeclaredMember(left, declarationSpan, qn.Right); case SyntaxKind.AliasQualifiedName: // this is not supposed to happen, but we allow for errors don't we! var an = (AliasQualifiedNameSyntax)name; return GetDeclaredMember(container, declarationSpan, an.Name); default: throw ExceptionUtilities.UnexpectedValue(name.Kind()); } } /// <summary> /// Finds the member in the containing symbol which is inside the given declaration span. /// </summary> private Symbol GetDeclaredMember(NamespaceOrTypeSymbol container, TextSpan declarationSpan, string name = null) { if ((object)container == null) { return null; } // look for any member with same declaration location var collection = name != null ? container.GetMembers(name) : container.GetMembersUnordered(); Symbol zeroWidthMatch = null; foreach (var symbol in collection) { var namedType = symbol as ImplicitNamedTypeSymbol; if ((object)namedType != null && namedType.IsImplicitClass) { // look inside wrapper around illegally placed members in namespaces var result = GetDeclaredMember(namedType, declarationSpan, name); if ((object)result != null) { return result; } } foreach (var loc in symbol.Locations) { if (loc.IsInSource && loc.SourceTree == this.SyntaxTree && declarationSpan.Contains(loc.SourceSpan)) { if (loc.SourceSpan.IsEmpty && loc.SourceSpan.End == declarationSpan.Start) { // exclude decls created via syntax recovery zeroWidthMatch = symbol; } else { return symbol; } } } // Handle the case of the implementation of a partial method. var partial = symbol.Kind == SymbolKind.Method ? ((MethodSymbol)symbol).PartialImplementationPart : null; if ((object)partial != null) { var loc = partial.Locations[0]; if (loc.IsInSource && loc.SourceTree == this.SyntaxTree && declarationSpan.Contains(loc.SourceSpan)) { return partial; } } } // If we didn't find anything better than the symbol that matched because of syntax error recovery, then return that. // Otherwise, if there's a name, try again without a name. // Otherwise, give up. return zeroWidthMatch ?? (name != null ? GetDeclaredMember(container, declarationSpan) : null); } /// <summary> /// Given a variable declarator syntax, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a variable.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override ISymbol GetDeclaredSymbol(VariableDeclaratorSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); var field = declarationSyntax.Parent == null ? null : declarationSyntax.Parent.Parent as BaseFieldDeclarationSyntax; if (field != null) { var container = GetDeclaredTypeMemberContainer(field); Debug.Assert((object)container != null); var result = this.GetDeclaredMember(container, declarationSyntax.Span, declarationSyntax.Identifier.ValueText); Debug.Assert((object)result != null); return result.GetPublicSymbol(); } // Might be a local variable. var memberModel = this.GetMemberModel(declarationSyntax); return memberModel?.GetDeclaredSymbol(declarationSyntax, cancellationToken); } public override ISymbol GetDeclaredSymbol(SingleVariableDesignationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { // Might be a local variable. var memberModel = this.GetMemberModel(declarationSyntax); ISymbol local = memberModel?.GetDeclaredSymbol(declarationSyntax, cancellationToken); if (local != null) { return local; } // Might be a field Binder binder = GetEnclosingBinder(declarationSyntax.Position); return binder?.LookupDeclaredField(declarationSyntax).GetPublicSymbol(); } internal override LocalSymbol GetAdjustedLocalSymbol(SourceLocalSymbol originalSymbol) { var position = originalSymbol.IdentifierToken.SpanStart; return GetMemberModel(position)?.GetAdjustedLocalSymbol(originalSymbol) ?? originalSymbol; } /// <summary> /// Given a labeled statement syntax, get the corresponding label symbol. /// </summary> /// <param name="declarationSyntax">The syntax node of the labeled statement.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The label symbol for that label.</returns> public override ILabelSymbol GetDeclaredSymbol(LabeledStatementSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); var memberModel = this.GetMemberModel(declarationSyntax); return memberModel == null ? null : memberModel.GetDeclaredSymbol(declarationSyntax, cancellationToken); } /// <summary> /// Given a switch label syntax, get the corresponding label symbol. /// </summary> /// <param name="declarationSyntax">The syntax node of the switch label.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The label symbol for that label.</returns> public override ILabelSymbol GetDeclaredSymbol(SwitchLabelSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); var memberModel = this.GetMemberModel(declarationSyntax); return memberModel == null ? null : memberModel.GetDeclaredSymbol(declarationSyntax, cancellationToken); } /// <summary> /// Given a using declaration get the corresponding symbol for the using alias that was introduced. /// </summary> /// <param name="declarationSyntax"></param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The alias symbol that was declared.</returns> /// <remarks> /// If the using directive is an error because it attempts to introduce an alias for which an existing alias was /// previously declared in the same scope, the result is a newly-constructed AliasSymbol (i.e. not one from the /// symbol table). /// </remarks> public override IAliasSymbol GetDeclaredSymbol( UsingDirectiveSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); if (declarationSyntax.Alias == null) { return null; } Binder binder = _binderFactory.GetInNamespaceBinder(declarationSyntax.Parent); for (; binder != null; binder = binder.Next) { var usingAliases = binder.UsingAliases; if (!usingAliases.IsDefault) { foreach (var alias in usingAliases) { if (alias.Alias.Locations[0].SourceSpan == declarationSyntax.Alias.Name.Span) { return alias.Alias.GetPublicSymbol(); } } break; } } return null; } /// <summary> /// Given an extern alias declaration get the corresponding symbol for the alias that was introduced. /// </summary> /// <param name="declarationSyntax"></param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The alias symbol that was declared, or null if a duplicate alias symbol was declared.</returns> public override IAliasSymbol GetDeclaredSymbol(ExternAliasDirectiveSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); var binder = _binderFactory.GetInNamespaceBinder(declarationSyntax.Parent); for (; binder != null; binder = binder.Next) { var externAliases = binder.ExternAliases; if (!externAliases.IsDefault) { foreach (var alias in externAliases) { if (alias.Alias.Locations[0].SourceSpan == declarationSyntax.Identifier.Span) { return alias.Alias.GetPublicSymbol(); } } break; } } return null; } /// <summary> /// Given a base field declaration syntax, get the corresponding symbols. /// </summary> /// <param name="declarationSyntax">The syntax node that declares one or more fields or events.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The field symbols that were declared.</returns> internal override ImmutableArray<ISymbol> GetDeclaredSymbols(BaseFieldDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); var builder = new ArrayBuilder<ISymbol>(); foreach (var declarator in declarationSyntax.Declaration.Variables) { var field = this.GetDeclaredSymbol(declarator, cancellationToken) as ISymbol; if (field != null) { builder.Add(field); } } return builder.ToImmutableAndFree(); } private ParameterSymbol GetMethodParameterSymbol( ParameterSyntax parameter, CancellationToken cancellationToken) { Debug.Assert(parameter != null); var paramList = parameter.Parent as ParameterListSyntax; if (paramList == null) { return null; } var memberDecl = paramList.Parent as MemberDeclarationSyntax; if (memberDecl == null) { return null; } MethodSymbol method; if (memberDecl is RecordDeclarationSyntax recordDecl && recordDecl.ParameterList == paramList) { method = TryGetSynthesizedRecordConstructor(recordDecl); } else { method = (GetDeclaredSymbol(memberDecl, cancellationToken) as IMethodSymbol).GetSymbol(); } if ((object)method == null) { return null; } return GetParameterSymbol(method.Parameters, parameter, cancellationToken) ?? ((object)method.PartialDefinitionPart == null ? null : GetParameterSymbol(method.PartialDefinitionPart.Parameters, parameter, cancellationToken)); } private ParameterSymbol GetIndexerParameterSymbol( ParameterSyntax parameter, CancellationToken cancellationToken) { Debug.Assert(parameter != null); var paramList = parameter.Parent as BracketedParameterListSyntax; if (paramList == null) { return null; } var memberDecl = paramList.Parent as MemberDeclarationSyntax; if (memberDecl == null) { return null; } var property = (GetDeclaredSymbol(memberDecl, cancellationToken) as IPropertySymbol).GetSymbol(); if ((object)property == null) { return null; } return GetParameterSymbol(property.Parameters, parameter, cancellationToken); } private ParameterSymbol GetDelegateParameterSymbol( ParameterSyntax parameter, CancellationToken cancellationToken) { Debug.Assert(parameter != null); var paramList = parameter.Parent as ParameterListSyntax; if (paramList == null) { return null; } var memberDecl = paramList.Parent as DelegateDeclarationSyntax; if (memberDecl == null) { return null; } var delegateType = (GetDeclaredSymbol(memberDecl, cancellationToken) as INamedTypeSymbol).GetSymbol(); if ((object)delegateType == null) { return null; } var delegateInvoke = delegateType.DelegateInvokeMethod; if ((object)delegateInvoke == null || delegateInvoke.HasUseSiteError) { return null; } return GetParameterSymbol(delegateInvoke.Parameters, parameter, cancellationToken); } /// <summary> /// Given a parameter declaration syntax node, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a parameter.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The parameter that was declared.</returns> public override IParameterSymbol GetDeclaredSymbol(ParameterSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); MemberSemanticModel memberModel = this.GetMemberModel(declarationSyntax); if (memberModel != null) { // Could be parameter of lambda. return memberModel.GetDeclaredSymbol(declarationSyntax, cancellationToken); } return GetDeclaredNonLambdaParameterSymbol(declarationSyntax, cancellationToken).GetPublicSymbol(); } private ParameterSymbol GetDeclaredNonLambdaParameterSymbol(ParameterSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { return GetMethodParameterSymbol(declarationSyntax, cancellationToken) ?? GetIndexerParameterSymbol(declarationSyntax, cancellationToken) ?? GetDelegateParameterSymbol(declarationSyntax, cancellationToken); } /// <summary> /// Given a type parameter declaration (field or method), get the corresponding symbol /// </summary> /// <param name="typeParameter"></param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> public override ITypeParameterSymbol GetDeclaredSymbol(TypeParameterSyntax typeParameter, CancellationToken cancellationToken = default(CancellationToken)) { if (typeParameter == null) { throw new ArgumentNullException(nameof(typeParameter)); } if (!IsInTree(typeParameter)) { throw new ArgumentException("typeParameter not within tree"); } if (typeParameter.Parent is TypeParameterListSyntax typeParamList) { ISymbol parameterizedSymbol = null; switch (typeParamList.Parent) { case MemberDeclarationSyntax memberDecl: parameterizedSymbol = GetDeclaredSymbol(memberDecl, cancellationToken); break; case LocalFunctionStatementSyntax localDecl: parameterizedSymbol = GetDeclaredSymbol(localDecl, cancellationToken); break; default: throw ExceptionUtilities.UnexpectedValue(typeParameter.Parent.Kind()); } switch (parameterizedSymbol.GetSymbol()) { case NamedTypeSymbol typeSymbol: return this.GetTypeParameterSymbol(typeSymbol.TypeParameters, typeParameter).GetPublicSymbol(); case MethodSymbol methodSymbol: return (this.GetTypeParameterSymbol(methodSymbol.TypeParameters, typeParameter) ?? ((object)methodSymbol.PartialDefinitionPart == null ? null : this.GetTypeParameterSymbol(methodSymbol.PartialDefinitionPart.TypeParameters, typeParameter))).GetPublicSymbol(); } } return null; } private TypeParameterSymbol GetTypeParameterSymbol(ImmutableArray<TypeParameterSymbol> parameters, TypeParameterSyntax parameter) { foreach (var symbol in parameters) { foreach (var location in symbol.Locations) { if (location.SourceTree == this.SyntaxTree && parameter.Span.Contains(location.SourceSpan)) { return symbol; } } } return null; } public override ControlFlowAnalysis AnalyzeControlFlow(StatementSyntax firstStatement, StatementSyntax lastStatement) { ValidateStatementRange(firstStatement, lastStatement); var context = RegionAnalysisContext(firstStatement, lastStatement); var result = new CSharpControlFlowAnalysis(context); return result; } private void ValidateStatementRange(StatementSyntax firstStatement, StatementSyntax lastStatement) { if (firstStatement == null) { throw new ArgumentNullException(nameof(firstStatement)); } if (lastStatement == null) { throw new ArgumentNullException(nameof(lastStatement)); } if (!IsInTree(firstStatement)) { throw new ArgumentException("statements not within tree"); } // Global statements don't have their parent in common, but should belong to the same compilation unit bool isGlobalStatement = firstStatement.Parent is GlobalStatementSyntax; if (isGlobalStatement && (lastStatement.Parent is not GlobalStatementSyntax || firstStatement.Parent.Parent != lastStatement.Parent.Parent)) { throw new ArgumentException("global statements not within the same compilation unit"); } // Non-global statements, the parents should be the same if (!isGlobalStatement && (firstStatement.Parent == null || firstStatement.Parent != lastStatement.Parent)) { throw new ArgumentException("statements not within the same statement list"); } if (firstStatement.SpanStart > lastStatement.SpanStart) { throw new ArgumentException("first statement does not precede last statement"); } } public override DataFlowAnalysis AnalyzeDataFlow(ExpressionSyntax expression) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } if (!IsInTree(expression)) { throw new ArgumentException("expression not within tree"); } var context = RegionAnalysisContext(expression); var result = new CSharpDataFlowAnalysis(context); return result; } public override DataFlowAnalysis AnalyzeDataFlow(StatementSyntax firstStatement, StatementSyntax lastStatement) { ValidateStatementRange(firstStatement, lastStatement); var context = RegionAnalysisContext(firstStatement, lastStatement); var result = new CSharpDataFlowAnalysis(context); return result; } private static BoundNode GetBoundRoot(MemberSemanticModel memberModel, out Symbol member) { member = memberModel.MemberSymbol; return memberModel.GetBoundRoot(); } private NamespaceOrTypeSymbol GetDeclaredTypeMemberContainer(CSharpSyntaxNode memberDeclaration) { if (memberDeclaration.Parent.Kind() == SyntaxKind.CompilationUnit) { // top-level namespace: if (memberDeclaration.Kind() is SyntaxKind.NamespaceDeclaration or SyntaxKind.FileScopedNamespaceDeclaration) { return _compilation.Assembly.GlobalNamespace; } // top-level members in script or interactive code: if (this.SyntaxTree.Options.Kind != SourceCodeKind.Regular) { return this.Compilation.ScriptClass; } // top-level type in an explicitly declared namespace: if (SyntaxFacts.IsTypeDeclaration(memberDeclaration.Kind())) { return _compilation.Assembly.GlobalNamespace; } // other top-level members: return _compilation.Assembly.GlobalNamespace.ImplicitType; } var container = GetDeclaredNamespaceOrType(memberDeclaration.Parent); Debug.Assert((object)container != null); // member in a type: if (!container.IsNamespace) { return container; } // a namespace or a type in an explicitly declared namespace: if (memberDeclaration.Kind() is SyntaxKind.NamespaceDeclaration or SyntaxKind.FileScopedNamespaceDeclaration || SyntaxFacts.IsTypeDeclaration(memberDeclaration.Kind())) { return container; } // another member in a namespace: return ((NamespaceSymbol)container).ImplicitType; } private Symbol GetDeclaredMemberSymbol(CSharpSyntaxNode declarationSyntax) { CheckSyntaxNode(declarationSyntax); var container = GetDeclaredTypeMemberContainer(declarationSyntax); var name = GetDeclarationName(declarationSyntax); return this.GetDeclaredMember(container, declarationSyntax.Span, name); } public override AwaitExpressionInfo GetAwaitExpressionInfo(AwaitExpressionSyntax node) { MemberSemanticModel memberModel = GetMemberModel(node); return memberModel == null ? default(AwaitExpressionInfo) : memberModel.GetAwaitExpressionInfo(node); } public override ForEachStatementInfo GetForEachStatementInfo(ForEachStatementSyntax node) { MemberSemanticModel memberModel = GetMemberModel(node); return memberModel == null ? default(ForEachStatementInfo) : memberModel.GetForEachStatementInfo(node); } public override ForEachStatementInfo GetForEachStatementInfo(CommonForEachStatementSyntax node) { MemberSemanticModel memberModel = GetMemberModel(node); return memberModel == null ? default(ForEachStatementInfo) : memberModel.GetForEachStatementInfo(node); } public override DeconstructionInfo GetDeconstructionInfo(AssignmentExpressionSyntax node) { MemberSemanticModel memberModel = GetMemberModel(node); return memberModel?.GetDeconstructionInfo(node) ?? default; } public override DeconstructionInfo GetDeconstructionInfo(ForEachVariableStatementSyntax node) { MemberSemanticModel memberModel = GetMemberModel(node); return memberModel?.GetDeconstructionInfo(node) ?? default; } internal override Symbol RemapSymbolIfNecessaryCore(Symbol symbol) { Debug.Assert(symbol is LocalSymbol or ParameterSymbol or MethodSymbol { MethodKind: MethodKind.LambdaMethod }); if (symbol.Locations.IsDefaultOrEmpty) { return symbol; } var location = symbol.Locations[0]; // The symbol may be from a distinct syntax tree - perhaps the // symbol was returned from LookupSymbols() for instance. if (location.SourceTree != this.SyntaxTree) { return symbol; } var position = CheckAndAdjustPosition(location.SourceSpan.Start); var memberModel = GetMemberModel(position); return memberModel?.RemapSymbolIfNecessaryCore(symbol) ?? symbol; } internal override Func<SyntaxNode, bool> GetSyntaxNodesToAnalyzeFilter(SyntaxNode declaredNode, ISymbol declaredSymbol) { switch (declaredNode) { case CompilationUnitSyntax unit when SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(Compilation, unit, fallbackToMainEntryPoint: false) is SynthesizedSimpleProgramEntryPointSymbol entryPoint: switch (declaredSymbol.Kind) { case SymbolKind.Namespace: Debug.Assert(((INamespaceSymbol)declaredSymbol).IsGlobalNamespace); // Do not include top level global statements into a global namespace return (node) => node.Kind() != SyntaxKind.GlobalStatement || node.Parent != unit; case SymbolKind.Method: Debug.Assert((object)declaredSymbol.GetSymbol() == (object)entryPoint); // Include only global statements at the top level return (node) => node.Parent != unit || node.Kind() == SyntaxKind.GlobalStatement; case SymbolKind.NamedType: Debug.Assert((object)declaredSymbol.GetSymbol() == (object)entryPoint.ContainingSymbol); return (node) => false; default: ExceptionUtilities.UnexpectedValue(declaredSymbol.Kind); break; } break; case RecordDeclarationSyntax recordDeclaration when TryGetSynthesizedRecordConstructor(recordDeclaration) is SynthesizedRecordConstructor ctor: if (recordDeclaration.IsKind(SyntaxKind.RecordDeclaration)) { switch (declaredSymbol.Kind) { case SymbolKind.Method: Debug.Assert((object)declaredSymbol.GetSymbol() == (object)ctor); return (node) => { // Accept only nodes that either match, or above/below of a 'parameter list'/'base arguments list'. if (node.Parent == recordDeclaration) { return node == recordDeclaration.ParameterList || node == recordDeclaration.BaseList; } else if (node.Parent is BaseListSyntax baseList) { return node == recordDeclaration.PrimaryConstructorBaseTypeIfClass; } else if (node.Parent is PrimaryConstructorBaseTypeSyntax baseType && baseType == recordDeclaration.PrimaryConstructorBaseTypeIfClass) { return node == baseType.ArgumentList; } return true; }; case SymbolKind.NamedType: Debug.Assert((object)declaredSymbol.GetSymbol() == (object)ctor.ContainingSymbol); // Accept nodes that do not match a 'parameter list'/'base arguments list'. return (node) => node != recordDeclaration.ParameterList && !(node.Kind() == SyntaxKind.ArgumentList && node == recordDeclaration.PrimaryConstructorBaseTypeIfClass?.ArgumentList); default: ExceptionUtilities.UnexpectedValue(declaredSymbol.Kind); break; } } else { switch (declaredSymbol.Kind) { case SymbolKind.Method: Debug.Assert((object)declaredSymbol.GetSymbol() == (object)ctor); return (node) => { // Accept only nodes that either match, or above/below of a 'parameter list'. if (node.Parent == recordDeclaration) { return node == recordDeclaration.ParameterList; } return true; }; case SymbolKind.NamedType: Debug.Assert((object)declaredSymbol.GetSymbol() == (object)ctor.ContainingSymbol); // Accept nodes that do not match a 'parameter list'. return (node) => node != recordDeclaration.ParameterList; default: ExceptionUtilities.UnexpectedValue(declaredSymbol.Kind); break; } } break; case PrimaryConstructorBaseTypeSyntax { Parent: BaseListSyntax { Parent: RecordDeclarationSyntax recordDeclaration } } baseType when recordDeclaration.PrimaryConstructorBaseTypeIfClass == declaredNode && TryGetSynthesizedRecordConstructor(recordDeclaration) is SynthesizedRecordConstructor ctor: if ((object)declaredSymbol.GetSymbol() == (object)ctor) { // Only 'base arguments list' or nodes below it return (node) => node != baseType.Type; } break; case ParameterSyntax param when declaredSymbol.Kind == SymbolKind.Property && param.Parent?.Parent is RecordDeclarationSyntax recordDeclaration && recordDeclaration.ParameterList == param.Parent: Debug.Assert(declaredSymbol.GetSymbol() is SynthesizedRecordPropertySymbol); return (node) => false; } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Allows asking semantic questions about any node in a SyntaxTree within a Compilation. /// </summary> internal partial class SyntaxTreeSemanticModel : CSharpSemanticModel { private readonly CSharpCompilation _compilation; private readonly SyntaxTree _syntaxTree; /// <summary> /// Note, the name of this field could be somewhat confusing because it is also /// used to store models for attributes and default parameter values, which are /// not members. /// </summary> private ImmutableDictionary<CSharpSyntaxNode, MemberSemanticModel> _memberModels = ImmutableDictionary<CSharpSyntaxNode, MemberSemanticModel>.Empty; private readonly BinderFactory _binderFactory; private Func<CSharpSyntaxNode, MemberSemanticModel> _createMemberModelFunction; private readonly bool _ignoresAccessibility; private ScriptLocalScopeBinder.Labels _globalStatementLabels; private static readonly Func<CSharpSyntaxNode, bool> s_isMemberDeclarationFunction = IsMemberDeclaration; #nullable enable internal SyntaxTreeSemanticModel(CSharpCompilation compilation, SyntaxTree syntaxTree, bool ignoreAccessibility = false) { _compilation = compilation; _syntaxTree = syntaxTree; _ignoresAccessibility = ignoreAccessibility; if (!this.Compilation.SyntaxTrees.Contains(syntaxTree)) { throw new ArgumentOutOfRangeException(nameof(syntaxTree), CSharpResources.TreeNotPartOfCompilation); } _binderFactory = compilation.GetBinderFactory(SyntaxTree, ignoreAccessibility); } internal SyntaxTreeSemanticModel(CSharpCompilation parentCompilation, SyntaxTree parentSyntaxTree, SyntaxTree speculatedSyntaxTree) { _compilation = parentCompilation; _syntaxTree = speculatedSyntaxTree; _binderFactory = _compilation.GetBinderFactory(parentSyntaxTree); } /// <summary> /// The compilation this object was obtained from. /// </summary> public override CSharpCompilation Compilation { get { return _compilation; } } /// <summary> /// The root node of the syntax tree that this object is associated with. /// </summary> internal override CSharpSyntaxNode Root { get { return (CSharpSyntaxNode)_syntaxTree.GetRoot(); } } /// <summary> /// The SyntaxTree that this object is associated with. /// </summary> public override SyntaxTree SyntaxTree { get { return _syntaxTree; } } /// <summary> /// Returns true if this is a SemanticModel that ignores accessibility rules when answering semantic questions. /// </summary> public override bool IgnoresAccessibility { get { return _ignoresAccessibility; } } private void VerifySpanForGetDiagnostics(TextSpan? span) { if (span.HasValue && !this.Root.FullSpan.Contains(span.Value)) { throw new ArgumentException("span"); } } public override ImmutableArray<Diagnostic> GetSyntaxDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)) { VerifySpanForGetDiagnostics(span); return Compilation.GetDiagnosticsForSyntaxTree( CompilationStage.Parse, this.SyntaxTree, span, includeEarlierStages: false, cancellationToken: cancellationToken); } public override ImmutableArray<Diagnostic> GetDeclarationDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)) { VerifySpanForGetDiagnostics(span); return Compilation.GetDiagnosticsForSyntaxTree( CompilationStage.Declare, this.SyntaxTree, span, includeEarlierStages: false, cancellationToken: cancellationToken); } public override ImmutableArray<Diagnostic> GetMethodBodyDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)) { VerifySpanForGetDiagnostics(span); return Compilation.GetDiagnosticsForSyntaxTree( CompilationStage.Compile, this.SyntaxTree, span, includeEarlierStages: false, cancellationToken: cancellationToken); } public override ImmutableArray<Diagnostic> GetDiagnostics(TextSpan? span = null, CancellationToken cancellationToken = default(CancellationToken)) { VerifySpanForGetDiagnostics(span); return Compilation.GetDiagnosticsForSyntaxTree( CompilationStage.Compile, this.SyntaxTree, span, includeEarlierStages: true, cancellationToken: cancellationToken); } #nullable disable /// <summary> /// Gets the enclosing binder associated with the node /// </summary> /// <param name="position"></param> /// <returns></returns> internal override Binder GetEnclosingBinderInternal(int position) { AssertPositionAdjusted(position); SyntaxToken token = this.Root.FindTokenIncludingCrefAndNameAttributes(position); // If we're before the start of the first token, just return // the binder for the compilation unit. if (position == 0 && position != token.SpanStart) { return _binderFactory.GetBinder(this.Root, position).WithAdditionalFlags(GetSemanticModelBinderFlags()); } MemberSemanticModel memberModel = GetMemberModel(position); if (memberModel != null) { return memberModel.GetEnclosingBinder(position); } return _binderFactory.GetBinder((CSharpSyntaxNode)token.Parent, position).WithAdditionalFlags(GetSemanticModelBinderFlags()); } internal override IOperation GetOperationWorker(CSharpSyntaxNode node, CancellationToken cancellationToken) { MemberSemanticModel model; switch (node) { case ConstructorDeclarationSyntax constructor: model = (constructor.HasAnyBody() || constructor.Initializer != null) ? GetOrAddModel(node) : null; break; case BaseMethodDeclarationSyntax method: model = method.HasAnyBody() ? GetOrAddModel(node) : null; break; case AccessorDeclarationSyntax accessor: model = (accessor.Body != null || accessor.ExpressionBody != null) ? GetOrAddModel(node) : null; break; case RecordDeclarationSyntax { ParameterList: { }, PrimaryConstructorBaseTypeIfClass: { } } recordDeclaration when TryGetSynthesizedRecordConstructor(recordDeclaration) is SynthesizedRecordConstructor: model = GetOrAddModel(recordDeclaration); break; default: model = this.GetMemberModel(node); break; } if (model != null) { return model.GetOperationWorker(node, cancellationToken); } else { return null; } } internal override SymbolInfo GetSymbolInfoWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)) { ValidateSymbolInfoOptions(options); // in case this is right side of a qualified name or member access (or part of a cref) node = SyntaxFactory.GetStandaloneNode(node); var model = this.GetMemberModel(node); SymbolInfo result; XmlNameAttributeSyntax attrSyntax; CrefSyntax crefSyntax; if (model != null) { // Expression occurs in an executable code (method body or initializer) context. Use that // model to get the information. result = model.GetSymbolInfoWorker(node, options, cancellationToken); // If we didn't get anything and were in Type/Namespace only context, let's bind normally and see // if any symbol comes out. if ((object)result.Symbol == null && result.CandidateReason == CandidateReason.None && node is ExpressionSyntax && SyntaxFacts.IsInNamespaceOrTypeContext((ExpressionSyntax)node)) { var binder = this.GetEnclosingBinder(GetAdjustedNodePosition(node)); if (binder != null) { // Wrap the binder in a LocalScopeBinder because Binder.BindExpression assumes there // will be one in the binder chain and one isn't necessarily required for the batch case. binder = new LocalScopeBinder(binder); BoundExpression bound = binder.BindExpression((ExpressionSyntax)node, BindingDiagnosticBag.Discarded); SymbolInfo info = GetSymbolInfoForNode(options, bound, bound, boundNodeForSyntacticParent: null, binderOpt: null); if ((object)info.Symbol != null) { result = new SymbolInfo(null, ImmutableArray.Create<ISymbol>(info.Symbol), CandidateReason.NotATypeOrNamespace); } else if (!info.CandidateSymbols.IsEmpty) { result = new SymbolInfo(null, info.CandidateSymbols, CandidateReason.NotATypeOrNamespace); } } } } else if (node.Parent.Kind() == SyntaxKind.XmlNameAttribute && (attrSyntax = (XmlNameAttributeSyntax)node.Parent).Identifier == node) { result = SymbolInfo.None; var binder = this.GetEnclosingBinder(GetAdjustedNodePosition(node)); if (binder != null) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var symbols = binder.BindXmlNameAttribute(attrSyntax, ref discardedUseSiteInfo); // NOTE: We don't need to call GetSymbolInfoForSymbol because the symbols // can only be parameters or type parameters. Debug.Assert(symbols.All(s => s.Kind == SymbolKind.TypeParameter || s.Kind == SymbolKind.Parameter)); switch (symbols.Length) { case 0: result = SymbolInfo.None; break; case 1: result = SymbolInfoFactory.Create(symbols, LookupResultKind.Viable, isDynamic: false); break; default: result = SymbolInfoFactory.Create(symbols, LookupResultKind.Ambiguous, isDynamic: false); break; } } } else if ((crefSyntax = node as CrefSyntax) != null) { int adjustedPosition = GetAdjustedNodePosition(crefSyntax); result = GetCrefSymbolInfo(adjustedPosition, crefSyntax, options, HasParameterList(crefSyntax)); } else { // if expression is not part of a member context then caller may really just have a // reference to a type or namespace name var symbol = GetSemanticInfoSymbolInNonMemberContext(node, bindVarAsAliasFirst: (options & SymbolInfoOptions.PreserveAliases) != 0); result = (object)symbol != null ? GetSymbolInfoForSymbol(symbol, options) : SymbolInfo.None; } return result; } internal override SymbolInfo GetCollectionInitializerSymbolInfoWorker(InitializerExpressionSyntax collectionInitializer, ExpressionSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { var model = this.GetMemberModel(collectionInitializer); if (model != null) { // Expression occurs in an executable code (method body or initializer) context. Use that // model to get the information. return model.GetCollectionInitializerSymbolInfoWorker(collectionInitializer, node, cancellationToken); } return SymbolInfo.None; } internal override CSharpTypeInfo GetTypeInfoWorker(CSharpSyntaxNode node, CancellationToken cancellationToken = default(CancellationToken)) { // in case this is right side of a qualified name or member access (or part of a cref) node = SyntaxFactory.GetStandaloneNode(node); var model = this.GetMemberModel(node); if (model != null) { // Expression occurs in an executable code (method body or initializer) context. Use that // model to get the information. return model.GetTypeInfoWorker(node, cancellationToken); } else { // if expression is not part of a member context then caller may really just have a // reference to a type or namespace name var symbol = GetSemanticInfoSymbolInNonMemberContext(node, bindVarAsAliasFirst: false); // Don't care about aliases here. return (object)symbol != null ? GetTypeInfoForSymbol(symbol) : CSharpTypeInfo.None; } } // Common helper method for GetSymbolInfoWorker and GetTypeInfoWorker, which is called when there is no member model for the given syntax node. // Even if the expression is not part of a member context, the caller may really just have a reference to a type or namespace name. // If so, the methods binds the syntax as a namespace or type or alias symbol. Otherwise, it returns null. private Symbol GetSemanticInfoSymbolInNonMemberContext(CSharpSyntaxNode node, bool bindVarAsAliasFirst) { Debug.Assert(this.GetMemberModel(node) == null); var binder = this.GetEnclosingBinder(GetAdjustedNodePosition(node)); if (binder != null) { // if expression is not part of a member context then caller may really just have a // reference to a type or namespace name var type = node as TypeSyntax; if ((object)type != null) { // determine if this type is part of a base declaration being resolved var basesBeingResolved = GetBasesBeingResolved(type); if (SyntaxFacts.IsNamespaceAliasQualifier(type)) { return binder.BindNamespaceAliasSymbol(node as IdentifierNameSyntax, BindingDiagnosticBag.Discarded); } else if (SyntaxFacts.IsInTypeOnlyContext(type)) { if (!type.IsVar) { return binder.BindTypeOrAlias(type, BindingDiagnosticBag.Discarded, basesBeingResolved).Symbol; } Symbol result = bindVarAsAliasFirst ? binder.BindTypeOrAlias(type, BindingDiagnosticBag.Discarded, basesBeingResolved).Symbol : null; // CONSIDER: we might bind "var" twice - once to see if it is an alias and again // as the type of a declared field. This should only happen for GetAliasInfo // calls on implicitly-typed fields (rare?). If it becomes a problem, then we // probably need to have the FieldSymbol retain alias info when it does its own // binding and expose it to us here. if ((object)result == null || result.Kind == SymbolKind.ErrorType) { // We might be in a field declaration with "var" keyword as the type name. // Implicitly typed field symbols are not allowed in regular C#, // but they are allowed in interactive scenario. // However, we can return fieldSymbol.Type for implicitly typed field symbols in both cases. // Note that for regular C#, fieldSymbol.Type would be an error type. var variableDecl = type.Parent as VariableDeclarationSyntax; if (variableDecl != null && variableDecl.Variables.Any()) { var fieldSymbol = GetDeclaredFieldSymbol(variableDecl.Variables.First()); if ((object)fieldSymbol != null) { result = fieldSymbol.Type; } } } return result ?? binder.BindTypeOrAlias(type, BindingDiagnosticBag.Discarded, basesBeingResolved).Symbol; } else { return binder.BindNamespaceOrTypeOrAliasSymbol(type, BindingDiagnosticBag.Discarded, basesBeingResolved, basesBeingResolved != null).Symbol; } } } return null; } internal override ImmutableArray<Symbol> GetMemberGroupWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)) { // in case this is right side of a qualified name or member access (or part of a cref) node = SyntaxFactory.GetStandaloneNode(node); var model = this.GetMemberModel(node); return model == null ? ImmutableArray<Symbol>.Empty : model.GetMemberGroupWorker(node, options, cancellationToken); } internal override ImmutableArray<IPropertySymbol> GetIndexerGroupWorker(CSharpSyntaxNode node, SymbolInfoOptions options, CancellationToken cancellationToken = default(CancellationToken)) { // in case this is right side of a qualified name or member access (or part of a cref) node = SyntaxFactory.GetStandaloneNode(node); var model = this.GetMemberModel(node); return model == null ? ImmutableArray<IPropertySymbol>.Empty : model.GetIndexerGroupWorker(node, options, cancellationToken); } internal override Optional<object> GetConstantValueWorker(CSharpSyntaxNode node, CancellationToken cancellationToken) { // in case this is right side of a qualified name or member access node = SyntaxFactory.GetStandaloneNode(node); var model = this.GetMemberModel(node); return model == null ? default(Optional<object>) : model.GetConstantValueWorker(node, cancellationToken); } public override QueryClauseInfo GetQueryClauseInfo(QueryClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(node); var model = this.GetMemberModel(node); return (model == null) ? default(QueryClauseInfo) : model.GetQueryClauseInfo(node, cancellationToken); } public override SymbolInfo GetSymbolInfo(SelectOrGroupClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(node); var model = this.GetMemberModel(node); return (model == null) ? SymbolInfo.None : model.GetSymbolInfo(node, cancellationToken); } public override TypeInfo GetTypeInfo(SelectOrGroupClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(node); var model = this.GetMemberModel(node); return (model == null) ? CSharpTypeInfo.None : model.GetTypeInfo(node, cancellationToken); } public override IPropertySymbol GetDeclaredSymbol(AnonymousObjectMemberDeclaratorSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declaratorSyntax); var model = this.GetMemberModel(declaratorSyntax); return (model == null) ? null : model.GetDeclaredSymbol(declaratorSyntax, cancellationToken); } public override INamedTypeSymbol GetDeclaredSymbol(AnonymousObjectCreationExpressionSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declaratorSyntax); var model = this.GetMemberModel(declaratorSyntax); return (model == null) ? null : model.GetDeclaredSymbol(declaratorSyntax, cancellationToken); } public override INamedTypeSymbol GetDeclaredSymbol(TupleExpressionSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declaratorSyntax); var model = this.GetMemberModel(declaratorSyntax); return (model == null) ? null : model.GetDeclaredSymbol(declaratorSyntax, cancellationToken); } public override ISymbol GetDeclaredSymbol(ArgumentSyntax declaratorSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declaratorSyntax); var model = this.GetMemberModel(declaratorSyntax); return (model == null) ? null : model.GetDeclaredSymbol(declaratorSyntax, cancellationToken); } public override IRangeVariableSymbol GetDeclaredSymbol(QueryClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(node); var model = this.GetMemberModel(node); return (model == null) ? null : model.GetDeclaredSymbol(node, cancellationToken); } public override IRangeVariableSymbol GetDeclaredSymbol(JoinIntoClauseSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(node); var model = this.GetMemberModel(node); return (model == null) ? null : model.GetDeclaredSymbol(node, cancellationToken); } public override IRangeVariableSymbol GetDeclaredSymbol(QueryContinuationSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(node); var model = this.GetMemberModel(node); return (model == null) ? null : model.GetDeclaredSymbol(node, cancellationToken); } public override SymbolInfo GetSymbolInfo(OrderingSyntax node, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(node); var model = this.GetMemberModel(node); return (model == null) ? SymbolInfo.None : model.GetSymbolInfo(node, cancellationToken); } private ConsList<TypeSymbol> GetBasesBeingResolved(TypeSyntax expression) { // if the expression is the child of a base-list node, then the expression should be // bound in the context of the containing symbols base being resolved. for (; expression != null && expression.Parent != null; expression = expression.Parent as TypeSyntax) { var parent = expression.Parent; if (parent is BaseTypeSyntax baseType && parent.Parent != null && parent.Parent.Kind() == SyntaxKind.BaseList && baseType.Type == expression) { // we have a winner var decl = (BaseTypeDeclarationSyntax)parent.Parent.Parent; var symbol = this.GetDeclaredSymbol(decl); return ConsList<TypeSymbol>.Empty.Prepend(symbol.GetSymbol().OriginalDefinition); } } return null; } public override Conversion ClassifyConversion(ExpressionSyntax expression, ITypeSymbol destination, bool isExplicitInSource = false) { TypeSymbol csdestination = destination.EnsureCSharpSymbolOrNull(nameof(destination)); if (expression.Kind() == SyntaxKind.DeclarationExpression) { // Conversion from a declaration is unspecified. return Conversion.NoConversion; } if (isExplicitInSource) { return ClassifyConversionForCast(expression, csdestination); } CheckSyntaxNode(expression); if ((object)destination == null) { throw new ArgumentNullException(nameof(destination)); } // TODO(cyrusn): Check arguments. This is a public entrypoint, so we must do appropriate // checks here. However, no other methods in this type do any checking currently. So I'm // going to hold off on this until we do a full sweep of the API. var model = this.GetMemberModel(expression); if (model == null) { // 'expression' must just be reference to a type or namespace name outside of an // expression context. Currently we bail in that case. However, is this a question // that a client would be asking and would expect sensible results for? return Conversion.NoConversion; } return model.ClassifyConversion(expression, destination); } internal override Conversion ClassifyConversionForCast(ExpressionSyntax expression, TypeSymbol destination) { CheckSyntaxNode(expression); if ((object)destination == null) { throw new ArgumentNullException(nameof(destination)); } var model = this.GetMemberModel(expression); if (model == null) { // 'expression' must just be reference to a type or namespace name outside of an // expression context. Currently we bail in that case. However, is this a question // that a client would be asking and would expect sensible results for? return Conversion.NoConversion; } return model.ClassifyConversionForCast(expression, destination); } public override bool IsSpeculativeSemanticModel { get { return false; } } public override int OriginalPositionForSpeculation { get { return 0; } } public override CSharpSemanticModel ParentModel { get { return null; } } internal override SemanticModel ContainingModelOrSelf { get { return this; } } internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, TypeSyntax type, SpeculativeBindingOption bindingOption, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var model = this.GetMemberModel(position); if (model != null) { return model.TryGetSpeculativeSemanticModelCore(parentModel, position, type, bindingOption, out speculativeModel); } Binder binder = GetSpeculativeBinder(position, type, bindingOption); if (binder != null) { speculativeModel = SpeculativeSyntaxTreeSemanticModel.Create(parentModel, type, binder, position, bindingOption); return true; } speculativeModel = null; return false; } internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, CrefSyntax crefSyntax, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); Binder binder = GetEnclosingBinder(position); if (binder?.InCref == true) { speculativeModel = SpeculativeSyntaxTreeSemanticModel.Create(parentModel, crefSyntax, binder, position); return true; } speculativeModel = null; return false; } internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, StatementSyntax statement, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var model = this.GetMemberModel(position); if (model != null) { return model.TryGetSpeculativeSemanticModelCore(parentModel, position, statement, out speculativeModel); } speculativeModel = null; return false; } internal sealed override bool TryGetSpeculativeSemanticModelForMethodBodyCore(SyntaxTreeSemanticModel parentModel, int position, BaseMethodDeclarationSyntax method, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var model = this.GetMemberModel(position); if (model != null) { return model.TryGetSpeculativeSemanticModelForMethodBodyCore(parentModel, position, method, out speculativeModel); } speculativeModel = null; return false; } internal sealed override bool TryGetSpeculativeSemanticModelForMethodBodyCore(SyntaxTreeSemanticModel parentModel, int position, AccessorDeclarationSyntax accessor, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var model = this.GetMemberModel(position); if (model != null) { return model.TryGetSpeculativeSemanticModelForMethodBodyCore(parentModel, position, accessor, out speculativeModel); } speculativeModel = null; return false; } internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, EqualsValueClauseSyntax initializer, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var model = this.GetMemberModel(position); if (model != null) { return model.TryGetSpeculativeSemanticModelCore(parentModel, position, initializer, out speculativeModel); } speculativeModel = null; return false; } internal override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, ArrowExpressionClauseSyntax expressionBody, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var model = this.GetMemberModel(position); if (model != null) { return model.TryGetSpeculativeSemanticModelCore(parentModel, position, expressionBody, out speculativeModel); } speculativeModel = null; return false; } internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, ConstructorInitializerSyntax constructorInitializer, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var existingConstructorInitializer = this.Root.FindToken(position).Parent.AncestorsAndSelf().OfType<ConstructorInitializerSyntax>().FirstOrDefault(); if (existingConstructorInitializer != null) { var model = this.GetMemberModel(position); if (model != null) { return model.TryGetSpeculativeSemanticModelCore(parentModel, position, constructorInitializer, out speculativeModel); } } speculativeModel = null; return false; } internal sealed override bool TryGetSpeculativeSemanticModelCore(SyntaxTreeSemanticModel parentModel, int position, PrimaryConstructorBaseTypeSyntax constructorInitializer, out SemanticModel speculativeModel) { position = CheckAndAdjustPosition(position); var existingConstructorInitializer = this.Root.FindToken(position).Parent.AncestorsAndSelf().OfType<PrimaryConstructorBaseTypeSyntax>().FirstOrDefault(); if (existingConstructorInitializer != null) { var model = this.GetMemberModel(existingConstructorInitializer); if (model != null) { return model.TryGetSpeculativeSemanticModelCore(parentModel, position, constructorInitializer, out speculativeModel); } } speculativeModel = null; return false; } internal override BoundExpression GetSpeculativelyBoundExpression(int position, ExpressionSyntax expression, SpeculativeBindingOption bindingOption, out Binder binder, out ImmutableArray<Symbol> crefSymbols) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } // If the given position is in a member that we can get a semantic model for, we want to defer to that implementation // of GetSpeculativelyBoundExpression so it can take nullability into account. if (bindingOption == SpeculativeBindingOption.BindAsExpression) { position = CheckAndAdjustPosition(position); var model = GetMemberModel(position); if (model is object) { return model.GetSpeculativelyBoundExpression(position, expression, bindingOption, out binder, out crefSymbols); } } return GetSpeculativelyBoundExpressionWithoutNullability(position, expression, bindingOption, out binder, out crefSymbols); } internal AttributeSemanticModel CreateSpeculativeAttributeSemanticModel(int position, AttributeSyntax attribute, Binder binder, AliasSymbol aliasOpt, NamedTypeSymbol attributeType) { var memberModel = IsNullableAnalysisEnabledAtSpeculativePosition(position, attribute) ? GetMemberModel(position) : null; return AttributeSemanticModel.CreateSpeculative(this, attribute, attributeType, aliasOpt, binder, memberModel?.GetRemappedSymbols(), position); } internal bool IsNullableAnalysisEnabledAtSpeculativePosition(int position, SyntaxNode speculativeSyntax) { Debug.Assert(speculativeSyntax.SyntaxTree != SyntaxTree); // https://github.com/dotnet/roslyn/issues/50234: CSharpSyntaxTree.IsNullableAnalysisEnabled() does not differentiate // between no '#nullable' directives and '#nullable restore' - it returns null in both cases. Since we fallback to the // directives in the original syntax tree, we're not handling '#nullable restore' correctly in the speculative text. return ((CSharpSyntaxTree)speculativeSyntax.SyntaxTree).IsNullableAnalysisEnabled(speculativeSyntax.Span) ?? Compilation.IsNullableAnalysisEnabledIn((CSharpSyntaxTree)SyntaxTree, new TextSpan(position, 0)); } private MemberSemanticModel GetMemberModel(int position) { AssertPositionAdjusted(position); CSharpSyntaxNode node = (CSharpSyntaxNode)Root.FindTokenIncludingCrefAndNameAttributes(position).Parent; CSharpSyntaxNode memberDecl = GetMemberDeclaration(node); bool outsideMemberDecl = false; if (memberDecl != null) { switch (memberDecl.Kind()) { case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: // NOTE: not UnknownAccessorDeclaration since there's no corresponding method symbol from which to build a member model. outsideMemberDecl = !LookupPosition.IsInBody(position, (AccessorDeclarationSyntax)memberDecl); break; case SyntaxKind.ConstructorDeclaration: var constructorDecl = (ConstructorDeclarationSyntax)memberDecl; outsideMemberDecl = !LookupPosition.IsInConstructorParameterScope(position, constructorDecl) && !LookupPosition.IsInParameterList(position, constructorDecl); break; case SyntaxKind.RecordDeclaration: { var recordDecl = (RecordDeclarationSyntax)memberDecl; if (recordDecl.ParameterList is null) { outsideMemberDecl = true; } else { var argumentList = recordDecl.PrimaryConstructorBaseTypeIfClass?.ArgumentList; outsideMemberDecl = argumentList is null || !LookupPosition.IsBetweenTokens(position, argumentList.OpenParenToken, argumentList.CloseParenToken); } } break; case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.MethodDeclaration: case SyntaxKind.OperatorDeclaration: var methodDecl = (BaseMethodDeclarationSyntax)memberDecl; outsideMemberDecl = !LookupPosition.IsInBody(position, methodDecl) && !LookupPosition.IsInParameterList(position, methodDecl); break; } } return outsideMemberDecl ? null : GetMemberModel(node); } // Try to get a member semantic model that encloses "node". If there is not an enclosing // member semantic model, return null. internal override MemberSemanticModel GetMemberModel(SyntaxNode node) { // Documentation comments can never legally appear within members, so there's no point // in building out the MemberSemanticModel to handle them. Instead, just say have // SyntaxTreeSemanticModel handle them, regardless of location. if (IsInDocumentationComment(node)) { return null; } var memberDecl = GetMemberDeclaration(node) ?? (node as CompilationUnitSyntax); if (memberDecl != null) { var span = node.Span; switch (memberDecl.Kind()) { case SyntaxKind.MethodDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.OperatorDeclaration: { var methodDecl = (BaseMethodDeclarationSyntax)memberDecl; var expressionBody = methodDecl.GetExpressionBodySyntax(); return (expressionBody?.FullSpan.Contains(span) == true || methodDecl.Body?.FullSpan.Contains(span) == true) ? GetOrAddModel(methodDecl) : null; } case SyntaxKind.ConstructorDeclaration: { ConstructorDeclarationSyntax constructorDecl = (ConstructorDeclarationSyntax)memberDecl; var expressionBody = constructorDecl.GetExpressionBodySyntax(); return (constructorDecl.Initializer?.FullSpan.Contains(span) == true || expressionBody?.FullSpan.Contains(span) == true || constructorDecl.Body?.FullSpan.Contains(span) == true) ? GetOrAddModel(constructorDecl) : null; } case SyntaxKind.RecordDeclaration: { var recordDecl = (RecordDeclarationSyntax)memberDecl; return recordDecl.ParameterList is object && recordDecl.PrimaryConstructorBaseTypeIfClass is PrimaryConstructorBaseTypeSyntax baseWithArguments && (node == baseWithArguments || baseWithArguments.ArgumentList.FullSpan.Contains(span)) ? GetOrAddModel(memberDecl) : null; } case SyntaxKind.DestructorDeclaration: { DestructorDeclarationSyntax destructorDecl = (DestructorDeclarationSyntax)memberDecl; var expressionBody = destructorDecl.GetExpressionBodySyntax(); return (expressionBody?.FullSpan.Contains(span) == true || destructorDecl.Body?.FullSpan.Contains(span) == true) ? GetOrAddModel(destructorDecl) : null; } case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: // NOTE: not UnknownAccessorDeclaration since there's no corresponding method symbol from which to build a member model. { var accessorDecl = (AccessorDeclarationSyntax)memberDecl; return (accessorDecl.ExpressionBody?.FullSpan.Contains(span) == true || accessorDecl.Body?.FullSpan.Contains(span) == true) ? GetOrAddModel(accessorDecl) : null; } case SyntaxKind.IndexerDeclaration: { var indexerDecl = (IndexerDeclarationSyntax)memberDecl; return GetOrAddModelIfContains(indexerDecl.ExpressionBody, span); } case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: { var fieldDecl = (BaseFieldDeclarationSyntax)memberDecl; foreach (var variableDecl in fieldDecl.Declaration.Variables) { var binding = GetOrAddModelIfContains(variableDecl.Initializer, span); if (binding != null) { return binding; } } } break; case SyntaxKind.EnumMemberDeclaration: { var enumDecl = (EnumMemberDeclarationSyntax)memberDecl; return (enumDecl.EqualsValue != null) ? GetOrAddModelIfContains(enumDecl.EqualsValue, span) : null; } case SyntaxKind.PropertyDeclaration: { var propertyDecl = (PropertyDeclarationSyntax)memberDecl; return GetOrAddModelIfContains(propertyDecl.Initializer, span) ?? GetOrAddModelIfContains(propertyDecl.ExpressionBody, span); } case SyntaxKind.GlobalStatement: if (SyntaxFacts.IsSimpleProgramTopLevelStatement((GlobalStatementSyntax)memberDecl)) { return GetOrAddModel((CompilationUnitSyntax)memberDecl.Parent); } return GetOrAddModel(memberDecl); case SyntaxKind.CompilationUnit: if (SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(Compilation, (CompilationUnitSyntax)memberDecl, fallbackToMainEntryPoint: false) is object) { return GetOrAddModel(memberDecl); } break; case SyntaxKind.Attribute: return GetOrAddModelForAttribute((AttributeSyntax)memberDecl); case SyntaxKind.Parameter: if (node != memberDecl) { return GetOrAddModelForParameter((ParameterSyntax)memberDecl, span); } else { return GetMemberModel(memberDecl.Parent); } } } return null; } /// <summary> /// Internal for test purposes only /// </summary> internal ImmutableDictionary<CSharpSyntaxNode, MemberSemanticModel> TestOnlyMemberModels => _memberModels; private MemberSemanticModel GetOrAddModelForAttribute(AttributeSyntax attribute) { MemberSemanticModel containing = attribute.Parent != null ? GetMemberModel(attribute.Parent) : null; if (containing == null) { return GetOrAddModel(attribute); } return ImmutableInterlocked.GetOrAdd(ref _memberModels, attribute, (node, binderAndModel) => CreateModelForAttribute(binderAndModel.binder, (AttributeSyntax)node, binderAndModel.model), (binder: containing.GetEnclosingBinder(attribute.SpanStart), model: containing)); } private static bool IsInDocumentationComment(SyntaxNode node) { for (SyntaxNode curr = node; curr != null; curr = curr.Parent) { if (SyntaxFacts.IsDocumentationCommentTrivia(curr.Kind())) { return true; } } return false; } // Check parameter for a default value containing span, and create an InitializerSemanticModel for binding the default value if so. // Otherwise, return model for enclosing context. private MemberSemanticModel GetOrAddModelForParameter(ParameterSyntax paramDecl, TextSpan span) { EqualsValueClauseSyntax defaultValueSyntax = paramDecl.Default; MemberSemanticModel containing = paramDecl.Parent != null ? GetMemberModel(paramDecl.Parent) : null; if (containing == null) { return GetOrAddModelIfContains(defaultValueSyntax, span); } if (defaultValueSyntax != null && defaultValueSyntax.FullSpan.Contains(span)) { var parameterSymbol = containing.GetDeclaredSymbol(paramDecl).GetSymbol<ParameterSymbol>(); if ((object)parameterSymbol != null) { return ImmutableInterlocked.GetOrAdd(ref _memberModels, defaultValueSyntax, (equalsValue, tuple) => InitializerSemanticModel.Create( this, tuple.paramDecl, tuple.parameterSymbol, tuple.containing.GetEnclosingBinder(tuple.paramDecl.SpanStart). CreateBinderForParameterDefaultValue(tuple.parameterSymbol, (EqualsValueClauseSyntax)equalsValue), tuple.containing.GetRemappedSymbols()), (compilation: this.Compilation, paramDecl, parameterSymbol, containing) ); } } return containing; } private static CSharpSyntaxNode GetMemberDeclaration(SyntaxNode node) { return node.FirstAncestorOrSelf(s_isMemberDeclarationFunction); } private MemberSemanticModel GetOrAddModelIfContains(CSharpSyntaxNode node, TextSpan span) { if (node != null && node.FullSpan.Contains(span)) { return GetOrAddModel(node); } return null; } private MemberSemanticModel GetOrAddModel(CSharpSyntaxNode node) { var createMemberModelFunction = _createMemberModelFunction ?? (_createMemberModelFunction = this.CreateMemberModel); return GetOrAddModel(node, createMemberModelFunction); } internal MemberSemanticModel GetOrAddModel(CSharpSyntaxNode node, Func<CSharpSyntaxNode, MemberSemanticModel> createMemberModelFunction) { return ImmutableInterlocked.GetOrAdd(ref _memberModels, node, createMemberModelFunction); } // Create a member model for the given declaration syntax. In certain very malformed // syntax trees, there may not be a symbol that can have a member model associated with it // (although we try to minimize such cases). In such cases, null is returned. private MemberSemanticModel CreateMemberModel(CSharpSyntaxNode node) { Binder defaultOuter() => _binderFactory.GetBinder(node).WithAdditionalFlags(this.IgnoresAccessibility ? BinderFlags.IgnoreAccessibility : BinderFlags.None); switch (node.Kind()) { case SyntaxKind.CompilationUnit: return createMethodBodySemanticModel(node, SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(Compilation, (CompilationUnitSyntax)node, fallbackToMainEntryPoint: false)); case SyntaxKind.MethodDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: { var memberDecl = (MemberDeclarationSyntax)node; var symbol = GetDeclaredSymbol(memberDecl).GetSymbol<SourceMemberMethodSymbol>(); return createMethodBodySemanticModel(memberDecl, symbol); } case SyntaxKind.RecordDeclaration: { SynthesizedRecordConstructor symbol = TryGetSynthesizedRecordConstructor((RecordDeclarationSyntax)node); if (symbol is null) { return null; } return createMethodBodySemanticModel(node, symbol); } case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: { var accessorDecl = (AccessorDeclarationSyntax)node; var symbol = GetDeclaredSymbol(accessorDecl).GetSymbol<SourceMemberMethodSymbol>(); return createMethodBodySemanticModel(accessorDecl, symbol); } case SyntaxKind.Block: // Don't throw, just use for the assert ExceptionUtilities.UnexpectedValue(node.Parent); break; case SyntaxKind.EqualsValueClause: switch (node.Parent.Kind()) { case SyntaxKind.VariableDeclarator: { var variableDecl = (VariableDeclaratorSyntax)node.Parent; FieldSymbol fieldSymbol = GetDeclaredFieldSymbol(variableDecl); return InitializerSemanticModel.Create( this, variableDecl, //pass in the entire field initializer to permit region analysis. fieldSymbol, //if we're in regular C#, then insert an extra binder to perform field initialization checks GetFieldOrPropertyInitializerBinder(fieldSymbol, defaultOuter(), variableDecl.Initializer)); } case SyntaxKind.PropertyDeclaration: { var propertyDecl = (PropertyDeclarationSyntax)node.Parent; var propertySymbol = GetDeclaredSymbol(propertyDecl).GetSymbol<SourcePropertySymbol>(); return InitializerSemanticModel.Create( this, propertyDecl, propertySymbol, GetFieldOrPropertyInitializerBinder(propertySymbol.BackingField, defaultOuter(), propertyDecl.Initializer)); } case SyntaxKind.Parameter: { // NOTE: we don't need to create a member model for lambda parameter default value // (which is bad code anyway) because lambdas only appear in code with associated // member models. ParameterSyntax parameterDecl = (ParameterSyntax)node.Parent; ParameterSymbol parameterSymbol = GetDeclaredNonLambdaParameterSymbol(parameterDecl); if ((object)parameterSymbol == null) return null; return InitializerSemanticModel.Create( this, parameterDecl, parameterSymbol, defaultOuter().CreateBinderForParameterDefaultValue(parameterSymbol, (EqualsValueClauseSyntax)node), parentRemappedSymbolsOpt: null); } case SyntaxKind.EnumMemberDeclaration: { var enumDecl = (EnumMemberDeclarationSyntax)node.Parent; var enumSymbol = GetDeclaredSymbol(enumDecl).GetSymbol<FieldSymbol>(); if ((object)enumSymbol == null) return null; return InitializerSemanticModel.Create( this, enumDecl, enumSymbol, GetFieldOrPropertyInitializerBinder(enumSymbol, defaultOuter(), enumDecl.EqualsValue)); } default: throw ExceptionUtilities.UnexpectedValue(node.Parent.Kind()); } case SyntaxKind.ArrowExpressionClause: { SourceMemberMethodSymbol symbol = null; var exprDecl = (ArrowExpressionClauseSyntax)node; if (node.Parent is BasePropertyDeclarationSyntax) { symbol = GetDeclaredSymbol(exprDecl).GetSymbol<SourceMemberMethodSymbol>(); } else { // Don't throw, just use for the assert ExceptionUtilities.UnexpectedValue(node.Parent); } ExecutableCodeBinder binder = symbol?.TryGetBodyBinder(_binderFactory, this.IgnoresAccessibility); if (binder == null) { return null; } return MethodBodySemanticModel.Create(this, symbol, new MethodBodySemanticModel.InitialState(exprDecl, binder: binder)); } case SyntaxKind.GlobalStatement: { var parent = node.Parent; // TODO (tomat): handle misplaced global statements if (parent.Kind() == SyntaxKind.CompilationUnit && !this.IsRegularCSharp && (object)_compilation.ScriptClass != null) { var scriptInitializer = _compilation.ScriptClass.GetScriptInitializer(); Debug.Assert((object)scriptInitializer != null); if ((object)scriptInitializer == null) { return null; } // Share labels across all global statements. if (_globalStatementLabels == null) { Interlocked.CompareExchange(ref _globalStatementLabels, new ScriptLocalScopeBinder.Labels(scriptInitializer, (CompilationUnitSyntax)parent), null); } return MethodBodySemanticModel.Create( this, scriptInitializer, new MethodBodySemanticModel.InitialState(node, binder: new ExecutableCodeBinder(node, scriptInitializer, new ScriptLocalScopeBinder(_globalStatementLabels, defaultOuter())))); } } break; case SyntaxKind.Attribute: return CreateModelForAttribute(defaultOuter(), (AttributeSyntax)node, containingModel: null); } return null; MemberSemanticModel createMethodBodySemanticModel(CSharpSyntaxNode memberDecl, SourceMemberMethodSymbol symbol) { ExecutableCodeBinder binder = symbol?.TryGetBodyBinder(_binderFactory, this.IgnoresAccessibility); if (binder == null) { return null; } return MethodBodySemanticModel.Create(this, symbol, new MethodBodySemanticModel.InitialState(memberDecl, binder: binder)); } } private SynthesizedRecordConstructor TryGetSynthesizedRecordConstructor(RecordDeclarationSyntax node) { NamedTypeSymbol recordType = GetDeclaredType(node); var symbol = recordType.GetMembersUnordered().OfType<SynthesizedRecordConstructor>().SingleOrDefault(); if (symbol?.SyntaxRef.SyntaxTree != node.SyntaxTree || symbol.GetSyntax() != node) { return null; } return symbol; } private AttributeSemanticModel CreateModelForAttribute(Binder enclosingBinder, AttributeSyntax attribute, MemberSemanticModel containingModel) { AliasSymbol aliasOpt; var attributeType = (NamedTypeSymbol)enclosingBinder.BindType(attribute.Name, BindingDiagnosticBag.Discarded, out aliasOpt).Type; return AttributeSemanticModel.Create( this, attribute, attributeType, aliasOpt, enclosingBinder.WithAdditionalFlags(BinderFlags.AttributeArgument), containingModel?.GetRemappedSymbols()); } private FieldSymbol GetDeclaredFieldSymbol(VariableDeclaratorSyntax variableDecl) { var declaredSymbol = GetDeclaredSymbol(variableDecl); if ((object)declaredSymbol != null) { switch (variableDecl.Parent.Parent.Kind()) { case SyntaxKind.FieldDeclaration: return declaredSymbol.GetSymbol<FieldSymbol>(); case SyntaxKind.EventFieldDeclaration: return (declaredSymbol.GetSymbol<EventSymbol>()).AssociatedField; } } return null; } private Binder GetFieldOrPropertyInitializerBinder(FieldSymbol symbol, Binder outer, EqualsValueClauseSyntax initializer) { // NOTE: checking for a containing script class is sufficient, but the regular C# test is quick and easy. outer = outer.GetFieldInitializerBinder(symbol, suppressBinderFlagsFieldInitializer: !this.IsRegularCSharp && symbol.ContainingType.IsScriptClass); if (initializer != null) { outer = new ExecutableCodeBinder(initializer, symbol, outer); } return outer; } private static bool IsMemberDeclaration(CSharpSyntaxNode node) { return (node is MemberDeclarationSyntax) || (node is AccessorDeclarationSyntax) || (node.Kind() == SyntaxKind.Attribute) || (node.Kind() == SyntaxKind.Parameter); } private bool IsRegularCSharp { get { return this.SyntaxTree.Options.Kind == SourceCodeKind.Regular; } } #region "GetDeclaredSymbol overloads for MemberDeclarationSyntax and its subtypes" /// <inheritdoc/> public override INamespaceSymbol GetDeclaredSymbol(NamespaceDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); return GetDeclaredNamespace(declarationSyntax).GetPublicSymbol(); } /// <inheritdoc/> public override INamespaceSymbol GetDeclaredSymbol(FileScopedNamespaceDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default) { CheckSyntaxNode(declarationSyntax); return GetDeclaredNamespace(declarationSyntax).GetPublicSymbol(); } private NamespaceSymbol GetDeclaredNamespace(BaseNamespaceDeclarationSyntax declarationSyntax) { Debug.Assert(declarationSyntax != null); NamespaceOrTypeSymbol container; if (declarationSyntax.Parent.Kind() == SyntaxKind.CompilationUnit) { container = _compilation.Assembly.GlobalNamespace; } else { container = GetDeclaredNamespaceOrType(declarationSyntax.Parent); } Debug.Assert((object)container != null); // We should get a namespace symbol since we match the symbol location with a namespace declaration syntax location. var symbol = (NamespaceSymbol)GetDeclaredMember(container, declarationSyntax.Span, declarationSyntax.Name); Debug.Assert((object)symbol != null); // Map to compilation-scoped namespace (Roslyn bug 9538) symbol = _compilation.GetCompilationNamespace(symbol); Debug.Assert((object)symbol != null); return symbol; } /// <summary> /// Given a type declaration, get the corresponding type symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a type.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The type symbol that was declared.</returns> /// <remarks> /// NOTE: We have no GetDeclaredSymbol overloads for subtypes of BaseTypeDeclarationSyntax as all of them return a NamedTypeSymbol. /// </remarks> public override INamedTypeSymbol GetDeclaredSymbol(BaseTypeDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); return GetDeclaredType(declarationSyntax).GetPublicSymbol(); } /// <summary> /// Given a delegate declaration, get the corresponding type symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a delegate.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The type symbol that was declared.</returns> public override INamedTypeSymbol GetDeclaredSymbol(DelegateDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); return GetDeclaredType(declarationSyntax).GetPublicSymbol(); } private NamedTypeSymbol GetDeclaredType(BaseTypeDeclarationSyntax declarationSyntax) { Debug.Assert(declarationSyntax != null); var name = declarationSyntax.Identifier.ValueText; return GetDeclaredNamedType(declarationSyntax, name); } private NamedTypeSymbol GetDeclaredType(DelegateDeclarationSyntax declarationSyntax) { Debug.Assert(declarationSyntax != null); var name = declarationSyntax.Identifier.ValueText; return GetDeclaredNamedType(declarationSyntax, name); } private NamedTypeSymbol GetDeclaredNamedType(CSharpSyntaxNode declarationSyntax, string name) { Debug.Assert(declarationSyntax != null); var container = GetDeclaredTypeMemberContainer(declarationSyntax); Debug.Assert((object)container != null); // try cast as we might get a non-type in error recovery scenarios: return GetDeclaredMember(container, declarationSyntax.Span, name) as NamedTypeSymbol; } private NamespaceOrTypeSymbol GetDeclaredNamespaceOrType(CSharpSyntaxNode declarationSyntax) { var namespaceDeclarationSyntax = declarationSyntax as BaseNamespaceDeclarationSyntax; if (namespaceDeclarationSyntax != null) { return GetDeclaredNamespace(namespaceDeclarationSyntax); } var typeDeclarationSyntax = declarationSyntax as BaseTypeDeclarationSyntax; if (typeDeclarationSyntax != null) { return GetDeclaredType(typeDeclarationSyntax); } var delegateDeclarationSyntax = declarationSyntax as DelegateDeclarationSyntax; if (delegateDeclarationSyntax != null) { return GetDeclaredType(delegateDeclarationSyntax); } return null; } /// <summary> /// Given a member declaration syntax, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a member.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> /// <remarks> /// NOTE: We have no GetDeclaredSymbol overloads for following subtypes of MemberDeclarationSyntax: /// NOTE: (1) GlobalStatementSyntax as they don't declare any symbols. /// NOTE: (2) IncompleteMemberSyntax as there are no symbols for incomplete members. /// NOTE: (3) BaseFieldDeclarationSyntax or its subtypes as these declarations can contain multiple variable declarators. /// NOTE: GetDeclaredSymbol should be called on the variable declarators directly. /// </remarks> public override ISymbol GetDeclaredSymbol(MemberDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); switch (declarationSyntax.Kind()) { // Few subtypes of MemberDeclarationSyntax don't declare any symbols or declare multiple symbols, return null for these cases. case SyntaxKind.GlobalStatement: // Global statements don't declare anything, even though they inherit from MemberDeclarationSyntax. return null; case SyntaxKind.IncompleteMember: // Incomplete members don't declare any symbols. return null; case SyntaxKind.EventFieldDeclaration: case SyntaxKind.FieldDeclaration: // these declarations can contain multiple variable declarators. GetDeclaredSymbol should be called on them directly. return null; default: return (GetDeclaredNamespaceOrType(declarationSyntax) ?? GetDeclaredMemberSymbol(declarationSyntax)).GetPublicSymbol(); } } public override IMethodSymbol GetDeclaredSymbol(CompilationUnitSyntax declarationSyntax, CancellationToken cancellationToken = default) { CheckSyntaxNode(declarationSyntax); return SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(Compilation, declarationSyntax, fallbackToMainEntryPoint: false).GetPublicSymbol(); } /// <summary> /// Given a local function declaration syntax, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a member.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override ISymbol GetDeclaredSymbol(LocalFunctionStatementSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); return this.GetMemberModel(declarationSyntax)?.GetDeclaredSymbol(declarationSyntax, cancellationToken); } /// <summary> /// Given a enum member declaration, get the corresponding field symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares an enum member.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override IFieldSymbol GetDeclaredSymbol(EnumMemberDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { return ((FieldSymbol)GetDeclaredMemberSymbol(declarationSyntax)).GetPublicSymbol(); } /// <summary> /// Given a base method declaration syntax, get the corresponding method symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a method.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> /// <remarks> /// NOTE: We have no GetDeclaredSymbol overloads for subtypes of BaseMethodDeclarationSyntax as all of them return a MethodSymbol. /// </remarks> public override IMethodSymbol GetDeclaredSymbol(BaseMethodDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { return ((MethodSymbol)GetDeclaredMemberSymbol(declarationSyntax)).GetPublicSymbol(); } #region "GetDeclaredSymbol overloads for BasePropertyDeclarationSyntax and its subtypes" /// <summary> /// Given a syntax node that declares a property, indexer or an event, get the corresponding declared symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a property, indexer or an event.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override ISymbol GetDeclaredSymbol(BasePropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { return GetDeclaredMemberSymbol(declarationSyntax).GetPublicSymbol(); } /// <summary> /// Given a syntax node that declares a property, get the corresponding declared symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a property, indexer or an event.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override IPropertySymbol GetDeclaredSymbol(PropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { return ((PropertySymbol)GetDeclaredMemberSymbol(declarationSyntax)).GetPublicSymbol(); } /// <summary> /// Given a syntax node that declares an indexer, get the corresponding declared symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares an indexer.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override IPropertySymbol GetDeclaredSymbol(IndexerDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { return ((PropertySymbol)GetDeclaredMemberSymbol(declarationSyntax)).GetPublicSymbol(); } /// <summary> /// Given a syntax node that declares a (custom) event, get the corresponding event symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a event.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override IEventSymbol GetDeclaredSymbol(EventDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { return ((EventSymbol)GetDeclaredMemberSymbol(declarationSyntax)).GetPublicSymbol(); } #endregion #endregion /// <summary> /// Given a syntax node that declares a property or member accessor, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares an accessor.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override IMethodSymbol GetDeclaredSymbol(AccessorDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); if (declarationSyntax.Kind() == SyntaxKind.UnknownAccessorDeclaration) { // this is not a real accessor, so we shouldn't return anything. return null; } var propertyOrEventDecl = declarationSyntax.Parent.Parent; switch (propertyOrEventDecl.Kind()) { case SyntaxKind.PropertyDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.EventDeclaration: case SyntaxKind.EventFieldDeclaration: // NOTE: it's an error for field-like events to have accessors, // but we want to bind them anyway for error tolerance reasons. var container = GetDeclaredTypeMemberContainer(propertyOrEventDecl); Debug.Assert((object)container != null); Debug.Assert(declarationSyntax.Keyword.Kind() != SyntaxKind.IdentifierToken); return (this.GetDeclaredMember(container, declarationSyntax.Span) as MethodSymbol).GetPublicSymbol(); default: throw ExceptionUtilities.UnexpectedValue(propertyOrEventDecl.Kind()); } } public override IMethodSymbol GetDeclaredSymbol(ArrowExpressionClauseSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); var containingMemberSyntax = declarationSyntax.Parent; NamespaceOrTypeSymbol container; switch (containingMemberSyntax.Kind()) { case SyntaxKind.PropertyDeclaration: case SyntaxKind.IndexerDeclaration: container = GetDeclaredTypeMemberContainer(containingMemberSyntax); Debug.Assert((object)container != null); // We are looking for the SourcePropertyAccessorSymbol here, // not the SourcePropertySymbol, so use declarationSyntax // to exclude the property symbol from being retrieved. return (this.GetDeclaredMember(container, declarationSyntax.Span) as MethodSymbol).GetPublicSymbol(); default: // Don't throw, use only for the assert ExceptionUtilities.UnexpectedValue(containingMemberSyntax.Kind()); return null; } } private string GetDeclarationName(CSharpSyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.MethodDeclaration: { var methodDecl = (MethodDeclarationSyntax)declaration; return GetDeclarationName(declaration, methodDecl.ExplicitInterfaceSpecifier, methodDecl.Identifier.ValueText); } case SyntaxKind.PropertyDeclaration: { var propertyDecl = (PropertyDeclarationSyntax)declaration; return GetDeclarationName(declaration, propertyDecl.ExplicitInterfaceSpecifier, propertyDecl.Identifier.ValueText); } case SyntaxKind.IndexerDeclaration: { var indexerDecl = (IndexerDeclarationSyntax)declaration; return GetDeclarationName(declaration, indexerDecl.ExplicitInterfaceSpecifier, WellKnownMemberNames.Indexer); } case SyntaxKind.EventDeclaration: { var eventDecl = (EventDeclarationSyntax)declaration; return GetDeclarationName(declaration, eventDecl.ExplicitInterfaceSpecifier, eventDecl.Identifier.ValueText); } case SyntaxKind.DelegateDeclaration: return ((DelegateDeclarationSyntax)declaration).Identifier.ValueText; case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.ClassDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.RecordDeclaration: return ((BaseTypeDeclarationSyntax)declaration).Identifier.ValueText; case SyntaxKind.VariableDeclarator: return ((VariableDeclaratorSyntax)declaration).Identifier.ValueText; case SyntaxKind.EnumMemberDeclaration: return ((EnumMemberDeclarationSyntax)declaration).Identifier.ValueText; case SyntaxKind.DestructorDeclaration: return WellKnownMemberNames.DestructorName; case SyntaxKind.ConstructorDeclaration: if (((ConstructorDeclarationSyntax)declaration).Modifiers.Any(SyntaxKind.StaticKeyword)) { return WellKnownMemberNames.StaticConstructorName; } else { return WellKnownMemberNames.InstanceConstructorName; } case SyntaxKind.OperatorDeclaration: { var operatorDecl = (OperatorDeclarationSyntax)declaration; return GetDeclarationName(declaration, operatorDecl.ExplicitInterfaceSpecifier, OperatorFacts.OperatorNameFromDeclaration(operatorDecl)); } case SyntaxKind.ConversionOperatorDeclaration: { var operatorDecl = (ConversionOperatorDeclarationSyntax)declaration; return GetDeclarationName(declaration, operatorDecl.ExplicitInterfaceSpecifier, OperatorFacts.OperatorNameFromDeclaration(operatorDecl)); } case SyntaxKind.EventFieldDeclaration: case SyntaxKind.FieldDeclaration: throw new ArgumentException(CSharpResources.InvalidGetDeclarationNameMultipleDeclarators); case SyntaxKind.IncompleteMember: // There is no name - that's why it's an incomplete member. return null; default: throw ExceptionUtilities.UnexpectedValue(declaration.Kind()); } } private string GetDeclarationName(CSharpSyntaxNode declaration, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifierOpt, string memberName) { if (explicitInterfaceSpecifierOpt == null) { return memberName; } // For an explicit interface implementation, we actually have several options: // Option 1: do nothing - it will retry without the name // Option 2: detect explicit impl and return null // Option 3: get a binder and figure out the name // For now, we're going with Option 3 return ExplicitInterfaceHelpers.GetMemberName(_binderFactory.GetBinder(declaration), explicitInterfaceSpecifierOpt, memberName); } private Symbol GetDeclaredMember(NamespaceOrTypeSymbol container, TextSpan declarationSpan, NameSyntax name) { switch (name.Kind()) { case SyntaxKind.GenericName: case SyntaxKind.IdentifierName: return GetDeclaredMember(container, declarationSpan, ((SimpleNameSyntax)name).Identifier.ValueText); case SyntaxKind.QualifiedName: var qn = (QualifiedNameSyntax)name; var left = GetDeclaredMember(container, declarationSpan, qn.Left) as NamespaceOrTypeSymbol; Debug.Assert((object)left != null); return GetDeclaredMember(left, declarationSpan, qn.Right); case SyntaxKind.AliasQualifiedName: // this is not supposed to happen, but we allow for errors don't we! var an = (AliasQualifiedNameSyntax)name; return GetDeclaredMember(container, declarationSpan, an.Name); default: throw ExceptionUtilities.UnexpectedValue(name.Kind()); } } /// <summary> /// Finds the member in the containing symbol which is inside the given declaration span. /// </summary> private Symbol GetDeclaredMember(NamespaceOrTypeSymbol container, TextSpan declarationSpan, string name = null) { if ((object)container == null) { return null; } // look for any member with same declaration location var collection = name != null ? container.GetMembers(name) : container.GetMembersUnordered(); Symbol zeroWidthMatch = null; foreach (var symbol in collection) { var namedType = symbol as ImplicitNamedTypeSymbol; if ((object)namedType != null && namedType.IsImplicitClass) { // look inside wrapper around illegally placed members in namespaces var result = GetDeclaredMember(namedType, declarationSpan, name); if ((object)result != null) { return result; } } foreach (var loc in symbol.Locations) { if (loc.IsInSource && loc.SourceTree == this.SyntaxTree && declarationSpan.Contains(loc.SourceSpan)) { if (loc.SourceSpan.IsEmpty && loc.SourceSpan.End == declarationSpan.Start) { // exclude decls created via syntax recovery zeroWidthMatch = symbol; } else { return symbol; } } } // Handle the case of the implementation of a partial method. var partial = symbol.Kind == SymbolKind.Method ? ((MethodSymbol)symbol).PartialImplementationPart : null; if ((object)partial != null) { var loc = partial.Locations[0]; if (loc.IsInSource && loc.SourceTree == this.SyntaxTree && declarationSpan.Contains(loc.SourceSpan)) { return partial; } } } // If we didn't find anything better than the symbol that matched because of syntax error recovery, then return that. // Otherwise, if there's a name, try again without a name. // Otherwise, give up. return zeroWidthMatch ?? (name != null ? GetDeclaredMember(container, declarationSpan) : null); } /// <summary> /// Given a variable declarator syntax, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a variable.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The symbol that was declared.</returns> public override ISymbol GetDeclaredSymbol(VariableDeclaratorSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); var field = declarationSyntax.Parent == null ? null : declarationSyntax.Parent.Parent as BaseFieldDeclarationSyntax; if (field != null) { var container = GetDeclaredTypeMemberContainer(field); Debug.Assert((object)container != null); var result = this.GetDeclaredMember(container, declarationSyntax.Span, declarationSyntax.Identifier.ValueText); Debug.Assert((object)result != null); return result.GetPublicSymbol(); } // Might be a local variable. var memberModel = this.GetMemberModel(declarationSyntax); return memberModel?.GetDeclaredSymbol(declarationSyntax, cancellationToken); } public override ISymbol GetDeclaredSymbol(SingleVariableDesignationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { // Might be a local variable. var memberModel = this.GetMemberModel(declarationSyntax); ISymbol local = memberModel?.GetDeclaredSymbol(declarationSyntax, cancellationToken); if (local != null) { return local; } // Might be a field Binder binder = GetEnclosingBinder(declarationSyntax.Position); return binder?.LookupDeclaredField(declarationSyntax).GetPublicSymbol(); } internal override LocalSymbol GetAdjustedLocalSymbol(SourceLocalSymbol originalSymbol) { var position = originalSymbol.IdentifierToken.SpanStart; return GetMemberModel(position)?.GetAdjustedLocalSymbol(originalSymbol) ?? originalSymbol; } /// <summary> /// Given a labeled statement syntax, get the corresponding label symbol. /// </summary> /// <param name="declarationSyntax">The syntax node of the labeled statement.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The label symbol for that label.</returns> public override ILabelSymbol GetDeclaredSymbol(LabeledStatementSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); var memberModel = this.GetMemberModel(declarationSyntax); return memberModel == null ? null : memberModel.GetDeclaredSymbol(declarationSyntax, cancellationToken); } /// <summary> /// Given a switch label syntax, get the corresponding label symbol. /// </summary> /// <param name="declarationSyntax">The syntax node of the switch label.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The label symbol for that label.</returns> public override ILabelSymbol GetDeclaredSymbol(SwitchLabelSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); var memberModel = this.GetMemberModel(declarationSyntax); return memberModel == null ? null : memberModel.GetDeclaredSymbol(declarationSyntax, cancellationToken); } /// <summary> /// Given a using declaration get the corresponding symbol for the using alias that was introduced. /// </summary> /// <param name="declarationSyntax"></param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The alias symbol that was declared.</returns> /// <remarks> /// If the using directive is an error because it attempts to introduce an alias for which an existing alias was /// previously declared in the same scope, the result is a newly-constructed AliasSymbol (i.e. not one from the /// symbol table). /// </remarks> public override IAliasSymbol GetDeclaredSymbol( UsingDirectiveSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); if (declarationSyntax.Alias == null) { return null; } Binder binder = _binderFactory.GetInNamespaceBinder(declarationSyntax.Parent); for (; binder != null; binder = binder.Next) { var usingAliases = binder.UsingAliases; if (!usingAliases.IsDefault) { foreach (var alias in usingAliases) { if (alias.Alias.Locations[0].SourceSpan == declarationSyntax.Alias.Name.Span) { return alias.Alias.GetPublicSymbol(); } } break; } } return null; } /// <summary> /// Given an extern alias declaration get the corresponding symbol for the alias that was introduced. /// </summary> /// <param name="declarationSyntax"></param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The alias symbol that was declared, or null if a duplicate alias symbol was declared.</returns> public override IAliasSymbol GetDeclaredSymbol(ExternAliasDirectiveSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); var binder = _binderFactory.GetInNamespaceBinder(declarationSyntax.Parent); for (; binder != null; binder = binder.Next) { var externAliases = binder.ExternAliases; if (!externAliases.IsDefault) { foreach (var alias in externAliases) { if (alias.Alias.Locations[0].SourceSpan == declarationSyntax.Identifier.Span) { return alias.Alias.GetPublicSymbol(); } } break; } } return null; } /// <summary> /// Given a base field declaration syntax, get the corresponding symbols. /// </summary> /// <param name="declarationSyntax">The syntax node that declares one or more fields or events.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The field symbols that were declared.</returns> internal override ImmutableArray<ISymbol> GetDeclaredSymbols(BaseFieldDeclarationSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); var builder = new ArrayBuilder<ISymbol>(); foreach (var declarator in declarationSyntax.Declaration.Variables) { var field = this.GetDeclaredSymbol(declarator, cancellationToken) as ISymbol; if (field != null) { builder.Add(field); } } return builder.ToImmutableAndFree(); } private ParameterSymbol GetMethodParameterSymbol( ParameterSyntax parameter, CancellationToken cancellationToken) { Debug.Assert(parameter != null); var paramList = parameter.Parent as ParameterListSyntax; if (paramList == null) { return null; } var memberDecl = paramList.Parent as MemberDeclarationSyntax; if (memberDecl == null) { return null; } MethodSymbol method; if (memberDecl is RecordDeclarationSyntax recordDecl && recordDecl.ParameterList == paramList) { method = TryGetSynthesizedRecordConstructor(recordDecl); } else { method = (GetDeclaredSymbol(memberDecl, cancellationToken) as IMethodSymbol).GetSymbol(); } if ((object)method == null) { return null; } return GetParameterSymbol(method.Parameters, parameter, cancellationToken) ?? ((object)method.PartialDefinitionPart == null ? null : GetParameterSymbol(method.PartialDefinitionPart.Parameters, parameter, cancellationToken)); } private ParameterSymbol GetIndexerParameterSymbol( ParameterSyntax parameter, CancellationToken cancellationToken) { Debug.Assert(parameter != null); var paramList = parameter.Parent as BracketedParameterListSyntax; if (paramList == null) { return null; } var memberDecl = paramList.Parent as MemberDeclarationSyntax; if (memberDecl == null) { return null; } var property = (GetDeclaredSymbol(memberDecl, cancellationToken) as IPropertySymbol).GetSymbol(); if ((object)property == null) { return null; } return GetParameterSymbol(property.Parameters, parameter, cancellationToken); } private ParameterSymbol GetDelegateParameterSymbol( ParameterSyntax parameter, CancellationToken cancellationToken) { Debug.Assert(parameter != null); var paramList = parameter.Parent as ParameterListSyntax; if (paramList == null) { return null; } var memberDecl = paramList.Parent as DelegateDeclarationSyntax; if (memberDecl == null) { return null; } var delegateType = (GetDeclaredSymbol(memberDecl, cancellationToken) as INamedTypeSymbol).GetSymbol(); if ((object)delegateType == null) { return null; } var delegateInvoke = delegateType.DelegateInvokeMethod; if ((object)delegateInvoke == null || delegateInvoke.HasUseSiteError) { return null; } return GetParameterSymbol(delegateInvoke.Parameters, parameter, cancellationToken); } /// <summary> /// Given a parameter declaration syntax node, get the corresponding symbol. /// </summary> /// <param name="declarationSyntax">The syntax node that declares a parameter.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The parameter that was declared.</returns> public override IParameterSymbol GetDeclaredSymbol(ParameterSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { CheckSyntaxNode(declarationSyntax); MemberSemanticModel memberModel = this.GetMemberModel(declarationSyntax); if (memberModel != null) { // Could be parameter of lambda. return memberModel.GetDeclaredSymbol(declarationSyntax, cancellationToken); } return GetDeclaredNonLambdaParameterSymbol(declarationSyntax, cancellationToken).GetPublicSymbol(); } private ParameterSymbol GetDeclaredNonLambdaParameterSymbol(ParameterSyntax declarationSyntax, CancellationToken cancellationToken = default(CancellationToken)) { return GetMethodParameterSymbol(declarationSyntax, cancellationToken) ?? GetIndexerParameterSymbol(declarationSyntax, cancellationToken) ?? GetDelegateParameterSymbol(declarationSyntax, cancellationToken); } /// <summary> /// Given a type parameter declaration (field or method), get the corresponding symbol /// </summary> /// <param name="typeParameter"></param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> public override ITypeParameterSymbol GetDeclaredSymbol(TypeParameterSyntax typeParameter, CancellationToken cancellationToken = default(CancellationToken)) { if (typeParameter == null) { throw new ArgumentNullException(nameof(typeParameter)); } if (!IsInTree(typeParameter)) { throw new ArgumentException("typeParameter not within tree"); } if (typeParameter.Parent is TypeParameterListSyntax typeParamList) { ISymbol parameterizedSymbol = null; switch (typeParamList.Parent) { case MemberDeclarationSyntax memberDecl: parameterizedSymbol = GetDeclaredSymbol(memberDecl, cancellationToken); break; case LocalFunctionStatementSyntax localDecl: parameterizedSymbol = GetDeclaredSymbol(localDecl, cancellationToken); break; default: throw ExceptionUtilities.UnexpectedValue(typeParameter.Parent.Kind()); } switch (parameterizedSymbol.GetSymbol()) { case NamedTypeSymbol typeSymbol: return this.GetTypeParameterSymbol(typeSymbol.TypeParameters, typeParameter).GetPublicSymbol(); case MethodSymbol methodSymbol: return (this.GetTypeParameterSymbol(methodSymbol.TypeParameters, typeParameter) ?? ((object)methodSymbol.PartialDefinitionPart == null ? null : this.GetTypeParameterSymbol(methodSymbol.PartialDefinitionPart.TypeParameters, typeParameter))).GetPublicSymbol(); } } return null; } private TypeParameterSymbol GetTypeParameterSymbol(ImmutableArray<TypeParameterSymbol> parameters, TypeParameterSyntax parameter) { foreach (var symbol in parameters) { foreach (var location in symbol.Locations) { if (location.SourceTree == this.SyntaxTree && parameter.Span.Contains(location.SourceSpan)) { return symbol; } } } return null; } public override ControlFlowAnalysis AnalyzeControlFlow(StatementSyntax firstStatement, StatementSyntax lastStatement) { ValidateStatementRange(firstStatement, lastStatement); var context = RegionAnalysisContext(firstStatement, lastStatement); var result = new CSharpControlFlowAnalysis(context); return result; } private void ValidateStatementRange(StatementSyntax firstStatement, StatementSyntax lastStatement) { if (firstStatement == null) { throw new ArgumentNullException(nameof(firstStatement)); } if (lastStatement == null) { throw new ArgumentNullException(nameof(lastStatement)); } if (!IsInTree(firstStatement)) { throw new ArgumentException("statements not within tree"); } // Global statements don't have their parent in common, but should belong to the same compilation unit bool isGlobalStatement = firstStatement.Parent is GlobalStatementSyntax; if (isGlobalStatement && (lastStatement.Parent is not GlobalStatementSyntax || firstStatement.Parent.Parent != lastStatement.Parent.Parent)) { throw new ArgumentException("global statements not within the same compilation unit"); } // Non-global statements, the parents should be the same if (!isGlobalStatement && (firstStatement.Parent == null || firstStatement.Parent != lastStatement.Parent)) { throw new ArgumentException("statements not within the same statement list"); } if (firstStatement.SpanStart > lastStatement.SpanStart) { throw new ArgumentException("first statement does not precede last statement"); } } public override DataFlowAnalysis AnalyzeDataFlow(ExpressionSyntax expression) { if (expression == null) { throw new ArgumentNullException(nameof(expression)); } if (!IsInTree(expression)) { throw new ArgumentException("expression not within tree"); } var context = RegionAnalysisContext(expression); var result = new CSharpDataFlowAnalysis(context); return result; } public override DataFlowAnalysis AnalyzeDataFlow(StatementSyntax firstStatement, StatementSyntax lastStatement) { ValidateStatementRange(firstStatement, lastStatement); var context = RegionAnalysisContext(firstStatement, lastStatement); var result = new CSharpDataFlowAnalysis(context); return result; } private static BoundNode GetBoundRoot(MemberSemanticModel memberModel, out Symbol member) { member = memberModel.MemberSymbol; return memberModel.GetBoundRoot(); } private NamespaceOrTypeSymbol GetDeclaredTypeMemberContainer(CSharpSyntaxNode memberDeclaration) { if (memberDeclaration.Parent.Kind() == SyntaxKind.CompilationUnit) { // top-level namespace: if (memberDeclaration.Kind() is SyntaxKind.NamespaceDeclaration or SyntaxKind.FileScopedNamespaceDeclaration) { return _compilation.Assembly.GlobalNamespace; } // top-level members in script or interactive code: if (this.SyntaxTree.Options.Kind != SourceCodeKind.Regular) { return this.Compilation.ScriptClass; } // top-level type in an explicitly declared namespace: if (SyntaxFacts.IsTypeDeclaration(memberDeclaration.Kind())) { return _compilation.Assembly.GlobalNamespace; } // other top-level members: return _compilation.Assembly.GlobalNamespace.ImplicitType; } var container = GetDeclaredNamespaceOrType(memberDeclaration.Parent); Debug.Assert((object)container != null); // member in a type: if (!container.IsNamespace) { return container; } // a namespace or a type in an explicitly declared namespace: if (memberDeclaration.Kind() is SyntaxKind.NamespaceDeclaration or SyntaxKind.FileScopedNamespaceDeclaration || SyntaxFacts.IsTypeDeclaration(memberDeclaration.Kind())) { return container; } // another member in a namespace: return ((NamespaceSymbol)container).ImplicitType; } private Symbol GetDeclaredMemberSymbol(CSharpSyntaxNode declarationSyntax) { CheckSyntaxNode(declarationSyntax); var container = GetDeclaredTypeMemberContainer(declarationSyntax); var name = GetDeclarationName(declarationSyntax); return this.GetDeclaredMember(container, declarationSyntax.Span, name); } public override AwaitExpressionInfo GetAwaitExpressionInfo(AwaitExpressionSyntax node) { MemberSemanticModel memberModel = GetMemberModel(node); return memberModel == null ? default(AwaitExpressionInfo) : memberModel.GetAwaitExpressionInfo(node); } public override ForEachStatementInfo GetForEachStatementInfo(ForEachStatementSyntax node) { MemberSemanticModel memberModel = GetMemberModel(node); return memberModel == null ? default(ForEachStatementInfo) : memberModel.GetForEachStatementInfo(node); } public override ForEachStatementInfo GetForEachStatementInfo(CommonForEachStatementSyntax node) { MemberSemanticModel memberModel = GetMemberModel(node); return memberModel == null ? default(ForEachStatementInfo) : memberModel.GetForEachStatementInfo(node); } public override DeconstructionInfo GetDeconstructionInfo(AssignmentExpressionSyntax node) { MemberSemanticModel memberModel = GetMemberModel(node); return memberModel?.GetDeconstructionInfo(node) ?? default; } public override DeconstructionInfo GetDeconstructionInfo(ForEachVariableStatementSyntax node) { MemberSemanticModel memberModel = GetMemberModel(node); return memberModel?.GetDeconstructionInfo(node) ?? default; } internal override Symbol RemapSymbolIfNecessaryCore(Symbol symbol) { Debug.Assert(symbol is LocalSymbol or ParameterSymbol or MethodSymbol { MethodKind: MethodKind.LambdaMethod }); if (symbol.Locations.IsDefaultOrEmpty) { return symbol; } var location = symbol.Locations[0]; // The symbol may be from a distinct syntax tree - perhaps the // symbol was returned from LookupSymbols() for instance. if (location.SourceTree != this.SyntaxTree) { return symbol; } var position = CheckAndAdjustPosition(location.SourceSpan.Start); var memberModel = GetMemberModel(position); return memberModel?.RemapSymbolIfNecessaryCore(symbol) ?? symbol; } internal override Func<SyntaxNode, bool> GetSyntaxNodesToAnalyzeFilter(SyntaxNode declaredNode, ISymbol declaredSymbol) { switch (declaredNode) { case CompilationUnitSyntax unit when SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(Compilation, unit, fallbackToMainEntryPoint: false) is SynthesizedSimpleProgramEntryPointSymbol entryPoint: switch (declaredSymbol.Kind) { case SymbolKind.Namespace: Debug.Assert(((INamespaceSymbol)declaredSymbol).IsGlobalNamespace); // Do not include top level global statements into a global namespace return (node) => node.Kind() != SyntaxKind.GlobalStatement || node.Parent != unit; case SymbolKind.Method: Debug.Assert((object)declaredSymbol.GetSymbol() == (object)entryPoint); // Include only global statements at the top level return (node) => node.Parent != unit || node.Kind() == SyntaxKind.GlobalStatement; case SymbolKind.NamedType: Debug.Assert((object)declaredSymbol.GetSymbol() == (object)entryPoint.ContainingSymbol); return (node) => false; default: ExceptionUtilities.UnexpectedValue(declaredSymbol.Kind); break; } break; case RecordDeclarationSyntax recordDeclaration when TryGetSynthesizedRecordConstructor(recordDeclaration) is SynthesizedRecordConstructor ctor: if (recordDeclaration.IsKind(SyntaxKind.RecordDeclaration)) { switch (declaredSymbol.Kind) { case SymbolKind.Method: Debug.Assert((object)declaredSymbol.GetSymbol() == (object)ctor); return (node) => { // Accept only nodes that either match, or above/below of a 'parameter list'/'base arguments list'. if (node.Parent == recordDeclaration) { return node == recordDeclaration.ParameterList || node == recordDeclaration.BaseList; } else if (node.Parent is BaseListSyntax baseList) { return node == recordDeclaration.PrimaryConstructorBaseTypeIfClass; } else if (node.Parent is PrimaryConstructorBaseTypeSyntax baseType && baseType == recordDeclaration.PrimaryConstructorBaseTypeIfClass) { return node == baseType.ArgumentList; } return true; }; case SymbolKind.NamedType: Debug.Assert((object)declaredSymbol.GetSymbol() == (object)ctor.ContainingSymbol); // Accept nodes that do not match a 'parameter list'/'base arguments list'. return (node) => node != recordDeclaration.ParameterList && !(node.Kind() == SyntaxKind.ArgumentList && node == recordDeclaration.PrimaryConstructorBaseTypeIfClass?.ArgumentList); default: ExceptionUtilities.UnexpectedValue(declaredSymbol.Kind); break; } } else { switch (declaredSymbol.Kind) { case SymbolKind.Method: Debug.Assert((object)declaredSymbol.GetSymbol() == (object)ctor); return (node) => { // Accept only nodes that either match, or above/below of a 'parameter list'. if (node.Parent == recordDeclaration) { return node == recordDeclaration.ParameterList; } return true; }; case SymbolKind.NamedType: Debug.Assert((object)declaredSymbol.GetSymbol() == (object)ctor.ContainingSymbol); // Accept nodes that do not match a 'parameter list'. return (node) => node != recordDeclaration.ParameterList; default: ExceptionUtilities.UnexpectedValue(declaredSymbol.Kind); break; } } break; case PrimaryConstructorBaseTypeSyntax { Parent: BaseListSyntax { Parent: RecordDeclarationSyntax recordDeclaration } } baseType when recordDeclaration.PrimaryConstructorBaseTypeIfClass == declaredNode && TryGetSynthesizedRecordConstructor(recordDeclaration) is SynthesizedRecordConstructor ctor: if ((object)declaredSymbol.GetSymbol() == (object)ctor) { // Only 'base arguments list' or nodes below it return (node) => node != baseType.Type; } break; case ParameterSyntax param when declaredSymbol.Kind == SymbolKind.Property && param.Parent?.Parent is RecordDeclarationSyntax recordDeclaration && recordDeclaration.ParameterList == param.Parent: Debug.Assert(declaredSymbol.GetSymbol() is SynthesizedRecordPropertySymbol); return (node) => false; } return null; } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/EditorFeatures/Core/Implementation/IPreviewFactoryService.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; namespace Microsoft.CodeAnalysis.Editor { internal interface IPreviewFactoryService { SolutionPreviewResult GetSolutionPreviews(Solution oldSolution, Solution newSolution, CancellationToken cancellationToken); SolutionPreviewResult GetSolutionPreviews(Solution oldSolution, Solution newSolution, double zoomLevel, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; namespace Microsoft.CodeAnalysis.Editor { internal interface IPreviewFactoryService { SolutionPreviewResult GetSolutionPreviews(Solution oldSolution, Solution newSolution, CancellationToken cancellationToken); SolutionPreviewResult GetSolutionPreviews(Solution oldSolution, Solution newSolution, double zoomLevel, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Features/Core/Portable/MoveToNamespace/IMoveToNamespaceOptionsService.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.Host; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.MoveToNamespace { internal interface IMoveToNamespaceOptionsService : IWorkspaceService { MoveToNamespaceOptionsResult GetChangeNamespaceOptions( string defaultNamespace, ImmutableArray<string> availableNamespaces, ISyntaxFacts syntaxFactsService); } }
// Licensed to the .NET Foundation under one or more 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.Host; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.MoveToNamespace { internal interface IMoveToNamespaceOptionsService : IWorkspaceService { MoveToNamespaceOptionsResult GetChangeNamespaceOptions( string defaultNamespace, ImmutableArray<string> availableNamespaces, ISyntaxFacts syntaxFactsService); } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/Operations/IndentBlockOperation.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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting.Rules { /// <summary> /// set indentation level for the given text span. it can be relative, absolute or dependent to other tokens /// </summary> internal sealed class IndentBlockOperation { internal IndentBlockOperation(SyntaxToken startToken, SyntaxToken endToken, TextSpan textSpan, int indentationDelta, IndentBlockOption option) { Contract.ThrowIfFalse(option.IsMaskOn(IndentBlockOption.PositionMask)); Contract.ThrowIfTrue(textSpan.Start < 0 || textSpan.Length < 0); Contract.ThrowIfTrue(startToken.RawKind == 0); Contract.ThrowIfTrue(endToken.RawKind == 0); this.BaseToken = default; this.TextSpan = textSpan; this.Option = option; this.StartToken = startToken; this.EndToken = endToken; this.IsRelativeIndentation = false; this.IndentationDeltaOrPosition = indentationDelta; } internal IndentBlockOperation(SyntaxToken baseToken, SyntaxToken startToken, SyntaxToken endToken, TextSpan textSpan, int indentationDelta, IndentBlockOption option) { Contract.ThrowIfFalse(option.IsMaskOn(IndentBlockOption.PositionMask)); Contract.ThrowIfFalse(option.IsMaskOn(IndentBlockOption.RelativePositionMask)); Contract.ThrowIfFalse(baseToken.Span.End <= textSpan.Start); Contract.ThrowIfTrue(textSpan.Start < 0 || textSpan.Length < 0); Contract.ThrowIfTrue(startToken.RawKind == 0); Contract.ThrowIfTrue(endToken.RawKind == 0); this.BaseToken = baseToken; this.TextSpan = textSpan; this.Option = option; this.StartToken = startToken; this.EndToken = endToken; this.IsRelativeIndentation = true; this.IndentationDeltaOrPosition = indentationDelta; } public SyntaxToken BaseToken { get; } public TextSpan TextSpan { get; } public IndentBlockOption Option { get; } public SyntaxToken StartToken { get; } public SyntaxToken EndToken { get; } public bool IsRelativeIndentation { get; } public int IndentationDeltaOrPosition { get; } #if DEBUG public override string ToString() => $"Indent {TextSpan} from '{StartToken}' to '{EndToken}', by {IndentationDeltaOrPosition}, with base token '{BaseToken}'"; #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. using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting.Rules { /// <summary> /// set indentation level for the given text span. it can be relative, absolute or dependent to other tokens /// </summary> internal sealed class IndentBlockOperation { internal IndentBlockOperation(SyntaxToken startToken, SyntaxToken endToken, TextSpan textSpan, int indentationDelta, IndentBlockOption option) { Contract.ThrowIfFalse(option.IsMaskOn(IndentBlockOption.PositionMask)); Contract.ThrowIfTrue(textSpan.Start < 0 || textSpan.Length < 0); Contract.ThrowIfTrue(startToken.RawKind == 0); Contract.ThrowIfTrue(endToken.RawKind == 0); this.BaseToken = default; this.TextSpan = textSpan; this.Option = option; this.StartToken = startToken; this.EndToken = endToken; this.IsRelativeIndentation = false; this.IndentationDeltaOrPosition = indentationDelta; } internal IndentBlockOperation(SyntaxToken baseToken, SyntaxToken startToken, SyntaxToken endToken, TextSpan textSpan, int indentationDelta, IndentBlockOption option) { Contract.ThrowIfFalse(option.IsMaskOn(IndentBlockOption.PositionMask)); Contract.ThrowIfFalse(option.IsMaskOn(IndentBlockOption.RelativePositionMask)); Contract.ThrowIfFalse(baseToken.Span.End <= textSpan.Start); Contract.ThrowIfTrue(textSpan.Start < 0 || textSpan.Length < 0); Contract.ThrowIfTrue(startToken.RawKind == 0); Contract.ThrowIfTrue(endToken.RawKind == 0); this.BaseToken = baseToken; this.TextSpan = textSpan; this.Option = option; this.StartToken = startToken; this.EndToken = endToken; this.IsRelativeIndentation = true; this.IndentationDeltaOrPosition = indentationDelta; } public SyntaxToken BaseToken { get; } public TextSpan TextSpan { get; } public IndentBlockOption Option { get; } public SyntaxToken StartToken { get; } public SyntaxToken EndToken { get; } public bool IsRelativeIndentation { get; } public int IndentationDeltaOrPosition { get; } #if DEBUG public override string ToString() => $"Indent {TextSpan} from '{StartToken}' to '{EndToken}', by {IndentationDeltaOrPosition}, with base token '{BaseToken}'"; #endif } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/CPS/ICodeModelFactory.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.ProjectSystem { /// <summary> /// Provides file/project code model for a given project context. /// </summary> internal interface ICodeModelFactory { EnvDTE.FileCodeModel GetFileCodeModel(IWorkspaceProjectContext context, EnvDTE.ProjectItem item); EnvDTE.CodeModel GetCodeModel(IWorkspaceProjectContext context, EnvDTE.Project project); } }
// Licensed to the .NET Foundation under one or more 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.ProjectSystem { /// <summary> /// Provides file/project code model for a given project context. /// </summary> internal interface ICodeModelFactory { EnvDTE.FileCodeModel GetFileCodeModel(IWorkspaceProjectContext context, EnvDTE.ProjectItem item); EnvDTE.CodeModel GetCodeModel(IWorkspaceProjectContext context, EnvDTE.Project project); } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/VisualStudio/Core/Impl/Options/Style/NamingPreferences/NamingStyles/NamingStyleDialog.xaml.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.Windows; using Microsoft.VisualStudio.PlatformUI; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options.Style.NamingPreferences { /// <summary> /// Interaction logic for NamingStyleDialog.xaml /// </summary> internal partial class NamingStyleDialog : DialogWindow { private readonly NamingStyleViewModel _viewModel; public string DialogTitle => ServicesVSResources.Naming_Style; public string NamingStyleTitleLabelText => ServicesVSResources.Naming_Style_Title_colon; public string RequiredPrefixLabelText => ServicesVSResources.Required_Prefix_colon; public string RequiredSuffixLabelText => ServicesVSResources.Required_Suffix_colon; public string WordSeparatorLabelText => ServicesVSResources.Word_Separator_colon; public string CapitalizationLabelText => ServicesVSResources.Capitalization_colon; public string SampleIdentifierLabelText => ServicesVSResources.Sample_Identifier_colon; public string OK => ServicesVSResources.OK; public string Cancel => ServicesVSResources.Cancel; internal NamingStyleDialog(NamingStyleViewModel viewModel) { _viewModel = viewModel; InitializeComponent(); DataContext = viewModel; } private void OK_Click(object sender, RoutedEventArgs e) { if (_viewModel.TrySubmit()) { DialogResult = true; } } private void Cancel_Click(object sender, RoutedEventArgs e) => DialogResult = 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.Windows; using Microsoft.VisualStudio.PlatformUI; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options.Style.NamingPreferences { /// <summary> /// Interaction logic for NamingStyleDialog.xaml /// </summary> internal partial class NamingStyleDialog : DialogWindow { private readonly NamingStyleViewModel _viewModel; public string DialogTitle => ServicesVSResources.Naming_Style; public string NamingStyleTitleLabelText => ServicesVSResources.Naming_Style_Title_colon; public string RequiredPrefixLabelText => ServicesVSResources.Required_Prefix_colon; public string RequiredSuffixLabelText => ServicesVSResources.Required_Suffix_colon; public string WordSeparatorLabelText => ServicesVSResources.Word_Separator_colon; public string CapitalizationLabelText => ServicesVSResources.Capitalization_colon; public string SampleIdentifierLabelText => ServicesVSResources.Sample_Identifier_colon; public string OK => ServicesVSResources.OK; public string Cancel => ServicesVSResources.Cancel; internal NamingStyleDialog(NamingStyleViewModel viewModel) { _viewModel = viewModel; InitializeComponent(); DataContext = viewModel; } private void OK_Click(object sender, RoutedEventArgs e) { if (_viewModel.TrySubmit()) { DialogResult = true; } } private void Cancel_Click(object sender, RoutedEventArgs e) => DialogResult = false; } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Features/Core/Portable/CodeFixes/Iterator/AbstractIteratorCodeFixProvider.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; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeFixes.Iterator { internal abstract class AbstractIteratorCodeFixProvider : CodeFixProvider { public override FixAllProvider GetFixAllProvider() { // Fix All is not supported by this code fix return null; } protected abstract Task<CodeAction> GetCodeFixAsync(SyntaxNode root, SyntaxNode node, Document document, Diagnostic diagnostics, CancellationToken cancellationToken); public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); if (!TryGetNode(root, context.Span, out var node)) { return; } var diagnostic = context.Diagnostics.FirstOrDefault(); var codeAction = await GetCodeFixAsync(root, node, context.Document, diagnostic, context.CancellationToken).ConfigureAwait(false); if (codeAction != null) { context.RegisterCodeFix(codeAction, diagnostic); } } protected virtual bool TryGetNode(SyntaxNode root, TextSpan span, out SyntaxNode node) { node = null; var ancestors = root.FindToken(span.Start).GetAncestors<SyntaxNode>(); if (!ancestors.Any()) { return false; } node = ancestors.FirstOrDefault(n => n.Span.Contains(span) && n != root); return node != null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeFixes.Iterator { internal abstract class AbstractIteratorCodeFixProvider : CodeFixProvider { public override FixAllProvider GetFixAllProvider() { // Fix All is not supported by this code fix return null; } protected abstract Task<CodeAction> GetCodeFixAsync(SyntaxNode root, SyntaxNode node, Document document, Diagnostic diagnostics, CancellationToken cancellationToken); public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); if (!TryGetNode(root, context.Span, out var node)) { return; } var diagnostic = context.Diagnostics.FirstOrDefault(); var codeAction = await GetCodeFixAsync(root, node, context.Document, diagnostic, context.CancellationToken).ConfigureAwait(false); if (codeAction != null) { context.RegisterCodeFix(codeAction, diagnostic); } } protected virtual bool TryGetNode(SyntaxNode root, TextSpan span, out SyntaxNode node) { node = null; var ancestors = root.FindToken(span.Start).GetAncestors<SyntaxNode>(); if (!ancestors.Any()) { return false; } node = ancestors.FirstOrDefault(n => n.Span.Contains(span) && n != root); return node != null; } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/Core/Portable/DiaSymReader/Writer/SymUnmanagedWriterFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; namespace Microsoft.DiaSymReader { internal static class SymUnmanagedWriterFactory { /// <summary> /// Creates a Windows PDB writer. /// </summary> /// <param name="metadataProvider"><see cref="ISymWriterMetadataProvider"/> implementation.</param> /// <param name="options">Options.</param> /// <remarks> /// Tries to load the implementation of the PDB writer from Microsoft.DiaSymReader.Native.{platform}.dll library first. /// It searches for this library in the directory Microsoft.DiaSymReader.dll is loaded from, /// the application directory, the %WinDir%\System32 directory, and user directories in the DLL search path, in this order. /// If not found in the above locations and <see cref="SymUnmanagedWriterCreationOptions.UseAlternativeLoadPath"/> option is specified /// the directory specified by MICROSOFT_DIASYMREADER_NATIVE_ALT_LOAD_PATH environment variable is also searched. /// If the Microsoft.DiaSymReader.Native.{platform}.dll library can't be found and <see cref="SymUnmanagedWriterCreationOptions.UseComRegistry"/> /// option is specified checks if the PDB reader is available from a globally registered COM object. This COM object is provided /// by .NET Framework and has limited functionality (features like determinism and source link are not supported). /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="metadataProvider"/>is null.</exception> /// <exception cref="DllNotFoundException">The SymWriter implementation is not available or failed to load.</exception> /// <exception cref="SymUnmanagedWriterException">Error creating the PDB writer. See inner exception for root cause.</exception> public static SymUnmanagedWriter CreateWriter( ISymWriterMetadataProvider metadataProvider, SymUnmanagedWriterCreationOptions options = SymUnmanagedWriterCreationOptions.Default) { if (metadataProvider == null) { throw new ArgumentNullException(nameof(metadataProvider)); } var symWriter = SymUnmanagedFactory.CreateObject( createReader: false, useAlternativeLoadPath: (options & SymUnmanagedWriterCreationOptions.UseAlternativeLoadPath) != 0, useComRegistry: (options & SymUnmanagedWriterCreationOptions.UseComRegistry) != 0, moduleName: out var implModuleName, loadException: out var loadException); if (symWriter == null) { Debug.Assert(loadException != null); if (loadException is DllNotFoundException) { throw loadException; } throw new DllNotFoundException(loadException.Message, loadException); } if (!(symWriter is ISymUnmanagedWriter5 symWriter5)) { throw new SymUnmanagedWriterException(new NotSupportedException(), implModuleName); } object metadataEmitAndImport = new SymWriterMetadataAdapter(metadataProvider); var pdbStream = new ComMemoryStream(); try { if ((options & SymUnmanagedWriterCreationOptions.Deterministic) != 0) { if (symWriter is ISymUnmanagedWriter8 symWriter8) { symWriter8.InitializeDeterministic(metadataEmitAndImport, pdbStream); } else { throw new NotSupportedException(); } } else { // The file name is irrelevant as long as it's specified. // SymWriter only uses it for filling CodeView debug directory data when asked for them, but we never do. symWriter5.Initialize(metadataEmitAndImport, "filename.pdb", pdbStream, fullBuild: true); } } catch (Exception e) { throw new SymUnmanagedWriterException(e, implModuleName); } return new SymUnmanagedWriterImpl(pdbStream, symWriter5, implModuleName); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; namespace Microsoft.DiaSymReader { internal static class SymUnmanagedWriterFactory { /// <summary> /// Creates a Windows PDB writer. /// </summary> /// <param name="metadataProvider"><see cref="ISymWriterMetadataProvider"/> implementation.</param> /// <param name="options">Options.</param> /// <remarks> /// Tries to load the implementation of the PDB writer from Microsoft.DiaSymReader.Native.{platform}.dll library first. /// It searches for this library in the directory Microsoft.DiaSymReader.dll is loaded from, /// the application directory, the %WinDir%\System32 directory, and user directories in the DLL search path, in this order. /// If not found in the above locations and <see cref="SymUnmanagedWriterCreationOptions.UseAlternativeLoadPath"/> option is specified /// the directory specified by MICROSOFT_DIASYMREADER_NATIVE_ALT_LOAD_PATH environment variable is also searched. /// If the Microsoft.DiaSymReader.Native.{platform}.dll library can't be found and <see cref="SymUnmanagedWriterCreationOptions.UseComRegistry"/> /// option is specified checks if the PDB reader is available from a globally registered COM object. This COM object is provided /// by .NET Framework and has limited functionality (features like determinism and source link are not supported). /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="metadataProvider"/>is null.</exception> /// <exception cref="DllNotFoundException">The SymWriter implementation is not available or failed to load.</exception> /// <exception cref="SymUnmanagedWriterException">Error creating the PDB writer. See inner exception for root cause.</exception> public static SymUnmanagedWriter CreateWriter( ISymWriterMetadataProvider metadataProvider, SymUnmanagedWriterCreationOptions options = SymUnmanagedWriterCreationOptions.Default) { if (metadataProvider == null) { throw new ArgumentNullException(nameof(metadataProvider)); } var symWriter = SymUnmanagedFactory.CreateObject( createReader: false, useAlternativeLoadPath: (options & SymUnmanagedWriterCreationOptions.UseAlternativeLoadPath) != 0, useComRegistry: (options & SymUnmanagedWriterCreationOptions.UseComRegistry) != 0, moduleName: out var implModuleName, loadException: out var loadException); if (symWriter == null) { Debug.Assert(loadException != null); if (loadException is DllNotFoundException) { throw loadException; } throw new DllNotFoundException(loadException.Message, loadException); } if (!(symWriter is ISymUnmanagedWriter5 symWriter5)) { throw new SymUnmanagedWriterException(new NotSupportedException(), implModuleName); } object metadataEmitAndImport = new SymWriterMetadataAdapter(metadataProvider); var pdbStream = new ComMemoryStream(); try { if ((options & SymUnmanagedWriterCreationOptions.Deterministic) != 0) { if (symWriter is ISymUnmanagedWriter8 symWriter8) { symWriter8.InitializeDeterministic(metadataEmitAndImport, pdbStream); } else { throw new NotSupportedException(); } } else { // The file name is irrelevant as long as it's specified. // SymWriter only uses it for filling CodeView debug directory data when asked for them, but we never do. symWriter5.Initialize(metadataEmitAndImport, "filename.pdb", pdbStream, fullBuild: true); } } catch (Exception e) { throw new SymUnmanagedWriterException(e, implModuleName); } return new SymUnmanagedWriterImpl(pdbStream, symWriter5, implModuleName); } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Workspaces/CoreTest/CodeCleanup/FixIncorrectTokenTests.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.Threading.Tasks; using Microsoft.CodeAnalysis.CodeCleanup; using Microsoft.CodeAnalysis.CodeCleanup.Providers; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.CodeCleanup { [UseExportProvider] public class FixIncorrectTokensTests { [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_WithMatchingIf() { var code = @" Module Program Sub Main(args As String()) [|If args IsNot Nothing Then System.Console.WriteLine(args) endif|] End Sub End Module"; var expected = @" Module Program Sub Main(args As String()) If args IsNot Nothing Then System.Console.WriteLine(args) End If End Sub End Module"; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_WithMatchingIf_Directive() { var code = @"[| #If c = 0 Then #Endif|]"; var expected = @" #If c = 0 Then #End If"; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_WithoutMatchingIf() { var code = @" Module Program Sub Main(args As String()) [|EndIf|] End Sub End Module"; var expected = @" Module Program Sub Main(args As String()) End If End Sub End Module"; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_WithoutMatchingIf_Directive() { var code = @"[| Class X End Class #Endif|]"; var expected = @" Class X End Class #End If"; await VerifyAsync(code, expected); } [Fact(Skip = "889521")] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_SameLineAsIf() { var code = @" Module Program Sub Main(args As String()) If args IsNot Nothing Then [|EndIf|] End Sub End Module"; var expected = @" Module Program Sub Main(args As String()) If args IsNot Nothing Then End If End Sub End Module"; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_SameLineAsIf_Invalid() { var code = @" Module Program Sub Main(args As String()) If args IsNot Nothing [|EndIf|] End Sub End Module"; var expected = @" Module Program Sub Main(args As String()) If args IsNot Nothing EndIf End Sub End Module"; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_SameLineAsIf_Directive() { var code = @"[| #If c = 0 Then #Endif|]"; var expected = @" #If c = 0 Then #Endif"; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_WithLeadingTrivia() { var code = @" Module Program Sub Main(args As String()) [|If args IsNot Nothing Then System.Console.WriteLine(args) ' Dummy Endif EndIf|] End Sub End Module"; var expected = @" Module Program Sub Main(args As String()) If args IsNot Nothing Then System.Console.WriteLine(args) ' Dummy Endif End If End Sub End Module"; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_WithLeadingTrivia_Directive() { var code = @"[| #If c = 0 Then '#Endif #Endif |]"; var expected = @" #If c = 0 Then '#Endif #End If "; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_InvocationExpressionArgument() { var code = @" Module Program Sub Main(args As String()) [|If args IsNot Nothing Then System.Console.WriteLine(args) InvocationExpression EndIf|] End Sub End Module"; var expected = @" Module Program Sub Main(args As String()) If args IsNot Nothing Then System.Console.WriteLine(args) InvocationExpression EndIf End Sub End Module"; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_InvalidDirectiveCases() { var code = @"[| ' BadDirective cases #If c = 0 Then #InvocationExpression #Endif #If c = 0 Then InvocationExpression# #Endif #If c = 0 Then InvocationExpression #Endif ' Missing EndIfDirective cases #If c = 0 Then #InvocationExpression #Endif #If c = 0 Then InvocationExpression# #Endif #If c = 0 Then InvocationExpression #Endif |]"; var expected = @" ' BadDirective cases #If c = 0 Then #InvocationExpression #Endif #If c = 0 Then InvocationExpression# #Endif #If c = 0 Then InvocationExpression #Endif ' Missing EndIfDirective cases #If c = 0 Then #InvocationExpression #End If #If c = 0 Then InvocationExpression# #End If #If c = 0 Then InvocationExpression #End If "; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_WithTrailingTrivia() { var code = @" Module Program Sub Main(args As String()) [|If args IsNot Nothing Then System.Console.WriteLine(args) EndIf ' Dummy EndIf|] End Sub End Module"; var expected = @" Module Program Sub Main(args As String()) If args IsNot Nothing Then System.Console.WriteLine(args) End If ' Dummy EndIf End Sub End Module"; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_WithTrailingTrivia_Directive() { var code = @"[| #If c = 0 Then #Endif '#Endif |]"; var expected = @" #If c = 0 Then #End If '#Endif "; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_WithIdentifierTokenTrailingTrivia() { var code = @" Module Program Sub Main(args As String()) [|If args IsNot Nothing Then System.Console.WriteLine(args) EndIf IdentifierToken|] End Sub End Module"; var expected = @" Module Program Sub Main(args As String()) If args IsNot Nothing Then System.Console.WriteLine(args) End If IdentifierToken End Sub End Module"; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_InvalidDirectiveCases_02() { var code = @"[| ' BadDirective cases #If c = 0 Then #Endif #IdentifierToken #If c = 0 Then #Endif IdentifierToken# #If c = 0 Then #Endif IdentifierToken ' Missing EndIfDirective cases #If c = 0 Then #Endif #IdentifierToken #If c = 0 Then #Endif IdentifierToken# #If c = 0 Then #Endif IdentifierToken |]"; var expected = @" ' BadDirective cases #If c = 0 Then #End If #IdentifierToken #If c = 0 Then #End If IdentifierToken# #If c = 0 Then #End If IdentifierToken ' Missing EndIfDirective cases #If c = 0 Then #End If #IdentifierToken #If c = 0 Then #End If IdentifierToken# #If c = 0 Then #End If IdentifierToken "; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_WithLeadingAndTrailingTrivia() { var code = @" Module Program Sub Main(args As String()) [|If args IsNot Nothing Then System.Console.WriteLine(args) ' Dummy EndIf EndIf ' Dummy EndIf|] End Sub End Module"; var expected = @" Module Program Sub Main(args As String()) If args IsNot Nothing Then System.Console.WriteLine(args) ' Dummy EndIf End If ' Dummy EndIf End Sub End Module"; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_WithLeadingAndTrailingTrivia_Directive() { var code = @"[| #If c = 0 Then '#Endif #Endif '#Endif |]"; var expected = @" #If c = 0 Then '#Endif #End If '#Endif "; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_WithLeadingAndTrailingInvocationExpressions() { var code = @" Module Program Sub Main(args As String()) [|If args IsNot Nothing Then System.Console.WriteLine(args) IdentifierToken EndIf IdentifierToken|] End Sub End Module"; var expected = @" Module Program Sub Main(args As String()) If args IsNot Nothing Then System.Console.WriteLine(args) IdentifierToken End If IdentifierToken End Sub End Module"; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_WithLeadingAndTrailingInvocationExpressions_Directive() { var code = @"[| ' BadDirective cases #If c = 0 Then #InvalidTrivia #Endif #InvalidTrivia #If c = 0 Then InvalidTrivia #Endif InvalidTrivia #If c = 0 Then InvalidTrivia# #Endif InvalidTrivia# ' Missing EndIfDirective cases #If c = 0 Then #InvalidTrivia #Endif #InvalidTrivia #If c = 0 Then InvalidTrivia #Endif InvalidTrivia #If c = 0 Then InvalidTrivia# #Endif InvalidTrivia# |]"; var expected = @" ' BadDirective cases #If c = 0 Then #InvalidTrivia #Endif #InvalidTrivia #If c = 0 Then InvalidTrivia #Endif InvalidTrivia #If c = 0 Then InvalidTrivia# #Endif InvalidTrivia# ' Missing EndIfDirective cases #If c = 0 Then #InvalidTrivia #End If #InvalidTrivia #If c = 0 Then InvalidTrivia #End If InvalidTrivia #If c = 0 Then InvalidTrivia# #End If InvalidTrivia# "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5722, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixPrimitiveTypeKeywords_ValidCases() { var code = @"[| Imports SystemAlias = System Imports SystemInt16Alias = System.Short Imports SystemUInt16Alias = System.ushort Imports SystemInt32Alias = System.INTEGER Imports SystemUInt32Alias = System.UInteger Imports SystemInt64Alias = System.Long Imports SystemUInt64Alias = System.uLong Imports SystemDateTimeAlias = System.Date Module Program Sub Main(args As String()) Dim a1 As System.Short = 0 Dim b1 As SystemAlias.SHORT = a1 Dim c1 As SystemInt16Alias = b1 Dim a2 As System.UShort = 0 Dim b2 As SystemAlias.USHORT = a2 Dim c2 As SystemUInt16Alias = b2 Dim a3 As System.Integer = 0 Dim b3 As SystemAlias.INTEGER = a3 Dim c3 As SystemInt32Alias = b3 Dim a4 As System.UInteger = 0 Dim b4 As SystemAlias.UINTEGER = a4 Dim c4 As SystemUInt32Alias = b4 Dim a5 As System.Long = 0 Dim b5 As SystemAlias.LONG = a5 Dim c5 As SystemInt64Alias = b5 Dim a6 As System.ULong = 0 Dim b6 As SystemAlias.ULONG = 0 Dim c6 As SystemUInt64Alias = 0 Dim a7 As System.Date = Nothing Dim b7 As SystemAlias.DATE = Nothing Dim c7 As SystemDateTimeAlias = Nothing End Sub End Module |]"; var expected = @" Imports SystemAlias = System Imports SystemInt16Alias = System.Int16 Imports SystemUInt16Alias = System.UInt16 Imports SystemInt32Alias = System.Int32 Imports SystemUInt32Alias = System.UInt32 Imports SystemInt64Alias = System.Int64 Imports SystemUInt64Alias = System.UInt64 Imports SystemDateTimeAlias = System.DateTime Module Program Sub Main(args As String()) Dim a1 As System.Int16 = 0 Dim b1 As SystemAlias.Int16 = a1 Dim c1 As SystemInt16Alias = b1 Dim a2 As System.UInt16 = 0 Dim b2 As SystemAlias.UInt16 = a2 Dim c2 As SystemUInt16Alias = b2 Dim a3 As System.Int32 = 0 Dim b3 As SystemAlias.Int32 = a3 Dim c3 As SystemInt32Alias = b3 Dim a4 As System.UInt32 = 0 Dim b4 As SystemAlias.UInt32 = a4 Dim c4 As SystemUInt32Alias = b4 Dim a5 As System.Int64 = 0 Dim b5 As SystemAlias.Int64 = a5 Dim c5 As SystemInt64Alias = b5 Dim a6 As System.UInt64 = 0 Dim b6 As SystemAlias.UInt64 = 0 Dim c6 As SystemUInt64Alias = 0 Dim a7 As System.DateTime = Nothing Dim b7 As SystemAlias.DateTime = Nothing Dim c7 As SystemDateTimeAlias = Nothing End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5722, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixPrimitiveTypeKeywords_InvalidCases() { // With a user defined type named System // No fixups as System binds to type not a namespace. var code = @" Imports SystemAlias = System Imports SystemInt16Alias = System.Short Imports SystemUInt16Alias = System.ushort Imports SystemInt32Alias = System.INTEGER Imports SystemUInt32Alias = System.UInteger Imports SystemInt64Alias = System.Long Imports SystemUInt64Alias = System.uLong Imports SystemDateTimeAlias = System.Date Class System End Class Module Program Sub Main(args As String()) Dim a1 As System.Short = 0 Dim b1 As SystemAlias.SHORT = a1 Dim c1 As SystemInt16Alias = b1 Dim d1 As System.System.Short = 0 Dim e1 As Short = 0 Dim a2 As System.UShort = 0 Dim b2 As SystemAlias.USHORT = a2 Dim c2 As SystemUInt16Alias = b2 Dim d2 As System.System.UShort = 0 Dim e2 As UShort = 0 Dim a3 As System.Integer = 0 Dim b3 As SystemAlias.INTEGER = a3 Dim c3 As SystemInt32Alias = b3 Dim d3 As System.System.Integer = 0 Dim e3 As Integer = 0 Dim a4 As System.UInteger = 0 Dim b4 As SystemAlias.UINTEGER = a4 Dim c4 As SystemUInt32Alias = b4 Dim d4 As System.System.UInteger = 0 Dim e4 As UInteger = 0 Dim a5 As System.Long = 0 Dim b5 As SystemAlias.LONG = a5 Dim c5 As SystemInt64Alias = b5 Dim d5 As System.System.Long = 0 Dim e5 As Long = 0 Dim a6 As System.ULong = 0 Dim b6 As SystemAlias.ULONG = 0 Dim c6 As SystemUInt64Alias = 0 Dim d6 As System.System.ULong = 0 Dim e6 As ULong = 0 Dim a7 As System.Date = Nothing Dim b7 As SystemAlias.DATE = Nothing Dim c7 As SystemDateTimeAlias = Nothing Dim d7 As System.System.Date = 0 Dim e7 As Date = 0 End Sub End Module "; await VerifyAsync(@"[|" + code + @"|]", expectedResult: code); // No Fixes in trivia code = @" Imports SystemAlias = System 'Imports SystemInt16Alias = System.Short Module Program Sub Main(args As String()) ' Dim a1 As System.Short = 0 ' Dim b1 As SystemAlias.SHORT = a1 End Sub End Module "; await VerifyAsync(@"[|" + code + @"|]", expectedResult: code); } [Fact] [WorkItem(606015, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/606015")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixFullWidthSingleQuotes() { var code = @"[| ‘fullwidth 1  ’fullwidth 2 ‘‘fullwidth 3 ’'fullwidth 4 '‘fullwidth 5 ‘’fullwidth 6 ‘’‘’fullwidth 7 '‘’‘’fullwidth 8|]"; var expected = @" 'fullwidth 1  'fullwidth 2 '‘fullwidth 3 ''fullwidth 4 '‘fullwidth 5 '’fullwidth 6 '’‘’fullwidth 7 '‘’‘’fullwidth 8"; await VerifyAsync(code, expected); } [Fact] [WorkItem(707135, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/707135")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixFullWidthSingleQuotes2() { var savedCulture = System.Threading.Thread.CurrentThread.CurrentCulture; try { System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("zh-CN"); var code = @"[|‘’fullwidth 1|]"; var expected = @"'’fullwidth 1"; await VerifyAsync(code, expected); } finally { System.Threading.Thread.CurrentThread.CurrentCulture = savedCulture; } } private static string FixLineEndings(string text) => text.Replace("\r\n", "\n").Replace("\n", "\r\n"); private static async Task VerifyAsync(string codeWithMarker, string expectedResult) { codeWithMarker = FixLineEndings(codeWithMarker); expectedResult = FixLineEndings(expectedResult); MarkupTestFile.GetSpans(codeWithMarker, out var codeWithoutMarker, out ImmutableArray<TextSpan> textSpans); var document = CreateDocument(codeWithoutMarker, LanguageNames.VisualBasic); var codeCleanups = CodeCleaner.GetDefaultProviders(document).WhereAsArray(p => p.Name == PredefinedCodeCleanupProviderNames.FixIncorrectTokens || p.Name == PredefinedCodeCleanupProviderNames.Format); var cleanDocument = await CodeCleaner.CleanupAsync(document, textSpans[0], codeCleanups); Assert.Equal(expectedResult, (await cleanDocument.GetSyntaxRootAsync()).ToFullString()); } private static Document CreateDocument(string code, string language) { var solution = new AdhocWorkspace().CurrentSolution; var projectId = ProjectId.CreateNewId(); var project = solution.AddProject(projectId, "Project", "Project.dll", language).GetProject(projectId); return project.AddMetadataReference(TestMetadata.Net451.mscorlib) .AddDocument("Document", SourceText.From(code)); } } }
// Licensed to the .NET Foundation under one or more 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.Threading.Tasks; using Microsoft.CodeAnalysis.CodeCleanup; using Microsoft.CodeAnalysis.CodeCleanup.Providers; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.CodeCleanup { [UseExportProvider] public class FixIncorrectTokensTests { [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_WithMatchingIf() { var code = @" Module Program Sub Main(args As String()) [|If args IsNot Nothing Then System.Console.WriteLine(args) endif|] End Sub End Module"; var expected = @" Module Program Sub Main(args As String()) If args IsNot Nothing Then System.Console.WriteLine(args) End If End Sub End Module"; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_WithMatchingIf_Directive() { var code = @"[| #If c = 0 Then #Endif|]"; var expected = @" #If c = 0 Then #End If"; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_WithoutMatchingIf() { var code = @" Module Program Sub Main(args As String()) [|EndIf|] End Sub End Module"; var expected = @" Module Program Sub Main(args As String()) End If End Sub End Module"; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_WithoutMatchingIf_Directive() { var code = @"[| Class X End Class #Endif|]"; var expected = @" Class X End Class #End If"; await VerifyAsync(code, expected); } [Fact(Skip = "889521")] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_SameLineAsIf() { var code = @" Module Program Sub Main(args As String()) If args IsNot Nothing Then [|EndIf|] End Sub End Module"; var expected = @" Module Program Sub Main(args As String()) If args IsNot Nothing Then End If End Sub End Module"; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_SameLineAsIf_Invalid() { var code = @" Module Program Sub Main(args As String()) If args IsNot Nothing [|EndIf|] End Sub End Module"; var expected = @" Module Program Sub Main(args As String()) If args IsNot Nothing EndIf End Sub End Module"; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_SameLineAsIf_Directive() { var code = @"[| #If c = 0 Then #Endif|]"; var expected = @" #If c = 0 Then #Endif"; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_WithLeadingTrivia() { var code = @" Module Program Sub Main(args As String()) [|If args IsNot Nothing Then System.Console.WriteLine(args) ' Dummy Endif EndIf|] End Sub End Module"; var expected = @" Module Program Sub Main(args As String()) If args IsNot Nothing Then System.Console.WriteLine(args) ' Dummy Endif End If End Sub End Module"; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_WithLeadingTrivia_Directive() { var code = @"[| #If c = 0 Then '#Endif #Endif |]"; var expected = @" #If c = 0 Then '#Endif #End If "; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_InvocationExpressionArgument() { var code = @" Module Program Sub Main(args As String()) [|If args IsNot Nothing Then System.Console.WriteLine(args) InvocationExpression EndIf|] End Sub End Module"; var expected = @" Module Program Sub Main(args As String()) If args IsNot Nothing Then System.Console.WriteLine(args) InvocationExpression EndIf End Sub End Module"; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_InvalidDirectiveCases() { var code = @"[| ' BadDirective cases #If c = 0 Then #InvocationExpression #Endif #If c = 0 Then InvocationExpression# #Endif #If c = 0 Then InvocationExpression #Endif ' Missing EndIfDirective cases #If c = 0 Then #InvocationExpression #Endif #If c = 0 Then InvocationExpression# #Endif #If c = 0 Then InvocationExpression #Endif |]"; var expected = @" ' BadDirective cases #If c = 0 Then #InvocationExpression #Endif #If c = 0 Then InvocationExpression# #Endif #If c = 0 Then InvocationExpression #Endif ' Missing EndIfDirective cases #If c = 0 Then #InvocationExpression #End If #If c = 0 Then InvocationExpression# #End If #If c = 0 Then InvocationExpression #End If "; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_WithTrailingTrivia() { var code = @" Module Program Sub Main(args As String()) [|If args IsNot Nothing Then System.Console.WriteLine(args) EndIf ' Dummy EndIf|] End Sub End Module"; var expected = @" Module Program Sub Main(args As String()) If args IsNot Nothing Then System.Console.WriteLine(args) End If ' Dummy EndIf End Sub End Module"; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_WithTrailingTrivia_Directive() { var code = @"[| #If c = 0 Then #Endif '#Endif |]"; var expected = @" #If c = 0 Then #End If '#Endif "; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_WithIdentifierTokenTrailingTrivia() { var code = @" Module Program Sub Main(args As String()) [|If args IsNot Nothing Then System.Console.WriteLine(args) EndIf IdentifierToken|] End Sub End Module"; var expected = @" Module Program Sub Main(args As String()) If args IsNot Nothing Then System.Console.WriteLine(args) End If IdentifierToken End Sub End Module"; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_InvalidDirectiveCases_02() { var code = @"[| ' BadDirective cases #If c = 0 Then #Endif #IdentifierToken #If c = 0 Then #Endif IdentifierToken# #If c = 0 Then #Endif IdentifierToken ' Missing EndIfDirective cases #If c = 0 Then #Endif #IdentifierToken #If c = 0 Then #Endif IdentifierToken# #If c = 0 Then #Endif IdentifierToken |]"; var expected = @" ' BadDirective cases #If c = 0 Then #End If #IdentifierToken #If c = 0 Then #End If IdentifierToken# #If c = 0 Then #End If IdentifierToken ' Missing EndIfDirective cases #If c = 0 Then #End If #IdentifierToken #If c = 0 Then #End If IdentifierToken# #If c = 0 Then #End If IdentifierToken "; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_WithLeadingAndTrailingTrivia() { var code = @" Module Program Sub Main(args As String()) [|If args IsNot Nothing Then System.Console.WriteLine(args) ' Dummy EndIf EndIf ' Dummy EndIf|] End Sub End Module"; var expected = @" Module Program Sub Main(args As String()) If args IsNot Nothing Then System.Console.WriteLine(args) ' Dummy EndIf End If ' Dummy EndIf End Sub End Module"; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_WithLeadingAndTrailingTrivia_Directive() { var code = @"[| #If c = 0 Then '#Endif #Endif '#Endif |]"; var expected = @" #If c = 0 Then '#Endif #End If '#Endif "; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_WithLeadingAndTrailingInvocationExpressions() { var code = @" Module Program Sub Main(args As String()) [|If args IsNot Nothing Then System.Console.WriteLine(args) IdentifierToken EndIf IdentifierToken|] End Sub End Module"; var expected = @" Module Program Sub Main(args As String()) If args IsNot Nothing Then System.Console.WriteLine(args) IdentifierToken End If IdentifierToken End Sub End Module"; await VerifyAsync(code, expected); } [Fact] [WorkItem(17313, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixEndIfKeyword_WithLeadingAndTrailingInvocationExpressions_Directive() { var code = @"[| ' BadDirective cases #If c = 0 Then #InvalidTrivia #Endif #InvalidTrivia #If c = 0 Then InvalidTrivia #Endif InvalidTrivia #If c = 0 Then InvalidTrivia# #Endif InvalidTrivia# ' Missing EndIfDirective cases #If c = 0 Then #InvalidTrivia #Endif #InvalidTrivia #If c = 0 Then InvalidTrivia #Endif InvalidTrivia #If c = 0 Then InvalidTrivia# #Endif InvalidTrivia# |]"; var expected = @" ' BadDirective cases #If c = 0 Then #InvalidTrivia #Endif #InvalidTrivia #If c = 0 Then InvalidTrivia #Endif InvalidTrivia #If c = 0 Then InvalidTrivia# #Endif InvalidTrivia# ' Missing EndIfDirective cases #If c = 0 Then #InvalidTrivia #End If #InvalidTrivia #If c = 0 Then InvalidTrivia #End If InvalidTrivia #If c = 0 Then InvalidTrivia# #End If InvalidTrivia# "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5722, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixPrimitiveTypeKeywords_ValidCases() { var code = @"[| Imports SystemAlias = System Imports SystemInt16Alias = System.Short Imports SystemUInt16Alias = System.ushort Imports SystemInt32Alias = System.INTEGER Imports SystemUInt32Alias = System.UInteger Imports SystemInt64Alias = System.Long Imports SystemUInt64Alias = System.uLong Imports SystemDateTimeAlias = System.Date Module Program Sub Main(args As String()) Dim a1 As System.Short = 0 Dim b1 As SystemAlias.SHORT = a1 Dim c1 As SystemInt16Alias = b1 Dim a2 As System.UShort = 0 Dim b2 As SystemAlias.USHORT = a2 Dim c2 As SystemUInt16Alias = b2 Dim a3 As System.Integer = 0 Dim b3 As SystemAlias.INTEGER = a3 Dim c3 As SystemInt32Alias = b3 Dim a4 As System.UInteger = 0 Dim b4 As SystemAlias.UINTEGER = a4 Dim c4 As SystemUInt32Alias = b4 Dim a5 As System.Long = 0 Dim b5 As SystemAlias.LONG = a5 Dim c5 As SystemInt64Alias = b5 Dim a6 As System.ULong = 0 Dim b6 As SystemAlias.ULONG = 0 Dim c6 As SystemUInt64Alias = 0 Dim a7 As System.Date = Nothing Dim b7 As SystemAlias.DATE = Nothing Dim c7 As SystemDateTimeAlias = Nothing End Sub End Module |]"; var expected = @" Imports SystemAlias = System Imports SystemInt16Alias = System.Int16 Imports SystemUInt16Alias = System.UInt16 Imports SystemInt32Alias = System.Int32 Imports SystemUInt32Alias = System.UInt32 Imports SystemInt64Alias = System.Int64 Imports SystemUInt64Alias = System.UInt64 Imports SystemDateTimeAlias = System.DateTime Module Program Sub Main(args As String()) Dim a1 As System.Int16 = 0 Dim b1 As SystemAlias.Int16 = a1 Dim c1 As SystemInt16Alias = b1 Dim a2 As System.UInt16 = 0 Dim b2 As SystemAlias.UInt16 = a2 Dim c2 As SystemUInt16Alias = b2 Dim a3 As System.Int32 = 0 Dim b3 As SystemAlias.Int32 = a3 Dim c3 As SystemInt32Alias = b3 Dim a4 As System.UInt32 = 0 Dim b4 As SystemAlias.UInt32 = a4 Dim c4 As SystemUInt32Alias = b4 Dim a5 As System.Int64 = 0 Dim b5 As SystemAlias.Int64 = a5 Dim c5 As SystemInt64Alias = b5 Dim a6 As System.UInt64 = 0 Dim b6 As SystemAlias.UInt64 = 0 Dim c6 As SystemUInt64Alias = 0 Dim a7 As System.DateTime = Nothing Dim b7 As SystemAlias.DateTime = Nothing Dim c7 As SystemDateTimeAlias = Nothing End Sub End Module "; await VerifyAsync(code, expected); } [Fact] [WorkItem(5722, "DevDiv_Projects/Roslyn")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixPrimitiveTypeKeywords_InvalidCases() { // With a user defined type named System // No fixups as System binds to type not a namespace. var code = @" Imports SystemAlias = System Imports SystemInt16Alias = System.Short Imports SystemUInt16Alias = System.ushort Imports SystemInt32Alias = System.INTEGER Imports SystemUInt32Alias = System.UInteger Imports SystemInt64Alias = System.Long Imports SystemUInt64Alias = System.uLong Imports SystemDateTimeAlias = System.Date Class System End Class Module Program Sub Main(args As String()) Dim a1 As System.Short = 0 Dim b1 As SystemAlias.SHORT = a1 Dim c1 As SystemInt16Alias = b1 Dim d1 As System.System.Short = 0 Dim e1 As Short = 0 Dim a2 As System.UShort = 0 Dim b2 As SystemAlias.USHORT = a2 Dim c2 As SystemUInt16Alias = b2 Dim d2 As System.System.UShort = 0 Dim e2 As UShort = 0 Dim a3 As System.Integer = 0 Dim b3 As SystemAlias.INTEGER = a3 Dim c3 As SystemInt32Alias = b3 Dim d3 As System.System.Integer = 0 Dim e3 As Integer = 0 Dim a4 As System.UInteger = 0 Dim b4 As SystemAlias.UINTEGER = a4 Dim c4 As SystemUInt32Alias = b4 Dim d4 As System.System.UInteger = 0 Dim e4 As UInteger = 0 Dim a5 As System.Long = 0 Dim b5 As SystemAlias.LONG = a5 Dim c5 As SystemInt64Alias = b5 Dim d5 As System.System.Long = 0 Dim e5 As Long = 0 Dim a6 As System.ULong = 0 Dim b6 As SystemAlias.ULONG = 0 Dim c6 As SystemUInt64Alias = 0 Dim d6 As System.System.ULong = 0 Dim e6 As ULong = 0 Dim a7 As System.Date = Nothing Dim b7 As SystemAlias.DATE = Nothing Dim c7 As SystemDateTimeAlias = Nothing Dim d7 As System.System.Date = 0 Dim e7 As Date = 0 End Sub End Module "; await VerifyAsync(@"[|" + code + @"|]", expectedResult: code); // No Fixes in trivia code = @" Imports SystemAlias = System 'Imports SystemInt16Alias = System.Short Module Program Sub Main(args As String()) ' Dim a1 As System.Short = 0 ' Dim b1 As SystemAlias.SHORT = a1 End Sub End Module "; await VerifyAsync(@"[|" + code + @"|]", expectedResult: code); } [Fact] [WorkItem(606015, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/606015")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixFullWidthSingleQuotes() { var code = @"[| ‘fullwidth 1  ’fullwidth 2 ‘‘fullwidth 3 ’'fullwidth 4 '‘fullwidth 5 ‘’fullwidth 6 ‘’‘’fullwidth 7 '‘’‘’fullwidth 8|]"; var expected = @" 'fullwidth 1  'fullwidth 2 '‘fullwidth 3 ''fullwidth 4 '‘fullwidth 5 '’fullwidth 6 '’‘’fullwidth 7 '‘’‘’fullwidth 8"; await VerifyAsync(code, expected); } [Fact] [WorkItem(707135, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/707135")] [Trait(Traits.Feature, Traits.Features.FixIncorrectTokens)] public async Task FixFullWidthSingleQuotes2() { var savedCulture = System.Threading.Thread.CurrentThread.CurrentCulture; try { System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("zh-CN"); var code = @"[|‘’fullwidth 1|]"; var expected = @"'’fullwidth 1"; await VerifyAsync(code, expected); } finally { System.Threading.Thread.CurrentThread.CurrentCulture = savedCulture; } } private static string FixLineEndings(string text) => text.Replace("\r\n", "\n").Replace("\n", "\r\n"); private static async Task VerifyAsync(string codeWithMarker, string expectedResult) { codeWithMarker = FixLineEndings(codeWithMarker); expectedResult = FixLineEndings(expectedResult); MarkupTestFile.GetSpans(codeWithMarker, out var codeWithoutMarker, out ImmutableArray<TextSpan> textSpans); var document = CreateDocument(codeWithoutMarker, LanguageNames.VisualBasic); var codeCleanups = CodeCleaner.GetDefaultProviders(document).WhereAsArray(p => p.Name == PredefinedCodeCleanupProviderNames.FixIncorrectTokens || p.Name == PredefinedCodeCleanupProviderNames.Format); var cleanDocument = await CodeCleaner.CleanupAsync(document, textSpans[0], codeCleanups); Assert.Equal(expectedResult, (await cleanDocument.GetSyntaxRootAsync()).ToFullString()); } private static Document CreateDocument(string code, string language) { var solution = new AdhocWorkspace().CurrentSolution; var projectId = ProjectId.CreateNewId(); var project = solution.AddProject(projectId, "Project", "Project.dll", language).GetProject(projectId); return project.AddMetadataReference(TestMetadata.Net451.mscorlib) .AddDocument("Document", SourceText.From(code)); } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Workspaces/Core/Portable/Classification/AbstractClassificationService.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.ReassignedVariable; namespace Microsoft.CodeAnalysis.Classification { internal abstract class AbstractClassificationService : IClassificationService { public abstract void AddLexicalClassifications(SourceText text, TextSpan textSpan, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken); public abstract ClassifiedSpan AdjustStaleClassification(SourceText text, ClassifiedSpan classifiedSpan); public async Task AddSemanticClassificationsAsync(Document document, TextSpan textSpan, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { var classificationService = document.GetLanguageService<ISyntaxClassificationService>(); if (classificationService == null) { // When renaming a file's extension through VS when it's opened in editor, // the content type might change and the content type changed event can be // raised before the renaming propagate through VS workspace. As a result, // the document we got (based on the buffer) could still be the one in the workspace // before rename happened. This would cause us problem if the document is supported // by workspace but not a roslyn language (e.g. xaml, F#, etc.), since none of the roslyn // language services would be available. // // If this is the case, we will simply bail out. It's OK to ignore the request // because when the buffer eventually get associated with the correct document in roslyn // workspace, we will be invoked again. // // For example, if you open a xaml from from a WPF project in designer view, // and then rename file extension from .xaml to .cs, then the document we received // here would still belong to the special "-xaml" project. return; } var client = await RemoteHostClient.TryGetClientAsync(document.Project, cancellationToken).ConfigureAwait(false); if (client != null) { // Call the project overload. Semantic classification only needs the current project's information // to classify properly. var classifiedSpans = await client.TryInvokeAsync<IRemoteSemanticClassificationService, SerializableClassifiedSpans>( document.Project, (service, solutionInfo, cancellationToken) => service.GetSemanticClassificationsAsync(solutionInfo, document.Id, textSpan, cancellationToken), cancellationToken).ConfigureAwait(false); // if the remote call fails do nothing (error has already been reported) if (classifiedSpans.HasValue) classifiedSpans.Value.Rehydrate(result); } else { await AddSemanticClassificationsInCurrentProcessAsync( document, textSpan, result, cancellationToken).ConfigureAwait(false); } } public static async Task AddSemanticClassificationsInCurrentProcessAsync( Document document, TextSpan textSpan, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { var classificationService = document.GetRequiredLanguageService<ISyntaxClassificationService>(); var reassignedVariableService = document.GetRequiredLanguageService<IReassignedVariableService>(); var extensionManager = document.Project.Solution.Workspace.Services.GetRequiredService<IExtensionManager>(); var classifiers = classificationService.GetDefaultSyntaxClassifiers(); var getNodeClassifiers = extensionManager.CreateNodeExtensionGetter(classifiers, c => c.SyntaxNodeTypes); var getTokenClassifiers = extensionManager.CreateTokenExtensionGetter(classifiers, c => c.SyntaxTokenKinds); await classificationService.AddSemanticClassificationsAsync(document, textSpan, getNodeClassifiers, getTokenClassifiers, result, cancellationToken).ConfigureAwait(false); var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var classifyReassignedVariables = options.GetOption(ClassificationOptions.ClassifyReassignedVariables); if (classifyReassignedVariables) { var reassignedVariableSpans = await reassignedVariableService.GetLocationsAsync(document, textSpan, cancellationToken).ConfigureAwait(false); foreach (var span in reassignedVariableSpans) result.Add(new ClassifiedSpan(span, ClassificationTypeNames.ReassignedVariable)); } } public async Task AddSyntacticClassificationsAsync(Document document, TextSpan textSpan, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); AddSyntacticClassifications(document.Project.Solution.Workspace, root, textSpan, result, cancellationToken); } public void AddSyntacticClassifications( Workspace workspace, SyntaxNode? root, TextSpan textSpan, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { if (root == null) return; var classificationService = workspace.Services.GetLanguageServices(root.Language).GetService<ISyntaxClassificationService>(); if (classificationService == null) return; classificationService.AddSyntacticClassifications(root, textSpan, result, cancellationToken); } /// <summary> /// Helper to add all the values of <paramref name="temp"/> into <paramref name="result"/> /// without causing any allocations or boxing of enumerators. /// </summary> protected static void AddRange(ArrayBuilder<ClassifiedSpan> temp, List<ClassifiedSpan> result) { foreach (var span in temp) { result.Add(span); } } public ValueTask<TextChangeRange?> ComputeSyntacticChangeRangeAsync(Document oldDocument, Document newDocument, TimeSpan timeout, CancellationToken cancellationToken) => default; public TextChangeRange? ComputeSyntacticChangeRange(Workspace workspace, SyntaxNode oldRoot, SyntaxNode newRoot, TimeSpan timeout, CancellationToken cancellationToken) { var classificationService = workspace.Services.GetLanguageServices(oldRoot.Language).GetService<ISyntaxClassificationService>(); return classificationService?.ComputeSyntacticChangeRange(oldRoot, newRoot, timeout, 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.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.ReassignedVariable; namespace Microsoft.CodeAnalysis.Classification { internal abstract class AbstractClassificationService : IClassificationService { public abstract void AddLexicalClassifications(SourceText text, TextSpan textSpan, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken); public abstract ClassifiedSpan AdjustStaleClassification(SourceText text, ClassifiedSpan classifiedSpan); public async Task AddSemanticClassificationsAsync(Document document, TextSpan textSpan, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { var classificationService = document.GetLanguageService<ISyntaxClassificationService>(); if (classificationService == null) { // When renaming a file's extension through VS when it's opened in editor, // the content type might change and the content type changed event can be // raised before the renaming propagate through VS workspace. As a result, // the document we got (based on the buffer) could still be the one in the workspace // before rename happened. This would cause us problem if the document is supported // by workspace but not a roslyn language (e.g. xaml, F#, etc.), since none of the roslyn // language services would be available. // // If this is the case, we will simply bail out. It's OK to ignore the request // because when the buffer eventually get associated with the correct document in roslyn // workspace, we will be invoked again. // // For example, if you open a xaml from from a WPF project in designer view, // and then rename file extension from .xaml to .cs, then the document we received // here would still belong to the special "-xaml" project. return; } var client = await RemoteHostClient.TryGetClientAsync(document.Project, cancellationToken).ConfigureAwait(false); if (client != null) { // Call the project overload. Semantic classification only needs the current project's information // to classify properly. var classifiedSpans = await client.TryInvokeAsync<IRemoteSemanticClassificationService, SerializableClassifiedSpans>( document.Project, (service, solutionInfo, cancellationToken) => service.GetSemanticClassificationsAsync(solutionInfo, document.Id, textSpan, cancellationToken), cancellationToken).ConfigureAwait(false); // if the remote call fails do nothing (error has already been reported) if (classifiedSpans.HasValue) classifiedSpans.Value.Rehydrate(result); } else { await AddSemanticClassificationsInCurrentProcessAsync( document, textSpan, result, cancellationToken).ConfigureAwait(false); } } public static async Task AddSemanticClassificationsInCurrentProcessAsync( Document document, TextSpan textSpan, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { var classificationService = document.GetRequiredLanguageService<ISyntaxClassificationService>(); var reassignedVariableService = document.GetRequiredLanguageService<IReassignedVariableService>(); var extensionManager = document.Project.Solution.Workspace.Services.GetRequiredService<IExtensionManager>(); var classifiers = classificationService.GetDefaultSyntaxClassifiers(); var getNodeClassifiers = extensionManager.CreateNodeExtensionGetter(classifiers, c => c.SyntaxNodeTypes); var getTokenClassifiers = extensionManager.CreateTokenExtensionGetter(classifiers, c => c.SyntaxTokenKinds); await classificationService.AddSemanticClassificationsAsync(document, textSpan, getNodeClassifiers, getTokenClassifiers, result, cancellationToken).ConfigureAwait(false); var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var classifyReassignedVariables = options.GetOption(ClassificationOptions.ClassifyReassignedVariables); if (classifyReassignedVariables) { var reassignedVariableSpans = await reassignedVariableService.GetLocationsAsync(document, textSpan, cancellationToken).ConfigureAwait(false); foreach (var span in reassignedVariableSpans) result.Add(new ClassifiedSpan(span, ClassificationTypeNames.ReassignedVariable)); } } public async Task AddSyntacticClassificationsAsync(Document document, TextSpan textSpan, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); AddSyntacticClassifications(document.Project.Solution.Workspace, root, textSpan, result, cancellationToken); } public void AddSyntacticClassifications( Workspace workspace, SyntaxNode? root, TextSpan textSpan, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { if (root == null) return; var classificationService = workspace.Services.GetLanguageServices(root.Language).GetService<ISyntaxClassificationService>(); if (classificationService == null) return; classificationService.AddSyntacticClassifications(root, textSpan, result, cancellationToken); } /// <summary> /// Helper to add all the values of <paramref name="temp"/> into <paramref name="result"/> /// without causing any allocations or boxing of enumerators. /// </summary> protected static void AddRange(ArrayBuilder<ClassifiedSpan> temp, List<ClassifiedSpan> result) { foreach (var span in temp) { result.Add(span); } } public ValueTask<TextChangeRange?> ComputeSyntacticChangeRangeAsync(Document oldDocument, Document newDocument, TimeSpan timeout, CancellationToken cancellationToken) => default; public TextChangeRange? ComputeSyntacticChangeRange(Workspace workspace, SyntaxNode oldRoot, SyntaxNode newRoot, TimeSpan timeout, CancellationToken cancellationToken) { var classificationService = workspace.Services.GetLanguageServices(oldRoot.Language).GetService<ISyntaxClassificationService>(); return classificationService?.ComputeSyntacticChangeRange(oldRoot, newRoot, timeout, cancellationToken); } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/EditorFeatures/CSharpTest/AssignOutParameters/AssignOutParametersAboveReturnTests.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 Xunit; using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier< Microsoft.CodeAnalysis.Testing.EmptyDiagnosticAnalyzer, Microsoft.CodeAnalysis.CSharp.AssignOutParameters.AssignOutParametersAboveReturnCodeFixProvider>; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AssignOutParameters { public class AssignOutParametersAboveReturnTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestForSimpleReturn() { await VerifyCS.VerifyCodeFixAsync( @"class C { char M(out int i) { {|CS0177:return 'a';|} } }", @"class C { char M(out int i) { i = 0; return 'a'; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestForSwitchSectionReturn() { await VerifyCS.VerifyCodeFixAsync( @"class C { char M(out int i) { switch (0) { default: {|CS0177:return 'a';|} } } }", @"class C { char M(out int i) { switch (0) { default: i = 0; return 'a'; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestMissingWhenVariableAssigned() { var code = @"class C { char M(out int i) { i = 0; return 'a'; } }"; await VerifyCS.VerifyCodeFixAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestWhenNotAssignedThroughAllPaths1() { await VerifyCS.VerifyCodeFixAsync( @"class C { char M(bool b, out int i) { if (b) i = 1; {|CS0177:return 'a';|} } }", @"class C { char M(bool b, out int i) { if (b) i = 1; i = 0; return 'a'; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestWhenNotAssignedThroughAllPaths2() { await VerifyCS.VerifyCodeFixAsync( @"class C { bool M(out int i1, out int i2) { {|CS0177:return Try(out i1) || Try(out i2);|} } bool Try(out int i) { i = 0; return true; } }", @"class C { bool M(out int i1, out int i2) { i2 = 0; return Try(out i1) || Try(out i2); } bool Try(out int i) { i = 0; return true; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestMissingWhenAssignedThroughAllPaths() { var code = @"class C { char M(bool b, out int i) { if (b) i = 1; else i = 2; return 'a'; } }"; await VerifyCS.VerifyCodeFixAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestMultiple() { await VerifyCS.VerifyCodeFixAsync( @"class C { char M(out int i, out string s) { {|CS0177:{|CS0177:return 'a';|}|} } }", @"class C { char M(out int i, out string s) { i = 0; s = null; return 'a'; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestMultiple_AssignedInReturn1() { await VerifyCS.VerifyCodeFixAsync( @"class C { string M(out int i, out string s) { {|CS0177:return s = """";|} } }", @"class C { string M(out int i, out string s) { i = 0; return s = """"; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestMultiple_AssignedInReturn2() { await VerifyCS.VerifyCodeFixAsync( @"class C { string M(out int i, out string s) { {|CS0177:return (i = 0).ToString();|} } }", @"class C { string M(out int i, out string s) { s = null; return (i = 0).ToString(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestNestedReturn() { await VerifyCS.VerifyCodeFixAsync( @"class C { char M(out int i) { if (true) { {|CS0177:return 'a';|} } } }", @"class C { char M(out int i) { if (true) { i = 0; return 'a'; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestNestedReturnNoBlock() { await VerifyCS.VerifyCodeFixAsync( @"class C { char M(out int i) { if (true) {|CS0177:return 'a';|} } }", @"class C { char M(out int i) { if (true) { i = 0; return 'a'; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestNestedReturnEvenWhenWrittenAfter() { await VerifyCS.VerifyCodeFixAsync( @"class C { char M(bool b, out int i) { if (b) { {|CS0177:return 'a';|} } i = 1; throw null; } }", @"class C { char M(bool b, out int i) { if (b) { i = 0; return 'a'; } i = 1; throw null; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestForExpressionBodyMember() { await VerifyCS.VerifyCodeFixAsync( @"class C { char M(out int i) => {|CS0177:'a'|}; }", @"class C { char M(out int i) { i = 0; return 'a'; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestForLambdaExpressionBody() { await VerifyCS.VerifyCodeFixAsync( @"class C { delegate char D(out int i); void X() { D d = (out int i) => {|CS0177:'a'|}; } }", @"class C { delegate char D(out int i); void X() { D d = (out int i) => { i = 0; return 'a'; }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestMissingForLocalFunctionExpressionBody() { await VerifyCS.VerifyCodeFixAsync( @"class C { void X() { char {|CS0177:D|}(out int i) => 'a'; D(out _); } }", @"class C { void X() { char D(out int i) { i = 0; return 'a'; } D(out _); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestForLambdaBlockBody() { await VerifyCS.VerifyCodeFixAsync( @"class C { delegate char D(out int i); void X() { D d = (out int i) => { {|CS0177:return 'a';|} }; } }", @"class C { delegate char D(out int i); void X() { D d = (out int i) => { i = 0; return 'a'; }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestForLocalFunctionBlockBody() { await VerifyCS.VerifyCodeFixAsync( @"class C { void X() { char D(out int i) { {|CS0177:return 'a';|} } D(out _); } }", @"class C { void X() { char D(out int i) { i = 0; return 'a'; } D(out _); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestForOutParamInSinglePath() { var code = @"class C { char M(bool b, out int i) { if (b) i = 1; else SomeMethod(out i); return 'a'; } void SomeMethod(out int i) => i = 0; }"; await VerifyCS.VerifyCodeFixAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestFixAll1() { await VerifyCS.VerifyCodeFixAsync( @"class C { char M(bool b, out int i, out int j) { if (b) { {|CS0177:{|CS0177:return 'a';|}|} } else { {|CS0177:{|CS0177:return 'a';|}|} } } }", @"class C { char M(bool b, out int i, out int j) { if (b) { i = 0; j = 0; return 'a'; } else { i = 0; j = 0; return 'a'; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestFixAll1_MultipleMethods() { await VerifyCS.VerifyCodeFixAsync( @"class C { char M(bool b, out int i, out int j) { if (b) { {|CS0177:{|CS0177:return 'a';|}|} } else { {|CS0177:{|CS0177:return 'a';|}|} } } char N(bool b, out int i, out int j) { if (b) { {|CS0177:{|CS0177:return 'a';|}|} } else { {|CS0177:{|CS0177:return 'a';|}|} } } }", @"class C { char M(bool b, out int i, out int j) { if (b) { i = 0; j = 0; return 'a'; } else { i = 0; j = 0; return 'a'; } } char N(bool b, out int i, out int j) { if (b) { i = 0; j = 0; return 'a'; } else { i = 0; j = 0; return 'a'; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestFixAll2() { await VerifyCS.VerifyCodeFixAsync( @"class C { char M(bool b, out int i, out int j) { if (b) {|CS0177:{|CS0177:return 'a';|}|} else {|CS0177:{|CS0177:return 'a';|}|} } }", @"class C { char M(bool b, out int i, out int j) { if (b) { i = 0; j = 0; return 'a'; } else { i = 0; j = 0; return 'a'; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestFixAll2_MultipleMethods() { await VerifyCS.VerifyCodeFixAsync( @"class C { char M(bool b, out int i, out int j) { if (b) {|CS0177:{|CS0177:return 'a';|}|} else {|CS0177:{|CS0177:return 'a';|}|} } char N(bool b, out int i, out int j) { if (b) {|CS0177:{|CS0177:return 'a';|}|} else {|CS0177:{|CS0177:return 'a';|}|} } }", @"class C { char M(bool b, out int i, out int j) { if (b) { i = 0; j = 0; return 'a'; } else { i = 0; j = 0; return 'a'; } } char N(bool b, out int i, out int j) { if (b) { i = 0; j = 0; return 'a'; } else { i = 0; j = 0; return 'a'; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestFixAll3() { await VerifyCS.VerifyCodeFixAsync( @"class C { char M(bool b, out int i, out int j) { if (b) { i = 0; {|CS0177:return 'a';|} } else { j = 0; {|CS0177:return 'a';|} } } }", @"class C { char M(bool b, out int i, out int j) { if (b) { i = 0; j = 0; return 'a'; } else { j = 0; i = 0; return 'a'; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestFixAll3_MultipleMethods() { await VerifyCS.VerifyCodeFixAsync( @"class C { char M(bool b, out int i, out int j) { if (b) { i = 0; {|CS0177:return 'a';|} } else { j = 0; {|CS0177:return 'a';|} } } char N(bool b, out int i, out int j) { if (b) { i = 0; {|CS0177:return 'a';|} } else { j = 0; {|CS0177:return 'a';|} } } }", @"class C { char M(bool b, out int i, out int j) { if (b) { i = 0; j = 0; return 'a'; } else { j = 0; i = 0; return 'a'; } } char N(bool b, out int i, out int j) { if (b) { i = 0; j = 0; return 'a'; } else { j = 0; i = 0; return 'a'; } } }"); } } }
// Licensed to the .NET Foundation under one or more 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 Xunit; using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier< Microsoft.CodeAnalysis.Testing.EmptyDiagnosticAnalyzer, Microsoft.CodeAnalysis.CSharp.AssignOutParameters.AssignOutParametersAboveReturnCodeFixProvider>; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AssignOutParameters { public class AssignOutParametersAboveReturnTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestForSimpleReturn() { await VerifyCS.VerifyCodeFixAsync( @"class C { char M(out int i) { {|CS0177:return 'a';|} } }", @"class C { char M(out int i) { i = 0; return 'a'; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestForSwitchSectionReturn() { await VerifyCS.VerifyCodeFixAsync( @"class C { char M(out int i) { switch (0) { default: {|CS0177:return 'a';|} } } }", @"class C { char M(out int i) { switch (0) { default: i = 0; return 'a'; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestMissingWhenVariableAssigned() { var code = @"class C { char M(out int i) { i = 0; return 'a'; } }"; await VerifyCS.VerifyCodeFixAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestWhenNotAssignedThroughAllPaths1() { await VerifyCS.VerifyCodeFixAsync( @"class C { char M(bool b, out int i) { if (b) i = 1; {|CS0177:return 'a';|} } }", @"class C { char M(bool b, out int i) { if (b) i = 1; i = 0; return 'a'; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestWhenNotAssignedThroughAllPaths2() { await VerifyCS.VerifyCodeFixAsync( @"class C { bool M(out int i1, out int i2) { {|CS0177:return Try(out i1) || Try(out i2);|} } bool Try(out int i) { i = 0; return true; } }", @"class C { bool M(out int i1, out int i2) { i2 = 0; return Try(out i1) || Try(out i2); } bool Try(out int i) { i = 0; return true; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestMissingWhenAssignedThroughAllPaths() { var code = @"class C { char M(bool b, out int i) { if (b) i = 1; else i = 2; return 'a'; } }"; await VerifyCS.VerifyCodeFixAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestMultiple() { await VerifyCS.VerifyCodeFixAsync( @"class C { char M(out int i, out string s) { {|CS0177:{|CS0177:return 'a';|}|} } }", @"class C { char M(out int i, out string s) { i = 0; s = null; return 'a'; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestMultiple_AssignedInReturn1() { await VerifyCS.VerifyCodeFixAsync( @"class C { string M(out int i, out string s) { {|CS0177:return s = """";|} } }", @"class C { string M(out int i, out string s) { i = 0; return s = """"; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestMultiple_AssignedInReturn2() { await VerifyCS.VerifyCodeFixAsync( @"class C { string M(out int i, out string s) { {|CS0177:return (i = 0).ToString();|} } }", @"class C { string M(out int i, out string s) { s = null; return (i = 0).ToString(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestNestedReturn() { await VerifyCS.VerifyCodeFixAsync( @"class C { char M(out int i) { if (true) { {|CS0177:return 'a';|} } } }", @"class C { char M(out int i) { if (true) { i = 0; return 'a'; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestNestedReturnNoBlock() { await VerifyCS.VerifyCodeFixAsync( @"class C { char M(out int i) { if (true) {|CS0177:return 'a';|} } }", @"class C { char M(out int i) { if (true) { i = 0; return 'a'; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestNestedReturnEvenWhenWrittenAfter() { await VerifyCS.VerifyCodeFixAsync( @"class C { char M(bool b, out int i) { if (b) { {|CS0177:return 'a';|} } i = 1; throw null; } }", @"class C { char M(bool b, out int i) { if (b) { i = 0; return 'a'; } i = 1; throw null; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestForExpressionBodyMember() { await VerifyCS.VerifyCodeFixAsync( @"class C { char M(out int i) => {|CS0177:'a'|}; }", @"class C { char M(out int i) { i = 0; return 'a'; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestForLambdaExpressionBody() { await VerifyCS.VerifyCodeFixAsync( @"class C { delegate char D(out int i); void X() { D d = (out int i) => {|CS0177:'a'|}; } }", @"class C { delegate char D(out int i); void X() { D d = (out int i) => { i = 0; return 'a'; }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestMissingForLocalFunctionExpressionBody() { await VerifyCS.VerifyCodeFixAsync( @"class C { void X() { char {|CS0177:D|}(out int i) => 'a'; D(out _); } }", @"class C { void X() { char D(out int i) { i = 0; return 'a'; } D(out _); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestForLambdaBlockBody() { await VerifyCS.VerifyCodeFixAsync( @"class C { delegate char D(out int i); void X() { D d = (out int i) => { {|CS0177:return 'a';|} }; } }", @"class C { delegate char D(out int i); void X() { D d = (out int i) => { i = 0; return 'a'; }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestForLocalFunctionBlockBody() { await VerifyCS.VerifyCodeFixAsync( @"class C { void X() { char D(out int i) { {|CS0177:return 'a';|} } D(out _); } }", @"class C { void X() { char D(out int i) { i = 0; return 'a'; } D(out _); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestForOutParamInSinglePath() { var code = @"class C { char M(bool b, out int i) { if (b) i = 1; else SomeMethod(out i); return 'a'; } void SomeMethod(out int i) => i = 0; }"; await VerifyCS.VerifyCodeFixAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestFixAll1() { await VerifyCS.VerifyCodeFixAsync( @"class C { char M(bool b, out int i, out int j) { if (b) { {|CS0177:{|CS0177:return 'a';|}|} } else { {|CS0177:{|CS0177:return 'a';|}|} } } }", @"class C { char M(bool b, out int i, out int j) { if (b) { i = 0; j = 0; return 'a'; } else { i = 0; j = 0; return 'a'; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestFixAll1_MultipleMethods() { await VerifyCS.VerifyCodeFixAsync( @"class C { char M(bool b, out int i, out int j) { if (b) { {|CS0177:{|CS0177:return 'a';|}|} } else { {|CS0177:{|CS0177:return 'a';|}|} } } char N(bool b, out int i, out int j) { if (b) { {|CS0177:{|CS0177:return 'a';|}|} } else { {|CS0177:{|CS0177:return 'a';|}|} } } }", @"class C { char M(bool b, out int i, out int j) { if (b) { i = 0; j = 0; return 'a'; } else { i = 0; j = 0; return 'a'; } } char N(bool b, out int i, out int j) { if (b) { i = 0; j = 0; return 'a'; } else { i = 0; j = 0; return 'a'; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestFixAll2() { await VerifyCS.VerifyCodeFixAsync( @"class C { char M(bool b, out int i, out int j) { if (b) {|CS0177:{|CS0177:return 'a';|}|} else {|CS0177:{|CS0177:return 'a';|}|} } }", @"class C { char M(bool b, out int i, out int j) { if (b) { i = 0; j = 0; return 'a'; } else { i = 0; j = 0; return 'a'; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestFixAll2_MultipleMethods() { await VerifyCS.VerifyCodeFixAsync( @"class C { char M(bool b, out int i, out int j) { if (b) {|CS0177:{|CS0177:return 'a';|}|} else {|CS0177:{|CS0177:return 'a';|}|} } char N(bool b, out int i, out int j) { if (b) {|CS0177:{|CS0177:return 'a';|}|} else {|CS0177:{|CS0177:return 'a';|}|} } }", @"class C { char M(bool b, out int i, out int j) { if (b) { i = 0; j = 0; return 'a'; } else { i = 0; j = 0; return 'a'; } } char N(bool b, out int i, out int j) { if (b) { i = 0; j = 0; return 'a'; } else { i = 0; j = 0; return 'a'; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestFixAll3() { await VerifyCS.VerifyCodeFixAsync( @"class C { char M(bool b, out int i, out int j) { if (b) { i = 0; {|CS0177:return 'a';|} } else { j = 0; {|CS0177:return 'a';|} } } }", @"class C { char M(bool b, out int i, out int j) { if (b) { i = 0; j = 0; return 'a'; } else { j = 0; i = 0; return 'a'; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAssignOutParameters)] public async Task TestFixAll3_MultipleMethods() { await VerifyCS.VerifyCodeFixAsync( @"class C { char M(bool b, out int i, out int j) { if (b) { i = 0; {|CS0177:return 'a';|} } else { j = 0; {|CS0177:return 'a';|} } } char N(bool b, out int i, out int j) { if (b) { i = 0; {|CS0177:return 'a';|} } else { j = 0; {|CS0177:return 'a';|} } } }", @"class C { char M(bool b, out int i, out int j) { if (b) { i = 0; j = 0; return 'a'; } else { j = 0; i = 0; return 'a'; } } char N(bool b, out int i, out int j) { if (b) { i = 0; j = 0; return 'a'; } else { j = 0; i = 0; return 'a'; } } }"); } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/EditorFeatures/Core/FindUsages/IDefinitionsAndReferencesFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Features.RQName; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.FindSymbols.Finders; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.FindUsages { using static FindUsagesHelpers; internal interface IDefinitionsAndReferencesFactory : IWorkspaceService { Task<DefinitionItem?> GetThirdPartyDefinitionItemAsync( Solution solution, DefinitionItem definitionItem, CancellationToken cancellationToken); } [ExportWorkspaceService(typeof(IDefinitionsAndReferencesFactory)), Shared] internal class DefaultDefinitionsAndReferencesFactory : IDefinitionsAndReferencesFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultDefinitionsAndReferencesFactory() { } /// <summary> /// Provides an extension point that allows for other workspace layers to add additional /// results to the results found by the FindReferences engine. /// </summary> public virtual Task<DefinitionItem?> GetThirdPartyDefinitionItemAsync( Solution solution, DefinitionItem definitionItem, CancellationToken cancellationToken) { return SpecializedTasks.Null<DefinitionItem>(); } } internal static class DefinitionItemExtensions { private static readonly SymbolDisplayFormat s_namePartsFormat = new( memberOptions: SymbolDisplayMemberOptions.IncludeContainingType); public static DefinitionItem ToNonClassifiedDefinitionItem( this ISymbol definition, Solution solution, bool includeHiddenLocations) { // Because we're passing in 'false' for 'includeClassifiedSpans', this won't ever have // to actually do async work. This is because the only asynchrony is when we are trying // to compute the classified spans for the locations of the definition. So it's totally // fine to pass in CancellationToken.None and block on the result. return ToDefinitionItemAsync( definition, solution, isPrimary: false, includeHiddenLocations, includeClassifiedSpans: false, options: FindReferencesSearchOptions.Default, cancellationToken: CancellationToken.None).WaitAndGetResult_CanCallOnBackground(CancellationToken.None); } public static Task<DefinitionItem> ToNonClassifiedDefinitionItemAsync( this ISymbol definition, Solution solution, bool includeHiddenLocations, CancellationToken cancellationToken) { return ToDefinitionItemAsync( definition, solution, isPrimary: false, includeHiddenLocations, includeClassifiedSpans: false, options: FindReferencesSearchOptions.Default.With(unidirectionalHierarchyCascade: true), cancellationToken: cancellationToken); } public static Task<DefinitionItem> ToClassifiedDefinitionItemAsync( this ISymbol definition, Solution solution, bool isPrimary, bool includeHiddenLocations, FindReferencesSearchOptions options, CancellationToken cancellationToken) { return ToDefinitionItemAsync( definition, solution, isPrimary, includeHiddenLocations, includeClassifiedSpans: true, options, cancellationToken); } public static Task<DefinitionItem> ToClassifiedDefinitionItemAsync( this SymbolGroup group, Solution solution, bool isPrimary, bool includeHiddenLocations, FindReferencesSearchOptions options, CancellationToken cancellationToken) { // Make a single definition item that knows about all the locations of all the symbols in the group. var allLocations = group.Symbols.SelectMany(s => s.Locations).ToImmutableArray(); return ToDefinitionItemAsync(group.Symbols.First(), allLocations, solution, isPrimary, includeHiddenLocations, includeClassifiedSpans: true, options, cancellationToken); } private static Task<DefinitionItem> ToDefinitionItemAsync( ISymbol definition, Solution solution, bool isPrimary, bool includeHiddenLocations, bool includeClassifiedSpans, FindReferencesSearchOptions options, CancellationToken cancellationToken) { return ToDefinitionItemAsync(definition, definition.Locations, solution, isPrimary, includeHiddenLocations, includeClassifiedSpans, options, cancellationToken); } private static async Task<DefinitionItem> ToDefinitionItemAsync( ISymbol definition, ImmutableArray<Location> locations, Solution solution, bool isPrimary, bool includeHiddenLocations, bool includeClassifiedSpans, FindReferencesSearchOptions options, CancellationToken cancellationToken) { // Ensure we're working with the original definition for the symbol. I.e. When we're // creating definition items, we want to create them for types like Dictionary<TKey,TValue> // not some random instantiation of that type. // // This ensures that the type will both display properly to the user, as well as ensuring // that we can accurately resolve the type later on when we try to navigate to it. if (!definition.IsTupleField()) { // In an earlier implementation of the compiler APIs, tuples and tuple fields symbols were definitions // We pretend this is still the case definition = definition.OriginalDefinition; } var displayParts = GetDisplayParts(definition); var nameDisplayParts = definition.ToDisplayParts(s_namePartsFormat).ToTaggedText(); var tags = GlyphTags.GetTags(definition.GetGlyph()); var displayIfNoReferences = definition.ShouldShowWithNoReferenceLocations( options, showMetadataSymbolsWithoutReferences: false); var properties = GetProperties(definition, isPrimary); // If it's a namespace, don't create any normal location. Namespaces // come from many different sources, but we'll only show a single // root definition node for it. That node won't be navigable. using var sourceLocations = TemporaryArray<DocumentSpan>.Empty; if (definition.Kind != SymbolKind.Namespace) { foreach (var location in locations) { if (location.IsInMetadata) { return DefinitionItem.CreateMetadataDefinition( tags, displayParts, nameDisplayParts, solution, definition, properties, displayIfNoReferences); } else if (location.IsInSource) { if (!location.IsVisibleSourceLocation() && !includeHiddenLocations) { continue; } var document = solution.GetDocument(location.SourceTree); if (document != null) { var documentLocation = !includeClassifiedSpans ? new DocumentSpan(document, location.SourceSpan) : await ClassifiedSpansAndHighlightSpanFactory.GetClassifiedDocumentSpanAsync( document, location.SourceSpan, cancellationToken).ConfigureAwait(false); sourceLocations.Add(documentLocation); } } } } if (sourceLocations.Count == 0) { // If we got no definition locations, then create a sentinel one // that we can display but which will not allow navigation. return DefinitionItem.CreateNonNavigableItem( tags, displayParts, DefinitionItem.GetOriginationParts(definition), properties, displayIfNoReferences); } var displayableProperties = AbstractReferenceFinder.GetAdditionalFindUsagesProperties(definition); return DefinitionItem.Create( tags, displayParts, sourceLocations.ToImmutableAndClear(), nameDisplayParts, properties, displayableProperties, displayIfNoReferences); } private static ImmutableDictionary<string, string> GetProperties(ISymbol definition, bool isPrimary) { var properties = ImmutableDictionary<string, string>.Empty; if (isPrimary) { properties = properties.Add(DefinitionItem.Primary, ""); } var rqName = RQNameInternal.From(definition); if (rqName != null) { properties = properties.Add(DefinitionItem.RQNameKey1, rqName); } if (definition?.IsConstructor() == true) { // If the symbol being considered is a constructor include the containing type in case // a third party wants to navigate to that. rqName = RQNameInternal.From(definition.ContainingType); if (rqName != null) { properties = properties.Add(DefinitionItem.RQNameKey2, rqName); } } return properties; } public static async Task<SourceReferenceItem?> TryCreateSourceReferenceItemAsync( this ReferenceLocation referenceLocation, DefinitionItem definitionItem, bool includeHiddenLocations, CancellationToken cancellationToken) { var location = referenceLocation.Location; Debug.Assert(location.IsInSource); if (!location.IsVisibleSourceLocation() && !includeHiddenLocations) { return null; } var document = referenceLocation.Document; var sourceSpan = location.SourceSpan; var documentSpan = await ClassifiedSpansAndHighlightSpanFactory.GetClassifiedDocumentSpanAsync( document, sourceSpan, cancellationToken).ConfigureAwait(false); return new SourceReferenceItem(definitionItem, documentSpan, referenceLocation.SymbolUsageInfo, referenceLocation.AdditionalProperties); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Features.RQName; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.FindSymbols.Finders; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.FindUsages { using static FindUsagesHelpers; internal interface IDefinitionsAndReferencesFactory : IWorkspaceService { Task<DefinitionItem?> GetThirdPartyDefinitionItemAsync( Solution solution, DefinitionItem definitionItem, CancellationToken cancellationToken); } [ExportWorkspaceService(typeof(IDefinitionsAndReferencesFactory)), Shared] internal class DefaultDefinitionsAndReferencesFactory : IDefinitionsAndReferencesFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultDefinitionsAndReferencesFactory() { } /// <summary> /// Provides an extension point that allows for other workspace layers to add additional /// results to the results found by the FindReferences engine. /// </summary> public virtual Task<DefinitionItem?> GetThirdPartyDefinitionItemAsync( Solution solution, DefinitionItem definitionItem, CancellationToken cancellationToken) { return SpecializedTasks.Null<DefinitionItem>(); } } internal static class DefinitionItemExtensions { private static readonly SymbolDisplayFormat s_namePartsFormat = new( memberOptions: SymbolDisplayMemberOptions.IncludeContainingType); public static DefinitionItem ToNonClassifiedDefinitionItem( this ISymbol definition, Solution solution, bool includeHiddenLocations) { // Because we're passing in 'false' for 'includeClassifiedSpans', this won't ever have // to actually do async work. This is because the only asynchrony is when we are trying // to compute the classified spans for the locations of the definition. So it's totally // fine to pass in CancellationToken.None and block on the result. return ToDefinitionItemAsync( definition, solution, isPrimary: false, includeHiddenLocations, includeClassifiedSpans: false, options: FindReferencesSearchOptions.Default, cancellationToken: CancellationToken.None).WaitAndGetResult_CanCallOnBackground(CancellationToken.None); } public static Task<DefinitionItem> ToNonClassifiedDefinitionItemAsync( this ISymbol definition, Solution solution, bool includeHiddenLocations, CancellationToken cancellationToken) { return ToDefinitionItemAsync( definition, solution, isPrimary: false, includeHiddenLocations, includeClassifiedSpans: false, options: FindReferencesSearchOptions.Default.With(unidirectionalHierarchyCascade: true), cancellationToken: cancellationToken); } public static Task<DefinitionItem> ToClassifiedDefinitionItemAsync( this ISymbol definition, Solution solution, bool isPrimary, bool includeHiddenLocations, FindReferencesSearchOptions options, CancellationToken cancellationToken) { return ToDefinitionItemAsync( definition, solution, isPrimary, includeHiddenLocations, includeClassifiedSpans: true, options, cancellationToken); } public static Task<DefinitionItem> ToClassifiedDefinitionItemAsync( this SymbolGroup group, Solution solution, bool isPrimary, bool includeHiddenLocations, FindReferencesSearchOptions options, CancellationToken cancellationToken) { // Make a single definition item that knows about all the locations of all the symbols in the group. var allLocations = group.Symbols.SelectMany(s => s.Locations).ToImmutableArray(); return ToDefinitionItemAsync(group.Symbols.First(), allLocations, solution, isPrimary, includeHiddenLocations, includeClassifiedSpans: true, options, cancellationToken); } private static Task<DefinitionItem> ToDefinitionItemAsync( ISymbol definition, Solution solution, bool isPrimary, bool includeHiddenLocations, bool includeClassifiedSpans, FindReferencesSearchOptions options, CancellationToken cancellationToken) { return ToDefinitionItemAsync(definition, definition.Locations, solution, isPrimary, includeHiddenLocations, includeClassifiedSpans, options, cancellationToken); } private static async Task<DefinitionItem> ToDefinitionItemAsync( ISymbol definition, ImmutableArray<Location> locations, Solution solution, bool isPrimary, bool includeHiddenLocations, bool includeClassifiedSpans, FindReferencesSearchOptions options, CancellationToken cancellationToken) { // Ensure we're working with the original definition for the symbol. I.e. When we're // creating definition items, we want to create them for types like Dictionary<TKey,TValue> // not some random instantiation of that type. // // This ensures that the type will both display properly to the user, as well as ensuring // that we can accurately resolve the type later on when we try to navigate to it. if (!definition.IsTupleField()) { // In an earlier implementation of the compiler APIs, tuples and tuple fields symbols were definitions // We pretend this is still the case definition = definition.OriginalDefinition; } var displayParts = GetDisplayParts(definition); var nameDisplayParts = definition.ToDisplayParts(s_namePartsFormat).ToTaggedText(); var tags = GlyphTags.GetTags(definition.GetGlyph()); var displayIfNoReferences = definition.ShouldShowWithNoReferenceLocations( options, showMetadataSymbolsWithoutReferences: false); var properties = GetProperties(definition, isPrimary); // If it's a namespace, don't create any normal location. Namespaces // come from many different sources, but we'll only show a single // root definition node for it. That node won't be navigable. using var sourceLocations = TemporaryArray<DocumentSpan>.Empty; if (definition.Kind != SymbolKind.Namespace) { foreach (var location in locations) { if (location.IsInMetadata) { return DefinitionItem.CreateMetadataDefinition( tags, displayParts, nameDisplayParts, solution, definition, properties, displayIfNoReferences); } else if (location.IsInSource) { if (!location.IsVisibleSourceLocation() && !includeHiddenLocations) { continue; } var document = solution.GetDocument(location.SourceTree); if (document != null) { var documentLocation = !includeClassifiedSpans ? new DocumentSpan(document, location.SourceSpan) : await ClassifiedSpansAndHighlightSpanFactory.GetClassifiedDocumentSpanAsync( document, location.SourceSpan, cancellationToken).ConfigureAwait(false); sourceLocations.Add(documentLocation); } } } } if (sourceLocations.Count == 0) { // If we got no definition locations, then create a sentinel one // that we can display but which will not allow navigation. return DefinitionItem.CreateNonNavigableItem( tags, displayParts, DefinitionItem.GetOriginationParts(definition), properties, displayIfNoReferences); } var displayableProperties = AbstractReferenceFinder.GetAdditionalFindUsagesProperties(definition); return DefinitionItem.Create( tags, displayParts, sourceLocations.ToImmutableAndClear(), nameDisplayParts, properties, displayableProperties, displayIfNoReferences); } private static ImmutableDictionary<string, string> GetProperties(ISymbol definition, bool isPrimary) { var properties = ImmutableDictionary<string, string>.Empty; if (isPrimary) { properties = properties.Add(DefinitionItem.Primary, ""); } var rqName = RQNameInternal.From(definition); if (rqName != null) { properties = properties.Add(DefinitionItem.RQNameKey1, rqName); } if (definition?.IsConstructor() == true) { // If the symbol being considered is a constructor include the containing type in case // a third party wants to navigate to that. rqName = RQNameInternal.From(definition.ContainingType); if (rqName != null) { properties = properties.Add(DefinitionItem.RQNameKey2, rqName); } } return properties; } public static async Task<SourceReferenceItem?> TryCreateSourceReferenceItemAsync( this ReferenceLocation referenceLocation, DefinitionItem definitionItem, bool includeHiddenLocations, CancellationToken cancellationToken) { var location = referenceLocation.Location; Debug.Assert(location.IsInSource); if (!location.IsVisibleSourceLocation() && !includeHiddenLocations) { return null; } var document = referenceLocation.Document; var sourceSpan = location.SourceSpan; var documentSpan = await ClassifiedSpansAndHighlightSpanFactory.GetClassifiedDocumentSpanAsync( document, sourceSpan, cancellationToken).ConfigureAwait(false); return new SourceReferenceItem(definitionItem, documentSpan, referenceLocation.SymbolUsageInfo, referenceLocation.AdditionalProperties); } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/DynamicTests.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.Collections.ObjectModel; using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class DynamicTests : ExpressionCompilerTestBase { [Fact] public void Local_Simple() { var source = @"class C { static void M() { dynamic d = 1; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: true); Assert.Equal(TypeKind.Dynamic, method.ReturnType.TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x01); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (object V_0) //d IL_0000: ldloc.0 IL_0001: ret }"); locals.Free(); }); } [Fact] public void Local_Array() { var source = @"class C { static void M() { dynamic[] d = new dynamic[1]; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: true); Assert.Equal(TypeKind.Dynamic, ((ArrayTypeSymbol)method.ReturnType).ElementType.TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (dynamic[] V_0) //d IL_0000: ldloc.0 IL_0001: ret }"); locals.Free(); }); } [Fact] public void Local_Generic() { var source = @"class C { static void M() { System.Collections.Generic.List<dynamic> d = null; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: true); Assert.Equal(TypeKind.Dynamic, ((NamedTypeSymbol)method.ReturnType).TypeArguments().Single().TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (System.Collections.Generic.List<dynamic> V_0) //d IL_0000: ldloc.0 IL_0001: ret }"); locals.Free(); }); } [Fact] public void LocalConstant_Simple() { var source = @"class C { static void M() { const dynamic d = null; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: true); Assert.Equal(TypeKind.Dynamic, method.ReturnType.TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x01); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedFlags: DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); locals.Free(); }); } [Fact] public void LocalConstant_Array() { var source = @"class C { static void M() { const dynamic[] d = null; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: true); Assert.Equal(TypeKind.Dynamic, ((ArrayTypeSymbol)method.ReturnType).ElementType.TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedFlags: DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt: @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); locals.Free(); }); } [Fact] public void LocalConstant_Generic() { var source = @"class C { static void M() { const Generic<dynamic> d = null; } static dynamic ForceDynamicAttribute() { return null; } } class Generic<T> { } "; var comp = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: true); Assert.Equal(TypeKind.Dynamic, ((NamedTypeSymbol)method.ReturnType).TypeArguments().Single().TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedFlags: DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt: @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); locals.Free(); }); } [WorkItem(4106, "https://github.com/dotnet/roslyn/issues/4106")] [Fact] public void LocalDuplicateConstantAndNonConstantDynamic() { var source = @"class C { static void M() { { #line 799 dynamic a = null; const dynamic b = null; } { const dynamic[] a = null; #line 899 dynamic[] b = null; } } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 799); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[0], "a", 0x01); } else { VerifyCustomTypeInfo(locals[0], "a", null); // Dynamic info ignored because ambiguous. } VerifyCustomTypeInfo(locals[1], "b", 0x01); locals.Free(); context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 899); testData = new CompilationTestData(); locals = ArrayBuilder<LocalAndMethod>.GetInstance(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyCustomTypeInfo(locals[0], "b", 0x02); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[1], "a", 0x02); } else { VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous. } locals.Free(); }); } [WorkItem(4106, "https://github.com/dotnet/roslyn/issues/4106")] [Fact] public void LocalDuplicateConstantAndNonConstantNonDynamic() { var source = @"class C { static void M() { { #line 799 object a = null; const dynamic b = null; } { const dynamic[] a = null; #line 899 object[] b = null; } } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 799); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyCustomTypeInfo(locals[0], "a", null); VerifyCustomTypeInfo(locals[1], "b", 0x01); locals.Free(); context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 899); testData = new CompilationTestData(); locals = ArrayBuilder<LocalAndMethod>.GetInstance(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyCustomTypeInfo(locals[0], "b", null); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[1], "a", 0x02); } else { VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous. } locals.Free(); }); } [WorkItem(4106, "https://github.com/dotnet/roslyn/issues/4106")] [Fact] public void LocalDuplicateConstantAndConstantDynamic() { var source = @"class C { static void M() { { const dynamic a = null; const dynamic b = null; #line 799 object e = null; } { const dynamic[] a = null; const dynamic[] c = null; #line 899 object[] e = null; } { #line 999 object e = null; const dynamic a = null; const dynamic c = null; } } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 799); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(3, locals.Count); VerifyCustomTypeInfo(locals[0], "e", null); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[1], "a", 0x01); } else { VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous. } VerifyCustomTypeInfo(locals[2], "b", 0x01); locals.Free(); context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 899); testData = new CompilationTestData(); locals = ArrayBuilder<LocalAndMethod>.GetInstance(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(3, locals.Count); VerifyCustomTypeInfo(locals[0], "e", null); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[1], "a", 0x02); VerifyCustomTypeInfo(locals[2], "c", 0x02); } else { VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous. VerifyCustomTypeInfo(locals[2], "c", null); // Dynamic info ignored because ambiguous. } locals.Free(); context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 999); testData = new CompilationTestData(); locals = ArrayBuilder<LocalAndMethod>.GetInstance(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(3, locals.Count); VerifyCustomTypeInfo(locals[0], "e", null); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[1], "a", 0x01); VerifyCustomTypeInfo(locals[2], "c", 0x01); } else { VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous. VerifyCustomTypeInfo(locals[2], "c", null); // Dynamic info ignored because ambiguous. } locals.Free(); }); } [WorkItem(4106, "https://github.com/dotnet/roslyn/issues/4106")] [Fact] public void LocalDuplicateConstantAndConstantNonDynamic() { var source = @"class C { static void M() { { const dynamic a = null; const object c = null; #line 799 object e = null; } { const dynamic[] b = null; #line 899 object[] e = null; } { const object[] a = null; #line 999 object e = null; const dynamic[] c = null; } } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 799); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(3, locals.Count); VerifyCustomTypeInfo(locals[0], "e", null); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[1], "a", 0x01); } else { VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous. } VerifyCustomTypeInfo(locals[2], "c", null); locals.Free(); context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 899); testData = new CompilationTestData(); locals = ArrayBuilder<LocalAndMethod>.GetInstance(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyCustomTypeInfo(locals[0], "e", null); VerifyCustomTypeInfo(locals[1], "b", 0x02); locals.Free(); context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 999); testData = new CompilationTestData(); locals = ArrayBuilder<LocalAndMethod>.GetInstance(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(3, locals.Count); VerifyCustomTypeInfo(locals[0], "e", null); VerifyCustomTypeInfo(locals[1], "a", null); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[2], "c", 0x02); } else { VerifyCustomTypeInfo(locals[2], "c", null); // Dynamic info ignored because ambiguous. } locals.Free(); }); } [Fact] public void LocalsWithLongAndShortNames() { var source = @"class C { static void M() { const dynamic a123456789012345678901234567890123456789012345678901234567890123 = null; // 64 chars const dynamic b = null; dynamic c123456789012345678901234567890123456789012345678901234567890123 = null; // 64 chars dynamic d = null; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, methodName: "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(4, locals.Count); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[0], "c123456789012345678901234567890123456789012345678901234567890123", 0x01); VerifyCustomTypeInfo(locals[2], "a123456789012345678901234567890123456789012345678901234567890123", 0x01); } else { VerifyCustomTypeInfo(locals[0], "c123456789012345678901234567890123456789012345678901234567890123", null); // dynamic info dropped VerifyCustomTypeInfo(locals[2], "a123456789012345678901234567890123456789012345678901234567890123", null); // dynamic info dropped } VerifyCustomTypeInfo(locals[1], "d", 0x01); VerifyCustomTypeInfo(locals[3], "b", 0x01); locals.Free(); }); } [Fact] public void Parameter_Simple() { var source = @"class C { static void M(dynamic d) { } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilation(source, new[] { CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: true); Assert.Equal(TypeKind.Dynamic, method.ReturnType.TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x01); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); locals.Free(); }); } [Fact] public void Parameter_Array() { var source = @"class C { static void M(dynamic[] d) { } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilation(source, new[] { CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: true); Assert.Equal(TypeKind.Dynamic, ((ArrayTypeSymbol)method.ReturnType).ElementType.TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); locals.Free(); }); } [Fact] public void Parameter_Generic() { var source = @"class C { static void M(System.Collections.Generic.List<dynamic> d) { } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilation(source, new[] { CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: true); Assert.Equal(TypeKind.Dynamic, ((NamedTypeSymbol)method.ReturnType).TypeArguments().Single().TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); locals.Free(); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] [WorkItem(1087216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087216")] public void ComplexDynamicType() { var source = @"class C { static void M(Outer<dynamic[], object[]>.Inner<Outer<object, dynamic>[], dynamic> d) { } static dynamic ForceDynamicAttribute() { return null; } } public class Outer<T, U> { public class Inner<V, W> { } } "; var comp = CreateCompilation(source, new[] { CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: true); VerifyCustomTypeInfo(locals[0], "d", 0x04, 0x03); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); string error; var result = context.CompileExpression("d", out error); Assert.Null(error); VerifyCustomTypeInfo(result, 0x04, 0x03); // Note that the method produced by CompileAssignment returns void // so there is never custom type info. result = context.CompileAssignment("d", "d", out error); Assert.Null(error); VerifyCustomTypeInfo(result, null); ResultProperties resultProperties; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; testData = new CompilationTestData(); result = context.CompileExpression( "var dd = d;", DkmEvaluationFlags.None, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Null(error); VerifyCustomTypeInfo(result, null); Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 60 (0x3c) .maxstack 6 IL_0000: ldtoken ""Outer<dynamic[], object[]>.Inner<Outer<object, dynamic>[], dynamic>"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""dd"" IL_000f: ldstr ""108766ce-df68-46ee-b761-0dcb7ac805f1"" IL_0014: newobj ""System.Guid..ctor(string)"" IL_0019: ldc.i4.3 IL_001a: newarr ""byte"" IL_001f: dup IL_0020: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=3 <PrivateImplementationDetails>.D7FC9689723FC6A41ADF105022720FF986ABA464083E7F71C6B921F8164E8878"" IL_0025: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_002a: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])"" IL_002f: ldstr ""dd"" IL_0034: call ""Outer<dynamic[], object[]>.Inner<Outer<object, dynamic>[], dynamic> Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<Outer<dynamic[], object[]>.Inner<Outer<object, dynamic>[], dynamic>>(string)"" IL_0039: ldarg.0 IL_003a: stind.ref IL_003b: ret }"); locals.Free(); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void DynamicAliases() { var source = @"class C { static void M() { } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext( runtime, "C.M"); var aliases = ImmutableArray.Create( Alias( DkmClrAliasKind.Variable, "d1", "d1", typeof(object).AssemblyQualifiedName, MakeCustomTypeInfo(true)), Alias( DkmClrAliasKind.Variable, "d2", "d2", typeof(Dictionary<Dictionary<object, Dictionary<object[], object[]>>, object>).AssemblyQualifiedName, MakeCustomTypeInfo(false, false, true, false, false, false, false, true, false))); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var diagnostics = DiagnosticBag.GetInstance(); var testData = new CompilationTestData(); context.CompileGetLocals( locals, argumentsOnly: false, aliases: aliases, diagnostics: diagnostics, typeName: out typeName, testData: testData); diagnostics.Free(); Assert.Equal(2, locals.Count); VerifyCustomTypeInfo(locals[0], "d1", 0x01); VerifyLocal(testData, typeName, locals[0], "<>m0", "d1", expectedILOpt: @"{ // Code size 11 (0xb) .maxstack 1 IL_0000: ldstr ""d1"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: ret }"); VerifyCustomTypeInfo(locals[1], "d2", 0x84, 0x00); // Note: read flags right-to-left in each byte: 0010 0001 0(000 0000) VerifyLocal(testData, typeName, locals[1], "<>m1", "d2", expectedILOpt: @"{ // Code size 16 (0x10) .maxstack 1 IL_0000: ldstr ""d2"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: castclass ""System.Collections.Generic.Dictionary<System.Collections.Generic.Dictionary<dynamic, System.Collections.Generic.Dictionary<object[], dynamic[]>>, object>"" IL_000f: ret }"); locals.Free(); }); } private static ReadOnlyCollection<byte> MakeCustomTypeInfo(params bool[] flags) { Assert.NotNull(flags); var builder = ArrayBuilder<bool>.GetInstance(); builder.AddRange(flags); var bytes = DynamicFlagsCustomTypeInfo.ToBytes(builder); builder.Free(); return CustomTypeInfo.Encode(bytes, null); } [Fact] public void DynamicAttribute_NotAvailable() { var source = @"class C { static void M() { dynamic d = 1; } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: false); VerifyCustomTypeInfo(locals[0], "d", null); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (object V_0) //d IL_0000: ldloc.0 IL_0001: ret }"); locals.Free(); }); } [Fact] public void DynamicCall() { var source = @" class C { void M() { dynamic d = this; d.M(); } } "; var comp = CreateCompilation(source, new[] { CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); string error; var result = context.CompileExpression("d.M()", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, 0x01); var methodData = testData.GetMethodData("<>x.<>m0"); Assert.Equal(TypeKind.Dynamic, ((MethodSymbol)methodData.Method).ReturnType.TypeKind); methodData.VerifyIL(@" { // Code size 77 (0x4d) .maxstack 9 .locals init (object V_0) //d IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0037 IL_0007: ldc.i4.0 IL_0008: ldstr ""M"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.1 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.0 IL_0021: ldnull IL_0022: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0027: stelem.ref IL_0028: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002d: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0032: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0037: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_003c: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_0041: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0046: ldloc.0 IL_0047: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004c: ret } "); }); } [WorkItem(1160855, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1160855")] [Fact] public void AwaitDynamic() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class C { dynamic d; void M(int p) { d.Test(); // Force reference to runtime binder. } static void G(Func<Task<object>> f) { } } "; var comp = CreateCompilationWithCSharp(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); string error; var result = context.CompileExpression("G(async () => await d())", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, null); var methodData = testData.GetMethodData("<>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()"); methodData.VerifyIL(@" { // Code size 542 (0x21e) .maxstack 10 .locals init (int V_0, <>x.<>c__DisplayClass0_0 V_1, object V_2, object V_3, System.Runtime.CompilerServices.ICriticalNotifyCompletion V_4, System.Runtime.CompilerServices.INotifyCompletion V_5, System.Exception V_6) IL_0000: ldarg.0 IL_0001: ldfld ""int <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>1__state"" IL_0006: stloc.0 IL_0007: ldarg.0 IL_0008: ldfld ""<>x.<>c__DisplayClass0_0 <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>4__this"" IL_000d: stloc.1 .try { IL_000e: ldloc.0 IL_000f: brfalse IL_018a IL_0014: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__0"" IL_0019: brtrue.s IL_004b IL_001b: ldc.i4.0 IL_001c: ldstr ""GetAwaiter"" IL_0021: ldnull IL_0022: ldtoken ""C"" IL_0027: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_002c: ldc.i4.1 IL_002d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0032: dup IL_0033: ldc.i4.0 IL_0034: ldc.i4.0 IL_0035: ldnull IL_0036: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003b: stelem.ref IL_003c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0041: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0046: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__0"" IL_004b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__0"" IL_0050: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_0055: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__0"" IL_005a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_005f: brtrue.s IL_008b IL_0061: ldc.i4.0 IL_0062: ldtoken ""C"" IL_0067: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_006c: ldc.i4.1 IL_006d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0072: dup IL_0073: ldc.i4.0 IL_0074: ldc.i4.0 IL_0075: ldnull IL_0076: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_007b: stelem.ref IL_007c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0081: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0086: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_008b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0090: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_0095: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_009a: ldloc.1 IL_009b: ldfld ""C <>x.<>c__DisplayClass0_0.<>4__this"" IL_00a0: ldfld ""dynamic C.d"" IL_00a5: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00aa: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00af: stloc.3 IL_00b0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__2"" IL_00b5: brtrue.s IL_00dc IL_00b7: ldc.i4.s 16 IL_00b9: ldtoken ""bool"" IL_00be: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00c3: ldtoken ""C"" IL_00c8: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00cd: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_00d2: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00d7: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__2"" IL_00dc: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__2"" IL_00e1: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Target"" IL_00e6: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__2"" IL_00eb: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__1"" IL_00f0: brtrue.s IL_0121 IL_00f2: ldc.i4.0 IL_00f3: ldstr ""IsCompleted"" IL_00f8: ldtoken ""C"" IL_00fd: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0102: ldc.i4.1 IL_0103: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0108: dup IL_0109: ldc.i4.0 IL_010a: ldc.i4.0 IL_010b: ldnull IL_010c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0111: stelem.ref IL_0112: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0117: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_011c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__1"" IL_0121: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__1"" IL_0126: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_012b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__1"" IL_0130: ldloc.3 IL_0131: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_0136: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_013b: brtrue.s IL_01a1 IL_013d: ldarg.0 IL_013e: ldc.i4.0 IL_013f: dup IL_0140: stloc.0 IL_0141: stfld ""int <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>1__state"" IL_0146: ldarg.0 IL_0147: ldloc.3 IL_0148: stfld ""object <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>u__1"" IL_014d: ldloc.3 IL_014e: isinst ""System.Runtime.CompilerServices.ICriticalNotifyCompletion"" IL_0153: stloc.s V_4 IL_0155: ldloc.s V_4 IL_0157: brtrue.s IL_0174 IL_0159: ldloc.3 IL_015a: castclass ""System.Runtime.CompilerServices.INotifyCompletion"" IL_015f: stloc.s V_5 IL_0161: ldarg.0 IL_0162: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>t__builder"" IL_0167: ldloca.s V_5 IL_0169: ldarg.0 IL_016a: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.AwaitOnCompleted<System.Runtime.CompilerServices.INotifyCompletion, <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d>(ref System.Runtime.CompilerServices.INotifyCompletion, ref <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d)"" IL_016f: ldnull IL_0170: stloc.s V_5 IL_0172: br.s IL_0182 IL_0174: ldarg.0 IL_0175: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>t__builder"" IL_017a: ldloca.s V_4 IL_017c: ldarg.0 IL_017d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.ICriticalNotifyCompletion, <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d>(ref System.Runtime.CompilerServices.ICriticalNotifyCompletion, ref <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d)"" IL_0182: ldnull IL_0183: stloc.s V_4 IL_0185: leave IL_021d IL_018a: ldarg.0 IL_018b: ldfld ""object <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>u__1"" IL_0190: stloc.3 IL_0191: ldarg.0 IL_0192: ldnull IL_0193: stfld ""object <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>u__1"" IL_0198: ldarg.0 IL_0199: ldc.i4.m1 IL_019a: dup IL_019b: stloc.0 IL_019c: stfld ""int <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>1__state"" IL_01a1: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__3"" IL_01a6: brtrue.s IL_01d8 IL_01a8: ldc.i4.0 IL_01a9: ldstr ""GetResult"" IL_01ae: ldnull IL_01af: ldtoken ""C"" IL_01b4: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_01b9: ldc.i4.1 IL_01ba: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_01bf: dup IL_01c0: ldc.i4.0 IL_01c1: ldc.i4.0 IL_01c2: ldnull IL_01c3: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_01c8: stelem.ref IL_01c9: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_01ce: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_01d3: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__3"" IL_01d8: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__3"" IL_01dd: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_01e2: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__3"" IL_01e7: ldloc.3 IL_01e8: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_01ed: stloc.2 IL_01ee: leave.s IL_0209 } catch System.Exception { IL_01f0: stloc.s V_6 IL_01f2: ldarg.0 IL_01f3: ldc.i4.s -2 IL_01f5: stfld ""int <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>1__state"" IL_01fa: ldarg.0 IL_01fb: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>t__builder"" IL_0200: ldloc.s V_6 IL_0202: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetException(System.Exception)"" IL_0207: leave.s IL_021d } IL_0209: ldarg.0 IL_020a: ldc.i4.s -2 IL_020c: stfld ""int <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>1__state"" IL_0211: ldarg.0 IL_0212: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>t__builder"" IL_0217: ldloc.2 IL_0218: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetResult(object)"" IL_021d: ret } "); }); } [WorkItem(1072296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1072296")] [Fact] public void InvokeStaticMemberInLambda() { var source = @" class C { static dynamic x; static void Goo(dynamic y) { System.Action a = () => Goo(x); } } "; var comp = CreateCompilation(source, new[] { CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.Goo"); var testData = new CompilationTestData(); string error; var result = context.CompileAssignment("a", "() => Goo(x)", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, null); testData.GetMethodData("<>x.<>c.<<>m0>b__0_0").VerifyIL(@" { // Code size 106 (0x6a) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0046 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""Goo"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.s 33 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: dup IL_002e: ldc.i4.1 IL_002f: ldc.i4.0 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003c: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0041: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_004b: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>>.Target"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_0055: ldtoken ""<>x"" IL_005a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005f: ldsfld ""dynamic C.x"" IL_0064: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_0069: ret }"); context = CreateMethodContext(runtime, "C.<>c.<Goo>b__1_0"); testData = new CompilationTestData(); result = context.CompileExpression("Goo(x)", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, 0x01); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL(@" { // Code size 102 (0x66) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0042 IL_0007: ldc.i4.0 IL_0008: ldstr ""Goo"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.2 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.s 33 IL_0022: ldnull IL_0023: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0028: stelem.ref IL_0029: dup IL_002a: ldc.i4.1 IL_002b: ldc.i4.0 IL_002c: ldnull IL_002d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0032: stelem.ref IL_0033: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0038: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003d: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0042: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0047: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Target"" IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0051: ldtoken ""<>x"" IL_0056: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005b: ldsfld ""dynamic C.x"" IL_0060: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_0065: ret }"); }); } [WorkItem(1095613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1095613")] [Fact] public void HoistedLocalsLoseDynamicAttribute() { var source = @" class C { static void M(dynamic x) { dynamic y = 3; System.Func<dynamic> a = () => x + y; } static void Goo(int x) { M(x); } } "; var comp = CreateCompilation(source, new[] { CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); string error; var result = context.CompileExpression("Goo(x)", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, 0x01); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 103 (0x67) .maxstack 9 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 System.Func<dynamic> V_1) //a IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0042 IL_0007: ldc.i4.0 IL_0008: ldstr ""Goo"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.2 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.s 33 IL_0022: ldnull IL_0023: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0028: stelem.ref IL_0029: dup IL_002a: ldc.i4.1 IL_002b: ldc.i4.0 IL_002c: ldnull IL_002d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0032: stelem.ref IL_0033: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0038: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003d: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0042: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0047: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Target"" IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0051: ldtoken ""<>x"" IL_0056: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005b: ldloc.0 IL_005c: ldfld ""dynamic C.<>c__DisplayClass0_0.x"" IL_0061: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_0066: ret }"); testData = new CompilationTestData(); result = context.CompileExpression("Goo(y)", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, 0x01); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 103 (0x67) .maxstack 9 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 System.Func<dynamic> V_1) //a IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0042 IL_0007: ldc.i4.0 IL_0008: ldstr ""Goo"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.2 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.s 33 IL_0022: ldnull IL_0023: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0028: stelem.ref IL_0029: dup IL_002a: ldc.i4.1 IL_002b: ldc.i4.0 IL_002c: ldnull IL_002d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0032: stelem.ref IL_0033: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0038: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003d: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0042: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0047: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Target"" IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0051: ldtoken ""<>x"" IL_0056: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005b: ldloc.0 IL_005c: ldfld ""dynamic C.<>c__DisplayClass0_0.y"" IL_0061: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_0066: ret }"); }); } private static void VerifyCustomTypeInfo(LocalAndMethod localAndMethod, string expectedName, params byte[] expectedBytes) { Assert.Equal(localAndMethod.LocalName, expectedName); ReadOnlyCollection<byte> customTypeInfo; Guid customTypeInfoId = localAndMethod.GetCustomTypeInfo(out customTypeInfo); VerifyCustomTypeInfo(customTypeInfoId, customTypeInfo, expectedBytes); } private static void VerifyCustomTypeInfo(CompileResult compileResult, params byte[] expectedBytes) { ReadOnlyCollection<byte> customTypeInfo; Guid customTypeInfoId = compileResult.GetCustomTypeInfo(out customTypeInfo); VerifyCustomTypeInfo(customTypeInfoId, customTypeInfo, expectedBytes); } private static void VerifyCustomTypeInfo(Guid customTypeInfoId, ReadOnlyCollection<byte> customTypeInfo, params byte[] expectedBytes) { if (expectedBytes == null) { Assert.Equal(Guid.Empty, customTypeInfoId); Assert.Null(customTypeInfo); } else { Assert.Equal(CustomTypeInfo.PayloadTypeId, customTypeInfoId); // Include leading count byte. var builder = ArrayBuilder<byte>.GetInstance(); builder.Add((byte)expectedBytes.Length); builder.AddRange(expectedBytes); expectedBytes = builder.ToArrayAndFree(); Assert.Equal(expectedBytes, customTypeInfo); } } } }
// Licensed to the .NET Foundation under one or more 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.Collections.ObjectModel; using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class DynamicTests : ExpressionCompilerTestBase { [Fact] public void Local_Simple() { var source = @"class C { static void M() { dynamic d = 1; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: true); Assert.Equal(TypeKind.Dynamic, method.ReturnType.TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x01); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (object V_0) //d IL_0000: ldloc.0 IL_0001: ret }"); locals.Free(); }); } [Fact] public void Local_Array() { var source = @"class C { static void M() { dynamic[] d = new dynamic[1]; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: true); Assert.Equal(TypeKind.Dynamic, ((ArrayTypeSymbol)method.ReturnType).ElementType.TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (dynamic[] V_0) //d IL_0000: ldloc.0 IL_0001: ret }"); locals.Free(); }); } [Fact] public void Local_Generic() { var source = @"class C { static void M() { System.Collections.Generic.List<dynamic> d = null; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: true); Assert.Equal(TypeKind.Dynamic, ((NamedTypeSymbol)method.ReturnType).TypeArguments().Single().TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (System.Collections.Generic.List<dynamic> V_0) //d IL_0000: ldloc.0 IL_0001: ret }"); locals.Free(); }); } [Fact] public void LocalConstant_Simple() { var source = @"class C { static void M() { const dynamic d = null; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: true); Assert.Equal(TypeKind.Dynamic, method.ReturnType.TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x01); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedFlags: DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); locals.Free(); }); } [Fact] public void LocalConstant_Array() { var source = @"class C { static void M() { const dynamic[] d = null; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: true); Assert.Equal(TypeKind.Dynamic, ((ArrayTypeSymbol)method.ReturnType).ElementType.TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedFlags: DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt: @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); locals.Free(); }); } [Fact] public void LocalConstant_Generic() { var source = @"class C { static void M() { const Generic<dynamic> d = null; } static dynamic ForceDynamicAttribute() { return null; } } class Generic<T> { } "; var comp = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: true); Assert.Equal(TypeKind.Dynamic, ((NamedTypeSymbol)method.ReturnType).TypeArguments().Single().TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedFlags: DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt: @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); locals.Free(); }); } [WorkItem(4106, "https://github.com/dotnet/roslyn/issues/4106")] [Fact] public void LocalDuplicateConstantAndNonConstantDynamic() { var source = @"class C { static void M() { { #line 799 dynamic a = null; const dynamic b = null; } { const dynamic[] a = null; #line 899 dynamic[] b = null; } } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 799); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[0], "a", 0x01); } else { VerifyCustomTypeInfo(locals[0], "a", null); // Dynamic info ignored because ambiguous. } VerifyCustomTypeInfo(locals[1], "b", 0x01); locals.Free(); context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 899); testData = new CompilationTestData(); locals = ArrayBuilder<LocalAndMethod>.GetInstance(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyCustomTypeInfo(locals[0], "b", 0x02); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[1], "a", 0x02); } else { VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous. } locals.Free(); }); } [WorkItem(4106, "https://github.com/dotnet/roslyn/issues/4106")] [Fact] public void LocalDuplicateConstantAndNonConstantNonDynamic() { var source = @"class C { static void M() { { #line 799 object a = null; const dynamic b = null; } { const dynamic[] a = null; #line 899 object[] b = null; } } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 799); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyCustomTypeInfo(locals[0], "a", null); VerifyCustomTypeInfo(locals[1], "b", 0x01); locals.Free(); context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 899); testData = new CompilationTestData(); locals = ArrayBuilder<LocalAndMethod>.GetInstance(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyCustomTypeInfo(locals[0], "b", null); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[1], "a", 0x02); } else { VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous. } locals.Free(); }); } [WorkItem(4106, "https://github.com/dotnet/roslyn/issues/4106")] [Fact] public void LocalDuplicateConstantAndConstantDynamic() { var source = @"class C { static void M() { { const dynamic a = null; const dynamic b = null; #line 799 object e = null; } { const dynamic[] a = null; const dynamic[] c = null; #line 899 object[] e = null; } { #line 999 object e = null; const dynamic a = null; const dynamic c = null; } } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 799); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(3, locals.Count); VerifyCustomTypeInfo(locals[0], "e", null); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[1], "a", 0x01); } else { VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous. } VerifyCustomTypeInfo(locals[2], "b", 0x01); locals.Free(); context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 899); testData = new CompilationTestData(); locals = ArrayBuilder<LocalAndMethod>.GetInstance(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(3, locals.Count); VerifyCustomTypeInfo(locals[0], "e", null); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[1], "a", 0x02); VerifyCustomTypeInfo(locals[2], "c", 0x02); } else { VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous. VerifyCustomTypeInfo(locals[2], "c", null); // Dynamic info ignored because ambiguous. } locals.Free(); context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 999); testData = new CompilationTestData(); locals = ArrayBuilder<LocalAndMethod>.GetInstance(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(3, locals.Count); VerifyCustomTypeInfo(locals[0], "e", null); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[1], "a", 0x01); VerifyCustomTypeInfo(locals[2], "c", 0x01); } else { VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous. VerifyCustomTypeInfo(locals[2], "c", null); // Dynamic info ignored because ambiguous. } locals.Free(); }); } [WorkItem(4106, "https://github.com/dotnet/roslyn/issues/4106")] [Fact] public void LocalDuplicateConstantAndConstantNonDynamic() { var source = @"class C { static void M() { { const dynamic a = null; const object c = null; #line 799 object e = null; } { const dynamic[] b = null; #line 899 object[] e = null; } { const object[] a = null; #line 999 object e = null; const dynamic[] c = null; } } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 799); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(3, locals.Count); VerifyCustomTypeInfo(locals[0], "e", null); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[1], "a", 0x01); } else { VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous. } VerifyCustomTypeInfo(locals[2], "c", null); locals.Free(); context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 899); testData = new CompilationTestData(); locals = ArrayBuilder<LocalAndMethod>.GetInstance(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyCustomTypeInfo(locals[0], "e", null); VerifyCustomTypeInfo(locals[1], "b", 0x02); locals.Free(); context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 999); testData = new CompilationTestData(); locals = ArrayBuilder<LocalAndMethod>.GetInstance(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(3, locals.Count); VerifyCustomTypeInfo(locals[0], "e", null); VerifyCustomTypeInfo(locals[1], "a", null); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[2], "c", 0x02); } else { VerifyCustomTypeInfo(locals[2], "c", null); // Dynamic info ignored because ambiguous. } locals.Free(); }); } [Fact] public void LocalsWithLongAndShortNames() { var source = @"class C { static void M() { const dynamic a123456789012345678901234567890123456789012345678901234567890123 = null; // 64 chars const dynamic b = null; dynamic c123456789012345678901234567890123456789012345678901234567890123 = null; // 64 chars dynamic d = null; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, methodName: "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(4, locals.Count); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[0], "c123456789012345678901234567890123456789012345678901234567890123", 0x01); VerifyCustomTypeInfo(locals[2], "a123456789012345678901234567890123456789012345678901234567890123", 0x01); } else { VerifyCustomTypeInfo(locals[0], "c123456789012345678901234567890123456789012345678901234567890123", null); // dynamic info dropped VerifyCustomTypeInfo(locals[2], "a123456789012345678901234567890123456789012345678901234567890123", null); // dynamic info dropped } VerifyCustomTypeInfo(locals[1], "d", 0x01); VerifyCustomTypeInfo(locals[3], "b", 0x01); locals.Free(); }); } [Fact] public void Parameter_Simple() { var source = @"class C { static void M(dynamic d) { } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilation(source, new[] { CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: true); Assert.Equal(TypeKind.Dynamic, method.ReturnType.TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x01); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); locals.Free(); }); } [Fact] public void Parameter_Array() { var source = @"class C { static void M(dynamic[] d) { } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilation(source, new[] { CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: true); Assert.Equal(TypeKind.Dynamic, ((ArrayTypeSymbol)method.ReturnType).ElementType.TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); locals.Free(); }); } [Fact] public void Parameter_Generic() { var source = @"class C { static void M(System.Collections.Generic.List<dynamic> d) { } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilation(source, new[] { CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: true); Assert.Equal(TypeKind.Dynamic, ((NamedTypeSymbol)method.ReturnType).TypeArguments().Single().TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); locals.Free(); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] [WorkItem(1087216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087216")] public void ComplexDynamicType() { var source = @"class C { static void M(Outer<dynamic[], object[]>.Inner<Outer<object, dynamic>[], dynamic> d) { } static dynamic ForceDynamicAttribute() { return null; } } public class Outer<T, U> { public class Inner<V, W> { } } "; var comp = CreateCompilation(source, new[] { CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: true); VerifyCustomTypeInfo(locals[0], "d", 0x04, 0x03); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); string error; var result = context.CompileExpression("d", out error); Assert.Null(error); VerifyCustomTypeInfo(result, 0x04, 0x03); // Note that the method produced by CompileAssignment returns void // so there is never custom type info. result = context.CompileAssignment("d", "d", out error); Assert.Null(error); VerifyCustomTypeInfo(result, null); ResultProperties resultProperties; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; testData = new CompilationTestData(); result = context.CompileExpression( "var dd = d;", DkmEvaluationFlags.None, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Null(error); VerifyCustomTypeInfo(result, null); Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 60 (0x3c) .maxstack 6 IL_0000: ldtoken ""Outer<dynamic[], object[]>.Inner<Outer<object, dynamic>[], dynamic>"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""dd"" IL_000f: ldstr ""108766ce-df68-46ee-b761-0dcb7ac805f1"" IL_0014: newobj ""System.Guid..ctor(string)"" IL_0019: ldc.i4.3 IL_001a: newarr ""byte"" IL_001f: dup IL_0020: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=3 <PrivateImplementationDetails>.D7FC9689723FC6A41ADF105022720FF986ABA464083E7F71C6B921F8164E8878"" IL_0025: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_002a: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])"" IL_002f: ldstr ""dd"" IL_0034: call ""Outer<dynamic[], object[]>.Inner<Outer<object, dynamic>[], dynamic> Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<Outer<dynamic[], object[]>.Inner<Outer<object, dynamic>[], dynamic>>(string)"" IL_0039: ldarg.0 IL_003a: stind.ref IL_003b: ret }"); locals.Free(); }); } [ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")] public void DynamicAliases() { var source = @"class C { static void M() { } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext( runtime, "C.M"); var aliases = ImmutableArray.Create( Alias( DkmClrAliasKind.Variable, "d1", "d1", typeof(object).AssemblyQualifiedName, MakeCustomTypeInfo(true)), Alias( DkmClrAliasKind.Variable, "d2", "d2", typeof(Dictionary<Dictionary<object, Dictionary<object[], object[]>>, object>).AssemblyQualifiedName, MakeCustomTypeInfo(false, false, true, false, false, false, false, true, false))); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var diagnostics = DiagnosticBag.GetInstance(); var testData = new CompilationTestData(); context.CompileGetLocals( locals, argumentsOnly: false, aliases: aliases, diagnostics: diagnostics, typeName: out typeName, testData: testData); diagnostics.Free(); Assert.Equal(2, locals.Count); VerifyCustomTypeInfo(locals[0], "d1", 0x01); VerifyLocal(testData, typeName, locals[0], "<>m0", "d1", expectedILOpt: @"{ // Code size 11 (0xb) .maxstack 1 IL_0000: ldstr ""d1"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: ret }"); VerifyCustomTypeInfo(locals[1], "d2", 0x84, 0x00); // Note: read flags right-to-left in each byte: 0010 0001 0(000 0000) VerifyLocal(testData, typeName, locals[1], "<>m1", "d2", expectedILOpt: @"{ // Code size 16 (0x10) .maxstack 1 IL_0000: ldstr ""d2"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: castclass ""System.Collections.Generic.Dictionary<System.Collections.Generic.Dictionary<dynamic, System.Collections.Generic.Dictionary<object[], dynamic[]>>, object>"" IL_000f: ret }"); locals.Free(); }); } private static ReadOnlyCollection<byte> MakeCustomTypeInfo(params bool[] flags) { Assert.NotNull(flags); var builder = ArrayBuilder<bool>.GetInstance(); builder.AddRange(flags); var bytes = DynamicFlagsCustomTypeInfo.ToBytes(builder); builder.Free(); return CustomTypeInfo.Encode(bytes, null); } [Fact] public void DynamicAttribute_NotAvailable() { var source = @"class C { static void M() { dynamic d = 1; } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method; CheckAttribute(assembly, method, AttributeDescription.DynamicAttribute, expected: false); VerifyCustomTypeInfo(locals[0], "d", null); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (object V_0) //d IL_0000: ldloc.0 IL_0001: ret }"); locals.Free(); }); } [Fact] public void DynamicCall() { var source = @" class C { void M() { dynamic d = this; d.M(); } } "; var comp = CreateCompilation(source, new[] { CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); string error; var result = context.CompileExpression("d.M()", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, 0x01); var methodData = testData.GetMethodData("<>x.<>m0"); Assert.Equal(TypeKind.Dynamic, ((MethodSymbol)methodData.Method).ReturnType.TypeKind); methodData.VerifyIL(@" { // Code size 77 (0x4d) .maxstack 9 .locals init (object V_0) //d IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0037 IL_0007: ldc.i4.0 IL_0008: ldstr ""M"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.1 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.0 IL_0021: ldnull IL_0022: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0027: stelem.ref IL_0028: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002d: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0032: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0037: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_003c: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_0041: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0046: ldloc.0 IL_0047: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004c: ret } "); }); } [WorkItem(1160855, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1160855")] [Fact] public void AwaitDynamic() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class C { dynamic d; void M(int p) { d.Test(); // Force reference to runtime binder. } static void G(Func<Task<object>> f) { } } "; var comp = CreateCompilationWithCSharp(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); string error; var result = context.CompileExpression("G(async () => await d())", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, null); var methodData = testData.GetMethodData("<>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()"); methodData.VerifyIL(@" { // Code size 542 (0x21e) .maxstack 10 .locals init (int V_0, <>x.<>c__DisplayClass0_0 V_1, object V_2, object V_3, System.Runtime.CompilerServices.ICriticalNotifyCompletion V_4, System.Runtime.CompilerServices.INotifyCompletion V_5, System.Exception V_6) IL_0000: ldarg.0 IL_0001: ldfld ""int <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>1__state"" IL_0006: stloc.0 IL_0007: ldarg.0 IL_0008: ldfld ""<>x.<>c__DisplayClass0_0 <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>4__this"" IL_000d: stloc.1 .try { IL_000e: ldloc.0 IL_000f: brfalse IL_018a IL_0014: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__0"" IL_0019: brtrue.s IL_004b IL_001b: ldc.i4.0 IL_001c: ldstr ""GetAwaiter"" IL_0021: ldnull IL_0022: ldtoken ""C"" IL_0027: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_002c: ldc.i4.1 IL_002d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0032: dup IL_0033: ldc.i4.0 IL_0034: ldc.i4.0 IL_0035: ldnull IL_0036: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_003b: stelem.ref IL_003c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0041: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0046: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__0"" IL_004b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__0"" IL_0050: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_0055: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__0"" IL_005a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_005f: brtrue.s IL_008b IL_0061: ldc.i4.0 IL_0062: ldtoken ""C"" IL_0067: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_006c: ldc.i4.1 IL_006d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0072: dup IL_0073: ldc.i4.0 IL_0074: ldc.i4.0 IL_0075: ldnull IL_0076: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_007b: stelem.ref IL_007c: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0081: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0086: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_008b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0090: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_0095: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_009a: ldloc.1 IL_009b: ldfld ""C <>x.<>c__DisplayClass0_0.<>4__this"" IL_00a0: ldfld ""dynamic C.d"" IL_00a5: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00aa: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00af: stloc.3 IL_00b0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__2"" IL_00b5: brtrue.s IL_00dc IL_00b7: ldc.i4.s 16 IL_00b9: ldtoken ""bool"" IL_00be: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00c3: ldtoken ""C"" IL_00c8: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00cd: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_00d2: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00d7: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__2"" IL_00dc: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__2"" IL_00e1: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Target"" IL_00e6: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__2"" IL_00eb: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__1"" IL_00f0: brtrue.s IL_0121 IL_00f2: ldc.i4.0 IL_00f3: ldstr ""IsCompleted"" IL_00f8: ldtoken ""C"" IL_00fd: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0102: ldc.i4.1 IL_0103: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0108: dup IL_0109: ldc.i4.0 IL_010a: ldc.i4.0 IL_010b: ldnull IL_010c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0111: stelem.ref IL_0112: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0117: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_011c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__1"" IL_0121: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__1"" IL_0126: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_012b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__1"" IL_0130: ldloc.3 IL_0131: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_0136: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_013b: brtrue.s IL_01a1 IL_013d: ldarg.0 IL_013e: ldc.i4.0 IL_013f: dup IL_0140: stloc.0 IL_0141: stfld ""int <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>1__state"" IL_0146: ldarg.0 IL_0147: ldloc.3 IL_0148: stfld ""object <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>u__1"" IL_014d: ldloc.3 IL_014e: isinst ""System.Runtime.CompilerServices.ICriticalNotifyCompletion"" IL_0153: stloc.s V_4 IL_0155: ldloc.s V_4 IL_0157: brtrue.s IL_0174 IL_0159: ldloc.3 IL_015a: castclass ""System.Runtime.CompilerServices.INotifyCompletion"" IL_015f: stloc.s V_5 IL_0161: ldarg.0 IL_0162: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>t__builder"" IL_0167: ldloca.s V_5 IL_0169: ldarg.0 IL_016a: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.AwaitOnCompleted<System.Runtime.CompilerServices.INotifyCompletion, <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d>(ref System.Runtime.CompilerServices.INotifyCompletion, ref <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d)"" IL_016f: ldnull IL_0170: stloc.s V_5 IL_0172: br.s IL_0182 IL_0174: ldarg.0 IL_0175: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>t__builder"" IL_017a: ldloca.s V_4 IL_017c: ldarg.0 IL_017d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.ICriticalNotifyCompletion, <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d>(ref System.Runtime.CompilerServices.ICriticalNotifyCompletion, ref <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d)"" IL_0182: ldnull IL_0183: stloc.s V_4 IL_0185: leave IL_021d IL_018a: ldarg.0 IL_018b: ldfld ""object <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>u__1"" IL_0190: stloc.3 IL_0191: ldarg.0 IL_0192: ldnull IL_0193: stfld ""object <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>u__1"" IL_0198: ldarg.0 IL_0199: ldc.i4.m1 IL_019a: dup IL_019b: stloc.0 IL_019c: stfld ""int <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>1__state"" IL_01a1: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__3"" IL_01a6: brtrue.s IL_01d8 IL_01a8: ldc.i4.0 IL_01a9: ldstr ""GetResult"" IL_01ae: ldnull IL_01af: ldtoken ""C"" IL_01b4: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_01b9: ldc.i4.1 IL_01ba: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_01bf: dup IL_01c0: ldc.i4.0 IL_01c1: ldc.i4.0 IL_01c2: ldnull IL_01c3: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_01c8: stelem.ref IL_01c9: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_01ce: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_01d3: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__3"" IL_01d8: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__3"" IL_01dd: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_01e2: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__3"" IL_01e7: ldloc.3 IL_01e8: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_01ed: stloc.2 IL_01ee: leave.s IL_0209 } catch System.Exception { IL_01f0: stloc.s V_6 IL_01f2: ldarg.0 IL_01f3: ldc.i4.s -2 IL_01f5: stfld ""int <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>1__state"" IL_01fa: ldarg.0 IL_01fb: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>t__builder"" IL_0200: ldloc.s V_6 IL_0202: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetException(System.Exception)"" IL_0207: leave.s IL_021d } IL_0209: ldarg.0 IL_020a: ldc.i4.s -2 IL_020c: stfld ""int <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>1__state"" IL_0211: ldarg.0 IL_0212: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>t__builder"" IL_0217: ldloc.2 IL_0218: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetResult(object)"" IL_021d: ret } "); }); } [WorkItem(1072296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1072296")] [Fact] public void InvokeStaticMemberInLambda() { var source = @" class C { static dynamic x; static void Goo(dynamic y) { System.Action a = () => Goo(x); } } "; var comp = CreateCompilation(source, new[] { CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.Goo"); var testData = new CompilationTestData(); string error; var result = context.CompileAssignment("a", "() => Goo(x)", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, null); testData.GetMethodData("<>x.<>c.<<>m0>b__0_0").VerifyIL(@" { // Code size 106 (0x6a) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0046 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""Goo"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.s 33 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: dup IL_002e: ldc.i4.1 IL_002f: ldc.i4.0 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003c: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0041: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_004b: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>>.Target"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_0055: ldtoken ""<>x"" IL_005a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005f: ldsfld ""dynamic C.x"" IL_0064: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_0069: ret }"); context = CreateMethodContext(runtime, "C.<>c.<Goo>b__1_0"); testData = new CompilationTestData(); result = context.CompileExpression("Goo(x)", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, 0x01); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL(@" { // Code size 102 (0x66) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0042 IL_0007: ldc.i4.0 IL_0008: ldstr ""Goo"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.2 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.s 33 IL_0022: ldnull IL_0023: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0028: stelem.ref IL_0029: dup IL_002a: ldc.i4.1 IL_002b: ldc.i4.0 IL_002c: ldnull IL_002d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0032: stelem.ref IL_0033: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0038: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003d: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0042: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0047: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Target"" IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0051: ldtoken ""<>x"" IL_0056: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005b: ldsfld ""dynamic C.x"" IL_0060: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_0065: ret }"); }); } [WorkItem(1095613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1095613")] [Fact] public void HoistedLocalsLoseDynamicAttribute() { var source = @" class C { static void M(dynamic x) { dynamic y = 3; System.Func<dynamic> a = () => x + y; } static void Goo(int x) { M(x); } } "; var comp = CreateCompilation(source, new[] { CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); string error; var result = context.CompileExpression("Goo(x)", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, 0x01); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 103 (0x67) .maxstack 9 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 System.Func<dynamic> V_1) //a IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0042 IL_0007: ldc.i4.0 IL_0008: ldstr ""Goo"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.2 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.s 33 IL_0022: ldnull IL_0023: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0028: stelem.ref IL_0029: dup IL_002a: ldc.i4.1 IL_002b: ldc.i4.0 IL_002c: ldnull IL_002d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0032: stelem.ref IL_0033: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0038: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003d: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0042: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0047: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Target"" IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0051: ldtoken ""<>x"" IL_0056: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005b: ldloc.0 IL_005c: ldfld ""dynamic C.<>c__DisplayClass0_0.x"" IL_0061: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_0066: ret }"); testData = new CompilationTestData(); result = context.CompileExpression("Goo(y)", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, 0x01); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 103 (0x67) .maxstack 9 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 System.Func<dynamic> V_1) //a IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0042 IL_0007: ldc.i4.0 IL_0008: ldstr ""Goo"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.2 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.s 33 IL_0022: ldnull IL_0023: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0028: stelem.ref IL_0029: dup IL_002a: ldc.i4.1 IL_002b: ldc.i4.0 IL_002c: ldnull IL_002d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0032: stelem.ref IL_0033: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0038: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003d: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0042: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0047: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Target"" IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0051: ldtoken ""<>x"" IL_0056: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005b: ldloc.0 IL_005c: ldfld ""dynamic C.<>c__DisplayClass0_0.y"" IL_0061: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_0066: ret }"); }); } private static void VerifyCustomTypeInfo(LocalAndMethod localAndMethod, string expectedName, params byte[] expectedBytes) { Assert.Equal(localAndMethod.LocalName, expectedName); ReadOnlyCollection<byte> customTypeInfo; Guid customTypeInfoId = localAndMethod.GetCustomTypeInfo(out customTypeInfo); VerifyCustomTypeInfo(customTypeInfoId, customTypeInfo, expectedBytes); } private static void VerifyCustomTypeInfo(CompileResult compileResult, params byte[] expectedBytes) { ReadOnlyCollection<byte> customTypeInfo; Guid customTypeInfoId = compileResult.GetCustomTypeInfo(out customTypeInfo); VerifyCustomTypeInfo(customTypeInfoId, customTypeInfo, expectedBytes); } private static void VerifyCustomTypeInfo(Guid customTypeInfoId, ReadOnlyCollection<byte> customTypeInfo, params byte[] expectedBytes) { if (expectedBytes == null) { Assert.Equal(Guid.Empty, customTypeInfoId); Assert.Null(customTypeInfo); } else { Assert.Equal(CustomTypeInfo.PayloadTypeId, customTypeInfoId); // Include leading count byte. var builder = ArrayBuilder<byte>.GetInstance(); builder.Add((byte)expectedBytes.Length); builder.AddRange(expectedBytes); expectedBytes = builder.ToArrayAndFree(); Assert.Equal(expectedBytes, customTypeInfo); } } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/Test/Core/Mocks/TestMissingMetadataReferenceResolver.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Roslyn.Utilities; namespace Roslyn.Test.Utilities { internal class TestMissingMetadataReferenceResolver : MetadataReferenceResolver { internal struct ReferenceAndIdentity { public readonly MetadataReference Reference; public readonly AssemblyIdentity Identity; public ReferenceAndIdentity(MetadataReference reference, AssemblyIdentity identity) { Reference = reference; Identity = identity; } public override string ToString() { return $"{Reference.Display} -> {Identity.GetDisplayName()}"; } } private readonly Dictionary<string, MetadataReference> _map; public readonly List<ReferenceAndIdentity> ResolutionAttempts = new List<ReferenceAndIdentity>(); public TestMissingMetadataReferenceResolver(Dictionary<string, MetadataReference> map) { _map = map; } public override PortableExecutableReference ResolveMissingAssembly(MetadataReference definition, AssemblyIdentity referenceIdentity) { ResolutionAttempts.Add(new ReferenceAndIdentity(definition, referenceIdentity)); string nameAndVersion = referenceIdentity.Name + (referenceIdentity.Version != AssemblyIdentity.NullVersion ? $", {referenceIdentity.Version}" : ""); return _map.TryGetValue(nameAndVersion, out var reference) ? (PortableExecutableReference)reference : null; } public override bool ResolveMissingAssemblies => true; public override bool Equals(object other) => true; public override int GetHashCode() => 1; public override ImmutableArray<PortableExecutableReference> ResolveReference(string reference, string baseFilePath, MetadataReferenceProperties properties) => default(ImmutableArray<PortableExecutableReference>); public void VerifyResolutionAttempts(params string[] expected) { AssertEx.Equal(expected, ResolutionAttempts.Select(a => a.ToString())); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Roslyn.Utilities; namespace Roslyn.Test.Utilities { internal class TestMissingMetadataReferenceResolver : MetadataReferenceResolver { internal struct ReferenceAndIdentity { public readonly MetadataReference Reference; public readonly AssemblyIdentity Identity; public ReferenceAndIdentity(MetadataReference reference, AssemblyIdentity identity) { Reference = reference; Identity = identity; } public override string ToString() { return $"{Reference.Display} -> {Identity.GetDisplayName()}"; } } private readonly Dictionary<string, MetadataReference> _map; public readonly List<ReferenceAndIdentity> ResolutionAttempts = new List<ReferenceAndIdentity>(); public TestMissingMetadataReferenceResolver(Dictionary<string, MetadataReference> map) { _map = map; } public override PortableExecutableReference ResolveMissingAssembly(MetadataReference definition, AssemblyIdentity referenceIdentity) { ResolutionAttempts.Add(new ReferenceAndIdentity(definition, referenceIdentity)); string nameAndVersion = referenceIdentity.Name + (referenceIdentity.Version != AssemblyIdentity.NullVersion ? $", {referenceIdentity.Version}" : ""); return _map.TryGetValue(nameAndVersion, out var reference) ? (PortableExecutableReference)reference : null; } public override bool ResolveMissingAssemblies => true; public override bool Equals(object other) => true; public override int GetHashCode() => 1; public override ImmutableArray<PortableExecutableReference> ResolveReference(string reference, string baseFilePath, MetadataReferenceProperties properties) => default(ImmutableArray<PortableExecutableReference>); public void VerifyResolutionAttempts(params string[] expected) { AssertEx.Equal(expected, ResolutionAttempts.Select(a => a.ToString())); } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Features/Core/Portable/EditAndContinue/UnmappedActiveStatement.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 Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.EditAndContinue { internal readonly struct UnmappedActiveStatement { /// <summary> /// Unmapped span of the active statement /// (span within the file that contains #line directive that has an effect on the active statement, if there is any). /// </summary> public TextSpan UnmappedSpan { get; } /// <summary> /// Active statement - its <see cref="ActiveStatement.FileSpan"/> is mapped. /// </summary> public ActiveStatement Statement { get; } /// <summary> /// Mapped exception regions around the active statement. /// </summary> public ActiveStatementExceptionRegions ExceptionRegions { get; } public UnmappedActiveStatement(TextSpan unmappedSpan, ActiveStatement statement, ActiveStatementExceptionRegions exceptionRegions) { UnmappedSpan = unmappedSpan; Statement = statement; ExceptionRegions = exceptionRegions; } public void Deconstruct(out TextSpan unmappedSpan, out ActiveStatement statement, out ActiveStatementExceptionRegions exceptionRegions) { unmappedSpan = UnmappedSpan; statement = Statement; exceptionRegions = ExceptionRegions; } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.EditAndContinue { internal readonly struct UnmappedActiveStatement { /// <summary> /// Unmapped span of the active statement /// (span within the file that contains #line directive that has an effect on the active statement, if there is any). /// </summary> public TextSpan UnmappedSpan { get; } /// <summary> /// Active statement - its <see cref="ActiveStatement.FileSpan"/> is mapped. /// </summary> public ActiveStatement Statement { get; } /// <summary> /// Mapped exception regions around the active statement. /// </summary> public ActiveStatementExceptionRegions ExceptionRegions { get; } public UnmappedActiveStatement(TextSpan unmappedSpan, ActiveStatement statement, ActiveStatementExceptionRegions exceptionRegions) { UnmappedSpan = unmappedSpan; Statement = statement; ExceptionRegions = exceptionRegions; } public void Deconstruct(out TextSpan unmappedSpan, out ActiveStatement statement, out ActiveStatementExceptionRegions exceptionRegions) { unmappedSpan = UnmappedSpan; statement = Statement; exceptionRegions = ExceptionRegions; } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/VisualStudio/VisualBasic/Impl/Options/AutomationObject/AutomationObject.Obsolete.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options Partial Public Class AutomationObject <Obsolete("ClosedFileDiagnostics has been deprecated")> Public Property ClosedFileDiagnostics As Boolean Get Return False End Get Set(value As Boolean) End Set End Property <Obsolete("BasicClosedFileDiagnostics has been deprecated")> Public Property BasicClosedFileDiagnostics As Integer Get Return 0 End Get Set(value As Integer) End Set End Property 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. Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options Partial Public Class AutomationObject <Obsolete("ClosedFileDiagnostics has been deprecated")> Public Property ClosedFileDiagnostics As Boolean Get Return False End Get Set(value As Boolean) End Set End Property <Obsolete("BasicClosedFileDiagnostics has been deprecated")> Public Property BasicClosedFileDiagnostics As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class End Namespace
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ProtectedKeywordRecommender.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 Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ProtectedKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ProtectedKeywordRecommender() : base(SyntaxKind.ProtectedKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return IsValidContextForAccessor(context) || IsValidContextForType(context, cancellationToken) || IsValidContextForMember(context, cancellationToken); } private static bool IsValidContextForAccessor(CSharpSyntaxContext context) { if (context.TargetToken.IsAccessorDeclarationContext<PropertyDeclarationSyntax>(context.Position) || context.TargetToken.IsAccessorDeclarationContext<IndexerDeclarationSyntax>(context.Position)) { return CheckPreviousAccessibilityModifiers(context); } return false; } private static bool IsValidContextForMember(CSharpSyntaxContext context, CancellationToken cancellationToken) { if (context.IsMemberDeclarationContext(validModifiers: SyntaxKindSet.AllMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken)) { return CheckPreviousAccessibilityModifiers(context); } return false; } private static bool IsValidContextForType(CSharpSyntaxContext context, CancellationToken cancellationToken) { if (context.IsTypeDeclarationContext(validModifiers: SyntaxKindSet.AllTypeModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken)) { // protected things can't be in namespaces. var typeDecl = context.ContainingTypeDeclaration; if (typeDecl == null) { return false; } return CheckPreviousAccessibilityModifiers(context); } return false; } private static bool CheckPreviousAccessibilityModifiers(CSharpSyntaxContext context) { // We can show up after 'internal' and 'private'. var precedingModifiers = context.PrecedingModifiers; return !precedingModifiers.Contains(SyntaxKind.PublicKeyword) && !precedingModifiers.Contains(SyntaxKind.ProtectedKeyword); } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ProtectedKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ProtectedKeywordRecommender() : base(SyntaxKind.ProtectedKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return IsValidContextForAccessor(context) || IsValidContextForType(context, cancellationToken) || IsValidContextForMember(context, cancellationToken); } private static bool IsValidContextForAccessor(CSharpSyntaxContext context) { if (context.TargetToken.IsAccessorDeclarationContext<PropertyDeclarationSyntax>(context.Position) || context.TargetToken.IsAccessorDeclarationContext<IndexerDeclarationSyntax>(context.Position)) { return CheckPreviousAccessibilityModifiers(context); } return false; } private static bool IsValidContextForMember(CSharpSyntaxContext context, CancellationToken cancellationToken) { if (context.IsMemberDeclarationContext(validModifiers: SyntaxKindSet.AllMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken)) { return CheckPreviousAccessibilityModifiers(context); } return false; } private static bool IsValidContextForType(CSharpSyntaxContext context, CancellationToken cancellationToken) { if (context.IsTypeDeclarationContext(validModifiers: SyntaxKindSet.AllTypeModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken)) { // protected things can't be in namespaces. var typeDecl = context.ContainingTypeDeclaration; if (typeDecl == null) { return false; } return CheckPreviousAccessibilityModifiers(context); } return false; } private static bool CheckPreviousAccessibilityModifiers(CSharpSyntaxContext context) { // We can show up after 'internal' and 'private'. var precedingModifiers = context.PrecedingModifiers; return !precedingModifiers.Contains(SyntaxKind.PublicKeyword) && !precedingModifiers.Contains(SyntaxKind.ProtectedKeyword); } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Workspaces/Core/Portable/Options/PerLanguageOption.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; namespace Microsoft.CodeAnalysis.Options { /// <inheritdoc cref="PerLanguageOption2{T}"/> public class PerLanguageOption<T> : IPerLanguageOption<T> { private readonly OptionDefinition _optionDefinition; /// <inheritdoc cref="OptionDefinition.Feature"/> public string Feature => _optionDefinition.Feature; /// <inheritdoc cref="OptionDefinition.Group"/> internal OptionGroup Group => _optionDefinition.Group; /// <inheritdoc cref="OptionDefinition.Name"/> public string Name => _optionDefinition.Name; /// <inheritdoc cref="OptionDefinition.Type"/> public Type Type => _optionDefinition.Type; /// <inheritdoc cref="OptionDefinition.DefaultValue"/> public T DefaultValue => (T)_optionDefinition.DefaultValue!; /// <inheritdoc cref="PerLanguageOption2{T}.StorageLocations"/> public ImmutableArray<OptionStorageLocation> StorageLocations { get; } public PerLanguageOption(string feature, string name, T defaultValue) : this(feature, name, defaultValue, storageLocations: ImmutableArray<OptionStorageLocation>.Empty) { } public PerLanguageOption(string feature, string name, T defaultValue, params OptionStorageLocation[] storageLocations) : this(feature, group: OptionGroup.Default, name, defaultValue, storageLocations.ToImmutableArray()) { } internal PerLanguageOption(string feature, string name, T defaultValue, OptionStorageLocation storageLocation) : this(feature, name, defaultValue, storageLocations: ImmutableArray.Create(storageLocation)) { } internal PerLanguageOption(string feature, string name, T defaultValue, ImmutableArray<OptionStorageLocation> storageLocations) : this(feature, OptionGroup.Default, name, defaultValue, storageLocations) { } internal PerLanguageOption(string feature, OptionGroup group, string name, T defaultValue, ImmutableArray<OptionStorageLocation> storageLocations) : this(new OptionDefinition(feature, group, name, defaultValue, typeof(T), isPerLanguage: true), storageLocations) { } internal PerLanguageOption(OptionDefinition optionDefinition, ImmutableArray<OptionStorageLocation> storageLocations) { _optionDefinition = optionDefinition; StorageLocations = storageLocations; } OptionDefinition IOption2.OptionDefinition => _optionDefinition; OptionGroup IOptionWithGroup.Group => this.Group; object? IOption.DefaultValue => this.DefaultValue; bool IOption.IsPerLanguage => true; bool IEquatable<IOption2?>.Equals(IOption2? other) => Equals(other); public override string ToString() => _optionDefinition.ToString(); public override int GetHashCode() => _optionDefinition.GetHashCode(); public override bool Equals(object? obj) => Equals(obj as IOption2); private bool Equals(IOption2? other) { if (ReferenceEquals(this, other)) { return true; } return _optionDefinition == other?.OptionDefinition; } } }
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.CodeAnalysis.Options { /// <inheritdoc cref="PerLanguageOption2{T}"/> public class PerLanguageOption<T> : IPerLanguageOption<T> { private readonly OptionDefinition _optionDefinition; /// <inheritdoc cref="OptionDefinition.Feature"/> public string Feature => _optionDefinition.Feature; /// <inheritdoc cref="OptionDefinition.Group"/> internal OptionGroup Group => _optionDefinition.Group; /// <inheritdoc cref="OptionDefinition.Name"/> public string Name => _optionDefinition.Name; /// <inheritdoc cref="OptionDefinition.Type"/> public Type Type => _optionDefinition.Type; /// <inheritdoc cref="OptionDefinition.DefaultValue"/> public T DefaultValue => (T)_optionDefinition.DefaultValue!; /// <inheritdoc cref="PerLanguageOption2{T}.StorageLocations"/> public ImmutableArray<OptionStorageLocation> StorageLocations { get; } public PerLanguageOption(string feature, string name, T defaultValue) : this(feature, name, defaultValue, storageLocations: ImmutableArray<OptionStorageLocation>.Empty) { } public PerLanguageOption(string feature, string name, T defaultValue, params OptionStorageLocation[] storageLocations) : this(feature, group: OptionGroup.Default, name, defaultValue, storageLocations.ToImmutableArray()) { } internal PerLanguageOption(string feature, string name, T defaultValue, OptionStorageLocation storageLocation) : this(feature, name, defaultValue, storageLocations: ImmutableArray.Create(storageLocation)) { } internal PerLanguageOption(string feature, string name, T defaultValue, ImmutableArray<OptionStorageLocation> storageLocations) : this(feature, OptionGroup.Default, name, defaultValue, storageLocations) { } internal PerLanguageOption(string feature, OptionGroup group, string name, T defaultValue, ImmutableArray<OptionStorageLocation> storageLocations) : this(new OptionDefinition(feature, group, name, defaultValue, typeof(T), isPerLanguage: true), storageLocations) { } internal PerLanguageOption(OptionDefinition optionDefinition, ImmutableArray<OptionStorageLocation> storageLocations) { _optionDefinition = optionDefinition; StorageLocations = storageLocations; } OptionDefinition IOption2.OptionDefinition => _optionDefinition; OptionGroup IOptionWithGroup.Group => this.Group; object? IOption.DefaultValue => this.DefaultValue; bool IOption.IsPerLanguage => true; bool IEquatable<IOption2?>.Equals(IOption2? other) => Equals(other); public override string ToString() => _optionDefinition.ToString(); public override int GetHashCode() => _optionDefinition.GetHashCode(); public override bool Equals(object? obj) => Equals(obj as IOption2); private bool Equals(IOption2? other) { if (ReferenceEquals(this, other)) { return true; } return _optionDefinition == other?.OptionDefinition; } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/Core/Portable/Symbols/RefKind.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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Denotes the kind of reference. /// </summary> public enum RefKind : byte { /// <summary> /// Indicates a "value" parameter or return type. /// </summary> None = 0, /// <summary> /// Indicates a "ref" parameter or return type. /// </summary> Ref = 1, /// <summary> /// Indicates an "out" parameter. /// </summary> Out = 2, /// <summary> /// Indicates an "in" parameter. /// </summary> In = 3, /// <summary> /// Indicates a "ref readonly" return type. /// </summary> RefReadOnly = 3, // NOTE: There is an additional value of this enum type - RefKindExtensions.StrictIn == RefKind.In + 1 // It is used internally during lowering. // Consider that when adding values or changing this enum in some other way. } internal static class RefKindExtensions { internal static string ToParameterDisplayString(this RefKind kind) { switch (kind) { case RefKind.Out: return "out"; case RefKind.Ref: return "ref"; case RefKind.In: return "in"; default: throw ExceptionUtilities.UnexpectedValue(kind); } } internal static string ToArgumentDisplayString(this RefKind kind) { switch (kind) { case RefKind.Out: return "out"; case RefKind.Ref: return "ref"; case RefKind.In: return "in"; default: throw ExceptionUtilities.UnexpectedValue(kind); } } internal static string ToParameterPrefix(this RefKind kind) { switch (kind) { case RefKind.Out: return "out "; case RefKind.Ref: return "ref "; case RefKind.In: return "in "; case RefKind.None: return string.Empty; default: throw ExceptionUtilities.UnexpectedValue(kind); } } // Used internally to track `In` arguments that were specified with `In` modifier // as opposed to those that were specified with no modifiers and matched `In` parameter. // There is at least one kind of analysis that cares about this distinction - hoisting // of variables to the frame for async rewriting: a variable that was passed without the // `In` modifier may be correctly captured by value or by reference. internal const RefKind StrictIn = RefKind.In + 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. using System; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Denotes the kind of reference. /// </summary> public enum RefKind : byte { /// <summary> /// Indicates a "value" parameter or return type. /// </summary> None = 0, /// <summary> /// Indicates a "ref" parameter or return type. /// </summary> Ref = 1, /// <summary> /// Indicates an "out" parameter. /// </summary> Out = 2, /// <summary> /// Indicates an "in" parameter. /// </summary> In = 3, /// <summary> /// Indicates a "ref readonly" return type. /// </summary> RefReadOnly = 3, // NOTE: There is an additional value of this enum type - RefKindExtensions.StrictIn == RefKind.In + 1 // It is used internally during lowering. // Consider that when adding values or changing this enum in some other way. } internal static class RefKindExtensions { internal static string ToParameterDisplayString(this RefKind kind) { switch (kind) { case RefKind.Out: return "out"; case RefKind.Ref: return "ref"; case RefKind.In: return "in"; default: throw ExceptionUtilities.UnexpectedValue(kind); } } internal static string ToArgumentDisplayString(this RefKind kind) { switch (kind) { case RefKind.Out: return "out"; case RefKind.Ref: return "ref"; case RefKind.In: return "in"; default: throw ExceptionUtilities.UnexpectedValue(kind); } } internal static string ToParameterPrefix(this RefKind kind) { switch (kind) { case RefKind.Out: return "out "; case RefKind.Ref: return "ref "; case RefKind.In: return "in "; case RefKind.None: return string.Empty; default: throw ExceptionUtilities.UnexpectedValue(kind); } } // Used internally to track `In` arguments that were specified with `In` modifier // as opposed to those that were specified with no modifiers and matched `In` parameter. // There is at least one kind of analysis that cares about this distinction - hoisting // of variables to the frame for async rewriting: a variable that was passed without the // `In` modifier may be correctly captured by value or by reference. internal const RefKind StrictIn = RefKind.In + 1; } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType_IEquatable_EqualsMethodSymbol.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.PooledObjects Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend NotInheritable Class AnonymousTypeManager Partial Private NotInheritable Class AnonymousType_IEquatable_EqualsMethodSymbol Inherits SynthesizedRegularMethodBase Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol) Private ReadOnly _interfaceMethod As ImmutableArray(Of MethodSymbol) Public Sub New(container As AnonymousTypeTemplateSymbol, interfaceMethod As MethodSymbol) MyBase.New(VisualBasicSyntaxTree.Dummy.GetRoot(), container, WellKnownMemberNames.ObjectEquals) _parameters = ImmutableArray.Create(Of ParameterSymbol)(New SynthesizedParameterSimpleSymbol(Me, container, 0, "val")) _interfaceMethod = ImmutableArray.Create(interfaceMethod) End Sub Private ReadOnly Property AnonymousType As AnonymousTypeTemplateSymbol Get Return DirectCast(Me.m_containingType, AnonymousTypeTemplateSymbol) End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverloads As Boolean Get Return True End Get End Property Friend Overrides ReadOnly Property ParameterCount As Integer Get Return 1 End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return Me._parameters End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol) Get Return _interfaceMethod End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.Public End Get End Property Public Overrides ReadOnly Property IsSub As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Return AnonymousType.Manager.System_Boolean End Get End Property Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedAttributes(compilationState, attributes) Dim compilation = DirectCast(Me.ContainingType, AnonymousTypeTemplateSymbol).Manager.Compilation AddSynthesizedAttribute(attributes, compilation.SynthesizeDebuggerHiddenAttribute()) End Sub Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return False End Get End Property Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.PooledObjects Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend NotInheritable Class AnonymousTypeManager Partial Private NotInheritable Class AnonymousType_IEquatable_EqualsMethodSymbol Inherits SynthesizedRegularMethodBase Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol) Private ReadOnly _interfaceMethod As ImmutableArray(Of MethodSymbol) Public Sub New(container As AnonymousTypeTemplateSymbol, interfaceMethod As MethodSymbol) MyBase.New(VisualBasicSyntaxTree.Dummy.GetRoot(), container, WellKnownMemberNames.ObjectEquals) _parameters = ImmutableArray.Create(Of ParameterSymbol)(New SynthesizedParameterSimpleSymbol(Me, container, 0, "val")) _interfaceMethod = ImmutableArray.Create(interfaceMethod) End Sub Private ReadOnly Property AnonymousType As AnonymousTypeTemplateSymbol Get Return DirectCast(Me.m_containingType, AnonymousTypeTemplateSymbol) End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverloads As Boolean Get Return True End Get End Property Friend Overrides ReadOnly Property ParameterCount As Integer Get Return 1 End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return Me._parameters End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol) Get Return _interfaceMethod End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.Public End Get End Property Public Overrides ReadOnly Property IsSub As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Return AnonymousType.Manager.System_Boolean End Get End Property Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedAttributes(compilationState, attributes) Dim compilation = DirectCast(Me.ContainingType, AnonymousTypeTemplateSymbol).Manager.Compilation AddSynthesizedAttribute(attributes, compilation.SynthesizeDebuggerHiddenAttribute()) End Sub Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return False End Get End Property Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function End Class End Class End Namespace
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/Core/Portable/CommandLine/CommonCompiler.ExistingReferencesResolver.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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal abstract partial class CommonCompiler { /// <summary> /// Looks for metadata references among the assembly file references given to the compilation when constructed. /// When scripts are included into a project we don't want #r's to reference other assemblies than those /// specified explicitly in the project references. /// </summary> internal sealed class ExistingReferencesResolver : MetadataReferenceResolver, IEquatable<ExistingReferencesResolver> { private readonly MetadataReferenceResolver _resolver; private readonly ImmutableArray<MetadataReference> _availableReferences; private readonly Lazy<HashSet<AssemblyIdentity>> _lazyAvailableReferences; public ExistingReferencesResolver(MetadataReferenceResolver resolver, ImmutableArray<MetadataReference> availableReferences) { Debug.Assert(resolver != null); Debug.Assert(availableReferences != null); _resolver = resolver; _availableReferences = availableReferences; // Delay reading assembly identities until they are actually needed (only when #r is encountered). _lazyAvailableReferences = new Lazy<HashSet<AssemblyIdentity>>(() => new HashSet<AssemblyIdentity>( from reference in _availableReferences let identity = TryGetIdentity(reference) where identity != null select identity!)); } public override ImmutableArray<PortableExecutableReference> ResolveReference(string reference, string? baseFilePath, MetadataReferenceProperties properties) { var resolvedReferences = _resolver.ResolveReference(reference, baseFilePath, properties); return resolvedReferences.WhereAsArray(r => _lazyAvailableReferences.Value.Contains(TryGetIdentity(r)!)); } private static AssemblyIdentity? TryGetIdentity(MetadataReference metadataReference) { var peReference = metadataReference as PortableExecutableReference; if (peReference == null || peReference.Properties.Kind != MetadataImageKind.Assembly) { return null; } try { PEAssembly assembly = ((AssemblyMetadata)peReference.GetMetadataNoCopy()).GetAssembly()!; return assembly.Identity; } catch (Exception e) when (e is BadImageFormatException || e is IOException) { // ignore, metadata reading errors are reported by the compiler for the existing references return null; } } public override int GetHashCode() { return _resolver.GetHashCode(); } public bool Equals(ExistingReferencesResolver? other) { return other is object && _resolver.Equals(other._resolver) && _availableReferences.SequenceEqual(other._availableReferences); } public override bool Equals(object? other) => other is ExistingReferencesResolver obj && Equals(obj); } } }
// Licensed to the .NET Foundation under one or more 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal abstract partial class CommonCompiler { /// <summary> /// Looks for metadata references among the assembly file references given to the compilation when constructed. /// When scripts are included into a project we don't want #r's to reference other assemblies than those /// specified explicitly in the project references. /// </summary> internal sealed class ExistingReferencesResolver : MetadataReferenceResolver, IEquatable<ExistingReferencesResolver> { private readonly MetadataReferenceResolver _resolver; private readonly ImmutableArray<MetadataReference> _availableReferences; private readonly Lazy<HashSet<AssemblyIdentity>> _lazyAvailableReferences; public ExistingReferencesResolver(MetadataReferenceResolver resolver, ImmutableArray<MetadataReference> availableReferences) { Debug.Assert(resolver != null); Debug.Assert(availableReferences != null); _resolver = resolver; _availableReferences = availableReferences; // Delay reading assembly identities until they are actually needed (only when #r is encountered). _lazyAvailableReferences = new Lazy<HashSet<AssemblyIdentity>>(() => new HashSet<AssemblyIdentity>( from reference in _availableReferences let identity = TryGetIdentity(reference) where identity != null select identity!)); } public override ImmutableArray<PortableExecutableReference> ResolveReference(string reference, string? baseFilePath, MetadataReferenceProperties properties) { var resolvedReferences = _resolver.ResolveReference(reference, baseFilePath, properties); return resolvedReferences.WhereAsArray(r => _lazyAvailableReferences.Value.Contains(TryGetIdentity(r)!)); } private static AssemblyIdentity? TryGetIdentity(MetadataReference metadataReference) { var peReference = metadataReference as PortableExecutableReference; if (peReference == null || peReference.Properties.Kind != MetadataImageKind.Assembly) { return null; } try { PEAssembly assembly = ((AssemblyMetadata)peReference.GetMetadataNoCopy()).GetAssembly()!; return assembly.Identity; } catch (Exception e) when (e is BadImageFormatException || e is IOException) { // ignore, metadata reading errors are reported by the compiler for the existing references return null; } } public override int GetHashCode() { return _resolver.GetHashCode(); } public bool Equals(ExistingReferencesResolver? other) { return other is object && _resolver.Equals(other._resolver) && _availableReferences.SequenceEqual(other._availableReferences); } public override bool Equals(object? other) => other is ExistingReferencesResolver obj && Equals(obj); } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/VisualStudio/Core/Test/CodeModel/CSharp/CodeVariableTests.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.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.CSharp Public Class CodeVariableTests Inherits AbstractCodeVariableTests #Region "GetStartPoint() tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint_Field() Dim code = <Code> class C { int $$goo; } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBody, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=9, absoluteOffset:=19, lineLength:=12)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=15, lineLength:=12))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint_EnumMember() Dim code = <Code> enum E { $$Goo } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBody, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=14, lineLength:=7)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=14, lineLength:=7))) End Sub #End Region #Region "GetEndPoint() tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint_Field() Dim code = <Code> class C { int $$goo; } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBody, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=12, absoluteOffset:=22, lineLength:=12)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=13, absoluteOffset:=23, lineLength:=12))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint_EnumMember() Dim code = <Code> enum E { $$Goo } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBody, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=8, absoluteOffset:=17, lineLength:=7)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=8, absoluteOffset:=17, lineLength:=7))) End Sub #End Region #Region "Access tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess1() Dim code = <Code> class C { int $$x; } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPrivate) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess2() Dim code = <Code> class C { private int $$x; } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPrivate) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess3() Dim code = <Code> class C { protected int $$x; } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProtected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess4() Dim code = <Code> class C { protected internal int $$x; } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess5() Dim code = <Code> class C { internal int $$x; } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProject) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess6() Dim code = <Code> class C { public int $$x; } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess7() Dim code = <Code> enum E { $$Goo } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub #End Region #Region "Attributes tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes1() Dim code = <Code> class C { int $$Goo; } </Code> TestAttributes(code, NoElements) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes2() Dim code = <Code> using System; class C { [Serializable] int $$Goo; } </Code> TestAttributes(code, IsElement("Serializable")) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes3() Dim code = <Code>using System; class C { [Serializable] [CLSCompliant(true)] int $$Goo; } </Code> TestAttributes(code, IsElement("Serializable"), IsElement("CLSCompliant")) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes4() Dim code = <Code>using System; class C { [Serializable, CLSCompliant(true)] int $$Goo; } </Code> TestAttributes(code, IsElement("Serializable"), IsElement("CLSCompliant")) End Sub #End Region #Region "AddAttribute tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute1() As Task Dim code = <Code> using System; class C { int $$F; } </Code> Dim expected = <Code> using System; class C { [Serializable()] int F; } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute2() As Task Dim code = <Code> using System; class C { [Serializable] int $$F; } </Code> Dim expected = <Code> using System; class C { [Serializable] [CLSCompliant(true)] int F; } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "true", .Position = 1}) End Function <WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute_BelowDocComment() As Task Dim code = <Code> using System; class C { /// &lt;summary&gt;&lt;/summary&gt; int $$F; } </Code> Dim expected = <Code> using System; class C { /// &lt;summary&gt;&lt;/summary&gt; [CLSCompliant(true)] int F; } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "true"}) End Function #End Region #Region "ConstKind tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind1() Dim code = <Code> enum E { $$Goo } </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind2() Dim code = <Code> class C { int $$x; } </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind3() Dim code = <Code> class C { const int $$x; } </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind4() Dim code = <Code> class C { readonly int $$x; } </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind5() Dim code = <Code> class C { readonly const int $$x; } </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindConst Or EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly) End Sub #End Region #Region "FullName tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFullName1() Dim code = <Code> enum E { $$Goo = 1, Bar } </Code> TestFullName(code, "E.Goo") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFullName2() Dim code = <Code> enum E { Goo = 1, $$Bar } </Code> TestFullName(code, "E.Bar") End Sub #End Region #Region "InitExpression tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestInitExpression1() Dim code = <Code> class C { int $$i = 42; } </Code> TestInitExpression(code, "42") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestInitExpression2() Dim code = <Code> class C { const int $$i = 19 + 23; } </Code> TestInitExpression(code, "19 + 23") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestInitExpression3() Dim code = <Code> enum E { $$i = 19 + 23 } </Code> TestInitExpression(code, "19 + 23") End Sub #End Region #Region "IsConstant tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsConstant1() Dim code = <Code> enum E { $$Goo } </Code> TestIsConstant(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsConstant2() Dim code = <Code> class C { const int $$x = 0; } </Code> TestIsConstant(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsConstant3() Dim code = <Code> class C { readonly int $$x = 0; } </Code> TestIsConstant(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsConstant4() Dim code = <Code> class C { int $$x = 0; } </Code> TestIsConstant(code, False) End Sub #End Region #Region "IsShared tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsShared1() Dim code = <Code> class C { int $$x; } </Code> TestIsShared(code, False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsShared2() Dim code = <Code> class C { static int $$x; } </Code> TestIsShared(code, True) End Sub #End Region #Region "Name tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestName1() Dim code = <Code> enum E { $$Goo = 1, Bar } </Code> TestName(code, "Goo") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestName2() Dim code = <Code> enum E { Goo = 1, $$Bar } </Code> TestName(code, "Bar") End Sub #End Region #Region "Prototype tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassName() Dim code = <Code> namespace N { class C { int x$$ = 0; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "C.x") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_FullName() Dim code = <Code> namespace N { class C { int x$$ = 0; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeFullname, "N.C.x") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_InitExpression1() Dim code = <Code> namespace N { class C { int x$$ = 0; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression, "x = 0") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_InitExpression2() Dim code = <Code> namespace N { enum E { A$$ = 42 } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression, "A = 42") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_InitExpressionAndType1() Dim code = <Code> namespace N { class C { int x$$ = 0; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression Or EnvDTE.vsCMPrototype.vsCMPrototypeType, "int x = 0") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_InitExpressionAndType2() Dim code = <Code> namespace N { enum E { A$$ = 42 } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression Or EnvDTE.vsCMPrototype.vsCMPrototypeType, "N.E A = 42") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassNameInitExpressionAndType() Dim code = <Code> namespace N { enum E { A$$ = 42 } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression Or EnvDTE.vsCMPrototype.vsCMPrototypeType Or EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "N.E E.A = 42") End Sub #End Region #Region "Type tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestType1() Dim code = <Code> class C { int $$i; } </Code> TestTypeProp(code, New CodeTypeRefData With { .AsString = "int", .AsFullName = "System.Int32", .CodeTypeFullName = "System.Int32", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefInt }) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestType2() Dim code = <Code> class C { int i, $$j; } </Code> TestTypeProp(code, New CodeTypeRefData With { .AsString = "int", .AsFullName = "System.Int32", .CodeTypeFullName = "System.Int32", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefInt }) End Sub <WorkItem(888785, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/888785")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestArrayTypeName() Dim code = <Code> class C { int[] $$array; } </Code> TestTypeProp(code, New CodeTypeRefData With { .AsString = "int[]", .AsFullName = "System.Int32[]", .CodeTypeFullName = "System.Int32[]", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefArray }) End Sub #End Region #Region "Set Access tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetEnumAccess1() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetEnumAccess2() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetEnumAccess3() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPrivate, ThrowsArgumentException(Of EnvDTE.vsCMAccess)()) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess1() As Task Dim code = <Code> class C { int $$i; } </Code> Dim expected = <Code> class C { public int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess2() As Task Dim code = <Code> class C { public int $$i; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess3() As Task Dim code = <Code> class C { private int $$i; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess4() As Task Dim code = <Code> class C { int $$i; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess5() As Task Dim code = <Code> class C { public int $$i; } </Code> Dim expected = <Code> class C { protected internal int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess6() As Task Dim code = <Code> class C { #region Goo int x; #endregion int $$i; } </Code> Dim expected = <Code> class C { #region Goo int x; #endregion public int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess7() As Task Dim code = <Code> class C { #region Goo int x; #endregion public int $$i; } </Code> Dim expected = <Code> class C { #region Goo int x; #endregion protected internal int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess8() As Task Dim code = <Code> class C { #region Goo int x; #endregion public int $$i; } </Code> Dim expected = <Code> class C { #region Goo int x; #endregion int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess9() As Task Dim code = <Code> class C { #region Goo int $$x; #endregion } </Code> Dim expected = <Code> class C { #region Goo public int x; #endregion } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess10() As Task Dim code = <Code> class C { #region Goo public int $$x; #endregion } </Code> Dim expected = <Code> class C { #region Goo int x; #endregion } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess11() As Task Dim code = <Code> class C { #region Goo public int $$x; #endregion } </Code> Dim expected = <Code> class C { #region Goo protected internal int x; #endregion } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess12() As Task Dim code = <Code> class C { #region Goo [Goo] public int $$x; #endregion } </Code> Dim expected = <Code> class C { #region Goo [Goo] protected internal int x; #endregion } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess13() As Task Dim code = <Code> class C { #region Goo // Comment comment comment public int $$x; #endregion } </Code> Dim expected = <Code> class C { #region Goo // Comment comment comment protected internal int x; #endregion } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess14() As Task Dim code = <Code><![CDATA[ class C { #region Goo /// <summary> /// Comment comment comment /// </summary> public int $$x; #endregion } ]]></Code> Dim expected = <Code><![CDATA[ class C { #region Goo /// <summary> /// Comment comment comment /// </summary> protected internal int x; #endregion } ]]></Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function #End Region #Region "Set ConstKind tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind1() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind2() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind3() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone, ThrowsArgumentException(Of EnvDTE80.vsCMConstKind)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind4() As Task Dim code = <Code> class C { int $$x; } </Code> Dim expected = <Code> class C { int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind5() As Task Dim code = <Code> class C { int $$x; } </Code> Dim expected = <Code> class C { const int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind6() As Task Dim code = <Code> class C { const int $$x; } </Code> Dim expected = <Code> class C { int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind7() As Task Dim code = <Code> class C { int $$x; } </Code> Dim expected = <Code> class C { readonly int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind8() As Task Dim code = <Code> class C { readonly int $$x; } </Code> Dim expected = <Code> class C { int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKindWhenVolatileIsPresent1() As Task Dim code = <Code> class C { volatile int $$x; } </Code> Dim expected = <Code> class C { volatile const int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKindWhenVolatileIsPresent2() As Task Dim code = <Code> class C { volatile int $$x; } </Code> Dim expected = <Code> class C { volatile readonly int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKindWhenVolatileIsPresent3() As Task Dim code = <Code> class C { volatile readonly int $$x; } </Code> Dim expected = <Code> class C { volatile const int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKindWhenVolatileIsPresent4() As Task Dim code = <Code> class C { volatile readonly int $$x; } </Code> Dim expected = <Code> class C { volatile int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Function #End Region #Region "Set InitExpression tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression1() As Task Dim code = <Code> class C { int $$i; } </Code> Dim expected = <Code> class C { int i = 42; } </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression2() As Task Dim code = <Code> class C { int $$i = 42; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetInitExpression(code, expected, Nothing) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression3() As Task Dim code = <Code> class C { int $$i, j; } </Code> Dim expected = <Code> class C { int i = 42, j; } </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression4() As Task Dim code = <Code> class C { int i, $$j; } </Code> Dim expected = <Code> class C { int i, j = 42; } </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression5() As Task Dim code = <Code> class C { const int $$i = 0; } </Code> Dim expected = <Code> class C { const int i = 42; } </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression6() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo = 42 } </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression7() As Task Dim code = <Code> enum E { $$Goo = 42 } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetInitExpression(code, expected, Nothing) End Function #End Region #Region "Set IsConstant tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant1() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetIsConstant(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant2() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetIsConstant(code, expected, False, ThrowsCOMException(Of Boolean)(E_FAIL)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant3() As Task Dim code = <Code> class C { int $$i; } </Code> Dim expected = <Code> class C { const int i; } </Code> Await TestSetIsConstant(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant4() As Task Dim code = <Code> class C { int $$i; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetIsConstant(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant5() As Task Dim code = <Code> class C { const int $$i; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetIsConstant(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant6() As Task Dim code = <Code> class C { const int $$i; } </Code> Dim expected = <Code> class C { const int i; } </Code> Await TestSetIsConstant(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant7() As Task Dim code = <Code> class C { readonly int $$i; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetIsConstant(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant8() As Task Dim code = <Code> class C { readonly int $$i; } </Code> Dim expected = <Code> class C { readonly int i; } </Code> Await TestSetIsConstant(code, expected, True) End Function #End Region #Region "Set IsShared tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared1() As Task Dim code = <Code> class C { int $$i; } </Code> Dim expected = <Code> class C { static int i; } </Code> Await TestSetIsShared(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared2() As Task Dim code = <Code> class C { static int $$i; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetIsShared(code, expected, False) End Function #End Region #Region "Set Name tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName1() As Task Dim code = <Code> class C { int $$Goo; } </Code> Dim expected = <Code> class C { int Bar; } </Code> Await TestSetName(code, expected, "Bar", NoThrow(Of String)()) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName2() As Task Dim code = <Code> class C { #region Goo int $$Goo; #endregion } </Code> Dim expected = <Code> class C { #region Goo int Bar; #endregion } </Code> Await TestSetName(code, expected, "Bar", NoThrow(Of String)()) End Function #End Region #Region "Set Type tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetType1() As Task Dim code = <Code> class C { int $$i; } </Code> Dim expected = <Code> class C { double i; } </Code> Await TestSetTypeProp(code, expected, "double") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetType2() As Task Dim code = <Code> class C { int i, $$j; } </Code> Dim expected = <Code> class C { double i, j; } </Code> Await TestSetTypeProp(code, expected, "double") End Function #End Region <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestTypeDescriptor_GetProperties() Dim code = <Code> class S { int $$x; } </Code> TestPropertyDescriptors(Of EnvDTE80.CodeVariable2)(code) End Sub Protected Overrides ReadOnly Property LanguageName As String Get Return LanguageNames.CSharp End Get End Property 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.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.CSharp Public Class CodeVariableTests Inherits AbstractCodeVariableTests #Region "GetStartPoint() tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint_Field() Dim code = <Code> class C { int $$goo; } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBody, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=9, absoluteOffset:=19, lineLength:=12)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=15, lineLength:=12))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetStartPoint_EnumMember() Dim code = <Code> enum E { $$Goo } </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBody, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=14, lineLength:=7)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=14, lineLength:=7))) End Sub #End Region #Region "GetEndPoint() tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint_Field() Dim code = <Code> class C { int $$goo; } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBody, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=12, absoluteOffset:=22, lineLength:=12)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=13, absoluteOffset:=23, lineLength:=12))) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestGetEndPoint_EnumMember() Dim code = <Code> enum E { $$Goo } </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBody, ThrowsCOMException(E_FAIL)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeader, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartName, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=8, absoluteOffset:=17, lineLength:=7)), Part(EnvDTE.vsCMPart.vsCMPartWhole, ThrowsNotImplementedException), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=8, absoluteOffset:=17, lineLength:=7))) End Sub #End Region #Region "Access tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess1() Dim code = <Code> class C { int $$x; } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPrivate) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess2() Dim code = <Code> class C { private int $$x; } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPrivate) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess3() Dim code = <Code> class C { protected int $$x; } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProtected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess4() Dim code = <Code> class C { protected internal int $$x; } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess5() Dim code = <Code> class C { internal int $$x; } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProject) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess6() Dim code = <Code> class C { public int $$x; } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAccess7() Dim code = <Code> enum E { $$Goo } </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub #End Region #Region "Attributes tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes1() Dim code = <Code> class C { int $$Goo; } </Code> TestAttributes(code, NoElements) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes2() Dim code = <Code> using System; class C { [Serializable] int $$Goo; } </Code> TestAttributes(code, IsElement("Serializable")) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes3() Dim code = <Code>using System; class C { [Serializable] [CLSCompliant(true)] int $$Goo; } </Code> TestAttributes(code, IsElement("Serializable"), IsElement("CLSCompliant")) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestAttributes4() Dim code = <Code>using System; class C { [Serializable, CLSCompliant(true)] int $$Goo; } </Code> TestAttributes(code, IsElement("Serializable"), IsElement("CLSCompliant")) End Sub #End Region #Region "AddAttribute tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute1() As Task Dim code = <Code> using System; class C { int $$F; } </Code> Dim expected = <Code> using System; class C { [Serializable()] int F; } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"}) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute2() As Task Dim code = <Code> using System; class C { [Serializable] int $$F; } </Code> Dim expected = <Code> using System; class C { [Serializable] [CLSCompliant(true)] int F; } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "true", .Position = 1}) End Function <WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestAddAttribute_BelowDocComment() As Task Dim code = <Code> using System; class C { /// &lt;summary&gt;&lt;/summary&gt; int $$F; } </Code> Dim expected = <Code> using System; class C { /// &lt;summary&gt;&lt;/summary&gt; [CLSCompliant(true)] int F; } </Code> Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "true"}) End Function #End Region #Region "ConstKind tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind1() Dim code = <Code> enum E { $$Goo } </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind2() Dim code = <Code> class C { int $$x; } </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind3() Dim code = <Code> class C { const int $$x; } </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind4() Dim code = <Code> class C { readonly int $$x; } </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestConstKind5() Dim code = <Code> class C { readonly const int $$x; } </Code> TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindConst Or EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly) End Sub #End Region #Region "FullName tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFullName1() Dim code = <Code> enum E { $$Goo = 1, Bar } </Code> TestFullName(code, "E.Goo") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestFullName2() Dim code = <Code> enum E { Goo = 1, $$Bar } </Code> TestFullName(code, "E.Bar") End Sub #End Region #Region "InitExpression tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestInitExpression1() Dim code = <Code> class C { int $$i = 42; } </Code> TestInitExpression(code, "42") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestInitExpression2() Dim code = <Code> class C { const int $$i = 19 + 23; } </Code> TestInitExpression(code, "19 + 23") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestInitExpression3() Dim code = <Code> enum E { $$i = 19 + 23 } </Code> TestInitExpression(code, "19 + 23") End Sub #End Region #Region "IsConstant tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsConstant1() Dim code = <Code> enum E { $$Goo } </Code> TestIsConstant(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsConstant2() Dim code = <Code> class C { const int $$x = 0; } </Code> TestIsConstant(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsConstant3() Dim code = <Code> class C { readonly int $$x = 0; } </Code> TestIsConstant(code, True) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsConstant4() Dim code = <Code> class C { int $$x = 0; } </Code> TestIsConstant(code, False) End Sub #End Region #Region "IsShared tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsShared1() Dim code = <Code> class C { int $$x; } </Code> TestIsShared(code, False) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestIsShared2() Dim code = <Code> class C { static int $$x; } </Code> TestIsShared(code, True) End Sub #End Region #Region "Name tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestName1() Dim code = <Code> enum E { $$Goo = 1, Bar } </Code> TestName(code, "Goo") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestName2() Dim code = <Code> enum E { Goo = 1, $$Bar } </Code> TestName(code, "Bar") End Sub #End Region #Region "Prototype tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassName() Dim code = <Code> namespace N { class C { int x$$ = 0; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "C.x") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_FullName() Dim code = <Code> namespace N { class C { int x$$ = 0; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeFullname, "N.C.x") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_InitExpression1() Dim code = <Code> namespace N { class C { int x$$ = 0; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression, "x = 0") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_InitExpression2() Dim code = <Code> namespace N { enum E { A$$ = 42 } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression, "A = 42") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_InitExpressionAndType1() Dim code = <Code> namespace N { class C { int x$$ = 0; } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression Or EnvDTE.vsCMPrototype.vsCMPrototypeType, "int x = 0") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_InitExpressionAndType2() Dim code = <Code> namespace N { enum E { A$$ = 42 } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression Or EnvDTE.vsCMPrototype.vsCMPrototypeType, "N.E A = 42") End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestPrototype_ClassNameInitExpressionAndType() Dim code = <Code> namespace N { enum E { A$$ = 42 } } </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression Or EnvDTE.vsCMPrototype.vsCMPrototypeType Or EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "N.E E.A = 42") End Sub #End Region #Region "Type tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestType1() Dim code = <Code> class C { int $$i; } </Code> TestTypeProp(code, New CodeTypeRefData With { .AsString = "int", .AsFullName = "System.Int32", .CodeTypeFullName = "System.Int32", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefInt }) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestType2() Dim code = <Code> class C { int i, $$j; } </Code> TestTypeProp(code, New CodeTypeRefData With { .AsString = "int", .AsFullName = "System.Int32", .CodeTypeFullName = "System.Int32", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefInt }) End Sub <WorkItem(888785, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/888785")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestArrayTypeName() Dim code = <Code> class C { int[] $$array; } </Code> TestTypeProp(code, New CodeTypeRefData With { .AsString = "int[]", .AsFullName = "System.Int32[]", .CodeTypeFullName = "System.Int32[]", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefArray }) End Sub #End Region #Region "Set Access tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetEnumAccess1() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetEnumAccess2() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetEnumAccess3() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPrivate, ThrowsArgumentException(Of EnvDTE.vsCMAccess)()) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess1() As Task Dim code = <Code> class C { int $$i; } </Code> Dim expected = <Code> class C { public int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess2() As Task Dim code = <Code> class C { public int $$i; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess3() As Task Dim code = <Code> class C { private int $$i; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess4() As Task Dim code = <Code> class C { int $$i; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess5() As Task Dim code = <Code> class C { public int $$i; } </Code> Dim expected = <Code> class C { protected internal int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess6() As Task Dim code = <Code> class C { #region Goo int x; #endregion int $$i; } </Code> Dim expected = <Code> class C { #region Goo int x; #endregion public int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess7() As Task Dim code = <Code> class C { #region Goo int x; #endregion public int $$i; } </Code> Dim expected = <Code> class C { #region Goo int x; #endregion protected internal int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess8() As Task Dim code = <Code> class C { #region Goo int x; #endregion public int $$i; } </Code> Dim expected = <Code> class C { #region Goo int x; #endregion int i; } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess9() As Task Dim code = <Code> class C { #region Goo int $$x; #endregion } </Code> Dim expected = <Code> class C { #region Goo public int x; #endregion } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess10() As Task Dim code = <Code> class C { #region Goo public int $$x; #endregion } </Code> Dim expected = <Code> class C { #region Goo int x; #endregion } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess11() As Task Dim code = <Code> class C { #region Goo public int $$x; #endregion } </Code> Dim expected = <Code> class C { #region Goo protected internal int x; #endregion } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess12() As Task Dim code = <Code> class C { #region Goo [Goo] public int $$x; #endregion } </Code> Dim expected = <Code> class C { #region Goo [Goo] protected internal int x; #endregion } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess13() As Task Dim code = <Code> class C { #region Goo // Comment comment comment public int $$x; #endregion } </Code> Dim expected = <Code> class C { #region Goo // Comment comment comment protected internal int x; #endregion } </Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetAccess14() As Task Dim code = <Code><![CDATA[ class C { #region Goo /// <summary> /// Comment comment comment /// </summary> public int $$x; #endregion } ]]></Code> Dim expected = <Code><![CDATA[ class C { #region Goo /// <summary> /// Comment comment comment /// </summary> protected internal int x; #endregion } ]]></Code> Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Function #End Region #Region "Set ConstKind tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind1() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind2() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind3() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone, ThrowsArgumentException(Of EnvDTE80.vsCMConstKind)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind4() As Task Dim code = <Code> class C { int $$x; } </Code> Dim expected = <Code> class C { int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind5() As Task Dim code = <Code> class C { int $$x; } </Code> Dim expected = <Code> class C { const int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind6() As Task Dim code = <Code> class C { const int $$x; } </Code> Dim expected = <Code> class C { int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind7() As Task Dim code = <Code> class C { int $$x; } </Code> Dim expected = <Code> class C { readonly int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKind8() As Task Dim code = <Code> class C { readonly int $$x; } </Code> Dim expected = <Code> class C { int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKindWhenVolatileIsPresent1() As Task Dim code = <Code> class C { volatile int $$x; } </Code> Dim expected = <Code> class C { volatile const int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKindWhenVolatileIsPresent2() As Task Dim code = <Code> class C { volatile int $$x; } </Code> Dim expected = <Code> class C { volatile readonly int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKindWhenVolatileIsPresent3() As Task Dim code = <Code> class C { volatile readonly int $$x; } </Code> Dim expected = <Code> class C { volatile const int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindConst) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetConstKindWhenVolatileIsPresent4() As Task Dim code = <Code> class C { volatile readonly int $$x; } </Code> Dim expected = <Code> class C { volatile int x; } </Code> Await TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone) End Function #End Region #Region "Set InitExpression tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression1() As Task Dim code = <Code> class C { int $$i; } </Code> Dim expected = <Code> class C { int i = 42; } </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression2() As Task Dim code = <Code> class C { int $$i = 42; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetInitExpression(code, expected, Nothing) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression3() As Task Dim code = <Code> class C { int $$i, j; } </Code> Dim expected = <Code> class C { int i = 42, j; } </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression4() As Task Dim code = <Code> class C { int i, $$j; } </Code> Dim expected = <Code> class C { int i, j = 42; } </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression5() As Task Dim code = <Code> class C { const int $$i = 0; } </Code> Dim expected = <Code> class C { const int i = 42; } </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression6() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo = 42 } </Code> Await TestSetInitExpression(code, expected, "42") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetInitExpression7() As Task Dim code = <Code> enum E { $$Goo = 42 } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetInitExpression(code, expected, Nothing) End Function #End Region #Region "Set IsConstant tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant1() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetIsConstant(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant2() As Task Dim code = <Code> enum E { $$Goo } </Code> Dim expected = <Code> enum E { Goo } </Code> Await TestSetIsConstant(code, expected, False, ThrowsCOMException(Of Boolean)(E_FAIL)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant3() As Task Dim code = <Code> class C { int $$i; } </Code> Dim expected = <Code> class C { const int i; } </Code> Await TestSetIsConstant(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant4() As Task Dim code = <Code> class C { int $$i; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetIsConstant(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant5() As Task Dim code = <Code> class C { const int $$i; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetIsConstant(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant6() As Task Dim code = <Code> class C { const int $$i; } </Code> Dim expected = <Code> class C { const int i; } </Code> Await TestSetIsConstant(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant7() As Task Dim code = <Code> class C { readonly int $$i; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetIsConstant(code, expected, False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsConstant8() As Task Dim code = <Code> class C { readonly int $$i; } </Code> Dim expected = <Code> class C { readonly int i; } </Code> Await TestSetIsConstant(code, expected, True) End Function #End Region #Region "Set IsShared tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared1() As Task Dim code = <Code> class C { int $$i; } </Code> Dim expected = <Code> class C { static int i; } </Code> Await TestSetIsShared(code, expected, True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetIsShared2() As Task Dim code = <Code> class C { static int $$i; } </Code> Dim expected = <Code> class C { int i; } </Code> Await TestSetIsShared(code, expected, False) End Function #End Region #Region "Set Name tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName1() As Task Dim code = <Code> class C { int $$Goo; } </Code> Dim expected = <Code> class C { int Bar; } </Code> Await TestSetName(code, expected, "Bar", NoThrow(Of String)()) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetName2() As Task Dim code = <Code> class C { #region Goo int $$Goo; #endregion } </Code> Dim expected = <Code> class C { #region Goo int Bar; #endregion } </Code> Await TestSetName(code, expected, "Bar", NoThrow(Of String)()) End Function #End Region #Region "Set Type tests" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetType1() As Task Dim code = <Code> class C { int $$i; } </Code> Dim expected = <Code> class C { double i; } </Code> Await TestSetTypeProp(code, expected, "double") End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Async Function TestSetType2() As Task Dim code = <Code> class C { int i, $$j; } </Code> Dim expected = <Code> class C { double i, j; } </Code> Await TestSetTypeProp(code, expected, "double") End Function #End Region <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestTypeDescriptor_GetProperties() Dim code = <Code> class S { int $$x; } </Code> TestPropertyDescriptors(Of EnvDTE80.CodeVariable2)(code) End Sub Protected Overrides ReadOnly Property LanguageName As String Get Return LanguageNames.CSharp End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/EditorFeatures/Test2/Rename/CSharp/InteractiveTests.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.Rename.CSharp <[UseExportProvider]> Public Class InteractiveTests Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper Public Sub New(outputHelper As Abstractions.ITestOutputHelper) _outputHelper = outputHelper End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenamingTopLevelMethodsSupported(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Submission Language="C#" CommonReferences="true"> void [|$$Goo|]() { } </Submission> </Workspace>, host:=host, renameTo:="BarBaz") End Using 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 Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.CSharp <[UseExportProvider]> Public Class InteractiveTests Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper Public Sub New(outputHelper As Abstractions.ITestOutputHelper) _outputHelper = outputHelper End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenamingTopLevelMethodsSupported(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Submission Language="C#" CommonReferences="true"> void [|$$Goo|]() { } </Submission> </Workspace>, host:=host, renameTo:="BarBaz") End Using End Sub End Class End Namespace
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Tools/Source/RunTests/ProcessRunner.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.ObjectModel; using System.Diagnostics; using System.IO; using System.Threading; using System.Threading.Tasks; namespace RunTests { public readonly struct ProcessResult { public Process Process { get; } public int ExitCode { get; } public ReadOnlyCollection<string> OutputLines { get; } public ReadOnlyCollection<string> ErrorLines { get; } public ProcessResult(Process process, int exitCode, ReadOnlyCollection<string> outputLines, ReadOnlyCollection<string> errorLines) { Process = process; ExitCode = exitCode; OutputLines = outputLines; ErrorLines = errorLines; } } public readonly struct ProcessInfo { public Process Process { get; } public ProcessStartInfo StartInfo { get; } public Task<ProcessResult> Result { get; } public int Id => Process.Id; public ProcessInfo(Process process, ProcessStartInfo startInfo, Task<ProcessResult> result) { Process = process; StartInfo = startInfo; Result = result; } } public static class ProcessRunner { public static void OpenFile(string file) { if (File.Exists(file)) { Process.Start(file); } } public static ProcessInfo CreateProcess( string executable, string arguments, bool lowPriority = false, string? workingDirectory = null, bool captureOutput = false, bool displayWindow = true, Dictionary<string, string>? environmentVariables = null, Action<Process>? onProcessStartHandler = null, Action<DataReceivedEventArgs>? onOutputDataReceived = null, CancellationToken cancellationToken = default) => CreateProcess( CreateProcessStartInfo(executable, arguments, workingDirectory, captureOutput, displayWindow, environmentVariables), lowPriority: lowPriority, onProcessStartHandler: onProcessStartHandler, onOutputDataReceived: onOutputDataReceived, cancellationToken: cancellationToken); public static ProcessInfo CreateProcess( ProcessStartInfo processStartInfo, bool lowPriority = false, Action<Process>? onProcessStartHandler = null, Action<DataReceivedEventArgs>? onOutputDataReceived = null, CancellationToken cancellationToken = default) { var errorLines = new List<string>(); var outputLines = new List<string>(); var process = new Process(); var tcs = new TaskCompletionSource<ProcessResult>(); process.EnableRaisingEvents = true; process.StartInfo = processStartInfo; process.OutputDataReceived += (s, e) => { if (e.Data != null) { onOutputDataReceived?.Invoke(e); outputLines.Add(e.Data); } }; process.ErrorDataReceived += (s, e) => { if (e.Data != null) { errorLines.Add(e.Data); } }; process.Exited += (s, e) => { // We must call WaitForExit to make sure we've received all OutputDataReceived/ErrorDataReceived calls // or else we'll be returning a list we're still modifying. For paranoia, we'll start a task here rather // than enter right back into the Process type and start a wait which isn't guaranteed to be safe. Task.Run(() => { process.WaitForExit(); var result = new ProcessResult( process, process.ExitCode, new ReadOnlyCollection<string>(outputLines), new ReadOnlyCollection<string>(errorLines)); tcs.TrySetResult(result); }, cancellationToken); }; var registration = cancellationToken.Register(() => { if (tcs.TrySetCanceled()) { // If the underlying process is still running, we should kill it if (!process.HasExited) { try { process.Kill(); } catch (InvalidOperationException) { // Ignore, since the process is already dead } } } }); process.Start(); onProcessStartHandler?.Invoke(process); if (lowPriority) { process.PriorityClass = ProcessPriorityClass.BelowNormal; } if (processStartInfo.RedirectStandardOutput) { process.BeginOutputReadLine(); } if (processStartInfo.RedirectStandardError) { process.BeginErrorReadLine(); } return new ProcessInfo(process, processStartInfo, tcs.Task); } public static ProcessStartInfo CreateProcessStartInfo( string executable, string arguments, string? workingDirectory = null, bool captureOutput = false, bool displayWindow = true, Dictionary<string, string>? environmentVariables = null) { var processStartInfo = new ProcessStartInfo(executable, arguments); if (!string.IsNullOrEmpty(workingDirectory)) { processStartInfo.WorkingDirectory = workingDirectory; } if (environmentVariables != null) { foreach (var pair in environmentVariables) { processStartInfo.EnvironmentVariables[pair.Key] = pair.Value; } } if (captureOutput) { processStartInfo.UseShellExecute = false; processStartInfo.RedirectStandardOutput = true; processStartInfo.RedirectStandardError = true; } else { processStartInfo.CreateNoWindow = !displayWindow; processStartInfo.UseShellExecute = displayWindow; } return processStartInfo; } } }
// Licensed to the .NET Foundation under one or more 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.ObjectModel; using System.Diagnostics; using System.IO; using System.Threading; using System.Threading.Tasks; namespace RunTests { public readonly struct ProcessResult { public Process Process { get; } public int ExitCode { get; } public ReadOnlyCollection<string> OutputLines { get; } public ReadOnlyCollection<string> ErrorLines { get; } public ProcessResult(Process process, int exitCode, ReadOnlyCollection<string> outputLines, ReadOnlyCollection<string> errorLines) { Process = process; ExitCode = exitCode; OutputLines = outputLines; ErrorLines = errorLines; } } public readonly struct ProcessInfo { public Process Process { get; } public ProcessStartInfo StartInfo { get; } public Task<ProcessResult> Result { get; } public int Id => Process.Id; public ProcessInfo(Process process, ProcessStartInfo startInfo, Task<ProcessResult> result) { Process = process; StartInfo = startInfo; Result = result; } } public static class ProcessRunner { public static void OpenFile(string file) { if (File.Exists(file)) { Process.Start(file); } } public static ProcessInfo CreateProcess( string executable, string arguments, bool lowPriority = false, string? workingDirectory = null, bool captureOutput = false, bool displayWindow = true, Dictionary<string, string>? environmentVariables = null, Action<Process>? onProcessStartHandler = null, Action<DataReceivedEventArgs>? onOutputDataReceived = null, CancellationToken cancellationToken = default) => CreateProcess( CreateProcessStartInfo(executable, arguments, workingDirectory, captureOutput, displayWindow, environmentVariables), lowPriority: lowPriority, onProcessStartHandler: onProcessStartHandler, onOutputDataReceived: onOutputDataReceived, cancellationToken: cancellationToken); public static ProcessInfo CreateProcess( ProcessStartInfo processStartInfo, bool lowPriority = false, Action<Process>? onProcessStartHandler = null, Action<DataReceivedEventArgs>? onOutputDataReceived = null, CancellationToken cancellationToken = default) { var errorLines = new List<string>(); var outputLines = new List<string>(); var process = new Process(); var tcs = new TaskCompletionSource<ProcessResult>(); process.EnableRaisingEvents = true; process.StartInfo = processStartInfo; process.OutputDataReceived += (s, e) => { if (e.Data != null) { onOutputDataReceived?.Invoke(e); outputLines.Add(e.Data); } }; process.ErrorDataReceived += (s, e) => { if (e.Data != null) { errorLines.Add(e.Data); } }; process.Exited += (s, e) => { // We must call WaitForExit to make sure we've received all OutputDataReceived/ErrorDataReceived calls // or else we'll be returning a list we're still modifying. For paranoia, we'll start a task here rather // than enter right back into the Process type and start a wait which isn't guaranteed to be safe. Task.Run(() => { process.WaitForExit(); var result = new ProcessResult( process, process.ExitCode, new ReadOnlyCollection<string>(outputLines), new ReadOnlyCollection<string>(errorLines)); tcs.TrySetResult(result); }, cancellationToken); }; var registration = cancellationToken.Register(() => { if (tcs.TrySetCanceled()) { // If the underlying process is still running, we should kill it if (!process.HasExited) { try { process.Kill(); } catch (InvalidOperationException) { // Ignore, since the process is already dead } } } }); process.Start(); onProcessStartHandler?.Invoke(process); if (lowPriority) { process.PriorityClass = ProcessPriorityClass.BelowNormal; } if (processStartInfo.RedirectStandardOutput) { process.BeginOutputReadLine(); } if (processStartInfo.RedirectStandardError) { process.BeginErrorReadLine(); } return new ProcessInfo(process, processStartInfo, tcs.Task); } public static ProcessStartInfo CreateProcessStartInfo( string executable, string arguments, string? workingDirectory = null, bool captureOutput = false, bool displayWindow = true, Dictionary<string, string>? environmentVariables = null) { var processStartInfo = new ProcessStartInfo(executable, arguments); if (!string.IsNullOrEmpty(workingDirectory)) { processStartInfo.WorkingDirectory = workingDirectory; } if (environmentVariables != null) { foreach (var pair in environmentVariables) { processStartInfo.EnvironmentVariables[pair.Key] = pair.Value; } } if (captureOutput) { processStartInfo.UseShellExecute = false; processStartInfo.RedirectStandardOutput = true; processStartInfo.RedirectStandardError = true; } else { processStartInfo.CreateNoWindow = !displayWindow; processStartInfo.UseShellExecute = displayWindow; } return processStartInfo; } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/EditorFeatures/TestUtilities/Classification/FormattedClassifications.RegexTypes.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 Microsoft.CodeAnalysis.Classification; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Classification { public static partial class FormattedClassifications { public static class Regex { [DebuggerStepThrough] public static FormattedClassification Anchor(string value) => New(value, ClassificationTypeNames.RegexAnchor); [DebuggerStepThrough] public static FormattedClassification Grouping(string value) => New(value, ClassificationTypeNames.RegexGrouping); [DebuggerStepThrough] public static FormattedClassification OtherEscape(string value) => New(value, ClassificationTypeNames.RegexOtherEscape); [DebuggerStepThrough] public static FormattedClassification SelfEscapedCharacter(string value) => New(value, ClassificationTypeNames.RegexSelfEscapedCharacter); [DebuggerStepThrough] public static FormattedClassification Alternation(string value) => New(value, ClassificationTypeNames.RegexAlternation); [DebuggerStepThrough] public static FormattedClassification CharacterClass(string value) => New(value, ClassificationTypeNames.RegexCharacterClass); [DebuggerStepThrough] public static FormattedClassification Text(string value) => New(value, ClassificationTypeNames.RegexText); [DebuggerStepThrough] public static FormattedClassification Quantifier(string value) => New(value, ClassificationTypeNames.RegexQuantifier); [DebuggerStepThrough] public static FormattedClassification Comment(string value) => New(value, ClassificationTypeNames.RegexComment); } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Classification; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Classification { public static partial class FormattedClassifications { public static class Regex { [DebuggerStepThrough] public static FormattedClassification Anchor(string value) => New(value, ClassificationTypeNames.RegexAnchor); [DebuggerStepThrough] public static FormattedClassification Grouping(string value) => New(value, ClassificationTypeNames.RegexGrouping); [DebuggerStepThrough] public static FormattedClassification OtherEscape(string value) => New(value, ClassificationTypeNames.RegexOtherEscape); [DebuggerStepThrough] public static FormattedClassification SelfEscapedCharacter(string value) => New(value, ClassificationTypeNames.RegexSelfEscapedCharacter); [DebuggerStepThrough] public static FormattedClassification Alternation(string value) => New(value, ClassificationTypeNames.RegexAlternation); [DebuggerStepThrough] public static FormattedClassification CharacterClass(string value) => New(value, ClassificationTypeNames.RegexCharacterClass); [DebuggerStepThrough] public static FormattedClassification Text(string value) => New(value, ClassificationTypeNames.RegexText); [DebuggerStepThrough] public static FormattedClassification Quantifier(string value) => New(value, ClassificationTypeNames.RegexQuantifier); [DebuggerStepThrough] public static FormattedClassification Comment(string value) => New(value, ClassificationTypeNames.RegexComment); } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/VisualStudio/Core/Test/CodeModel/AbstractCodeInterfaceTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel Public MustInherit Class AbstractCodeInterfaceTests Inherits AbstractCodeElementTests(Of EnvDTE80.CodeInterface2) Protected Overrides Function GetStartPointFunc(codeElement As EnvDTE80.CodeInterface2) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint) Return Function(part) codeElement.GetStartPoint(part) End Function Protected Overrides Function GetEndPointFunc(codeElement As EnvDTE80.CodeInterface2) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint) Return Function(part) codeElement.GetEndPoint(part) End Function Protected Overrides Function GetAccess(codeElement As EnvDTE80.CodeInterface2) As EnvDTE.vsCMAccess Return codeElement.Access End Function Protected Overrides Function GetAttributes(codeElement As EnvDTE80.CodeInterface2) As EnvDTE.CodeElements Return codeElement.Attributes End Function Protected Overrides Function GetComment(codeElement As EnvDTE80.CodeInterface2) As String Return codeElement.Comment End Function Protected Overrides Function GetDocComment(codeElement As EnvDTE80.CodeInterface2) As String Return codeElement.DocComment End Function Protected Overrides Function GetFullName(codeElement As EnvDTE80.CodeInterface2) As String Return codeElement.FullName End Function Protected Overrides Function GetKind(codeElement As EnvDTE80.CodeInterface2) As EnvDTE.vsCMElement Return codeElement.Kind End Function Protected Overrides Function GetName(codeElement As EnvDTE80.CodeInterface2) As String Return codeElement.Name End Function Protected Overrides Function GetParent(codeElement As EnvDTE80.CodeInterface2) As Object Return codeElement.Parent End Function Protected Overrides Function GetParts(codeElement As EnvDTE80.CodeInterface2) As EnvDTE.CodeElements Return codeElement.Parts End Function Protected Overrides Function AddEvent(codeElement As EnvDTE80.CodeInterface2, data As EventData) As EnvDTE80.CodeEvent Return codeElement.AddEvent(data.Name, data.FullDelegateName, data.CreatePropertyStyleEvent, data.Position, data.Access) End Function Protected Overrides Function AddFunction(codeElement As EnvDTE80.CodeInterface2, data As FunctionData) As EnvDTE.CodeFunction Return codeElement.AddFunction(data.Name, data.Kind, data.Type, data.Position, data.Access) End Function Protected Overrides Function AddAttribute(codeElement As EnvDTE80.CodeInterface2, data As AttributeData) As EnvDTE.CodeAttribute Return codeElement.AddAttribute(data.Name, data.Value, data.Position) End Function Protected Overrides Function GetNameSetter(codeElement As EnvDTE80.CodeInterface2) As Action(Of String) Return Sub(name) codeElement.Name = name End Function Protected Overrides Function AddBase(codeElement As EnvDTE80.CodeInterface2, base As Object, position As Object) As EnvDTE.CodeElement Return codeElement.AddBase(base, position) End Function Protected Overrides Sub RemoveBase(codeElement As EnvDTE80.CodeInterface2, element As Object) codeElement.RemoveBase(element) 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. Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel Public MustInherit Class AbstractCodeInterfaceTests Inherits AbstractCodeElementTests(Of EnvDTE80.CodeInterface2) Protected Overrides Function GetStartPointFunc(codeElement As EnvDTE80.CodeInterface2) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint) Return Function(part) codeElement.GetStartPoint(part) End Function Protected Overrides Function GetEndPointFunc(codeElement As EnvDTE80.CodeInterface2) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint) Return Function(part) codeElement.GetEndPoint(part) End Function Protected Overrides Function GetAccess(codeElement As EnvDTE80.CodeInterface2) As EnvDTE.vsCMAccess Return codeElement.Access End Function Protected Overrides Function GetAttributes(codeElement As EnvDTE80.CodeInterface2) As EnvDTE.CodeElements Return codeElement.Attributes End Function Protected Overrides Function GetComment(codeElement As EnvDTE80.CodeInterface2) As String Return codeElement.Comment End Function Protected Overrides Function GetDocComment(codeElement As EnvDTE80.CodeInterface2) As String Return codeElement.DocComment End Function Protected Overrides Function GetFullName(codeElement As EnvDTE80.CodeInterface2) As String Return codeElement.FullName End Function Protected Overrides Function GetKind(codeElement As EnvDTE80.CodeInterface2) As EnvDTE.vsCMElement Return codeElement.Kind End Function Protected Overrides Function GetName(codeElement As EnvDTE80.CodeInterface2) As String Return codeElement.Name End Function Protected Overrides Function GetParent(codeElement As EnvDTE80.CodeInterface2) As Object Return codeElement.Parent End Function Protected Overrides Function GetParts(codeElement As EnvDTE80.CodeInterface2) As EnvDTE.CodeElements Return codeElement.Parts End Function Protected Overrides Function AddEvent(codeElement As EnvDTE80.CodeInterface2, data As EventData) As EnvDTE80.CodeEvent Return codeElement.AddEvent(data.Name, data.FullDelegateName, data.CreatePropertyStyleEvent, data.Position, data.Access) End Function Protected Overrides Function AddFunction(codeElement As EnvDTE80.CodeInterface2, data As FunctionData) As EnvDTE.CodeFunction Return codeElement.AddFunction(data.Name, data.Kind, data.Type, data.Position, data.Access) End Function Protected Overrides Function AddAttribute(codeElement As EnvDTE80.CodeInterface2, data As AttributeData) As EnvDTE.CodeAttribute Return codeElement.AddAttribute(data.Name, data.Value, data.Position) End Function Protected Overrides Function GetNameSetter(codeElement As EnvDTE80.CodeInterface2) As Action(Of String) Return Sub(name) codeElement.Name = name End Function Protected Overrides Function AddBase(codeElement As EnvDTE80.CodeInterface2, base As Object, position As Object) As EnvDTE.CodeElement Return codeElement.AddBase(base, position) End Function Protected Overrides Sub RemoveBase(codeElement As EnvDTE80.CodeInterface2, element As Object) codeElement.RemoveBase(element) End Sub End Class End Namespace
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Workspaces/Core/MSBuild/MSBuild/DiagnosticReportingMode.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.MSBuild { internal enum DiagnosticReportingMode { Throw, Log, Ignore } }
// Licensed to the .NET Foundation under one or more 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.MSBuild { internal enum DiagnosticReportingMode { Throw, Log, Ignore } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/VisualStudio/VisualBasic/Impl/Options/AutomationObject/AutomationObject.SymbolSearch.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.SymbolSearch Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options Partial Public Class AutomationObject Public Property Option_SuggestImportsForTypesInReferenceAssemblies As Boolean Get Return GetBooleanOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies) End Get Set(value As Boolean) SetBooleanOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, value) End Set End Property Public Property Option_SuggestImportsForTypesInNuGetPackages As Boolean Get Return GetBooleanOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages) End Get Set(value As Boolean) SetBooleanOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages, value) End Set End Property 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.SymbolSearch Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options Partial Public Class AutomationObject Public Property Option_SuggestImportsForTypesInReferenceAssemblies As Boolean Get Return GetBooleanOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies) End Get Set(value As Boolean) SetBooleanOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, value) End Set End Property Public Property Option_SuggestImportsForTypesInNuGetPackages As Boolean Get Return GetBooleanOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages) End Get Set(value As Boolean) SetBooleanOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages, value) End Set End Property End Class End Namespace
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/Core/Portable/SourceGeneration/Nodes/ISyntaxInputNode.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.Threading; using Microsoft.CodeAnalysis.Collections; namespace Microsoft.CodeAnalysis { internal interface ISyntaxInputNode { ISyntaxInputBuilder GetBuilder(DriverStateTable table); } internal interface ISyntaxInputBuilder { ISyntaxInputNode SyntaxInputNode { get; } void VisitTree(Lazy<SyntaxNode> root, EntryState state, SemanticModel? model, CancellationToken cancellationToken); void SaveStateAndFree(ImmutableSegmentedDictionary<object, IStateTable>.Builder tables); } }
// Licensed to the .NET Foundation under one or more 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.Threading; using Microsoft.CodeAnalysis.Collections; namespace Microsoft.CodeAnalysis { internal interface ISyntaxInputNode { ISyntaxInputBuilder GetBuilder(DriverStateTable table); } internal interface ISyntaxInputBuilder { ISyntaxInputNode SyntaxInputNode { get; } void VisitTree(Lazy<SyntaxNode> root, EntryState state, SemanticModel? model, CancellationToken cancellationToken); void SaveStateAndFree(ImmutableSegmentedDictionary<object, IStateTable>.Builder tables); } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Workspaces/Remote/Core/ISolutionSynchronizationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.Remote { internal interface ISolutionAssetStorageProvider : IWorkspaceService { SolutionAssetStorage AssetStorage { 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. using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.Remote { internal interface ISolutionAssetStorageProvider : IWorkspaceService { SolutionAssetStorage AssetStorage { get; } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/CSharp/Test/Symbol/Symbols/Metadata/MetadataMemberTests.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.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class MetadataMemberTests : CSharpTestBase { private const string VTableGapClassIL = @" .class public auto ansi beforefieldinit Class extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void _VtblGap1_1() cil managed { ret } .method public hidebysig specialname instance int32 _VtblGap2_1() cil managed { ret } .method public hidebysig specialname instance void set_GetterIsGap(int32 'value') cil managed { ret } .method public hidebysig specialname instance int32 get_SetterIsGap() cil managed { ret } .method public hidebysig specialname instance void _VtblGap3_1(int32 'value') cil managed { ret } .method public hidebysig specialname instance int32 _VtblGap4_1() cil managed { ret } .method public hidebysig specialname instance void _VtblGap5_1(int32 'value') cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .property instance int32 GetterIsGap() { .get instance int32 Class::_VtblGap2_1() .set instance void Class::set_GetterIsGap(int32) } // end of property Class::GetterIsGap .property instance int32 SetterIsGap() { .get instance int32 Class::get_SetterIsGap() .set instance void Class::_VtblGap3_1(int32) } // end of property Class::SetterIsGap .property instance int32 BothAccessorsAreGaps() { .get instance int32 Class::_VtblGap4_1() .set instance void Class::_VtblGap5_1(int32) } // end of property Class::BothAccessorsAreGaps } // end of class Class "; private const string VTableGapInterfaceIL = @" .class interface public abstract auto ansi Interface { .method public hidebysig newslot specialname rtspecialname abstract virtual instance void _VtblGap1_1() cil managed { } .method public hidebysig newslot specialname abstract virtual instance int32 _VtblGap2_1() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void set_GetterIsGap(int32 'value') cil managed { } .method public hidebysig newslot specialname abstract virtual instance int32 get_SetterIsGap() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void _VtblGap3_1(int32 'value') cil managed { } .method public hidebysig newslot specialname abstract virtual instance int32 _VtblGap4_1() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void _VtblGap5_1(int32 'value') cil managed { } .property instance int32 GetterIsGap() { .get instance int32 Interface::_VtblGap2_1() .set instance void Interface::set_GetterIsGap(int32) } // end of property Interface::GetterIsGap .property instance int32 SetterIsGap() { .get instance int32 Interface::get_SetterIsGap() .set instance void Interface::_VtblGap3_1(int32) } // end of property Interface::SetterIsGap .property instance int32 BothAccessorsAreGaps() { .get instance int32 Interface::_VtblGap4_1() .set instance void Interface::_VtblGap5_1(int32) } // end of property Interface::BothAccessorsAreGaps } // end of class Interface "; [WorkItem(537346, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537346")] [Fact] public void MetadataMethodSymbolCtor01() { var text = "public class A {}"; var compilation = CreateCompilation(text); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); Assert.Equal(RuntimeCorLibName.Name, mscorNS.Name); Assert.Equal(SymbolKind.Assembly, mscorNS.Kind); var ns1 = mscorNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol; var type1 = ns1.GetTypeMembers("StringComparer").Single() as NamedTypeSymbol; var ctor = type1.InstanceConstructors.Single(); Assert.Equal(type1, ctor.ContainingSymbol); Assert.Equal(WellKnownMemberNames.InstanceConstructorName, ctor.Name); Assert.Equal(SymbolKind.Method, ctor.Kind); Assert.Equal(MethodKind.Constructor, ctor.MethodKind); Assert.Equal(Accessibility.Protected, ctor.DeclaredAccessibility); Assert.True(ctor.IsDefinition); Assert.False(ctor.IsStatic); Assert.False(ctor.IsSealed); Assert.False(ctor.IsOverride); Assert.False(ctor.IsExtensionMethod); Assert.True(ctor.ReturnsVoid); Assert.False(ctor.IsVararg); // Bug - 2067 Assert.Equal("System.StringComparer." + WellKnownMemberNames.InstanceConstructorName + "()", ctor.ToTestDisplayString()); Assert.Equal(0, ctor.TypeParameters.Length); Assert.Equal("Void", ctor.ReturnType.Name); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [WorkItem(537345, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537345")] [Fact] public void MetadataMethodSymbol01() { var text = "public class A {}"; var compilation = CreateEmptyCompilation(text, new[] { MscorlibRef }); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); Assert.Equal("mscorlib", mscorNS.Name); Assert.Equal(SymbolKind.Assembly, mscorNS.Kind); var ns1 = mscorNS.GlobalNamespace.GetMembers("Microsoft").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Runtime").Single() as NamespaceSymbol; var ns3 = ns2.GetMembers("Hosting").Single() as NamespaceSymbol; var class1 = ns3.GetTypeMembers("StrongNameHelpers").First() as NamedTypeSymbol; var members = class1.GetMembers("StrongNameSignatureGeneration"); // 4 overloads Assert.Equal(4, members.Length); var member1 = members.Last() as MethodSymbol; Assert.Equal(mscorNS, member1.ContainingAssembly); Assert.Equal(class1, member1.ContainingSymbol); Assert.Equal(SymbolKind.Method, member1.Kind); Assert.Equal(MethodKind.Ordinary, member1.MethodKind); Assert.Equal(Accessibility.Public, member1.DeclaredAccessibility); Assert.True(member1.IsDefinition); Assert.True(member1.IsStatic); Assert.False(member1.IsAbstract); Assert.False(member1.IsSealed); Assert.False(member1.IsVirtual); Assert.False(member1.IsOverride); // Bug - // Assert.True(member1.IsOverloads); Assert.False(member1.IsGenericMethod); // Not Impl // Assert.False(member1.IsExtensionMethod); Assert.False(member1.ReturnsVoid); Assert.False(member1.IsVararg); var fullName = "System.Boolean Microsoft.Runtime.Hosting.StrongNameHelpers.StrongNameSignatureGeneration(System.String pwzFilePath, System.String pwzKeyContainer, System.Byte[] bKeyBlob, System.Int32 cbKeyBlob, ref System.IntPtr ppbSignatureBlob, out System.Int32 pcbSignatureBlob)"; Assert.Equal(fullName, member1.ToTestDisplayString()); Assert.Equal(0, member1.TypeArgumentsWithAnnotations.Length); Assert.Equal(0, member1.TypeParameters.Length); Assert.Equal(6, member1.Parameters.Length); Assert.Equal("Boolean", member1.ReturnType.Name); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [WorkItem(527150, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527150")] [WorkItem(527151, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527151")] [Fact] public void MetadataParameterSymbol01() { var text = "public class A {}"; var compilation = CreateEmptyCompilation(text, new[] { MscorlibRef }); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); Assert.Equal("mscorlib", mscorNS.Name); Assert.Equal(SymbolKind.Assembly, mscorNS.Kind); var ns1 = mscorNS.GlobalNamespace.GetMembers("Microsoft").Single() as NamespaceSymbol; var ns2 = (ns1.GetMembers("Runtime").Single() as NamespaceSymbol).GetMembers("Hosting").Single() as NamespaceSymbol; var class1 = ns2.GetTypeMembers("StrongNameHelpers").First() as NamedTypeSymbol; var members = class1.GetMembers("StrongNameSignatureGeneration"); var member1 = members.Last() as MethodSymbol; Assert.Equal(6, member1.Parameters.Length); var p1 = member1.Parameters[0] as ParameterSymbol; var p2 = member1.Parameters[1] as ParameterSymbol; var p3 = member1.Parameters[2] as ParameterSymbol; var p4 = member1.Parameters[3] as ParameterSymbol; var p5 = member1.Parameters[4] as ParameterSymbol; var p6 = member1.Parameters[5] as ParameterSymbol; Assert.Equal(mscorNS, p1.ContainingAssembly); Assert.Equal(class1, p1.ContainingType); Assert.Equal(member1, p1.ContainingSymbol); Assert.Equal(SymbolKind.Parameter, p1.Kind); Assert.Equal(Accessibility.NotApplicable, p1.DeclaredAccessibility); Assert.Equal("pwzFilePath", p1.Name); Assert.Equal("System.String pwzKeyContainer", p2.ToTestDisplayString()); Assert.Equal("String", p2.Type.Name); Assert.True(p2.IsDefinition); Assert.Equal("System.Byte[] bKeyBlob", p3.ToTestDisplayString()); Assert.Equal("System.Byte[]", p3.Type.ToTestDisplayString()); //array types do not have names - use ToTestDisplayString Assert.False(p1.IsStatic); Assert.False(p1.IsAbstract); Assert.False(p2.IsSealed); Assert.False(p2.IsVirtual); Assert.False(p3.IsOverride); Assert.False(p3.IsParams); Assert.False(p4.IsOptional); Assert.False(p4.HasExplicitDefaultValue); // Not Impl - out of scope // Assert.Null(p4.DefaultValue); Assert.Equal("ppbSignatureBlob", p5.Name); Assert.Equal("IntPtr", p5.Type.Name); Assert.Equal(RefKind.Ref, p5.RefKind); Assert.Equal("out System.Int32 pcbSignatureBlob", p6.ToTestDisplayString()); Assert.Equal(RefKind.Out, p6.RefKind); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [Fact] public void MetadataMethodSymbolGen02() { var text = "public class A {}"; var compilation = CreateCompilation(text); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); var ns1 = (mscorNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol).GetMembers("Collections").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Generic").Single() as NamespaceSymbol; var type1 = ns2.GetTypeMembers("IDictionary").First() as NamedTypeSymbol; var member1 = type1.GetMembers("Add").Single() as MethodSymbol; var member2 = type1.GetMembers("TryGetValue").Single() as MethodSymbol; Assert.Equal(mscorNS, member1.ContainingAssembly); Assert.Equal(type1, member1.ContainingSymbol); Assert.Equal(SymbolKind.Method, member1.Kind); // Not Impl //Assert.Equal(MethodKind.Ordinary, member2.MethodKind); Assert.Equal(Accessibility.Public, member2.DeclaredAccessibility); Assert.True(member2.IsDefinition); Assert.False(member1.IsStatic); Assert.True(member1.IsAbstract); Assert.False(member2.IsSealed); Assert.False(member2.IsVirtual); Assert.False(member2.IsOverride); //Assert.True(member1.IsOverloads); //Assert.True(member2.IsOverloads); Assert.False(member1.IsGenericMethod); // Not Impl //Assert.False(member1.IsExtensionMethod); Assert.True(member1.ReturnsVoid); Assert.False(member2.IsVararg); Assert.Equal(0, member1.TypeArgumentsWithAnnotations.Length); Assert.Equal(0, member2.TypeParameters.Length); Assert.Equal(2, member1.Parameters.Length); Assert.Equal("Boolean", member2.ReturnType.Name); Assert.Equal("System.Boolean System.Collections.Generic.IDictionary<TKey, TValue>.TryGetValue(TKey key, out TValue value)", member2.ToTestDisplayString()); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [Fact] public void MetadataParameterSymbolGen02() { var text = "public class A {}"; var compilation = CreateCompilation(text); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); var ns1 = (mscorNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol).GetMembers("Collections").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Generic").Single() as NamespaceSymbol; var type1 = ns2.GetTypeMembers("IDictionary").First() as NamedTypeSymbol; var member1 = type1.GetMembers("TryGetValue").Single() as MethodSymbol; Assert.Equal(2, member1.Parameters.Length); var p1 = member1.Parameters[0] as ParameterSymbol; var p2 = member1.Parameters[1] as ParameterSymbol; Assert.Equal(mscorNS, p1.ContainingAssembly); Assert.Equal(type1, p2.ContainingType); Assert.Equal(member1, p1.ContainingSymbol); Assert.Equal(SymbolKind.Parameter, p2.Kind); Assert.Equal(Accessibility.NotApplicable, p1.DeclaredAccessibility); Assert.Equal("value", p2.Name); Assert.Equal("TKey key", p1.ToTestDisplayString()); // Empty // Assert.Equal("TValue", p2.Type.Name); Assert.True(p2.IsDefinition); Assert.False(p1.IsStatic); Assert.False(p1.IsAbstract); Assert.False(p2.IsSealed); Assert.False(p2.IsVirtual); Assert.False(p1.IsOverride); Assert.False(p1.IsExtern); Assert.False(p1.IsParams); Assert.False(p2.IsOptional); Assert.False(p2.HasExplicitDefaultValue); // Not Impl - Not in M2 scope // Assert.Null(p2.DefaultValue); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [WorkItem(537424, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537424")] [Fact] public void MetadataMethodStaticAndInstanceCtor() { var text = @" class C { C() { } static C() { } }"; var compilation = CreateCompilation(text); Assert.False(compilation.GetDiagnostics().Any()); var classC = compilation.SourceModule.GlobalNamespace.GetTypeMembers("C").Single(); // NamedTypeSymbol.Constructors only contains instance constructors Assert.Equal(1, classC.InstanceConstructors.Length); Assert.Equal(1, classC.GetMembers(WellKnownMemberNames.StaticConstructorName).Length); } [ClrOnlyFact] public void ImportDecimalConstantAttribute() { const string ilSource = @" .class public C extends [mscorlib]System.Object { .field public static initonly valuetype [mscorlib]System.Decimal MyDecimalTen .custom instance void [mscorlib]System.Runtime.CompilerServices.DecimalConstantAttribute::.ctor(uint8, uint8, uint32, uint32, uint32) = ( 01 00 00 00 00 00 00 00 00 00 00 00 0A 00 00 00 00 00 ) } // end of class C"; const string cSharpSource = @" class B { static void Main() { var x = C.MyDecimalTen; System.Console.Write(x); } } "; CompileWithCustomILSource(cSharpSource, ilSource, expectedOutput: "10"); } [Fact] public void TypeAndNamespaceWithSameNameButDifferentArities() { var il = @" .class interface public abstract auto ansi A.B.C { } .class interface public abstract auto ansi A.B`1<T> { } "; var csharp = @""; var compilation = CreateCompilationWithILAndMscorlib40(csharp, il); var namespaceA = compilation.GlobalNamespace.GetMember<NamespaceSymbol>("A"); var members = namespaceA.GetMembers("B"); Assert.Equal(2, members.Length); Assert.NotNull(members[0]); Assert.NotNull(members[1]); } [Fact] public void TypeAndNamespaceWithSameNameAndArity() { var il = @" .class interface public abstract auto ansi A.B.C { } .class interface public abstract auto ansi A.B { } "; var csharp = @""; var compilation = CreateCompilationWithILAndMscorlib40(csharp, il); var namespaceA = compilation.GlobalNamespace.GetMember<NamespaceSymbol>("A"); var members = namespaceA.GetMembers("B"); Assert.Equal(2, members.Length); Assert.NotNull(members[0]); Assert.NotNull(members[1]); } // TODO: Update this test if we decide to include gaps in the symbol table for NoPIA (DevDiv #17472). [WorkItem(546951, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546951")] [Fact] public void VTableGapsNotInSymbolTable() { var csharp = @""; var comp = CreateCompilationWithILAndMscorlib40(csharp, VTableGapClassIL); comp.VerifyDiagnostics(); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Class"); AssertEx.None(type.GetMembersUnordered(), symbol => symbol.Name.StartsWith("_VtblGap", StringComparison.Ordinal)); // Dropped entirely. Assert.Equal(0, type.GetMembers("_VtblGap1_1").Length); // Dropped entirely, since both accessors are dropped. Assert.Equal(0, type.GetMembers("BothAccessorsAreGaps").Length); // Getter is silently dropped, property appears valid and write-only. var propWithoutGetter = type.GetMember<PropertySymbol>("GetterIsGap"); Assert.Null(propWithoutGetter.GetMethod); Assert.NotNull(propWithoutGetter.SetMethod); Assert.False(propWithoutGetter.MustCallMethodsDirectly); // Setter is silently dropped, property appears valid and read-only. var propWithoutSetter = type.GetMember<PropertySymbol>("SetterIsGap"); Assert.NotNull(propWithoutSetter.GetMethod); Assert.Null(propWithoutSetter.SetMethod); Assert.False(propWithoutSetter.MustCallMethodsDirectly); } [WorkItem(546951, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546951")] [Fact] public void CallVTableGap() { var csharp = @" class Test { static void Main() { Class c = new Class(); c._VtblGap1_1(); // CS1061 int x; x = c.BothAccessorsAreGaps; // CS1061 c.BothAccessorsAreGaps = x; // CS1061 x = c.GetterIsGap; // CS0154 c.GetterIsGap = x; x = c.SetterIsGap; c.SetterIsGap = x; // CS0200 } } "; var comp = CreateCompilationWithILAndMscorlib40(csharp, VTableGapClassIL); comp.VerifyDiagnostics( // (8,11): error CS1061: 'Class' does not contain a definition for '_VtblGap1_1' and no extension method '_VtblGap1_1' accepting a first argument of type 'Class' could be found (are you missing a using directive or an assembly reference?) // c._VtblGap1_1(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "_VtblGap1_1").WithArguments("Class", "_VtblGap1_1"), // (12,15): error CS1061: 'Class' does not contain a definition for 'BothAccessorsAreGaps' and no extension method 'BothAccessorsAreGaps' accepting a first argument of type 'Class' could be found (are you missing a using directive or an assembly reference?) // x = c.BothAccessorsAreGaps; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "BothAccessorsAreGaps").WithArguments("Class", "BothAccessorsAreGaps"), // (13,11): error CS1061: 'Class' does not contain a definition for 'BothAccessorsAreGaps' and no extension method 'BothAccessorsAreGaps' accepting a first argument of type 'Class' could be found (are you missing a using directive or an assembly reference?) // c.BothAccessorsAreGaps = x; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "BothAccessorsAreGaps").WithArguments("Class", "BothAccessorsAreGaps"), // (15,13): error CS0154: The property or indexer 'Class.GetterIsGap' cannot be used in this context because it lacks the get accessor // x = c.GetterIsGap; Diagnostic(ErrorCode.ERR_PropertyLacksGet, "c.GetterIsGap").WithArguments("Class.GetterIsGap"), // (19,9): error CS0200: Property or indexer 'Class.SetterIsGap' cannot be assigned to -- it is read only // c.SetterIsGap = x; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "c.SetterIsGap").WithArguments("Class.SetterIsGap")); } [WorkItem(546951, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546951")] [Fact] public void ImplementVTableGap() { var csharp = @" class Empty : Interface { } class Implicit : Interface { public void _VtblGap1_1() { } public int GetterIsGap { get; set; } public int SetterIsGap { get; set; } public int BothAccessorsAreGaps { get; set; } } class Explicit : Interface { void Interface._VtblGap1_1() { } int Interface.GetterIsGap { get; set; } int Interface.SetterIsGap { get; set; } int Interface.BothAccessorsAreGaps { get; set; } } "; var comp = CreateCompilationWithILAndMscorlib40(csharp, VTableGapInterfaceIL); comp.VerifyDiagnostics( // (2,7): error CS0535: 'Empty' does not implement interface member 'Interface.SetterIsGap' // class Empty : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Empty", "Interface.SetterIsGap"), // (2,7): error CS0535: 'Empty' does not implement interface member 'Interface.GetterIsGap' // class Empty : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Empty", "Interface.GetterIsGap"), // (17,33): error CS0550: 'Explicit.Interface.GetterIsGap.get' adds an accessor not found in interface member 'Interface.GetterIsGap' // int Interface.GetterIsGap { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("Explicit.Interface.GetterIsGap.get", "Interface.GetterIsGap"), // (18,38): error CS0550: 'Explicit.Interface.SetterIsGap.set' adds an accessor not found in interface member 'Interface.SetterIsGap' // int Interface.SetterIsGap { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("Explicit.Interface.SetterIsGap.set", "Interface.SetterIsGap"), // (19,19): error CS0539: 'Explicit.BothAccessorsAreGaps' in explicit interface declaration is not a member of interface // int Interface.BothAccessorsAreGaps { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "BothAccessorsAreGaps").WithArguments("Explicit.BothAccessorsAreGaps"), // (16,20): error CS0539: 'Explicit._VtblGap1_1()' in explicit interface declaration is not a member of interface // void Interface._VtblGap1_1() { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "_VtblGap1_1").WithArguments("Explicit._VtblGap1_1()")); } [Fact, WorkItem(1094411, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1094411")] public void Bug1094411_01() { var source1 = @" class Test { public int F; public int P {get; set;} public event System.Action E { add { } remove { } } public void M() {} } "; var members = new[] { "F", "P", "E", "M" }; var comp1 = CreateCompilation(source1, options: TestOptions.ReleaseDll); var test1 = comp1.GetTypeByMetadataName("Test"); var memberNames1 = new HashSet<string>(test1.MemberNames); foreach (var m in members) { Assert.True(memberNames1.Contains(m), m); } var comp2 = CreateCompilation("", new[] { comp1.EmitToImageReference() }); var test2 = comp2.GetTypeByMetadataName("Test"); var memberNames2 = new HashSet<string>(test2.MemberNames); foreach (var m in members) { Assert.True(memberNames2.Contains(m), m); } } [Fact, WorkItem(1094411, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1094411")] public void Bug1094411_02() { var source1 = @" class Test { public int F; public int P {get; set;} public event System.Action E { add { } remove { } } public void M() {} } "; var members = new[] { "F", "P", "E", "M" }; var comp1 = CreateCompilation(source1, options: TestOptions.ReleaseDll); var test1 = comp1.GetTypeByMetadataName("Test"); test1.GetMembers(); var memberNames1 = new HashSet<string>(test1.MemberNames); foreach (var m in members) { Assert.True(memberNames1.Contains(m), m); } var comp2 = CreateCompilation("", new[] { comp1.EmitToImageReference() }); var test2 = comp2.GetTypeByMetadataName("Test"); test2.GetMembers(); var memberNames2 = new HashSet<string>(test2.MemberNames); foreach (var m in members) { Assert.True(memberNames2.Contains(m), m); } } [Fact] public void TestMetadataImportOptions_01() { var expectedDiagnostics = new[] { // error CS7088: Invalid 'MetadataImportOptions' value: '255'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("MetadataImportOptions", "255").WithLocation(1, 1) }; var options = TestOptions.DebugDll; Assert.Equal(MetadataImportOptions.Public, options.MetadataImportOptions); options.VerifyErrors(); options = options.WithMetadataImportOptions(MetadataImportOptions.Internal); Assert.Equal(MetadataImportOptions.Internal, options.MetadataImportOptions); options.VerifyErrors(); options = options.WithMetadataImportOptions(MetadataImportOptions.All); Assert.Equal(MetadataImportOptions.All, options.MetadataImportOptions); options.VerifyErrors(); options = options.WithMetadataImportOptions(MetadataImportOptions.Public); Assert.Equal(MetadataImportOptions.Public, options.MetadataImportOptions); options.VerifyErrors(); options = options.WithMetadataImportOptions((MetadataImportOptions)byte.MaxValue); Assert.Equal((MetadataImportOptions)byte.MaxValue, options.MetadataImportOptions); options.VerifyErrors(expectedDiagnostics); var commonOptions = (CompilationOptions)options; commonOptions = commonOptions.WithMetadataImportOptions(MetadataImportOptions.Internal); Assert.Equal(MetadataImportOptions.Internal, ((CSharpCompilationOptions)commonOptions).MetadataImportOptions); ((CSharpCompilationOptions)commonOptions).VerifyErrors(); commonOptions = commonOptions.WithMetadataImportOptions(MetadataImportOptions.All); Assert.Equal(MetadataImportOptions.All, ((CSharpCompilationOptions)commonOptions).MetadataImportOptions); ((CSharpCompilationOptions)commonOptions).VerifyErrors(); commonOptions = commonOptions.WithMetadataImportOptions(MetadataImportOptions.Public); Assert.Equal(MetadataImportOptions.Public, ((CSharpCompilationOptions)commonOptions).MetadataImportOptions); ((CSharpCompilationOptions)commonOptions).VerifyErrors(); commonOptions = commonOptions.WithMetadataImportOptions((MetadataImportOptions)byte.MaxValue); Assert.Equal((MetadataImportOptions)byte.MaxValue, ((CSharpCompilationOptions)commonOptions).MetadataImportOptions); ((CSharpCompilationOptions)commonOptions).VerifyErrors(expectedDiagnostics); var source = @" public class C { public int P1 {get; set;} internal int P2 {get; set;} private int P3 {get; set;} } "; var compilation0 = CreateCompilation(source); options = TestOptions.DebugDll; var compilation = CreateCompilation("", options: options, references: new[] { compilation0.EmitToImageReference() }); var c = compilation.GetTypeByMetadataName("C"); Assert.NotEmpty(c.GetMembers("P1")); Assert.Empty(c.GetMembers("P2")); Assert.Empty(c.GetMembers("P3")); CompileAndVerify(compilation); compilation = compilation.WithOptions(options.WithMetadataImportOptions(MetadataImportOptions.Internal)); c = compilation.GetTypeByMetadataName("C"); Assert.NotEmpty(c.GetMembers("P1")); Assert.NotEmpty(c.GetMembers("P2")); Assert.Empty(c.GetMembers("P3")); CompileAndVerify(compilation); compilation = compilation.WithOptions(options.WithMetadataImportOptions(MetadataImportOptions.All)); c = compilation.GetTypeByMetadataName("C"); Assert.NotEmpty(c.GetMembers("P1")); Assert.NotEmpty(c.GetMembers("P2")); Assert.NotEmpty(c.GetMembers("P3")); CompileAndVerify(compilation); compilation = compilation.WithOptions(options.WithMetadataImportOptions((MetadataImportOptions)byte.MaxValue)); c = compilation.GetTypeByMetadataName("C"); Assert.NotEmpty(c.GetMembers("P1")); Assert.NotEmpty(c.GetMembers("P2")); Assert.Empty(c.GetMembers("P3")); compilation.VerifyEmitDiagnostics(expectedDiagnostics); compilation.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TestMetadataImportOptions_02() { var expectedDiagnostics = new[] { // error CS7088: Invalid 'MetadataImportOptions' value: '255'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("MetadataImportOptions", "255").WithLocation(1, 1) }; var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.Internal); Assert.Equal(MetadataImportOptions.Internal, options.MetadataImportOptions); options.VerifyErrors(); options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All); Assert.Equal(MetadataImportOptions.All, options.MetadataImportOptions); options.VerifyErrors(); options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.Public); Assert.Equal(MetadataImportOptions.Public, options.MetadataImportOptions); options.VerifyErrors(); options = TestOptions.DebugDll.WithMetadataImportOptions((MetadataImportOptions)byte.MaxValue); Assert.Equal((MetadataImportOptions)byte.MaxValue, options.MetadataImportOptions); options.VerifyErrors(expectedDiagnostics); var source = @" public class C { public int P1 {get; set;} internal int P2 {get; set;} private int P3 {get; set;} } "; var compilation0 = CreateCompilation(source); var compilation = CreateCompilation("", options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.Internal), references: new[] { compilation0.EmitToImageReference() }); var c = compilation.GetTypeByMetadataName("C"); Assert.NotEmpty(c.GetMembers("P1")); Assert.NotEmpty(c.GetMembers("P2")); Assert.Empty(c.GetMembers("P3")); CompileAndVerify(compilation); compilation = compilation.WithOptions(TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); c = compilation.GetTypeByMetadataName("C"); Assert.NotEmpty(c.GetMembers("P1")); Assert.NotEmpty(c.GetMembers("P2")); Assert.NotEmpty(c.GetMembers("P3")); CompileAndVerify(compilation); compilation = compilation.WithOptions(TestOptions.DebugDll.WithMetadataImportOptions((MetadataImportOptions)byte.MaxValue)); c = compilation.GetTypeByMetadataName("C"); Assert.NotEmpty(c.GetMembers("P1")); Assert.NotEmpty(c.GetMembers("P2")); Assert.Empty(c.GetMembers("P3")); compilation.VerifyEmitDiagnostics(expectedDiagnostics); compilation.VerifyDiagnostics(expectedDiagnostics); } } }
// Licensed to the .NET Foundation under one or more 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.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class MetadataMemberTests : CSharpTestBase { private const string VTableGapClassIL = @" .class public auto ansi beforefieldinit Class extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void _VtblGap1_1() cil managed { ret } .method public hidebysig specialname instance int32 _VtblGap2_1() cil managed { ret } .method public hidebysig specialname instance void set_GetterIsGap(int32 'value') cil managed { ret } .method public hidebysig specialname instance int32 get_SetterIsGap() cil managed { ret } .method public hidebysig specialname instance void _VtblGap3_1(int32 'value') cil managed { ret } .method public hidebysig specialname instance int32 _VtblGap4_1() cil managed { ret } .method public hidebysig specialname instance void _VtblGap5_1(int32 'value') cil managed { ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } .property instance int32 GetterIsGap() { .get instance int32 Class::_VtblGap2_1() .set instance void Class::set_GetterIsGap(int32) } // end of property Class::GetterIsGap .property instance int32 SetterIsGap() { .get instance int32 Class::get_SetterIsGap() .set instance void Class::_VtblGap3_1(int32) } // end of property Class::SetterIsGap .property instance int32 BothAccessorsAreGaps() { .get instance int32 Class::_VtblGap4_1() .set instance void Class::_VtblGap5_1(int32) } // end of property Class::BothAccessorsAreGaps } // end of class Class "; private const string VTableGapInterfaceIL = @" .class interface public abstract auto ansi Interface { .method public hidebysig newslot specialname rtspecialname abstract virtual instance void _VtblGap1_1() cil managed { } .method public hidebysig newslot specialname abstract virtual instance int32 _VtblGap2_1() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void set_GetterIsGap(int32 'value') cil managed { } .method public hidebysig newslot specialname abstract virtual instance int32 get_SetterIsGap() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void _VtblGap3_1(int32 'value') cil managed { } .method public hidebysig newslot specialname abstract virtual instance int32 _VtblGap4_1() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void _VtblGap5_1(int32 'value') cil managed { } .property instance int32 GetterIsGap() { .get instance int32 Interface::_VtblGap2_1() .set instance void Interface::set_GetterIsGap(int32) } // end of property Interface::GetterIsGap .property instance int32 SetterIsGap() { .get instance int32 Interface::get_SetterIsGap() .set instance void Interface::_VtblGap3_1(int32) } // end of property Interface::SetterIsGap .property instance int32 BothAccessorsAreGaps() { .get instance int32 Interface::_VtblGap4_1() .set instance void Interface::_VtblGap5_1(int32) } // end of property Interface::BothAccessorsAreGaps } // end of class Interface "; [WorkItem(537346, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537346")] [Fact] public void MetadataMethodSymbolCtor01() { var text = "public class A {}"; var compilation = CreateCompilation(text); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); Assert.Equal(RuntimeCorLibName.Name, mscorNS.Name); Assert.Equal(SymbolKind.Assembly, mscorNS.Kind); var ns1 = mscorNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol; var type1 = ns1.GetTypeMembers("StringComparer").Single() as NamedTypeSymbol; var ctor = type1.InstanceConstructors.Single(); Assert.Equal(type1, ctor.ContainingSymbol); Assert.Equal(WellKnownMemberNames.InstanceConstructorName, ctor.Name); Assert.Equal(SymbolKind.Method, ctor.Kind); Assert.Equal(MethodKind.Constructor, ctor.MethodKind); Assert.Equal(Accessibility.Protected, ctor.DeclaredAccessibility); Assert.True(ctor.IsDefinition); Assert.False(ctor.IsStatic); Assert.False(ctor.IsSealed); Assert.False(ctor.IsOverride); Assert.False(ctor.IsExtensionMethod); Assert.True(ctor.ReturnsVoid); Assert.False(ctor.IsVararg); // Bug - 2067 Assert.Equal("System.StringComparer." + WellKnownMemberNames.InstanceConstructorName + "()", ctor.ToTestDisplayString()); Assert.Equal(0, ctor.TypeParameters.Length); Assert.Equal("Void", ctor.ReturnType.Name); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [WorkItem(537345, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537345")] [Fact] public void MetadataMethodSymbol01() { var text = "public class A {}"; var compilation = CreateEmptyCompilation(text, new[] { MscorlibRef }); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); Assert.Equal("mscorlib", mscorNS.Name); Assert.Equal(SymbolKind.Assembly, mscorNS.Kind); var ns1 = mscorNS.GlobalNamespace.GetMembers("Microsoft").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Runtime").Single() as NamespaceSymbol; var ns3 = ns2.GetMembers("Hosting").Single() as NamespaceSymbol; var class1 = ns3.GetTypeMembers("StrongNameHelpers").First() as NamedTypeSymbol; var members = class1.GetMembers("StrongNameSignatureGeneration"); // 4 overloads Assert.Equal(4, members.Length); var member1 = members.Last() as MethodSymbol; Assert.Equal(mscorNS, member1.ContainingAssembly); Assert.Equal(class1, member1.ContainingSymbol); Assert.Equal(SymbolKind.Method, member1.Kind); Assert.Equal(MethodKind.Ordinary, member1.MethodKind); Assert.Equal(Accessibility.Public, member1.DeclaredAccessibility); Assert.True(member1.IsDefinition); Assert.True(member1.IsStatic); Assert.False(member1.IsAbstract); Assert.False(member1.IsSealed); Assert.False(member1.IsVirtual); Assert.False(member1.IsOverride); // Bug - // Assert.True(member1.IsOverloads); Assert.False(member1.IsGenericMethod); // Not Impl // Assert.False(member1.IsExtensionMethod); Assert.False(member1.ReturnsVoid); Assert.False(member1.IsVararg); var fullName = "System.Boolean Microsoft.Runtime.Hosting.StrongNameHelpers.StrongNameSignatureGeneration(System.String pwzFilePath, System.String pwzKeyContainer, System.Byte[] bKeyBlob, System.Int32 cbKeyBlob, ref System.IntPtr ppbSignatureBlob, out System.Int32 pcbSignatureBlob)"; Assert.Equal(fullName, member1.ToTestDisplayString()); Assert.Equal(0, member1.TypeArgumentsWithAnnotations.Length); Assert.Equal(0, member1.TypeParameters.Length); Assert.Equal(6, member1.Parameters.Length); Assert.Equal("Boolean", member1.ReturnType.Name); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [WorkItem(527150, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527150")] [WorkItem(527151, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527151")] [Fact] public void MetadataParameterSymbol01() { var text = "public class A {}"; var compilation = CreateEmptyCompilation(text, new[] { MscorlibRef }); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); Assert.Equal("mscorlib", mscorNS.Name); Assert.Equal(SymbolKind.Assembly, mscorNS.Kind); var ns1 = mscorNS.GlobalNamespace.GetMembers("Microsoft").Single() as NamespaceSymbol; var ns2 = (ns1.GetMembers("Runtime").Single() as NamespaceSymbol).GetMembers("Hosting").Single() as NamespaceSymbol; var class1 = ns2.GetTypeMembers("StrongNameHelpers").First() as NamedTypeSymbol; var members = class1.GetMembers("StrongNameSignatureGeneration"); var member1 = members.Last() as MethodSymbol; Assert.Equal(6, member1.Parameters.Length); var p1 = member1.Parameters[0] as ParameterSymbol; var p2 = member1.Parameters[1] as ParameterSymbol; var p3 = member1.Parameters[2] as ParameterSymbol; var p4 = member1.Parameters[3] as ParameterSymbol; var p5 = member1.Parameters[4] as ParameterSymbol; var p6 = member1.Parameters[5] as ParameterSymbol; Assert.Equal(mscorNS, p1.ContainingAssembly); Assert.Equal(class1, p1.ContainingType); Assert.Equal(member1, p1.ContainingSymbol); Assert.Equal(SymbolKind.Parameter, p1.Kind); Assert.Equal(Accessibility.NotApplicable, p1.DeclaredAccessibility); Assert.Equal("pwzFilePath", p1.Name); Assert.Equal("System.String pwzKeyContainer", p2.ToTestDisplayString()); Assert.Equal("String", p2.Type.Name); Assert.True(p2.IsDefinition); Assert.Equal("System.Byte[] bKeyBlob", p3.ToTestDisplayString()); Assert.Equal("System.Byte[]", p3.Type.ToTestDisplayString()); //array types do not have names - use ToTestDisplayString Assert.False(p1.IsStatic); Assert.False(p1.IsAbstract); Assert.False(p2.IsSealed); Assert.False(p2.IsVirtual); Assert.False(p3.IsOverride); Assert.False(p3.IsParams); Assert.False(p4.IsOptional); Assert.False(p4.HasExplicitDefaultValue); // Not Impl - out of scope // Assert.Null(p4.DefaultValue); Assert.Equal("ppbSignatureBlob", p5.Name); Assert.Equal("IntPtr", p5.Type.Name); Assert.Equal(RefKind.Ref, p5.RefKind); Assert.Equal("out System.Int32 pcbSignatureBlob", p6.ToTestDisplayString()); Assert.Equal(RefKind.Out, p6.RefKind); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [Fact] public void MetadataMethodSymbolGen02() { var text = "public class A {}"; var compilation = CreateCompilation(text); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); var ns1 = (mscorNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol).GetMembers("Collections").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Generic").Single() as NamespaceSymbol; var type1 = ns2.GetTypeMembers("IDictionary").First() as NamedTypeSymbol; var member1 = type1.GetMembers("Add").Single() as MethodSymbol; var member2 = type1.GetMembers("TryGetValue").Single() as MethodSymbol; Assert.Equal(mscorNS, member1.ContainingAssembly); Assert.Equal(type1, member1.ContainingSymbol); Assert.Equal(SymbolKind.Method, member1.Kind); // Not Impl //Assert.Equal(MethodKind.Ordinary, member2.MethodKind); Assert.Equal(Accessibility.Public, member2.DeclaredAccessibility); Assert.True(member2.IsDefinition); Assert.False(member1.IsStatic); Assert.True(member1.IsAbstract); Assert.False(member2.IsSealed); Assert.False(member2.IsVirtual); Assert.False(member2.IsOverride); //Assert.True(member1.IsOverloads); //Assert.True(member2.IsOverloads); Assert.False(member1.IsGenericMethod); // Not Impl //Assert.False(member1.IsExtensionMethod); Assert.True(member1.ReturnsVoid); Assert.False(member2.IsVararg); Assert.Equal(0, member1.TypeArgumentsWithAnnotations.Length); Assert.Equal(0, member2.TypeParameters.Length); Assert.Equal(2, member1.Parameters.Length); Assert.Equal("Boolean", member2.ReturnType.Name); Assert.Equal("System.Boolean System.Collections.Generic.IDictionary<TKey, TValue>.TryGetValue(TKey key, out TValue value)", member2.ToTestDisplayString()); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [Fact] public void MetadataParameterSymbolGen02() { var text = "public class A {}"; var compilation = CreateCompilation(text); var mscorlib = compilation.ExternalReferences[0]; var mscorNS = compilation.GetReferencedAssemblySymbol(mscorlib); var ns1 = (mscorNS.GlobalNamespace.GetMembers("System").Single() as NamespaceSymbol).GetMembers("Collections").Single() as NamespaceSymbol; var ns2 = ns1.GetMembers("Generic").Single() as NamespaceSymbol; var type1 = ns2.GetTypeMembers("IDictionary").First() as NamedTypeSymbol; var member1 = type1.GetMembers("TryGetValue").Single() as MethodSymbol; Assert.Equal(2, member1.Parameters.Length); var p1 = member1.Parameters[0] as ParameterSymbol; var p2 = member1.Parameters[1] as ParameterSymbol; Assert.Equal(mscorNS, p1.ContainingAssembly); Assert.Equal(type1, p2.ContainingType); Assert.Equal(member1, p1.ContainingSymbol); Assert.Equal(SymbolKind.Parameter, p2.Kind); Assert.Equal(Accessibility.NotApplicable, p1.DeclaredAccessibility); Assert.Equal("value", p2.Name); Assert.Equal("TKey key", p1.ToTestDisplayString()); // Empty // Assert.Equal("TValue", p2.Type.Name); Assert.True(p2.IsDefinition); Assert.False(p1.IsStatic); Assert.False(p1.IsAbstract); Assert.False(p2.IsSealed); Assert.False(p2.IsVirtual); Assert.False(p1.IsOverride); Assert.False(p1.IsExtern); Assert.False(p1.IsParams); Assert.False(p2.IsOptional); Assert.False(p2.HasExplicitDefaultValue); // Not Impl - Not in M2 scope // Assert.Null(p2.DefaultValue); Assert.Empty(compilation.GetDeclarationDiagnostics()); } [WorkItem(537424, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537424")] [Fact] public void MetadataMethodStaticAndInstanceCtor() { var text = @" class C { C() { } static C() { } }"; var compilation = CreateCompilation(text); Assert.False(compilation.GetDiagnostics().Any()); var classC = compilation.SourceModule.GlobalNamespace.GetTypeMembers("C").Single(); // NamedTypeSymbol.Constructors only contains instance constructors Assert.Equal(1, classC.InstanceConstructors.Length); Assert.Equal(1, classC.GetMembers(WellKnownMemberNames.StaticConstructorName).Length); } [ClrOnlyFact] public void ImportDecimalConstantAttribute() { const string ilSource = @" .class public C extends [mscorlib]System.Object { .field public static initonly valuetype [mscorlib]System.Decimal MyDecimalTen .custom instance void [mscorlib]System.Runtime.CompilerServices.DecimalConstantAttribute::.ctor(uint8, uint8, uint32, uint32, uint32) = ( 01 00 00 00 00 00 00 00 00 00 00 00 0A 00 00 00 00 00 ) } // end of class C"; const string cSharpSource = @" class B { static void Main() { var x = C.MyDecimalTen; System.Console.Write(x); } } "; CompileWithCustomILSource(cSharpSource, ilSource, expectedOutput: "10"); } [Fact] public void TypeAndNamespaceWithSameNameButDifferentArities() { var il = @" .class interface public abstract auto ansi A.B.C { } .class interface public abstract auto ansi A.B`1<T> { } "; var csharp = @""; var compilation = CreateCompilationWithILAndMscorlib40(csharp, il); var namespaceA = compilation.GlobalNamespace.GetMember<NamespaceSymbol>("A"); var members = namespaceA.GetMembers("B"); Assert.Equal(2, members.Length); Assert.NotNull(members[0]); Assert.NotNull(members[1]); } [Fact] public void TypeAndNamespaceWithSameNameAndArity() { var il = @" .class interface public abstract auto ansi A.B.C { } .class interface public abstract auto ansi A.B { } "; var csharp = @""; var compilation = CreateCompilationWithILAndMscorlib40(csharp, il); var namespaceA = compilation.GlobalNamespace.GetMember<NamespaceSymbol>("A"); var members = namespaceA.GetMembers("B"); Assert.Equal(2, members.Length); Assert.NotNull(members[0]); Assert.NotNull(members[1]); } // TODO: Update this test if we decide to include gaps in the symbol table for NoPIA (DevDiv #17472). [WorkItem(546951, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546951")] [Fact] public void VTableGapsNotInSymbolTable() { var csharp = @""; var comp = CreateCompilationWithILAndMscorlib40(csharp, VTableGapClassIL); comp.VerifyDiagnostics(); var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Class"); AssertEx.None(type.GetMembersUnordered(), symbol => symbol.Name.StartsWith("_VtblGap", StringComparison.Ordinal)); // Dropped entirely. Assert.Equal(0, type.GetMembers("_VtblGap1_1").Length); // Dropped entirely, since both accessors are dropped. Assert.Equal(0, type.GetMembers("BothAccessorsAreGaps").Length); // Getter is silently dropped, property appears valid and write-only. var propWithoutGetter = type.GetMember<PropertySymbol>("GetterIsGap"); Assert.Null(propWithoutGetter.GetMethod); Assert.NotNull(propWithoutGetter.SetMethod); Assert.False(propWithoutGetter.MustCallMethodsDirectly); // Setter is silently dropped, property appears valid and read-only. var propWithoutSetter = type.GetMember<PropertySymbol>("SetterIsGap"); Assert.NotNull(propWithoutSetter.GetMethod); Assert.Null(propWithoutSetter.SetMethod); Assert.False(propWithoutSetter.MustCallMethodsDirectly); } [WorkItem(546951, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546951")] [Fact] public void CallVTableGap() { var csharp = @" class Test { static void Main() { Class c = new Class(); c._VtblGap1_1(); // CS1061 int x; x = c.BothAccessorsAreGaps; // CS1061 c.BothAccessorsAreGaps = x; // CS1061 x = c.GetterIsGap; // CS0154 c.GetterIsGap = x; x = c.SetterIsGap; c.SetterIsGap = x; // CS0200 } } "; var comp = CreateCompilationWithILAndMscorlib40(csharp, VTableGapClassIL); comp.VerifyDiagnostics( // (8,11): error CS1061: 'Class' does not contain a definition for '_VtblGap1_1' and no extension method '_VtblGap1_1' accepting a first argument of type 'Class' could be found (are you missing a using directive or an assembly reference?) // c._VtblGap1_1(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "_VtblGap1_1").WithArguments("Class", "_VtblGap1_1"), // (12,15): error CS1061: 'Class' does not contain a definition for 'BothAccessorsAreGaps' and no extension method 'BothAccessorsAreGaps' accepting a first argument of type 'Class' could be found (are you missing a using directive or an assembly reference?) // x = c.BothAccessorsAreGaps; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "BothAccessorsAreGaps").WithArguments("Class", "BothAccessorsAreGaps"), // (13,11): error CS1061: 'Class' does not contain a definition for 'BothAccessorsAreGaps' and no extension method 'BothAccessorsAreGaps' accepting a first argument of type 'Class' could be found (are you missing a using directive or an assembly reference?) // c.BothAccessorsAreGaps = x; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "BothAccessorsAreGaps").WithArguments("Class", "BothAccessorsAreGaps"), // (15,13): error CS0154: The property or indexer 'Class.GetterIsGap' cannot be used in this context because it lacks the get accessor // x = c.GetterIsGap; Diagnostic(ErrorCode.ERR_PropertyLacksGet, "c.GetterIsGap").WithArguments("Class.GetterIsGap"), // (19,9): error CS0200: Property or indexer 'Class.SetterIsGap' cannot be assigned to -- it is read only // c.SetterIsGap = x; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "c.SetterIsGap").WithArguments("Class.SetterIsGap")); } [WorkItem(546951, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546951")] [Fact] public void ImplementVTableGap() { var csharp = @" class Empty : Interface { } class Implicit : Interface { public void _VtblGap1_1() { } public int GetterIsGap { get; set; } public int SetterIsGap { get; set; } public int BothAccessorsAreGaps { get; set; } } class Explicit : Interface { void Interface._VtblGap1_1() { } int Interface.GetterIsGap { get; set; } int Interface.SetterIsGap { get; set; } int Interface.BothAccessorsAreGaps { get; set; } } "; var comp = CreateCompilationWithILAndMscorlib40(csharp, VTableGapInterfaceIL); comp.VerifyDiagnostics( // (2,7): error CS0535: 'Empty' does not implement interface member 'Interface.SetterIsGap' // class Empty : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Empty", "Interface.SetterIsGap"), // (2,7): error CS0535: 'Empty' does not implement interface member 'Interface.GetterIsGap' // class Empty : Interface Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Empty", "Interface.GetterIsGap"), // (17,33): error CS0550: 'Explicit.Interface.GetterIsGap.get' adds an accessor not found in interface member 'Interface.GetterIsGap' // int Interface.GetterIsGap { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("Explicit.Interface.GetterIsGap.get", "Interface.GetterIsGap"), // (18,38): error CS0550: 'Explicit.Interface.SetterIsGap.set' adds an accessor not found in interface member 'Interface.SetterIsGap' // int Interface.SetterIsGap { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("Explicit.Interface.SetterIsGap.set", "Interface.SetterIsGap"), // (19,19): error CS0539: 'Explicit.BothAccessorsAreGaps' in explicit interface declaration is not a member of interface // int Interface.BothAccessorsAreGaps { get; set; } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "BothAccessorsAreGaps").WithArguments("Explicit.BothAccessorsAreGaps"), // (16,20): error CS0539: 'Explicit._VtblGap1_1()' in explicit interface declaration is not a member of interface // void Interface._VtblGap1_1() { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "_VtblGap1_1").WithArguments("Explicit._VtblGap1_1()")); } [Fact, WorkItem(1094411, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1094411")] public void Bug1094411_01() { var source1 = @" class Test { public int F; public int P {get; set;} public event System.Action E { add { } remove { } } public void M() {} } "; var members = new[] { "F", "P", "E", "M" }; var comp1 = CreateCompilation(source1, options: TestOptions.ReleaseDll); var test1 = comp1.GetTypeByMetadataName("Test"); var memberNames1 = new HashSet<string>(test1.MemberNames); foreach (var m in members) { Assert.True(memberNames1.Contains(m), m); } var comp2 = CreateCompilation("", new[] { comp1.EmitToImageReference() }); var test2 = comp2.GetTypeByMetadataName("Test"); var memberNames2 = new HashSet<string>(test2.MemberNames); foreach (var m in members) { Assert.True(memberNames2.Contains(m), m); } } [Fact, WorkItem(1094411, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1094411")] public void Bug1094411_02() { var source1 = @" class Test { public int F; public int P {get; set;} public event System.Action E { add { } remove { } } public void M() {} } "; var members = new[] { "F", "P", "E", "M" }; var comp1 = CreateCompilation(source1, options: TestOptions.ReleaseDll); var test1 = comp1.GetTypeByMetadataName("Test"); test1.GetMembers(); var memberNames1 = new HashSet<string>(test1.MemberNames); foreach (var m in members) { Assert.True(memberNames1.Contains(m), m); } var comp2 = CreateCompilation("", new[] { comp1.EmitToImageReference() }); var test2 = comp2.GetTypeByMetadataName("Test"); test2.GetMembers(); var memberNames2 = new HashSet<string>(test2.MemberNames); foreach (var m in members) { Assert.True(memberNames2.Contains(m), m); } } [Fact] public void TestMetadataImportOptions_01() { var expectedDiagnostics = new[] { // error CS7088: Invalid 'MetadataImportOptions' value: '255'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("MetadataImportOptions", "255").WithLocation(1, 1) }; var options = TestOptions.DebugDll; Assert.Equal(MetadataImportOptions.Public, options.MetadataImportOptions); options.VerifyErrors(); options = options.WithMetadataImportOptions(MetadataImportOptions.Internal); Assert.Equal(MetadataImportOptions.Internal, options.MetadataImportOptions); options.VerifyErrors(); options = options.WithMetadataImportOptions(MetadataImportOptions.All); Assert.Equal(MetadataImportOptions.All, options.MetadataImportOptions); options.VerifyErrors(); options = options.WithMetadataImportOptions(MetadataImportOptions.Public); Assert.Equal(MetadataImportOptions.Public, options.MetadataImportOptions); options.VerifyErrors(); options = options.WithMetadataImportOptions((MetadataImportOptions)byte.MaxValue); Assert.Equal((MetadataImportOptions)byte.MaxValue, options.MetadataImportOptions); options.VerifyErrors(expectedDiagnostics); var commonOptions = (CompilationOptions)options; commonOptions = commonOptions.WithMetadataImportOptions(MetadataImportOptions.Internal); Assert.Equal(MetadataImportOptions.Internal, ((CSharpCompilationOptions)commonOptions).MetadataImportOptions); ((CSharpCompilationOptions)commonOptions).VerifyErrors(); commonOptions = commonOptions.WithMetadataImportOptions(MetadataImportOptions.All); Assert.Equal(MetadataImportOptions.All, ((CSharpCompilationOptions)commonOptions).MetadataImportOptions); ((CSharpCompilationOptions)commonOptions).VerifyErrors(); commonOptions = commonOptions.WithMetadataImportOptions(MetadataImportOptions.Public); Assert.Equal(MetadataImportOptions.Public, ((CSharpCompilationOptions)commonOptions).MetadataImportOptions); ((CSharpCompilationOptions)commonOptions).VerifyErrors(); commonOptions = commonOptions.WithMetadataImportOptions((MetadataImportOptions)byte.MaxValue); Assert.Equal((MetadataImportOptions)byte.MaxValue, ((CSharpCompilationOptions)commonOptions).MetadataImportOptions); ((CSharpCompilationOptions)commonOptions).VerifyErrors(expectedDiagnostics); var source = @" public class C { public int P1 {get; set;} internal int P2 {get; set;} private int P3 {get; set;} } "; var compilation0 = CreateCompilation(source); options = TestOptions.DebugDll; var compilation = CreateCompilation("", options: options, references: new[] { compilation0.EmitToImageReference() }); var c = compilation.GetTypeByMetadataName("C"); Assert.NotEmpty(c.GetMembers("P1")); Assert.Empty(c.GetMembers("P2")); Assert.Empty(c.GetMembers("P3")); CompileAndVerify(compilation); compilation = compilation.WithOptions(options.WithMetadataImportOptions(MetadataImportOptions.Internal)); c = compilation.GetTypeByMetadataName("C"); Assert.NotEmpty(c.GetMembers("P1")); Assert.NotEmpty(c.GetMembers("P2")); Assert.Empty(c.GetMembers("P3")); CompileAndVerify(compilation); compilation = compilation.WithOptions(options.WithMetadataImportOptions(MetadataImportOptions.All)); c = compilation.GetTypeByMetadataName("C"); Assert.NotEmpty(c.GetMembers("P1")); Assert.NotEmpty(c.GetMembers("P2")); Assert.NotEmpty(c.GetMembers("P3")); CompileAndVerify(compilation); compilation = compilation.WithOptions(options.WithMetadataImportOptions((MetadataImportOptions)byte.MaxValue)); c = compilation.GetTypeByMetadataName("C"); Assert.NotEmpty(c.GetMembers("P1")); Assert.NotEmpty(c.GetMembers("P2")); Assert.Empty(c.GetMembers("P3")); compilation.VerifyEmitDiagnostics(expectedDiagnostics); compilation.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void TestMetadataImportOptions_02() { var expectedDiagnostics = new[] { // error CS7088: Invalid 'MetadataImportOptions' value: '255'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("MetadataImportOptions", "255").WithLocation(1, 1) }; var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.Internal); Assert.Equal(MetadataImportOptions.Internal, options.MetadataImportOptions); options.VerifyErrors(); options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All); Assert.Equal(MetadataImportOptions.All, options.MetadataImportOptions); options.VerifyErrors(); options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.Public); Assert.Equal(MetadataImportOptions.Public, options.MetadataImportOptions); options.VerifyErrors(); options = TestOptions.DebugDll.WithMetadataImportOptions((MetadataImportOptions)byte.MaxValue); Assert.Equal((MetadataImportOptions)byte.MaxValue, options.MetadataImportOptions); options.VerifyErrors(expectedDiagnostics); var source = @" public class C { public int P1 {get; set;} internal int P2 {get; set;} private int P3 {get; set;} } "; var compilation0 = CreateCompilation(source); var compilation = CreateCompilation("", options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.Internal), references: new[] { compilation0.EmitToImageReference() }); var c = compilation.GetTypeByMetadataName("C"); Assert.NotEmpty(c.GetMembers("P1")); Assert.NotEmpty(c.GetMembers("P2")); Assert.Empty(c.GetMembers("P3")); CompileAndVerify(compilation); compilation = compilation.WithOptions(TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); c = compilation.GetTypeByMetadataName("C"); Assert.NotEmpty(c.GetMembers("P1")); Assert.NotEmpty(c.GetMembers("P2")); Assert.NotEmpty(c.GetMembers("P3")); CompileAndVerify(compilation); compilation = compilation.WithOptions(TestOptions.DebugDll.WithMetadataImportOptions((MetadataImportOptions)byte.MaxValue)); c = compilation.GetTypeByMetadataName("C"); Assert.NotEmpty(c.GetMembers("P1")); Assert.NotEmpty(c.GetMembers("P2")); Assert.Empty(c.GetMembers("P3")); compilation.VerifyEmitDiagnostics(expectedDiagnostics); compilation.VerifyDiagnostics(expectedDiagnostics); } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/VisualStudio/Core/Def/Implementation/Library/ObjectBrowser/Lists/SymbolListItem.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 Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists { internal abstract class SymbolListItem : ObjectListItem { private readonly SymbolKey _symbolKey; private readonly Accessibility _accessibility; private readonly string _displayText; private readonly string _fullNameText; private readonly string _searchText; private readonly bool _supportsGoToDefinition; private readonly bool _supportsFindAllReferences; protected SymbolListItem(ProjectId projectId, ISymbol symbol, string displayText, string fullNameText, string searchText, bool isHidden) : base(projectId, symbol.GetGlyph().GetStandardGlyphGroup(), symbol.GetGlyph().GetStandardGlyphItem(), isHidden) { _symbolKey = symbol.GetSymbolKey(); _accessibility = symbol.DeclaredAccessibility; _displayText = displayText; _fullNameText = fullNameText; _searchText = searchText; _supportsGoToDefinition = symbol.Kind != SymbolKind.Namespace ? symbol.Locations.Any(l => l.IsInSource) : false; _supportsFindAllReferences = symbol.Kind != SymbolKind.Namespace; } public Accessibility Accessibility { get { return _accessibility; } } public override string DisplayText { get { return _displayText; } } public override string FullNameText { get { return _fullNameText; } } public override string SearchText { get { return _searchText; } } public override bool SupportsGoToDefinition { get { return _supportsGoToDefinition; } } public override bool SupportsFindAllReferences { get { return _supportsFindAllReferences; } } public ISymbol ResolveSymbol(Compilation compilation) => _symbolKey.Resolve(compilation, ignoreAssemblyKey: false).Symbol; } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists { internal abstract class SymbolListItem : ObjectListItem { private readonly SymbolKey _symbolKey; private readonly Accessibility _accessibility; private readonly string _displayText; private readonly string _fullNameText; private readonly string _searchText; private readonly bool _supportsGoToDefinition; private readonly bool _supportsFindAllReferences; protected SymbolListItem(ProjectId projectId, ISymbol symbol, string displayText, string fullNameText, string searchText, bool isHidden) : base(projectId, symbol.GetGlyph().GetStandardGlyphGroup(), symbol.GetGlyph().GetStandardGlyphItem(), isHidden) { _symbolKey = symbol.GetSymbolKey(); _accessibility = symbol.DeclaredAccessibility; _displayText = displayText; _fullNameText = fullNameText; _searchText = searchText; _supportsGoToDefinition = symbol.Kind != SymbolKind.Namespace ? symbol.Locations.Any(l => l.IsInSource) : false; _supportsFindAllReferences = symbol.Kind != SymbolKind.Namespace; } public Accessibility Accessibility { get { return _accessibility; } } public override string DisplayText { get { return _displayText; } } public override string FullNameText { get { return _fullNameText; } } public override string SearchText { get { return _searchText; } } public override bool SupportsGoToDefinition { get { return _supportsGoToDefinition; } } public override bool SupportsFindAllReferences { get { return _supportsFindAllReferences; } } public ISymbol ResolveSymbol(Compilation compilation) => _symbolKey.Resolve(compilation, ignoreAssemblyKey: false).Symbol; } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Analyzers/VisualBasic/Analyzers/NamingStyle/VisualBasicNamingStyleDiagnosticAnalyzer.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.Diagnostics Imports Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles Namespace Microsoft.CodeAnalysis.VisualBasic.Diagnostics.Analyzers <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Friend NotInheritable Class VisualBasicNamingStyleDiagnosticAnalyzer Inherits NamingStyleDiagnosticAnalyzerBase(Of SyntaxKind) Protected Overrides ReadOnly Property SupportedSyntaxKinds As ImmutableArray(Of SyntaxKind) = ImmutableArray.Create( SyntaxKind.ModifiedIdentifier, SyntaxKind.CatchStatement, SyntaxKind.Parameter, SyntaxKind.TypeParameter) Protected Overrides Function ShouldIgnore(symbol As ISymbol) As Boolean If symbol.IsExtern Then ' Extern symbols are mainly P/Invoke And runtime invoke, probably requiring their name ' to match external definition exactly. ' Simply ignoring them. Return True End If Return False 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.Diagnostics Imports Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles Namespace Microsoft.CodeAnalysis.VisualBasic.Diagnostics.Analyzers <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Friend NotInheritable Class VisualBasicNamingStyleDiagnosticAnalyzer Inherits NamingStyleDiagnosticAnalyzerBase(Of SyntaxKind) Protected Overrides ReadOnly Property SupportedSyntaxKinds As ImmutableArray(Of SyntaxKind) = ImmutableArray.Create( SyntaxKind.ModifiedIdentifier, SyntaxKind.CatchStatement, SyntaxKind.Parameter, SyntaxKind.TypeParameter) Protected Overrides Function ShouldIgnore(symbol As ISymbol) As Boolean If symbol.IsExtern Then ' Extern symbols are mainly P/Invoke And runtime invoke, probably requiring their name ' to match external definition exactly. ' Simply ignoring them. Return True End If Return False End Function End Class End Namespace
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/ExpressionEvaluator/Core/Source/ExpressionCompiler/MetadataContextId.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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { // Wrapper around Guid to ensure callers have asked for the correct id // rather than simply using the ModuleVersionId (which is unnecessary // when the Compilation references all loaded assemblies). internal readonly struct MetadataContextId : IEquatable<MetadataContextId> { internal readonly Guid ModuleVersionId; internal MetadataContextId(Guid moduleVersionId) { ModuleVersionId = moduleVersionId; } public bool Equals(MetadataContextId other) => ModuleVersionId.Equals(other.ModuleVersionId); public override bool Equals(object obj) => obj is MetadataContextId && Equals((MetadataContextId)obj); public override int GetHashCode() => ModuleVersionId.GetHashCode(); internal static MetadataContextId GetContextId(Guid moduleVersionId, MakeAssemblyReferencesKind kind) { return kind switch { MakeAssemblyReferencesKind.AllAssemblies => default, MakeAssemblyReferencesKind.AllReferences => new MetadataContextId(moduleVersionId), _ => throw ExceptionUtilities.UnexpectedValue(kind), }; } } }
// Licensed to the .NET Foundation under one or more 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { // Wrapper around Guid to ensure callers have asked for the correct id // rather than simply using the ModuleVersionId (which is unnecessary // when the Compilation references all loaded assemblies). internal readonly struct MetadataContextId : IEquatable<MetadataContextId> { internal readonly Guid ModuleVersionId; internal MetadataContextId(Guid moduleVersionId) { ModuleVersionId = moduleVersionId; } public bool Equals(MetadataContextId other) => ModuleVersionId.Equals(other.ModuleVersionId); public override bool Equals(object obj) => obj is MetadataContextId && Equals((MetadataContextId)obj); public override int GetHashCode() => ModuleVersionId.GetHashCode(); internal static MetadataContextId GetContextId(Guid moduleVersionId, MakeAssemblyReferencesKind kind) { return kind switch { MakeAssemblyReferencesKind.AllAssemblies => default, MakeAssemblyReferencesKind.AllReferences => new MetadataContextId(moduleVersionId), _ => throw ExceptionUtilities.UnexpectedValue(kind), }; } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/CSharp/Portable/Symbols/PublicModel/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.Collections.Generic; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel { internal abstract class TypeSymbol : NamespaceOrTypeSymbol, ISymbol, ITypeSymbol { protected TypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation) { NullableAnnotation = nullableAnnotation; } protected CodeAnalysis.NullableAnnotation NullableAnnotation { get; } protected abstract ITypeSymbol WithNullableAnnotation(CodeAnalysis.NullableAnnotation nullableAnnotation); internal abstract Symbols.TypeSymbol UnderlyingTypeSymbol { get; } CodeAnalysis.NullableAnnotation ITypeSymbol.NullableAnnotation => NullableAnnotation; ITypeSymbol ITypeSymbol.WithNullableAnnotation(CodeAnalysis.NullableAnnotation nullableAnnotation) { if (NullableAnnotation == nullableAnnotation) { return this; } else if (nullableAnnotation == UnderlyingTypeSymbol.DefaultNullableAnnotation) { return (ITypeSymbol)UnderlyingSymbol.ISymbol; } return WithNullableAnnotation(nullableAnnotation); } bool ISymbol.IsDefinition { get { return (object)this == ((ISymbol)this).OriginalDefinition; } } bool ISymbol.Equals(ISymbol other, CodeAnalysis.SymbolEqualityComparer equalityComparer) { return this.Equals(other as TypeSymbol, equalityComparer); } protected bool Equals(TypeSymbol otherType, CodeAnalysis.SymbolEqualityComparer equalityComparer) { if (otherType is null) { return false; } else if ((object)otherType == this) { return true; } var compareKind = equalityComparer.CompareKind; if (NullableAnnotation != otherType.NullableAnnotation && (compareKind & TypeCompareKind.IgnoreNullableModifiersForReferenceTypes) == 0 && ((compareKind & TypeCompareKind.ObliviousNullableModifierMatchesAny) == 0 || (NullableAnnotation != CodeAnalysis.NullableAnnotation.None && otherType.NullableAnnotation != CodeAnalysis.NullableAnnotation.None)) && !(UnderlyingTypeSymbol.IsValueType && !UnderlyingTypeSymbol.IsNullableType())) { return false; } return UnderlyingTypeSymbol.Equals(otherType.UnderlyingTypeSymbol, compareKind); } ITypeSymbol ITypeSymbol.OriginalDefinition { get { return UnderlyingTypeSymbol.OriginalDefinition.GetPublicSymbol(); } } INamedTypeSymbol ITypeSymbol.BaseType { get { return UnderlyingTypeSymbol.BaseTypeNoUseSiteDiagnostics.GetPublicSymbol(); } } ImmutableArray<INamedTypeSymbol> ITypeSymbol.Interfaces { get { return UnderlyingTypeSymbol.InterfacesNoUseSiteDiagnostics().GetPublicSymbols(); } } ImmutableArray<INamedTypeSymbol> ITypeSymbol.AllInterfaces { get { return UnderlyingTypeSymbol.AllInterfacesNoUseSiteDiagnostics.GetPublicSymbols(); } } ISymbol ITypeSymbol.FindImplementationForInterfaceMember(ISymbol interfaceMember) { return interfaceMember is Symbol symbol ? UnderlyingTypeSymbol.FindImplementationForInterfaceMember(symbol.UnderlyingSymbol).GetPublicSymbol() : null; } bool ITypeSymbol.IsUnmanagedType => !UnderlyingTypeSymbol.IsManagedTypeNoUseSiteDiagnostics; bool ITypeSymbol.IsReferenceType { get { return UnderlyingTypeSymbol.IsReferenceType; } } bool ITypeSymbol.IsValueType { get { return UnderlyingTypeSymbol.IsValueType; } } TypeKind ITypeSymbol.TypeKind { get { return UnderlyingTypeSymbol.TypeKind; } } bool ITypeSymbol.IsTupleType => UnderlyingTypeSymbol.IsTupleType; bool ITypeSymbol.IsNativeIntegerType => UnderlyingTypeSymbol.IsNativeIntegerType; string ITypeSymbol.ToDisplayString(CodeAnalysis.NullableFlowState topLevelNullability, SymbolDisplayFormat format) { return SymbolDisplay.ToDisplayString(this, topLevelNullability, format); } ImmutableArray<SymbolDisplayPart> ITypeSymbol.ToDisplayParts(CodeAnalysis.NullableFlowState topLevelNullability, SymbolDisplayFormat format) { return SymbolDisplay.ToDisplayParts(this, topLevelNullability, format); } string ITypeSymbol.ToMinimalDisplayString(SemanticModel semanticModel, CodeAnalysis.NullableFlowState topLevelNullability, int position, SymbolDisplayFormat format) { return SymbolDisplay.ToMinimalDisplayString(this, topLevelNullability, semanticModel, position, format); } ImmutableArray<SymbolDisplayPart> ITypeSymbol.ToMinimalDisplayParts(SemanticModel semanticModel, CodeAnalysis.NullableFlowState topLevelNullability, int position, SymbolDisplayFormat format) { return SymbolDisplay.ToMinimalDisplayParts(this, topLevelNullability, semanticModel, position, format); } bool ITypeSymbol.IsAnonymousType => UnderlyingTypeSymbol.IsAnonymousType; SpecialType ITypeSymbol.SpecialType => UnderlyingTypeSymbol.SpecialType; bool ITypeSymbol.IsRefLikeType => UnderlyingTypeSymbol.IsRefLikeType; bool ITypeSymbol.IsReadOnly => UnderlyingTypeSymbol.IsReadOnly; bool ITypeSymbol.IsRecord => UnderlyingTypeSymbol.IsRecord || UnderlyingTypeSymbol.IsRecordStruct; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel { internal abstract class TypeSymbol : NamespaceOrTypeSymbol, ISymbol, ITypeSymbol { protected TypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation) { NullableAnnotation = nullableAnnotation; } protected CodeAnalysis.NullableAnnotation NullableAnnotation { get; } protected abstract ITypeSymbol WithNullableAnnotation(CodeAnalysis.NullableAnnotation nullableAnnotation); internal abstract Symbols.TypeSymbol UnderlyingTypeSymbol { get; } CodeAnalysis.NullableAnnotation ITypeSymbol.NullableAnnotation => NullableAnnotation; ITypeSymbol ITypeSymbol.WithNullableAnnotation(CodeAnalysis.NullableAnnotation nullableAnnotation) { if (NullableAnnotation == nullableAnnotation) { return this; } else if (nullableAnnotation == UnderlyingTypeSymbol.DefaultNullableAnnotation) { return (ITypeSymbol)UnderlyingSymbol.ISymbol; } return WithNullableAnnotation(nullableAnnotation); } bool ISymbol.IsDefinition { get { return (object)this == ((ISymbol)this).OriginalDefinition; } } bool ISymbol.Equals(ISymbol other, CodeAnalysis.SymbolEqualityComparer equalityComparer) { return this.Equals(other as TypeSymbol, equalityComparer); } protected bool Equals(TypeSymbol otherType, CodeAnalysis.SymbolEqualityComparer equalityComparer) { if (otherType is null) { return false; } else if ((object)otherType == this) { return true; } var compareKind = equalityComparer.CompareKind; if (NullableAnnotation != otherType.NullableAnnotation && (compareKind & TypeCompareKind.IgnoreNullableModifiersForReferenceTypes) == 0 && ((compareKind & TypeCompareKind.ObliviousNullableModifierMatchesAny) == 0 || (NullableAnnotation != CodeAnalysis.NullableAnnotation.None && otherType.NullableAnnotation != CodeAnalysis.NullableAnnotation.None)) && !(UnderlyingTypeSymbol.IsValueType && !UnderlyingTypeSymbol.IsNullableType())) { return false; } return UnderlyingTypeSymbol.Equals(otherType.UnderlyingTypeSymbol, compareKind); } ITypeSymbol ITypeSymbol.OriginalDefinition { get { return UnderlyingTypeSymbol.OriginalDefinition.GetPublicSymbol(); } } INamedTypeSymbol ITypeSymbol.BaseType { get { return UnderlyingTypeSymbol.BaseTypeNoUseSiteDiagnostics.GetPublicSymbol(); } } ImmutableArray<INamedTypeSymbol> ITypeSymbol.Interfaces { get { return UnderlyingTypeSymbol.InterfacesNoUseSiteDiagnostics().GetPublicSymbols(); } } ImmutableArray<INamedTypeSymbol> ITypeSymbol.AllInterfaces { get { return UnderlyingTypeSymbol.AllInterfacesNoUseSiteDiagnostics.GetPublicSymbols(); } } ISymbol ITypeSymbol.FindImplementationForInterfaceMember(ISymbol interfaceMember) { return interfaceMember is Symbol symbol ? UnderlyingTypeSymbol.FindImplementationForInterfaceMember(symbol.UnderlyingSymbol).GetPublicSymbol() : null; } bool ITypeSymbol.IsUnmanagedType => !UnderlyingTypeSymbol.IsManagedTypeNoUseSiteDiagnostics; bool ITypeSymbol.IsReferenceType { get { return UnderlyingTypeSymbol.IsReferenceType; } } bool ITypeSymbol.IsValueType { get { return UnderlyingTypeSymbol.IsValueType; } } TypeKind ITypeSymbol.TypeKind { get { return UnderlyingTypeSymbol.TypeKind; } } bool ITypeSymbol.IsTupleType => UnderlyingTypeSymbol.IsTupleType; bool ITypeSymbol.IsNativeIntegerType => UnderlyingTypeSymbol.IsNativeIntegerType; string ITypeSymbol.ToDisplayString(CodeAnalysis.NullableFlowState topLevelNullability, SymbolDisplayFormat format) { return SymbolDisplay.ToDisplayString(this, topLevelNullability, format); } ImmutableArray<SymbolDisplayPart> ITypeSymbol.ToDisplayParts(CodeAnalysis.NullableFlowState topLevelNullability, SymbolDisplayFormat format) { return SymbolDisplay.ToDisplayParts(this, topLevelNullability, format); } string ITypeSymbol.ToMinimalDisplayString(SemanticModel semanticModel, CodeAnalysis.NullableFlowState topLevelNullability, int position, SymbolDisplayFormat format) { return SymbolDisplay.ToMinimalDisplayString(this, topLevelNullability, semanticModel, position, format); } ImmutableArray<SymbolDisplayPart> ITypeSymbol.ToMinimalDisplayParts(SemanticModel semanticModel, CodeAnalysis.NullableFlowState topLevelNullability, int position, SymbolDisplayFormat format) { return SymbolDisplay.ToMinimalDisplayParts(this, topLevelNullability, semanticModel, position, format); } bool ITypeSymbol.IsAnonymousType => UnderlyingTypeSymbol.IsAnonymousType; SpecialType ITypeSymbol.SpecialType => UnderlyingTypeSymbol.SpecialType; bool ITypeSymbol.IsRefLikeType => UnderlyingTypeSymbol.IsRefLikeType; bool ITypeSymbol.IsReadOnly => UnderlyingTypeSymbol.IsReadOnly; bool ITypeSymbol.IsRecord => UnderlyingTypeSymbol.IsRecord || UnderlyingTypeSymbol.IsRecordStruct; } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/VisualStudio/Core/Impl/Options/OptionBinding.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.ComponentModel; using Microsoft.CodeAnalysis.Options; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { internal class OptionBinding<T> : INotifyPropertyChanged { private readonly OptionStore _optionStore; private readonly Option2<T> _key; public event PropertyChangedEventHandler PropertyChanged; public OptionBinding(OptionStore optionStore, Option2<T> key) { _optionStore = optionStore; _key = key; _optionStore.OptionChanged += (sender, e) => { if (e.Option == _key) { PropertyChanged?.Raise(this, new PropertyChangedEventArgs(nameof(Value))); } }; } public T Value { get { return _optionStore.GetOption(_key); } set { _optionStore.SetOption(_key, 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. #nullable disable using System.ComponentModel; using Microsoft.CodeAnalysis.Options; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { internal class OptionBinding<T> : INotifyPropertyChanged { private readonly OptionStore _optionStore; private readonly Option2<T> _key; public event PropertyChangedEventHandler PropertyChanged; public OptionBinding(OptionStore optionStore, Option2<T> key) { _optionStore = optionStore; _key = key; _optionStore.OptionChanged += (sender, e) => { if (e.Option == _key) { PropertyChanged?.Raise(this, new PropertyChangedEventArgs(nameof(Value))); } }; } public T Value { get { return _optionStore.GetOption(_key); } set { _optionStore.SetOption(_key, value); } } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Workspaces/Core/Portable/Workspace/Host/HostWorkspaceServices.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { /// <summary> /// Per workspace services provided by the host environment. /// </summary> public abstract class HostWorkspaceServices { /// <summary> /// The host services this workspace services originated from. /// </summary> /// <returns></returns> public abstract HostServices HostServices { get; } /// <summary> /// The workspace corresponding to this workspace services instantiation /// </summary> public abstract Workspace Workspace { get; } /// <summary> /// Gets a workspace specific service provided by the host identified by the service type. /// If the host does not provide the service, this method returns null. /// </summary> public abstract TWorkspaceService? GetService<TWorkspaceService>() where TWorkspaceService : IWorkspaceService; /// <summary> /// Gets a workspace specific service provided by the host identified by the service type. /// If the host does not provide the service, this method throws <see cref="InvalidOperationException"/>. /// </summary> /// <exception cref="InvalidOperationException">The host does not provide the service.</exception> public TWorkspaceService GetRequiredService<TWorkspaceService>() where TWorkspaceService : IWorkspaceService { var service = GetService<TWorkspaceService>(); if (service == null) { throw new InvalidOperationException(string.Format(WorkspacesResources.Service_of_type_0_is_required_to_accomplish_the_task_but_is_not_available_from_the_workspace, typeof(TWorkspaceService).FullName)); } return service; } /// <summary> /// A service for storing information across that can be retrieved in a separate process. /// </summary> public virtual IPersistentStorageService PersistentStorage { get { return this.GetRequiredService<IPersistentStorageService>(); } } /// <summary> /// A service for storing information in a temporary location that only lasts for the duration of the process. /// </summary> public virtual ITemporaryStorageService TemporaryStorage { get { return this.GetRequiredService<ITemporaryStorageService>(); } } /// <summary> /// A factory that constructs <see cref="SourceText"/>. /// </summary> internal virtual ITextFactoryService TextFactory { get { return this.GetRequiredService<ITextFactoryService>(); } } /// <summary> /// A list of language names for supported language services. /// </summary> public virtual IEnumerable<string> SupportedLanguages { get { return SpecializedCollections.EmptyEnumerable<string>(); } } /// <summary> /// Returns true if the language is supported. /// </summary> public virtual bool IsSupported(string languageName) => false; /// <summary> /// Gets the <see cref="HostLanguageServices"/> for the language name. /// </summary> /// <exception cref="NotSupportedException">Thrown if the language isn't supported.</exception> public virtual HostLanguageServices GetLanguageServices(string languageName) => throw new NotSupportedException(string.Format(WorkspacesResources.The_language_0_is_not_supported, languageName)); public delegate bool MetadataFilter(IReadOnlyDictionary<string, object> metadata); /// <summary> /// Finds all language services of the corresponding type across all supported languages that match the filter criteria. /// </summary> public abstract IEnumerable<TLanguageService> FindLanguageServices<TLanguageService>(MetadataFilter filter); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { /// <summary> /// Per workspace services provided by the host environment. /// </summary> public abstract class HostWorkspaceServices { /// <summary> /// The host services this workspace services originated from. /// </summary> /// <returns></returns> public abstract HostServices HostServices { get; } /// <summary> /// The workspace corresponding to this workspace services instantiation /// </summary> public abstract Workspace Workspace { get; } /// <summary> /// Gets a workspace specific service provided by the host identified by the service type. /// If the host does not provide the service, this method returns null. /// </summary> public abstract TWorkspaceService? GetService<TWorkspaceService>() where TWorkspaceService : IWorkspaceService; /// <summary> /// Gets a workspace specific service provided by the host identified by the service type. /// If the host does not provide the service, this method throws <see cref="InvalidOperationException"/>. /// </summary> /// <exception cref="InvalidOperationException">The host does not provide the service.</exception> public TWorkspaceService GetRequiredService<TWorkspaceService>() where TWorkspaceService : IWorkspaceService { var service = GetService<TWorkspaceService>(); if (service == null) { throw new InvalidOperationException(string.Format(WorkspacesResources.Service_of_type_0_is_required_to_accomplish_the_task_but_is_not_available_from_the_workspace, typeof(TWorkspaceService).FullName)); } return service; } /// <summary> /// A service for storing information across that can be retrieved in a separate process. /// </summary> public virtual IPersistentStorageService PersistentStorage { get { return this.GetRequiredService<IPersistentStorageService>(); } } /// <summary> /// A service for storing information in a temporary location that only lasts for the duration of the process. /// </summary> public virtual ITemporaryStorageService TemporaryStorage { get { return this.GetRequiredService<ITemporaryStorageService>(); } } /// <summary> /// A factory that constructs <see cref="SourceText"/>. /// </summary> internal virtual ITextFactoryService TextFactory { get { return this.GetRequiredService<ITextFactoryService>(); } } /// <summary> /// A list of language names for supported language services. /// </summary> public virtual IEnumerable<string> SupportedLanguages { get { return SpecializedCollections.EmptyEnumerable<string>(); } } /// <summary> /// Returns true if the language is supported. /// </summary> public virtual bool IsSupported(string languageName) => false; /// <summary> /// Gets the <see cref="HostLanguageServices"/> for the language name. /// </summary> /// <exception cref="NotSupportedException">Thrown if the language isn't supported.</exception> public virtual HostLanguageServices GetLanguageServices(string languageName) => throw new NotSupportedException(string.Format(WorkspacesResources.The_language_0_is_not_supported, languageName)); public delegate bool MetadataFilter(IReadOnlyDictionary<string, object> metadata); /// <summary> /// Finds all language services of the corresponding type across all supported languages that match the filter criteria. /// </summary> public abstract IEnumerable<TLanguageService> FindLanguageServices<TLanguageService>(MetadataFilter filter); } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Features/Core/Portable/GoToDefinition/IGoToDefinitionSymbolService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.GoToDefinition { internal interface IGoToDefinitionSymbolService : ILanguageService { Task<(ISymbol?, TextSpan)> GetSymbolAndBoundSpanAsync(Document document, int position, bool includeType, CancellationToken cancellationToken); /// <summary> /// If the position is on a control flow keyword (continue, break, yield, return , etc), returns the relevant position in the corresponding control flow statement. /// Otherwise, returns null. /// </summary> Task<int?> GetTargetIfControlFlowAsync(Document document, int position, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.GoToDefinition { internal interface IGoToDefinitionSymbolService : ILanguageService { Task<(ISymbol?, TextSpan)> GetSymbolAndBoundSpanAsync(Document document, int position, bool includeType, CancellationToken cancellationToken); /// <summary> /// If the position is on a control flow keyword (continue, break, yield, return , etc), returns the relevant position in the corresponding control flow statement. /// Otherwise, returns null. /// </summary> Task<int?> GetTargetIfControlFlowAsync(Document document, int position, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/Test/Resources/Core/SymbolsTests/MultiTargeting/Source5Module.netmodule
MZ@ !L!This program cannot be run in DOS mode. $PEL+L ." @@ `@!W@  H.text4  `.reloc @@B"HX |( *BSJB v4.0.30319l#~ H#StringsT#US\#GUIDl#BlobG%3- " P ' '  <Module>mscorlibC5c3ns1C304C305.ctorSource5Module.netmodule |(rN΀vMz\V4 !" "_CorExeMainmscoree.dll% @ 02
MZ@ !L!This program cannot be run in DOS mode. $PEL+L ." @@ `@!W@  H.text4  `.reloc @@B"HX |( *BSJB v4.0.30319l#~ H#StringsT#US\#GUIDl#BlobG%3- " P ' '  <Module>mscorlibC5c3ns1C304C305.ctorSource5Module.netmodule |(rN΀vMz\V4 !" "_CorExeMainmscoree.dll% @ 02
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/EditorFeatures/CSharpTest/EditAndContinue/ActiveStatementTests.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.CSharp.Syntax; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.CSharp.UnitTests; using System.Linq; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { [UseExportProvider] public class ActiveStatementTests : EditingTestBase { #region Update [Fact] public void Update_Inner() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { while (true) { <AS:1>Goo(2);</AS:1> } } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "Goo(2);")); } [Fact] public void Update_Inner_NewCommentAtEndOfActiveStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1>// } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } /// <summary> /// CreateNewOnMetadataUpdate has no effect in presence of active statements (in break mode). /// </summary> [Fact] public void Update_Inner_Reloadable() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C { static void Main() { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C { static void Main() { while (true) { <AS:1>Goo(2);</AS:1> } } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "Goo(2);")); } [Fact] public void Update_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { while (true) { <AS:1>Goo(1);</AS:1> } } static void Goo(int a) { <AS:0>Console.WriteLine(a + 1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Update_Leaf_NewCommentAtEndOfActiveStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0>// } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } /// <summary> /// CreateNewOnMetadataUpdate has no effect in presence of active statements (in break mode). /// </summary> [Fact] public void Update_Leaf_Reloadable() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C { static void Main(string[] args) { while (true) { <AS:1>Goo(1);</AS:1> } } static void Goo(int a) { <AS:0>Console.WriteLine(a + 1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemantics(active, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Goo"), preserveLocalVariables: true) }); } [WorkItem(846588, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/846588")] [Fact] public void Update_Leaf_Block() { var src1 = @" class C : System.IDisposable { public void Dispose() {} static void Main(string[] args) { using (<AS:0>C x = null</AS:0>) {} } }"; var src2 = @" class C : System.IDisposable { public void Dispose() {} static void Main(string[] args) { using (<AS:0>C x = new C()</AS:0>) {} } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Delete in Method Body [Fact] public void Delete_Inner() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { while (true) { } <AS:1>}</AS:1> static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } // TODO (tomat): considering a change [Fact] public void Delete_Inner_MultipleParents() { var src1 = @" class C : IDisposable { unsafe static void Main(string[] args) { { <AS:1>Goo(1);</AS:1> } if (true) { <AS:2>Goo(2);</AS:2> } else { <AS:3>Goo(3);</AS:3> } int x = 1; switch (x) { case 1: case 2: <AS:4>Goo(4);</AS:4> break; default: <AS:5>Goo(5);</AS:5> break; } checked { <AS:6>Goo(4);</AS:6> } unchecked { <AS:7>Goo(7);</AS:7> } while (true) <AS:8>Goo(8);</AS:8> do <AS:9>Goo(9);</AS:9> while (true); for (int i = 0; i < 10; i++) <AS:10>Goo(10);</AS:10> foreach (var i in new[] { 1, 2}) <AS:11>Goo(11);</AS:11> using (var z = new C()) <AS:12>Goo(12);</AS:12> fixed (char* p = ""s"") <AS:13>Goo(13);</AS:13> label: <AS:14>Goo(14);</AS:14> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C : IDisposable { unsafe static void Main(string[] args) { { <AS:1>}</AS:1> if (true) { <AS:2>}</AS:2> else { <AS:3>}</AS:3> int x = 1; switch (x) { case 1: case 2: <AS:4>break;</AS:4> default: <AS:5>break;</AS:5> } checked { <AS:6>}</AS:6> unchecked { <AS:7>}</AS:7> <AS:8>while (true)</AS:8> { } do { } <AS:9>while (true);</AS:9> for (int i = 0; i < 10; <AS:10>i++</AS:10>) { } foreach (var i <AS:11>in</AS:11> new[] { 1, 2 }) { } using (<AS:12>var z = new C()</AS:12>) { } fixed (<AS:13>char* p = ""s""</AS:13>) { } label: <AS:14>{</AS:14> } } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "case 2:", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "default:", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "while (true)", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "do", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "for (int i = 0; i < 10; i++ )", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "foreach (var i in new[] { 1, 2 })", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "using ( var z = new C() )", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "fixed ( char* p = \"s\" )", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "label", FeaturesResources.code)); } [Fact] public void Delete_Leaf1() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>}</AS:0> } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Delete_Leaf2() { var src1 = @" class C { static void Goo(int a) { Console.WriteLine(1); Console.WriteLine(2); <AS:0>Console.WriteLine(3);</AS:0> Console.WriteLine(4); } }"; var src2 = @" class C { static void Goo(int a) { Console.WriteLine(1); Console.WriteLine(2); <AS:0>Console.WriteLine(4);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Delete_Leaf_InTry() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { try { <AS:0>Console.WriteLine(a);</AS:0> } catch { } } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { try { <AS:0>}</AS:0> catch { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Delete_Leaf_InTry2() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { try { try { <AS:0>Console.WriteLine(a);</AS:0> } catch { } } catch { } } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { try { try { <AS:0>}</AS:0> catch { } } catch { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Delete_Inner_CommentActiveStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { //Goo(1); <AS:1>}</AS:1> static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } [WorkItem(755959, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755959")] [Fact] public void Delete_Leaf_CommentActiveStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { //Console.WriteLine(a); <AS:0>}</AS:0> } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Delete_EntireNamespace() { var src1 = @" namespace N { class C { static void Main(String[] args) { <AS:0>Console.WriteLine(1);</AS:0> } } }"; var src2 = @"<AS:0></AS:0>"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.Delete, null, FeaturesResources.namespace_), Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "N.C"))); } #endregion #region Constructors [WorkItem(740949, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/740949")] [Fact] public void Updated_Inner_Constructor() { var src1 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; public Goo(int a) { <AS:0>this.value = a;</AS:0> } }"; var src2 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5*2);</AS:1> } } class Goo { int value; public Goo(int a) { <AS:0>this.value = a;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "Goo f = new Goo(5*2);")); } [WorkItem(741249, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/741249")] [Fact] public void Updated_Leaf_Constructor() { var src1 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; public Goo(int a) { <AS:0>this.value = a;</AS:0> } }"; var src2 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; public Goo(int a) { <AS:0>this.value = a*2;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Fact] public void Updated_Leaf_Constructor_Parameter() { var src1 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; <AS:0>public Goo(int a)</AS:0> { this.value = a; } }"; var src2 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; <AS:0>public Goo(int b)</AS:0> { this.value = b; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Goo..ctor")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Fact] public void Updated_Leaf_Constructor_Parameter_DefaultValue() { var src1 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; <AS:0>public Goo(int a = 5)</AS:0> { this.value = a; } }"; var src2 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; <AS:0>public Goo(int a = 42)</AS:0> { this.value = a; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InitializerUpdate, "int a = 42", FeaturesResources.parameter)); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Fact] public void Updated_Leaf_ConstructorChaining1() { var src1 = @" using System; class Test { static void Main(string[] args) { <AS:1>B b = new B(2, 3);</AS:1> } } class B : A { public B(int x, int y) : <AS:0>base(x + y, x - y)</AS:0> { } } class A { public A(int x, int y) : this(5 + x, y, 0) { } public A(int x, int y, int z) { } }"; var src2 = @" using System; class Test { static void Main(string[] args) { <AS:1>B b = new B(2, 3);</AS:1> } } class B : A { public B(int x, int y) : <AS:0>base(x + y + 5, x - y)</AS:0> { } } class A { public A(int x, int y) : this(x, y, 0) { } public A(int x, int y, int z) { } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Fact] public void Updated_Leaf_ConstructorChaining2() { var src1 = @" using System; class Test { static void Main(string[] args) { <AS:2>B b = new B(2, 3);</AS:2> } } class B : A { public B(int x, int y) : <AS:1>base(x + y, x - y)</AS:1> { } } class A { public A(int x, int y) : <AS:0>this(x, y, 0)</AS:0> { } public A(int x, int y, int z) { } }"; var src2 = @" using System; class Test { static void Main(string[] args) { <AS:2>B b = new B(2, 3);</AS:2> } } class B : A { public B(int x, int y) : <AS:1>base(x + y, x - y)</AS:1> { } } class A { public A(int x, int y) : <AS:0>this(5 + x, y, 0)</AS:0> { } public A(int x, int y, int z) { } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Fact] public void InstanceConstructorWithoutInitializer() { var src1 = @" class C { int a = 5; <AS:0>public C(int a)</AS:0> { } static void Main(string[] args) { <AS:1>C c = new C(3);</AS:1> } }"; var src2 = @" class C { int a = 42; <AS:0>public C(int a)</AS:0> { } static void Main(string[] args) { <AS:1>C c = new C(3);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializer_Internal_Update1() { var src1 = @" class D { public D(int d) {} } class C : D { int a = 5; public C(int a) : <AS:2>this(true)</AS:2> { } public C(bool b) : <AS:1>base(F())</AS:1> {} static int F() { <AS:0>return 1;</AS:0> } static void Main(string[] args) { <AS:3>C c = new C(3);</AS:3> } }"; var src2 = @" class D { public D(int d) {} } class C : D { int a = 5; public C(int a) : <AS:2>this(false)</AS:2> { } public C(bool b) : <AS:1>base(F())</AS:1> {} static int F() { <AS:0>return 1;</AS:0> } static void Main(string[] args) { <AS:3>C c = new C(3);</AS:3> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "this(false)")); } [Fact] public void InstanceConstructorWithInitializer_Internal_Update2() { var src1 = @" class D { public D(int d) {} } class C : D { public C() : <AS:1>base(F())</AS:1> {} static int F() { <AS:0>return 1;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class D { public D(int d) {} } class C : D { <AS:1>public C()</AS:1> {} static int F() { <AS:0>return 1;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "public C()")); } [Fact] public void InstanceConstructorWithInitializer_Internal_Update3() { var src1 = @" class D { public D(int d) <AS:0>{</AS:0> } } class C : D { <AS:1>public C()</AS:1> {} }"; var src2 = @" class D { public D(int d) <AS:0>{</AS:0> } } class C : D { public C() : <AS:1>base(1)</AS:1> {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "base(1)")); } [Fact] public void InstanceConstructorWithInitializer_Leaf_Update1() { var src1 = @" class D { public D(int d) { } } class C : D { public C() : <AS:0>base(1)</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class D { public D(int d) { } } class C : D { public C() : <AS:0>base(2)</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializer_Leaf_Update2() { var src1 = @" class D { public D() { } public D(int d) { } } class C : D { public C() : <AS:0>base(2)</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class D { public D() { } public D(int d) { } } class C : D { <AS:0>public C()</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializer_Leaf_Update3() { var src1 = @" class D { public D() { } public D(int d) { } } class C : D { <AS:0>public C()</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class D { public D() { } public D(int d) { } } class C : D { public C() : <AS:0>base(2)</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializerWithLambda_Update1() { var src1 = @" class C { public C() : this((a, b) => { <AS:0>Console.WriteLine(a + b);</AS:0> }) { } }"; var src2 = @" class C { public C() : base((a, b) => { <AS:0>Console.WriteLine(a - b);</AS:0> }) { } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializerWithLambda_Update2() { var src1 = @" class C { public C() : <AS:1>this((a, b) => { <AS:0>Console.WriteLine(a + b);</AS:0> })</AS:1> { Console.WriteLine(1); } }"; var src2 = @" class C { public C() : <AS:1>this((a, b) => { <AS:0>Console.WriteLine(a + b);</AS:0> })</AS:1> { Console.WriteLine(2); } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializerWithLambda_Update3() { var src1 = @" class C { public C() : <AS:1>this((a, b) => { <AS:0>Console.WriteLine(a + b);</AS:0> })</AS:1> { Console.WriteLine(1); } }"; var src2 = @" class C { public C() : <AS:1>this((a, b) => { <AS:0>Console.WriteLine(a - b);</AS:0> })</AS:1> { Console.WriteLine(1); } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Theory] [InlineData("class ")] [InlineData("struct")] public void InstanceConstructor_DeleteParameterless(string typeKind) { var src1 = "partial " + typeKind + " C { public C() { <AS:0>System.Console.WriteLine(1);</AS:0> } }"; var src2 = "<AS:0>partial " + typeKind + " C</AS:0> { }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "partial " + typeKind + " C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } #endregion #region Field and Property Initializers [Theory] [InlineData("class ")] [InlineData("struct")] public void InstancePropertyInitializer_Leaf_Update(string typeKind) { var src1 = @" " + typeKind + @" C { int a { get; } = <AS:0>1</AS:0>; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" " + typeKind + @" C { int a { get; } = <AS:0>2</AS:0>; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Theory] [InlineData("class ")] [InlineData("struct")] public void InstancePropertyInitializer_Leaf_Update_SynthesizedConstructor(string typeKind) { var src1 = @" " + typeKind + @" C { int a { get; } = <AS:0>1</AS:0>; static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" " + typeKind + @" C { int a { get; } = <AS:0>2</AS:0>; static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Theory] [InlineData("class ")] [InlineData("struct")] public void InstanceFieldInitializer_Leaf_Update1(string typeKind) { var src1 = @" " + typeKind + @" C { <AS:0>int a = 1</AS:0>, b = 2; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" " + typeKind + @" C { <AS:0>int a = 2</AS:0>, b = 2; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Theory] [InlineData("class ")] [InlineData("struct")] public void InstanceFieldInitializer_Leaf_Update1_SynthesizedConstructor(string typeKind) { var src1 = @" " + typeKind + @" C { <AS:0>int a = 1</AS:0>, b = 2; static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" " + typeKind + @" C { <AS:0>int a = 2</AS:0>, b = 2; static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceFieldInitializer_Internal_Update1() { var src1 = @" class C { <AS:1>int a = F(1)</AS:1>, b = F(2); public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class C { <AS:1>int a = F(2)</AS:1>, b = F(2); public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "int a = F(2)")); } [Fact] public void InstanceFieldInitializer_Internal_Update2() { var src1 = @" class C { int a = F(1), <AS:1>b = F(2)</AS:1>; public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class C { int a = F(1), <AS:1>b = F(3)</AS:1>; public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "b = F(3)")); } [Fact] public void InstancePropertyInitializer_Internal_Delete1() { var src1 = @" class C { int a { get; } = <AS:0>1</AS:0>; int b { get; } = 2; }"; var src2 = @" class C { int a { get { return 1; } } int b { get; } = <AS:0>2</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstancePropertyInitializer_Internal_Delete2() { var src1 = @" class C { int a { get; } = <AS:0>1</AS:0>; static int s { get; } = 2; int b { get; } = 2; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class C { int a { get; } static int s { get; } = 2; int b { get; } = <AS:0>3</AS:0>; public C() { } static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceFieldInitializer_Internal_Delete1() { var src1 = @" class C { <AS:1>int a = F(1)</AS:1>, b = F(2); public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class C { int a, <AS:1>b = F(2)</AS:1>; public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceFieldInitializer_Internal_Delete2() { var src1 = @" class C { int a = F(1), <AS:1>b = F(2)</AS:1>; public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class C { <AS:1>int a, b;</AS:1> public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstancePropertyAndFieldInitializers_Delete1() { var src1 = @" class C { int a { get; } = <AS:0>1</AS:0>; static int s { get; } = 2; int b = 2; }"; var src2 = @" class C { int a { get; } static int s { get; } = 2; <AS:0>int b = 3;</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstancePropertyAndFieldInitializers_Delete2() { var src1 = @" class C { int a = <AS:0>1</AS:0>; static int s { get; } = 2; int b { get; } = 2; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class C { int a; static int s { get; } = 2; int b { get; } = <AS:0>3</AS:0>; public C() { } static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceFieldInitializer_SingleDeclarator() { var src1 = @" class C { <AS:1>public static readonly int a = F(1);</AS:1> public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class C { <AS:1>public static readonly int <TS:1>a = F(1)</TS:1>;</AS:1> public C() {} public static int F(int a) { <TS:0><AS:0>return a + 1;</AS:0></TS:0> } static void Main(string[] args) { <TS:2><AS:2>C c = new C();</AS:2></TS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_Lambda1() { var src1 = @" class C { Func<int, int> a = z => <AS:0>z + 1</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1);</AS:1> } }"; var src2 = @" class C { Func<int, int> a = F(z => <AS:0>z + 1</AS:0>); static void Main(string[] args) { <AS:1>new C().a(1);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void PropertyInitializer_Lambda1() { var src1 = @" class C { Func<int, int> a { get; } = z => <AS:0>z + 1</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1);</AS:1> } }"; var src2 = @" class C { Func<int, int> a { get; } = F(z => <AS:0>z + 1</AS:0>); static void Main(string[] args) { <AS:1>new C().a(1);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_Lambda2() { var src1 = @" class C { Func<int, Func<int>> a = z => () => <AS:0>z + 1</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1)();</AS:1> } }"; var src2 = @" class C { Func<int, Func<int>> a = z => () => <AS:0>z + 2</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1)();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void PropertyInitializer_Lambda2() { var src1 = @" class C { Func<int, Func<int>> a { get; } = z => () => <AS:0>z + 1</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1)();</AS:1> } }"; var src2 = @" class C { Func<int, Func<int>> a { get; } = z => () => <AS:0>z + 2</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1)();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_InsertConst1() { var src1 = @" class C { <AS:0>int a = 1</AS:0>; public C() {} }"; var src2 = @" class C { <AS:0>const int a = 1;</AS:0> public C() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a = 1 ;]@24 -> [const int a = 1;]@24"); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ModifiersUpdate, "const int a = 1", FeaturesResources.const_field)); } [Fact] public void LocalInitializer_InsertConst1() { var src1 = @" class C { public void M() { <AS:0>int a = 1</AS:0>; } }"; var src2 = @" class C { public void M() { const int a = 1; <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_InsertConst2() { var src1 = @" class C { int <AS:0>a = 1</AS:0>, b = 2; public C() {} }"; var src2 = @" class C { <AS:0>const int a = 1, b = 2;</AS:0> public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ModifiersUpdate, "const int a = 1, b = 2", FeaturesResources.const_field), Diagnostic(RudeEditKind.ModifiersUpdate, "const int a = 1, b = 2", FeaturesResources.const_field)); } [Fact] public void LocalInitializer_InsertConst2() { var src1 = @" class C { public void M() { int <AS:0>a = 1</AS:0>, b = 2; } }"; var src2 = @" class C { public void M() { const int a = 1, b = 2; <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_Delete1() { var src1 = @" class C { <AS:0>int a = 1;</AS:0> int b = 1; public C() {} }"; var src2 = @" class C { int a; <AS:0>int b = 1;</AS:0> public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void LocalInitializer_Delete1() { var src1 = @" class C { public void M() { <AS:0>int a = 1</AS:0>; } }"; var src2 = @" class C { public void M() { int a; <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_Delete2() { var src1 = @" class C { int b = 1; int c; <AS:0>int a = 1;</AS:0> public C() {} }"; var src2 = @" class C { <AS:0>int b = 1;</AS:0> int c; int a; public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void LocalInitializer_Delete2() { var src1 = @" class C { public void M() { int b = 1; int c; <AS:0>int a = 1;</AS:0> } }"; var src2 = @" class C { public void M() { int b = 1; int c; int a; <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_Delete3() { var src1 = @" class C { int b = 1; int c; <AS:0>int a = 1;</AS:0> public C() {} }"; var src2 = @" class C { <AS:0>int b = 1;</AS:0> int c; public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active, Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.field, "a"))); } [Fact] public void LocalInitializer_Delete3() { var src1 = @" class C { public void M() { int b = 1; int c; <AS:0>int a = 1;</AS:0> } }"; var src2 = @" class C { public void M() { int b = 1; int c; <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_DeleteStaticInstance1() { var src1 = @" class C { <AS:0>int a = 1;</AS:0> static int b = 1; int c = 1; public C() {} }"; var src2 = @" class C { int a; static int b = 1; <AS:0>int c = 1;</AS:0> public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_DeleteStaticInstance2() { var src1 = @" class C { static int c = 1; <AS:0>static int a = 1;</AS:0> int b = 1; public C() {} }"; var src2 = @" class C { <AS:0>static int c = 1;</AS:0> static int a; int b = 1; public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_DeleteStaticInstance3() { var src1 = @" class C { <AS:0>static int a = 1;</AS:0> int b = 1; public C() {} }"; var src2 = @" class C { <AS:0>static int a;</AS:0> int b = 1; public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_DeleteMove1() { var src1 = @" class C { int b = 1; int c; <AS:0>int a = 1;</AS:0> public C() {} }"; var src2 = @" class C { int c; <AS:0>int b = 1;</AS:0> public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active, Diagnostic(RudeEditKind.Move, "int c", FeaturesResources.field), Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.field, "a"))); } [Fact] public void LocalInitializer_DeleteReorder1() { var src1 = @" class C { public void M() { int b = 1; <AS:0>int a = 1;</AS:0> int c; } }"; var src2 = @" class C { public void M() { int c; <AS:0>int b = 1;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldToProperty1() { var src1 = @" class C { int a = <AS:0>1</AS:0>; }"; // The placement of the active statement is not ideal, but acceptable. var src2 = @" <AS:0>class C</AS:0> { int a { get; } = 1; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active, Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.field, "a"))); } [Fact] public void PropertyToField1() { var src1 = @" class C { int a { get; } = <AS:0>1</AS:0>; }"; // The placement of the active statement is not ideal, but acceptable. var src2 = @" <AS:0>class C</AS:0> { int a = 1; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active, Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.auto_property, "a"))); } #endregion #region Lock Statement [Fact] public void LockBody_Update() { var src1 = @" class Test { private static object F() { <AS:0>return new object();</AS:0> } static void Main(string[] args) { <AS:1>lock (F())</AS:1> { System.Console.Write(0); } } }"; var src2 = @" class Test { private static object F() { <AS:0>return new object();</AS:0> } static void Main(string[] args) { <AS:1>lock (F())</AS:1> { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(755749, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755749")] [Fact] public void Lock_Insert_Leaf() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { <AS:0>System.Console.Write(5);</AS:0> } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { <AS:0>System.Console.Write(5);</AS:0> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "lock (lockThis)", CSharpFeaturesResources.lock_statement)); } [WorkItem(755749, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755749")] [Fact] public void Lock_Insert_Leaf2() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { { System.Console.Write(5); <AS:0>}</AS:0> } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { System.Console.Write(5); <AS:0>}</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "lock (lockThis)", CSharpFeaturesResources.lock_statement)); } [Fact] public void Lock_Insert_Leaf3() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { { System.Console.Write(5); } <AS:0>System.Console.Write(10);</AS:0> } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { System.Console.Write(5); } <AS:0>System.Console.Write(5);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lock_Insert_Leaf4() { var src1 = @" class Test { public static object a = new object(); public static object b = new object(); public static object c = new object(); public static object d = new object(); public static object e = new object(); static void Main(string[] args) { lock (a) { lock (b) { lock (c) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static object a = new object(); public static object b = new object(); public static object c = new object(); public static object d = new object(); public static object e = new object(); static void Main(string[] args) { lock (b) { lock (d) { lock (a) { lock (e) { <AS:0>System.Console.Write();</AS:0> } } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "lock (d)", CSharpFeaturesResources.lock_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "lock (e)", CSharpFeaturesResources.lock_statement)); } [Fact] public void Lock_Insert_Leaf5() { var src1 = @" class Test { public static object a = new object(); public static object b = new object(); public static object c = new object(); public static object d = new object(); public static object e = new object(); static void Main(string[] args) { lock (a) { lock (c) { lock (b) { lock (e) { <AS:0>System.Console.Write();</AS:0> } } } } } }"; var src2 = @" class Test { public static object a = new object(); public static object b = new object(); public static object c = new object(); public static object d = new object(); public static object e = new object(); static void Main(string[] args) { lock (b) { lock (d) { lock (a) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "lock (d)", CSharpFeaturesResources.lock_statement)); } [WorkItem(755752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755752")] [Fact] public void Lock_Update_Leaf() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { <AS:0>System.Console.Write(5);</AS:0> } } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (""test"") { <AS:0>System.Console.Write(5);</AS:0> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "lock (\"test\")", CSharpFeaturesResources.lock_statement)); } [Fact] public void Lock_Update_Leaf2() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { System.Console.Write(5); } <AS:0>System.Console.Write(5);</AS:0> } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (""test"") { System.Console.Write(5); } <AS:0>System.Console.Write(5);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lock_Delete_Leaf() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { <AS:0>System.Console.Write(5);</AS:0> } } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { <AS:0>System.Console.Write(5);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lock_Update_Lambda1() { var src1 = @" class C { static void Main(string[] args) { lock (F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static void Main(string[] args) { lock (F(a => a + 1)) { <AS:0>Console.WriteLine(2);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lock_Update_Lambda2() { var src1 = @" class C { static void Main(string[] args) { lock (F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static void Main(string[] args) { lock (G(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "lock (G(a => a))", CSharpFeaturesResources.lock_statement)); } #endregion #region Fixed Statement [Fact] public void FixedBody_Update() { var src1 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { unsafe { char* px2; fixed (<AS:1>char* pj = &F()</AS:1>) { System.Console.WriteLine(0); } } } }"; var src2 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { unsafe { char* px2; fixed (<AS:1>char* pj = &F()</AS:1>) { System.Console.WriteLine(1); } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(755742, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755742")] [Fact] public void Fixed_Insert_Leaf() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; <AS:0>px2 = null;</AS:0> } } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* pj = &value) { <AS:0>px2 = null;</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "fixed (int* pj = &value)", CSharpFeaturesResources.fixed_statement)); } [Fact] public void Fixed_Insert_Leaf2() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; <AS:0>}</AS:0> } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* pj = &value) { px2 = null; } <AS:0>}</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(755742, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755742")] [Fact] public void Fixed_Insert_Leaf3() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; <AS:0>px2 = null;</AS:0> fixed (int* pj = &value) { } } } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* pj = &value) { <AS:0>px2 = null;</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "fixed (int* pj = &value)", CSharpFeaturesResources.fixed_statement)); } [WorkItem(755742, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755742")] [Fact] public void Fixed_Reorder_Leaf1() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* a = &value) { fixed (int* b = &value) { <AS:0>px2 = null;</AS:0> } } } } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* b = &value) { fixed (int* a = &value) { <AS:0>px2 = null;</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(755746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755746")] [Fact] public void Fixed_Update_Leaf1() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* pj = &value) { <AS:0>px2 = null;</AS:0> } } } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* p = &value) { <AS:0>px2 = null;</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "fixed (int* p = &value)", CSharpFeaturesResources.fixed_statement)); } [WorkItem(755746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755746")] [Fact] public void Fixed_Update_Leaf2() { var src1 = @" class Test { public static int value1 = 10; public static int value2 = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* a = &value1) { fixed (int* b = &value1) { fixed (int* c = &value1) { <AS:0>px2 = null;</AS:0> } } } } } }"; var src2 = @" class Test { public static int value1 = 10; public static int value2 = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* c = &value1) { fixed (int* d = &value1) { fixed (int* a = &value2) { fixed (int* e = &value1) { <AS:0>px2 = null;</AS:0> } } } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "fixed (int* a = &value2)", CSharpFeaturesResources.fixed_statement), Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "fixed (int* d = &value1)", CSharpFeaturesResources.fixed_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "fixed (int* e = &value1)", CSharpFeaturesResources.fixed_statement)); } [Fact] public void Fixed_Delete_Leaf() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* pj = &value) { <AS:0>px2 = null;</AS:0> } } } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; <AS:0>px2 = null;</AS:0> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Fixed_Update_Lambda1() { var src1 = @" class C { static unsafe void Main(string[] args) { fixed (byte* p = &F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { fixed (byte* p = &F(a => a + 1)) { <AS:0>Console.WriteLine(2);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Fixed_Update_Lambda2() { var src1 = @" class C { static unsafe void Main(string[] args) { fixed (byte* p = &F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { fixed (byte* p = &G(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "fixed (byte* p = &G(a => a))", CSharpFeaturesResources.fixed_statement)); } #endregion #region ForEach Statement [Fact] public void ForEachBody_Update_ExpressionActive() { var src1 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (char c in <AS:1>F()</AS:1>) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (char c in <AS:1>F()</AS:1>) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariableBody_Update_ExpressionActive() { var src1 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach ((string s, int i) in <AS:1>F()</AS:1>) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach ((string s, int i) in <AS:1>F()</AS:1>) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachBody_Update_InKeywordActive() { var src1 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (char c <AS:1>in</AS:1> F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (char c <AS:1>in</AS:1> F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariableBody_Update_InKeywordActive() { var src1 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach ((string s, int i) <AS:1>in</AS:1> F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach ((string s, int i) <AS:1>in</AS:1> F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachBody_Update_VariableActive() { var src1 = @" class Test { private static string[] F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>string c</AS:1> in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static string[] F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>string c</AS:1> in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariableBody_Update_VariableActive() { var src1 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>(string s, int i)</AS:1> in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>(string s, int i)</AS:1> in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachBody_Update_ForeachKeywordActive() { var src1 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { <AS:1>foreach</AS:1> (char c in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { <AS:1>foreach</AS:1> (char c in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariableBody_Update_ForeachKeywordActive() { var src1 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { <AS:1>foreach</AS:1> ((string s, int i) in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { <AS:1>foreach</AS:1> ((string s, int i) in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_Update() { var src1 = @" class Test { private static string[] F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>string c</AS:1> in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static string[] F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>object c</AS:1> in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // not ideal, but good enough: edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "object c"), Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "foreach ( object c in F())", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEachDeconstructionVariable_Update() { var src1 = @" class Test { private static (int, (bool, double))[] F() { <AS:0>return new[] { (1, (true, 2.0)) };</AS:0> } static void Main(string[] args) { foreach (<AS:1>(int i, (bool b, double d))</AS:1> in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static (int, (bool, double))[] F() { <AS:0>return new[] { (1, (true, 2.0)) };</AS:0> } static void Main(string[] args) { foreach (<AS:1>(int i, (var b, double d))</AS:1> in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "(int i, (var b, double d))"), Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "foreach ( (int i, (var b, double d)) in F())", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEach_Reorder_Leaf() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var b in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var b in e1) { foreach (var c in e1) { foreach (var a in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_Reorder_Leaf() { var src1 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { foreach ((var a1, var a2) in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_Update_Leaf() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { <AS:0>System.Console.Write();</AS:0> } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var b in e1) { foreach (var c in e1) { foreach (var a in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var b in e1)", CSharpFeaturesResources.foreach_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var c in e1)", CSharpFeaturesResources.foreach_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var a in e1)", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEachVariable_Update_Leaf() { var src1 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { <AS:0>System.Console.Write();</AS:0> } }"; var src2 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { foreach ((var a1, var a2) in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var c in e1)", CSharpFeaturesResources.foreach_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach ((int b1, bool b2) in e1)", CSharpFeaturesResources.foreach_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach ((var a1, var a2) in e1)", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEach_Delete_Leaf1() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var b in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var b in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_Delete_Leaf1() { var src1 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach ((int b1, bool b2) in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_Delete_Leaf2() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var b in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var b in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_Delete_Leaf2() { var src1 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_Delete_Leaf3() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var b in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_Delete_Leaf3() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_Lambda1() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { Action a = () => { <AS:0>System.Console.Write();</AS:0> }; <AS:1>a();</AS:1> } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var b in e1) { foreach (var c in e1) { Action a = () => { foreach (var a in e1) { <AS:0>System.Console.Write();</AS:0> } }; } <AS:1>a();</AS:1> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var a in e1)", CSharpFeaturesResources.foreach_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var b in e1)", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEach_Update_Lambda1() { var src1 = @" class C { static unsafe void Main(string[] args) { foreach (var a in F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { foreach (var a in F(a => a + 1)) { <AS:0>Console.WriteLine(2);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_Update_Lambda2() { var src1 = @" class C { static unsafe void Main(string[] args) { foreach (var a in F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { foreach (var a in G(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "foreach (var a in G(a => a))", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEach_Update_Nullable() { var src1 = @" class C { static void F() { var arr = new int?[] { 0 }; foreach (var s in arr) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static void F() { var arr = new int[] { 0 }; foreach (var s in arr) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_DeleteBody() { var src1 = @" class C { static void F() { foreach (var s in new[] { 1 }) <AS:0>G();</AS:0> } } "; var src2 = @" class C { static void F() { foreach (var s in new[] { 1 }) <AS:0>;</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_DeleteBody() { var src1 = @" class C { static void F() { foreach ((var a1, var a2) in new[] { (1,1) }) <AS:0>G();</AS:0> } } "; var src2 = @" class C { static void F() { foreach ((var a1, var a2) in new[] { (1,1) }) <AS:0>;</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region For Statement [Fact] public void ForStatement_Initializer1() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (<AS:1>i = F(1)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (<AS:1>i = F(2)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "i = F(2)")); } [Fact] public void ForStatement_Initializer2() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (<AS:1>i = F(1)</AS:1>, F(1); i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (<AS:1>i = F(1)</AS:1>, F(2); i < 10; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForStatement_Initializer_Delete() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (<AS:1>i = F(1)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (; <AS:1>i < 10</AS:1>; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "for (; i < 10 ; i++)", FeaturesResources.code)); } [Fact] public void ForStatement_Declarator1() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>var i = F(1)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>var i = F(2)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "var i = F(2)")); } [Fact] public void ForStatement_Declarator2() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>int i = F(1)</AS:1>, j = F(1); i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>int i = F(1)</AS:1>, j = F(2); i < 10; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForStatement_Declarator3() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>int i = F(1)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>int i = F(1)</AS:1>, j = F(2); i < 10; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForStatement_Condition1() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; <AS:1>i < F(10)</AS:1>; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; <AS:1>i < F(20)</AS:1>; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "i < F(20)")); } [Fact] public void ForStatement_Condition_Delete() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; <AS:1>i < F(10)</AS:1>; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; ; <AS:1>i++</AS:1>) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "for (int i = 1; ; i++ )", FeaturesResources.code)); } [Fact] public void ForStatement_Incrementors1() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(1)</AS:1>) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(20); <AS:1>F(1)</AS:1>) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForStatement_Incrementors2() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(1)</AS:1>) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(2)</AS:1>) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "F(2)")); } [Fact] public void ForStatement_Incrementors3() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(1)</AS:1>) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(1)</AS:1>, i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForStatement_Incrementors4() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(1)</AS:1>, i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); i++, <AS:1>F(1)</AS:1>) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Using Statement and Local Declaration [Fact] public void UsingStatement_Expression_Update_Leaf() { var src1 = @" class Test { public static System.IDisposable a = null; public static System.IDisposable b = null; public static System.IDisposable c = null; static void Main(string[] args) { using (a) { using (b) { <AS:0>System.Console.Write();</AS:0> } } } }"; var src2 = @" class Test { public static System.IDisposable a = null; public static System.IDisposable b = null; public static System.IDisposable c = null; static void Main(string[] args) { using (a) { using (c) { using (b) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // Using with an expression generates code that stores the value of the expression in a compiler-generated temp. // This temp is not initialized when using is added around an active statement so the disposal is a no-op. // The user might expect that the object the field points to is disposed at the end of the using block, but it isn't. edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "using (c)", CSharpFeaturesResources.using_statement)); } [Fact] public void UsingStatement_Declaration_Update_Leaf() { var src1 = @" class Test { static void Main(string[] args) { using (var a = new Disposable()) { using (var b = new Disposable()) { <AS:0>System.Console.Write();</AS:0> } } } }"; var src2 = @" class Test { static void Main(string[] args) { using (var a = new Disposable()) { using (var c = new Disposable()) { using (var b = new Disposable()) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // Unlike using with an expression, using with a declaration does not introduce compiler-generated temps. // As with other local declarations that are added but not executed, the variable is not initialized and thus // there should be no expectation (or need) for its disposal. Hence we do not report a rude edit. edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingLocalDeclaration_Update_Leaf1() { var src1 = @" class Test { static void Main(string[] args) { using var a = new Disposable(), b = new Disposable(); <AS:0>System.Console.Write();</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { using var a = new Disposable(), c = new Disposable(), b = new Disposable(); <AS:0>System.Console.Write();</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // Unlike using with an expression, using local declaration does not introduce compiler-generated temps. // As with other local declarations that are added but not executed, the variable is not initialized and thus // there should be no expectation (or need) for its disposal. Hence we do not report a rude edit. edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingLocalDeclaration_Update_Leaf2() { var src1 = @" class Test { static void Main(string[] args) { using var a = new Disposable(); using var b = new Disposable(); <AS:0>System.Console.Write();</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { using var a = new Disposable(); using var c = new Disposable(); using var b = new Disposable(); <AS:0>System.Console.Write();</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // Unlike using with an expression, using local declaration does not introduce compiler-generated temps. // As with other local declarations that are added but not executed, the variable is not initialized and thus // there should be no expectation (or need) for its disposal. Hence we do not report a rude edit. edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingStatement_Update_NonLeaf1() { var src1 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (var a = new Disposable(1)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var src2 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (var a = new Disposable(2)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "}")); } [Fact] public void UsingStatement_Update_NonLeaf2() { var src1 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (Disposable a = new Disposable(1), b = Disposable(2)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var src2 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (Disposable a = new Disposable(1)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "}")); } [Fact] public void UsingStatement_Update_NonLeaf_Lambda() { var src1 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (var a = new Disposable(() => 1)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var src2 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (var a = new Disposable(() => 2)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingLocalDeclaration_Update_NonLeaf1() { var src1 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { if (F()) { using Disposable a = new Disposable(1); using Disposable b = new Disposable(2), c = new Disposable(3); <AS:1>}</AS:1> } }"; var src2 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { if (F()) { using Disposable a = new Disposable(1); using Disposable b = new Disposable(20), c = new Disposable(3); <AS:1>}</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "}")); } [Fact] public void UsingLocalDeclaration_Update_NonLeaf_Lambda() { var src1 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { if (F()) { using Disposable a = new Disposable(() => 1); { using var x = new Disposable(1); } using Disposable b = new Disposable(() => 2), c = new Disposable(() => 3); <AS:1>}</AS:1> } }"; var src2 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { if (F()) { using Disposable a = new Disposable(() => 10); { using var x = new Disposable(2); } Console.WriteLine(1); using Disposable b = new Disposable(() => 20), c = new Disposable(() => 30); <AS:1>}</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingStatement_Expression_InLambdaBody1() { var src1 = @" class Test { public static System.IDisposable a = null; public static System.IDisposable b = null; public static System.IDisposable c = null; public static System.IDisposable d = null; static void Main(string[] args) { using (a) { Action a = () => { using (b) { <AS:0>System.Console.Write();</AS:0> } }; } <AS:1>a();</AS:1> } }"; var src2 = @" class Test { public static System.IDisposable a = null; public static System.IDisposable b = null; public static System.IDisposable c = null; public static System.IDisposable d = null; static void Main(string[] args) { using (d) { Action a = () => { using (c) { using (b) { <AS:0>System.Console.Write();</AS:0> } } }; } <AS:1>a();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "using (c)", CSharpFeaturesResources.using_statement)); } [Fact] public void UsingStatement_Expression_Update_Lambda1() { var src1 = @" class C { static unsafe void Main(string[] args) { using (F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { using (F(a => a + 1)) { <AS:0>Console.WriteLine(2);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingStatement_Expression_Update_Lambda2() { var src1 = @" class C { static unsafe void Main(string[] args) { using (F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { using (G(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "using (G(a => a))", CSharpFeaturesResources.using_statement)); } #endregion #region Conditional Block Statements (If, Switch, While, Do) [Fact] public void IfBody_Update1() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>if (B())</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>if (B())</AS:1> { System.Console.WriteLine(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void IfBody_Update2() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>if (B())</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>if (!B())</AS:1> { System.Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "if (!B())")); } [Fact] public void IfBody_Update_Lambda() { var src1 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>if (B(() => 1))</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>if (B(() => 2))</AS:1> { System.Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void WhileBody_Update1() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>while (B())</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>while (B())</AS:1> { System.Console.WriteLine(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void WhileBody_Update2() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>while (B())</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>while (!B())</AS:1> { System.Console.WriteLine(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "while (!B())")); } [Fact] public void WhileBody_Update_Lambda() { var src1 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>while (B(() => 1))</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>while (B(() => 2))</AS:1> { System.Console.WriteLine(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void DoWhileBody_Update1() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { do { System.Console.WriteLine(0); } <AS:1>while (B());</AS:1> } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { do { System.Console.WriteLine(1); } <AS:1>while (B());</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void DoWhileBody_Update2() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { do { System.Console.WriteLine(0); } <AS:1>while (B());</AS:1> } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { do { System.Console.WriteLine(1); } <AS:1>while (!B());</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "while (!B());")); } [Fact] public void DoWhileBody_Update_Lambda() { var src1 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { do { System.Console.WriteLine(0); } <AS:1>while (B(() => 1));</AS:1> } }"; var src2 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { do { System.Console.WriteLine(1); } <AS:1>while (B(() => 2));</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void DoWhileBody_Delete() { var src1 = @" class C { static void F() { do <AS:0>G();</AS:0> while (true); } } "; var src2 = @" class C { static void F() { do <AS:0>;</AS:0> while (true); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void SwitchCase_Update1() { var src1 = @" class C { public static string F() <AS:0>{</AS:0> return null; } public static void Main() { <AS:1>switch (F())</AS:1> { case ""a"": System.Console.WriteLine(0); break; case ""b"": System.Console.WriteLine(1); break; } } }"; var src2 = @" class C { public static string F() <AS:0>{</AS:0> return null; } public static void Main() { <AS:1>switch (F())</AS:1> { case ""a"": System.Console.WriteLine(0); break; case ""b"": System.Console.WriteLine(2); break; } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void SwitchCase_Update_Lambda() { var src1 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>switch (B(() => 1))</AS:1> { case ""a"": System.Console.WriteLine(0); break; case ""b"": System.Console.WriteLine(1); break; } } }"; var src2 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>switch (B(() => 2))</AS:1> { case ""a"": System.Console.WriteLine(0); break; case ""b"": System.Console.WriteLine(2); break; } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Switch Statement When Clauses, Patterns [Fact] public void SwitchWhenClause_PatternUpdate1() { var src1 = @" class C { public static int Main() { switch (F()) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; case byte a when G5(a): return 10; case double b when G2(b): return 20; case C { X: 2 } when G4(9): return 30; case C { X: 2, Y: C { X: 1 } } c1 when G3(c1): return 40; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; case byte a when G5(a): return 10; case double b when G2(b): return 20; case C { X: 2 } when G4(9): return 30; case C { X: 2, Y: C { X: 2 } } c1 when G3(c1): return 40; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F())", CSharpFeaturesResources.switch_statement_case_clause)); } [Fact] public void SwitchWhenClause_PatternInsert() { var src1 = @" class C { public static int Main() { switch (F()) { case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F())", CSharpFeaturesResources.switch_statement_case_clause)); } [Fact] public void SwitchWhenClause_PatternDelete() { var src1 = @" class C { public static int Main() { switch (F()) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F())", CSharpFeaturesResources.switch_statement_case_clause)); } [Fact] public void SwitchWhenClause_WhenDelete() { var src1 = @" class C { public static int Main() { switch (F()) { case byte a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case byte a1: case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F())", CSharpFeaturesResources.switch_statement_case_clause)); } [Fact] public void SwitchWhenClause_WhenAdd() { var src1 = @" class C { public static int Main() { switch (F()) { case byte a1: case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case byte a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F())", CSharpFeaturesResources.switch_statement_case_clause)); } [Fact] public void SwitchWhenClause_WhenUpdate() { var src1 = @" class C { public static int Main() { switch (F()) { case byte a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case byte a1 when G1(a1 * 2): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void SwitchWhenClause_UpdateGoverningExpression() { var src1 = @" class C { public static int Main() { switch (F(1)) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F(2)) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F(2))", CSharpFeaturesResources.switch_statement)); } [Fact] public void Switch_PropertyPattern_Update_NonLeaf() { var src1 = @" class C { public int X { get => <AS:0>1</AS:0>; } public static int F(object obj) { <AS:1>switch (obj)</AS:1> { case C { X: 1 }: return 1; } return 0; } }"; var src2 = @" class C { public int X { get => <AS:0>1</AS:0>; } public static int F(object obj) { <AS:1>switch (obj)</AS:1> { case C { X: 2 }: return 1; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "switch (obj)")); } [Fact] public void Switch_PositionalPattern_Update_NonLeaf() { var src1 = @" class C { public void Deconstruct(out int x) => <AS:0>x = X</AS:0>; public static int F(object obj) { <AS:1>switch (obj)</AS:1> { case C ( x: 1 ): return 1; } return 0; } }"; var src2 = @" class C { public void Deconstruct(out int x) => <AS:0>x = X</AS:0>; public static int F(object obj) { <AS:1>switch (obj)</AS:1> { case C ( x: 2 ): return 1; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "switch (obj)")); } [Fact] public void Switch_VarPattern_Update_NonLeaf() { var src1 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case var (x, y): return 1; case 2: return 2; } return 0; } }"; var src2 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case var (x, y): return 1; case 3: return 2; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "switch (G())")); } [Fact] public void Switch_DiscardPattern_Update_NonLeaf() { var src1 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case bool _: return 1; } return 0; } }"; var src2 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case int _: return 1; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "switch (G())")); } [Fact] public void Switch_NoPatterns_Update_NonLeaf() { var src1 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case 1: return 1; } return 0; } }"; var src2 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case 2: return 1; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Switch Expression [Fact] public void SwitchExpression() { var src1 = @" class C { public static int Main() { Console.WriteLine(1); <AS:4>return F() switch { int a <AS:0>when F1()</AS:0> => <AS:1>F2()</AS:1>, bool b => <AS:2>F3()</AS:2>, _ => <AS:3>F4()</AS:3> };</AS:4> } }"; var src2 = @" class C { public static int Main() { Console.WriteLine(2); <AS:4>return F() switch { int a <AS:0>when F1()</AS:0> => <AS:1>F2()</AS:1>, bool b => <AS:2>F3()</AS:2>, _ => <AS:3>F4()</AS:3> };</AS:4> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void SwitchExpression_Lambda1() { var src1 = @" class C { public static int Main() => <AS:1>F() switch { 0 => new Func<int>(() => <AS:0>1</AS:0>)(), _ => 2}</AS:1>; }"; var src2 = @" class C { public static int Main() => <AS:1>F() switch { 0 => new Func<int>(() => <AS:0>3</AS:0>)(), _ => 2}</AS:1>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void SwitchExpression_Lambda2() { var src1 = @" class C { public static int Main() => <AS:1>F() switch { i => new Func<int>(() => <AS:0>i + 1</AS:0>)(), _ => 2}</AS:1>; }"; var src2 = @" class C { public static int Main() => <AS:1>F() switch { i => new Func<int>(() => <AS:0>i + 3</AS:0>)(), _ => 2}</AS:1>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_MemberExpressionBody() { var src1 = @" class C { public static int Main() => <AS:0>F() switch { 0 => 1, _ => 2}</AS:0>; }"; var src2 = @" class C { public static int Main() => <AS:0>G() switch { 0 => 10, _ => 20}</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_LambdaBody() { var src1 = @" class C { public static Func<int> M() => () => <AS:0>F() switch { 0 => 1, _ => 2}</AS:0>; }"; var src2 = @" class C { public static Func<int> M() => () => <AS:0>G() switch { 0 => 10, _ => 20}</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_QueryLambdaBody() { var src1 = @" class C { public static IEnumerable<int> M() { return from a in new[] { 1 } where <AS:0>F() <AS:1>switch { 0 => true, _ => false}</AS:0>/**/</AS:1> select a; } }"; var src2 = @" class C { public static IEnumerable<int> M() { return from a in new[] { 2 } where <AS:0>F() <AS:1>switch { 0 => true, _ => false}</AS:0>/**/</AS:1> select a; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_NestedInGoverningExpression() { var src1 = @" class C { public static int Main() => <AS:1>(F() switch { 0 => 1, _ => 2 }) switch { 1 => <AS:0>10</AS:0>, _ => 20 }</AS:1>; }"; var src2 = @" class C { public static int Main() => <AS:1>(G() switch { 0 => 10, _ => 20 }) switch { 10 => <AS:0>100</AS:0>, _ => 200 }</AS:1>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "(G() switch { 0 => 10, _ => 20 }) switch { 10 => 100 , _ => 200 }")); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_NestedInArm() { var src1 = @" class C { public static int Main() => F1() switch { 1 when F2() <AS:0>switch { 0 => true, _ => false }</AS:0> => F3() <AS:1>switch { 0 => 1, _ => 2 }</AS:1>, _ => 20 }; }"; var src2 = @" class C { public static int Main() => F1() switch { 1 when F2() <AS:0>switch { 0 => true, _ => false }</AS:0> => F3() <AS:1>switch { 0 => 1, _ => 2 }</AS:1>, _ => 20 }; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_Delete1() { var src1 = @" class C { public static int Main() { return Method() switch { true => G(), _ => F2() switch { 1 => <AS:0>0</AS:0>, _ => 2 } }; } }"; var src2 = @" class C { public static int Main() { return Method() switch { true => G(), _ => <AS:0>1</AS:0> }; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_Delete2() { var src1 = @" class C { public static int Main() { return F1() switch { 1 => 0, _ => F2() switch { 1 => <AS:0>0</AS:0>, _ => 2 } }; } }"; var src2 = @" class C { public static int Main() { return F1() switch { 1 => <AS:0>0</AS:0>, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_Delete3() { var src1 = @" class C { public static int Main() { return F1() switch { 1 when F2() switch { 1 => <AS:0>true</AS:0>, _ => false } => 0, _ => 2 }; } }"; var src2 = @" class C { public static int Main() { return F1() switch { 1 <AS:0>when F3()</AS:0> => 0, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Try [Fact] public void Try_Add_Inner() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } catch { } } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "try", CSharpFeaturesResources.try_block)); } [Fact] public void Try_Add_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { <AS:0>Console.WriteLine(1);</AS:0> } catch { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Try_Delete_Inner() { var src1 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>catch { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Goo();", CSharpFeaturesResources.try_block)); } [Fact] public void Try_Delete_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { <AS:0>Console.WriteLine(1);</AS:0> } catch { } } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Try_Update_Inner() { var src1 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>catch { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>catch (IOException) { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "try", CSharpFeaturesResources.try_block)); } [Fact] public void Try_Update_Inner2() { var src1 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>catch { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>catch { }</ER:1.0> Console.WriteLine(2); } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void TryFinally_Update_Inner() { var src1 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>finally { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>finally { }</ER:1.0> Console.WriteLine(2); } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Try_Update_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { <AS:0>Console.WriteLine(1);</AS:0> } catch { } } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { <AS:0>Console.WriteLine(1);</AS:0> } catch (IOException) { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void TryFinally_DeleteStatement_Inner() { var src1 = @" class C { static void Main() { <AS:0>Console.WriteLine(0);</AS:0> try { <AS:1>Console.WriteLine(1);</AS:1> } <ER:1.0>finally { Console.WriteLine(2); }</ER:1.0> } }"; var src2 = @" class C { static void Main() { <AS:0>Console.WriteLine(0);</AS:0> try { <AS:1>}</AS:1> finally { Console.WriteLine(2); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } [Fact] public void TryFinally_DeleteStatement_Leaf() { var src1 = @" class C { static void Main(string[] args) { <ER:0.0>try { Console.WriteLine(0); } finally { <AS:0>Console.WriteLine(1);</AS:0> }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { try { Console.WriteLine(0); } finally { <AS:0>}</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "finally", CSharpFeaturesResources.finally_clause)); } [Fact] public void Try_DeleteStatement_Inner() { var src1 = @" class C { static void Main() { <AS:0>Console.WriteLine(0);</AS:0> try { <AS:1>Console.WriteLine(1);</AS:1> } <ER:1.0>finally { Console.WriteLine(2); }</ER:1.0> } }"; var src2 = @" class C { static void Main() { <AS:0>Console.WriteLine(0);</AS:0> try { <AS:1>}</AS:1> <ER:1.0>finally { Console.WriteLine(2); }</ER:1.0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } [Fact] public void Try_DeleteStatement_Leaf() { var src1 = @" class C { static void Main() { try { <AS:0>Console.WriteLine(1);</AS:0> } finally { Console.WriteLine(2); } } }"; var src2 = @" class C { static void Main() { try { <AS:0>}</AS:0> finally { Console.WriteLine(2); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Catch [Fact] public void Catch_Add_Inner() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } catch { <AS:1>Goo();</AS:1> } } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Add_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { } catch { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Delete_Inner() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Goo();", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Delete_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { } <ER:0.0>catch { <AS:0>Console.WriteLine(1);</AS:0> }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Console.WriteLine(1);", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Update_Inner() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Update_InFilter_Inner() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) <AS:1>when (Goo(1))</AS:1> { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (Exception) <AS:1>when (Goo(1))</AS:1> { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Update_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { } <ER:0.0>catch { <AS:0>Console.WriteLine(1);</AS:0> }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { } <ER:0.0>catch (IOException) { <AS:0>Console.WriteLine(1);</AS:0> }</ER:0.0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void CatchFilter_Update_Inner() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) <AS:1>when (Goo(1))</AS:1> { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) <AS:1>when (Goo(2))</AS:1> { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "when (Goo(2))"), Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void CatchFilter_Update_Leaf1() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:0.0>catch (IOException) <AS:0>when (Goo(1))</AS:0> { }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:0.0>catch (IOException) <AS:0>when (Goo(2))</AS:0> { }</ER:0.0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void CatchFilter_Update_Leaf2() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:0.0>catch (IOException) <AS:0>when (Goo(1))</AS:0> { }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:0.0>catch (Exception) <AS:0>when (Goo(1))</AS:0> { }<ER:0.0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } #endregion #region Finally [Fact] public void Finally_Add_Inner() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } finally { <AS:1>Goo();</AS:1> } } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "finally", CSharpFeaturesResources.finally_clause)); } [Fact] public void Finally_Add_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { } finally { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "finally", CSharpFeaturesResources.finally_clause)); } [Fact] public void Finally_Delete_Inner() { var src1 = @" class C { static void Main(string[] args) { <ER:1.0>try { } finally { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Goo();", CSharpFeaturesResources.finally_clause)); } [Fact] public void Finally_Delete_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <ER:0.0>try { } finally { <AS:0>Console.WriteLine(1);</AS:0> }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Console.WriteLine(1);", CSharpFeaturesResources.finally_clause)); } #endregion #region Try-Catch-Finally [Fact] public void TryCatchFinally() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) { try { try { try { <AS:1>Goo();</AS:1> } catch { } } catch (Exception) { } } finally { } }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (Exception) { try { try { } finally { try { <AS:1>Goo();</AS:1> } catch { } } } catch (Exception) { } }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause), Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "try", CSharpFeaturesResources.try_block), Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Goo();", CSharpFeaturesResources.try_block), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "finally", CSharpFeaturesResources.finally_clause)); } [Fact, WorkItem(23865, "https://github.com/dotnet/roslyn/issues/23865")] public void TryCatchFinally_Regions() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) { try { try { try { <AS:1>Goo();</AS:1> } catch { } } catch (Exception) { } } finally { } }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) { try { try { try { <AS:1>Goo();</AS:1> } catch { } } catch (Exception) { } } finally { } }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // TODO: this is incorrect, we need to report a rude edit: edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(23865, "https://github.com/dotnet/roslyn/issues/23865")] public void TryCatchFinally2_Regions() { var src1 = @" class C { static void Main(string[] args) { try { try { try { try { <AS:1>Goo();</AS:1> } <ER:1.3>catch { }</ER:1.3> } <ER:1.2>catch (Exception) { }</ER:1.2> } <ER:1.1>finally { }</ER:1.1> } <ER:1.0>catch (IOException) { } finally { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { try { try { try { <AS:1>Goo();</AS:1> } <ER:1.3>catch { }</ER:1.3> } <ER:1.2>catch (Exception) { }</ER:1.2> } <ER:1.1>finally { }</ER:1.1> } <ER:1.0>catch (IOException) { } finally { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // TODO: this is incorrect, we need to report a rude edit since an ER span has been changed (empty line added): edits.VerifyRudeDiagnostics(active); } [Fact] public void TryFilter_Regions1() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException e) when (e == null) { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException e) when (e == null) { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void TryFilter_Regions2() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException e) <AS:1>when (e == null)</AS:1> { Goo(); }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException e) <AS:1>when (e == null)</AS:1> { Goo(); }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Try_Lambda1() { var src1 = @" using System; using System.Linq; class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { Func<int, int> f = null; try { f = x => <AS:1>1 + Goo(x)</AS:1>; } catch { } <AS:2>Console.Write(f(2));</AS:2> } }"; var src2 = @" using System; using System.Linq; class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { Func<int, int> f = null; f = x => <AS:1>1 + Goo(x)</AS:1>; <AS:2>Console.Write(f(2));</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Try_Lambda2() { var src1 = @" using System; using System.Linq; class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { Func<int, int> f = x => { try { <AS:1>return 1 + Goo(x);</AS:1> } <ER:1.0>catch { }</ER:1.0> }; <AS:2>Console.Write(f(2));</AS:2> } }"; var src2 = @" using System; using System.Linq; class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { Func<int, int> f = x => { <AS:1>return 1 + Goo(x);</AS:1> }; <AS:2>Console.Write(f(2));</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "return 1 + Goo(x);", CSharpFeaturesResources.try_block)); } [Fact] public void Try_Query_Join1() { var src1 = @" class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { try { q = from x in xs join y in ys on <AS:1>F()</AS:1> equals G() select 1; } catch { } <AS:2>q.ToArray();</AS:2> } }"; var src2 = @" class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { q = from x in xs join y in ys on <AS:1>F()</AS:1> equals G() select 1; <AS:2>q.ToArray();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Checked/Unchecked [Fact] public void CheckedUnchecked_Insert_Leaf() { var src1 = @" class Test { static void Main(string[] args) { int a = 1, b = 2; <AS:0>Console.WriteLine(a*b);</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { int a = 1, b = 2; checked { <AS:0>Console.WriteLine(a*b);</AS:0> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void CheckedUnchecked_Insert_Internal() { var src1 = @" class Test { static void Main(string[] args) { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { checked { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "checked", CSharpFeaturesResources.checked_statement)); } [Fact] public void CheckedUnchecked_Delete_Internal() { var src1 = @" class Test { static void Main(string[] args) { checked { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "System.Console.WriteLine(5 * M(1, 2));", CSharpFeaturesResources.checked_statement)); } [Fact] public void CheckedUnchecked_Update_Internal() { var src1 = @" class Test { static void Main(string[] args) { unchecked { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { checked { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "checked", CSharpFeaturesResources.checked_statement)); } [Fact] public void CheckedUnchecked_Lambda1() { var src1 = @" class Test { static void Main(string[] args) { unchecked { Action f = () => <AS:1>5 * M(1, 2)</AS:1>; } <AS:2>f();</AS:2> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { checked { Action f = () => <AS:1>5 * M(1, 2)</AS:1>; } <AS:2>f();</AS:2> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "checked", CSharpFeaturesResources.checked_statement)); } [Fact] public void CheckedUnchecked_Query1() { var src1 = @" using System.Collections.Generic; using System.Linq; class Test { static void Main() { IEnumerable<int> f; unchecked { f = from a in new[] { 5 } select <AS:1>M(a, int.MaxValue)</AS:1>; } <AS:2>f.ToArray();</AS:2> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var src2 = @" using System.Collections.Generic; using System.Linq; class Test { static void Main() { IEnumerable<int> f; checked { f = from a in new[] { 5 } select <AS:1>M(a, int.MaxValue)</AS:1>; } <AS:2>f.ToArray();</AS:2> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "checked", CSharpFeaturesResources.checked_statement)); } #endregion #region Lambdas [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_GeneralStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>F(a => <AS:0>1</AS:0>);</AS:1> } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>F(a => <AS:0>2</AS:0>);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_Nested1() { var src1 = @" class C { static void Main(string[] args) { <AS:2>F(b => <AS:1>F(a => <AS:0>1</AS:0>)</AS:1>);</AS:2> } } "; var src2 = @" class C { static void Main(string[] args) { <AS:2>F(b => <AS:1>F(a => <AS:0>2</AS:0>)</AS:1>);</AS:2> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_Nested2() { var src1 = @" class C { static void Main(string[] args) { <AS:2>F(b => <AS:1>F(a => <AS:0>1</AS:0>)</AS:1>);</AS:2> } } "; var src2 = @" class C { static void Main(string[] args) { <AS:2>F(b => <AS:1>G(a => <AS:0>2</AS:0>)</AS:1>);</AS:2> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "G(a => 2 )")); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_IfStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>if (F(a => <AS:0>1</AS:0>))</AS:1> { } } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>if (F(a => <AS:0>2</AS:0>))</AS:1> { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_WhileStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>while (F(a => <AS:0>1</AS:0>))</AS:1> { } } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>while (F(a => <AS:0>2</AS:0>))</AS:1> { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_DoStatement() { var src1 = @" class C { static void Main(string[] args) { do {} <AS:1>while (F(a => <AS:0>1</AS:0>));</AS:1> } } "; var src2 = @" class C { static void Main(string[] args) { do {} <AS:1>while (F(a => <AS:0>2</AS:0>));</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_SwitchStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>switch (F(a => <AS:0>1</AS:0>))</AS:1> { case 0: break; case 1: break; } } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>switch (F(a => <AS:0>2</AS:0>))</AS:1> { case 0: break; case 1: break; } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_LockStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>lock (F(a => <AS:0>1</AS:0>))</AS:1> {} } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>lock (F(a => <AS:0>2</AS:0>))</AS:1> {} } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_UsingStatement1() { var src1 = @" class C { static void Main(string[] args) { <AS:1>using (F(a => <AS:0>1</AS:0>))</AS:1> {} } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>using (F(a => <AS:0>2</AS:0>))</AS:1> {} } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_ExpressionToStatements() { var src1 = @" class C { static void Main(string[] args) { Func<int, int> f = a => <AS:0>1</AS:0>; } } "; var src2 = @" class C { static void Main(string[] args) { <AS:0>Func<int, int> f = a => { return 1; };</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_ExpressionToDelegate() { var src1 = @" using System; class C { static void Main() { Func<int, int> f = a => <AS:0>1</AS:0>; } } "; var src2 = @" using System; class C { static void Main() { <AS:0>Func<int, int> f = delegate(int a) { return 1; };</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_StatementsToExpression() { var src1 = @" class C { static void Main(string[] args) { Func<int, int> f = a => { <AS:0>return 1;</AS:0> }; } } "; var src2 = @" class C { static void Main(string[] args) { <AS:0>Func<int, int> f = a => 1;</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_DelegateToExpression() { var src1 = @" using System; class C { static void Main() { Func<int, int> f = delegate(int a) { <AS:0>return 1;</AS:0> }; } } "; var src2 = @" using System; class C { static void Main() { <AS:0>Func<int, int> f = a => 1;</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_StatementsToDelegate() { var src1 = @" using System; class C { static void Main() { Func<int, int> f = a => { <AS:0>return 1;</AS:0> }; } } "; var src2 = @" using System; class C { static void Main() { Func<int, int> f = delegate(int a) { <AS:0>return 2;</AS:0> }; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_ActiveStatementUpdate() { var src1 = @" using System; class C { static void Main(string[] args) { Func<int, int, int> f = (int a, int b) => <AS:0>a + b + 1</AS:0>; <AS:1>f(2);</AS:1> } }"; var src2 = @" using System; class C { static void Main(string[] args) { Func<int, int, int> f = (_, _) => <AS:0>10</AS:0>; <AS:1>f(2);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Lambdas_ActiveStatementRemoved1() { var src1 = @" class C { static void Main(string[] args) { Func<int, Func<int, int>> f = a => { return b => { <AS:0>return b;</AS:0> }; }; var z = f(1); <AS:1>z(2);</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { Func<int, int> f = b => { <AS:0>return b;</AS:0> }; var z = f; <AS:1>z(2);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "return b;", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_ActiveStatementRemoved2() { var src1 = @" class C { static void Main(string[] args) { Func<int, Func<int, int>> f = a => (b) => <AS:0>b</AS:0>; var z = f(1); <AS:1>z(2);</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { Func<int, int> f = <AS:0>(b)</AS:0> => b; var z = f; <AS:1>z(2);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "(b)", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_ActiveStatementRemoved3() { var src1 = @" class C { static void Main(string[] args) { Func<int, Func<int, int>> f = a => { Func<int, int> z; F(b => { <AS:0>return b;</AS:0> }, out z); return z; }; var z = f(1); <AS:1>z(2);</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { Func<int, int> f = b => { <AS:0>F(b);</AS:0> return 1; }; var z = f; <AS:1>z(2);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "F(b);", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_ActiveStatementRemoved4() { var src1 = @" class C { static void Main(string[] args) { Func<int, Func<int, int>> f = a => { <AS:1>z(2);</AS:1> return b => { <AS:0>return b;</AS:0> }; }; } }"; var src2 = @" class C { static void Main(string[] args) <AS:0,1>{</AS:0,1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "{", CSharpFeaturesResources.lambda), Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "{", CSharpFeaturesResources.lambda)); } [Fact] public void Queries_ActiveStatementRemoved_WhereClause() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b where <AS:0>b.goo</AS:0> select b.bar; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select b.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.where_clause)); } [Fact] public void Queries_ActiveStatementRemoved_LetClause() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b let x = <AS:0>b.goo</AS:0> select x; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select a.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.let_clause)); } [Fact] public void Queries_ActiveStatementRemoved_JoinClauseLeft() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b join c in d on <AS:0>a.goo</AS:0> equals c.bar select a.bar; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select a.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.join_clause)); } [Fact] public void Queries_ActiveStatementRemoved_OrderBy1() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b orderby <AS:0>a.x</AS:0>, a.y descending, a.z ascending select a; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select a.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.orderby_clause)); } [Fact] public void Queries_ActiveStatementRemoved_OrderBy2() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b orderby a.x, <AS:0>a.y</AS:0> descending, a.z ascending select a; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select a.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.orderby_clause)); } [Fact] public void Queries_ActiveStatementRemoved_OrderBy3() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b orderby a.x, a.y descending, <AS:0>a.z</AS:0> ascending select a; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select a.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.orderby_clause)); } [Fact] public void Queries_Remove_JoinInto1() { var src1 = @" class C { static void Main() { var q = from x in xs join y in ys on F() equals G() into g select <AS:0>1</AS:0>; } }"; var src2 = @" class C { static void Main() { var q = from x in xs join y in ys on F() equals G() select <AS:0>1</AS:0>; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Queries_Remove_QueryContinuation1() { var src1 = @" class C { static void Main() { var q = from x in xs group x by x.F() into g where <AS:0>g.F()</AS:0> select 1; } }"; var src2 = @" class C { static void Main() { var q = from x in xs group x by x.F() <AS:0>into</AS:0> g select 1; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "into", CSharpFeaturesResources.where_clause)); } [Fact] public void Queries_Remove_QueryContinuation2() { var src1 = @" class C { static void Main() { var q = from x in xs group x by x.F() into g select <AS:0>1</AS:0>; } }"; var src2 = @" class C { static void Main() { var q = from x in xs <AS:0>join</AS:0> y in ys on F() equals G() into g select 1; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "join", CSharpFeaturesResources.select_clause)); } [Fact] public void Queries_Select_Reduced1() { var src1 = @" class C { static void Main() { var q = from a in array where a > 0 select <AS:0>a + 1</AS:0>; } }"; var src2 = @" class C { static void Main() { var q = from a in array where a > 0 <AS:0>select</AS:0> a; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "select", CSharpFeaturesResources.select_clause)); } [Fact] public void Queries_Select_Reduced2() { var src1 = @" class C { static int F(IEnumerable<int> e) => <AS:0>1</AS:0>; static void Main() { <AS:1>F(from a in array where a > 0 select a + 1);</AS:1> } }"; var src2 = @" class C { static int F(IEnumerable<int> e) => <AS:0>1</AS:0>; static void Main() { <AS:1>F(from a in array where a > 0 select a);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "F(from a in array where a > 0 select a);")); } [Fact] public void Queries_GroupBy_Reduced1() { var src1 = @" class C { static void Main() { var q = from a in array group <AS:0>a + 1</AS:0> by a; } }"; var src2 = @" class C { static void Main() { var q = from a in array <AS:0>group</AS:0> a by a; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "group", CSharpFeaturesResources.groupby_clause)); } [Fact] public void Queries_GroupBy_Reduced2() { var src1 = @" class C { static int F(IEnumerable<IGrouping<int, int>> e) => <AS:0>1</AS:0>; static void Main() { <AS:1>F(from a in array group a by a);</AS:1> } }"; var src2 = @" class C { static int F(IEnumerable<IGrouping<int, int>> e) => <AS:0>1</AS:0>; static void Main() { <AS:1>F(from a in array group a + 1 by a);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "F(from a in array group a + 1 by a);")); } #endregion #region State Machines [Fact] public void MethodToIteratorMethod_WithActiveStatement() { var src1 = @" class C { static IEnumerable<int> F() { <AS:0>Console.WriteLine(1);</AS:0> return new[] { 1, 2, 3 }; } } "; var src2 = @" class C { static IEnumerable<int> F() { <AS:0>Console.WriteLine(1);</AS:0> yield return 1; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "yield return 1;", CSharpFeaturesResources.yield_return_statement)); } [Fact] public void MethodToIteratorMethod_WithActiveStatementInLambda() { var src1 = @" class C { static IEnumerable<int> F() { var f = new Action(() => { <AS:0>Console.WriteLine(1);</AS:0> }); return new[] { 1, 2, 3 }; } } "; var src2 = @" class C { static IEnumerable<int> F() { var f = new Action(() => { <AS:0>Console.WriteLine(1);</AS:0> }); yield return 1; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // should not contain RUDE_EDIT_INSERT_AROUND edits.VerifyRudeDiagnostics(active); } [Fact] public void MethodToIteratorMethod_WithoutActiveStatement() { var src1 = @" class C { static IEnumerable<int> F() { Console.WriteLine(1); return new[] { 1, 2, 3 }; } } "; var src2 = @" class C { static IEnumerable<int> F() { Console.WriteLine(1); yield return 1; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void MethodToAsyncMethod_WithActiveStatement_AwaitExpression() { var src1 = @" class C { static Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> return Task.FromResult(1); } } "; var src2 = @" class C { static async Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> return await Task.FromResult(1); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void MethodToAsyncMethod_WithActiveStatement_AwaitForEach() { var src1 = @" class C { static Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> return Task.FromResult(1); } } "; var src2 = @" class C { static async Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> await foreach (var x in AsyncIter()) { } return 1; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "await foreach (var x in AsyncIter())", CSharpFeaturesResources.asynchronous_foreach_statement)); } [Fact] public void MethodToAsyncMethod_WithActiveStatement_AwaitUsing() { var src1 = @" class C { static Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> return Task.FromResult(1); } } "; var src2 = @" class C { static async Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> await using IAsyncDisposable x = new AsyncDisposable(), y = new AsyncDisposable(); return 1; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "x = new AsyncDisposable()", CSharpFeaturesResources.asynchronous_using_declaration), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "y = new AsyncDisposable()", CSharpFeaturesResources.asynchronous_using_declaration)); } [Fact] public void MethodToAsyncMethod_WithActiveStatement_NoAwait1() { var src1 = @" class C { static void F() <AS:0>{</AS:0> Console.WriteLine(1); } } "; var src2 = @" class C { static async void F() <AS:0>{</AS:0> Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "static async void F()")); } [Fact] public void MethodToAsyncMethod_WithActiveStatement_NoAwait2() { var src1 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var src2 = @" class C { static async void F() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "static async void F()")); } [Fact] public void MethodToAsyncMethod_WithActiveStatementInLambda1() { var src1 = @" class C { static Task<int> F() { var f = new Action(() => { <AS:0>Console.WriteLine(1);</AS:0> }); return Task.FromResult(1); } } "; var src2 = @" class C { static async Task<int> F() { var f = new Action(() => { <AS:0>Console.WriteLine(1);</AS:0> }); return await Task.FromResult(1); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // should not contain RUDE_EDIT_INSERT_AROUND edits.VerifyRudeDiagnostics(active); } [Fact] public void MethodToAsyncMethod_WithActiveStatementInLambda_2() { var src1 = @" class C { static void F() { var f = new Action(() => { <AS:1>Console.WriteLine(1);</AS:1> }); <AS:0>f();</AS:0> } } "; var src2 = @" class C { static async void F() { var f = new Action(() => { <AS:1>Console.WriteLine(1);</AS:1> }); <AS:0>f();</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "static async void F()")); } [Fact] public void MethodToAsyncMethod_WithLambda() { var src1 = @" class C { static void F() <AS:0>{</AS:0> var f = new Action(() => { Console.WriteLine(1); }); f(); } } "; var src2 = @" class C { static async void F() <AS:0>{</AS:0> var f = new Action(() => { Console.WriteLine(1); }); f(); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "static async void F()")); } [Fact] public void MethodToAsyncMethod_WithoutActiveStatement_1() { var src1 = @" class C { static Task<int> F() { Console.WriteLine(1); return Task.FromResult(1); } } "; var src2 = @" class C { static async Task<int> F() { Console.WriteLine(1); return await Task.FromResult(1); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void MethodToAsyncMethod_WithoutActiveStatement_2() { var src1 = @" class C { static void F() { Console.WriteLine(1); } } "; var src2 = @" class C { static async void F() { Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void LambdaToAsyncLambda_WithActiveStatement() { var src1 = @" using System; using System.Threading.Tasks; class C { static void F() { var f = new Func<Task<int>>(() => { <AS:0>Console.WriteLine(1);</AS:0> return Task.FromResult(1); }); } } "; var src2 = @" using System; using System.Threading.Tasks; class C { static void F() { var f = new Func<Task<int>>(async () => { <AS:0>Console.WriteLine(1);</AS:0> return await Task.FromResult(1); }); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void LambdaToAsyncLambda_WithActiveStatement_NoAwait() { var src1 = @" using System; class C { static void F() { var f = new Action(() => { <AS:0>Console.WriteLine(1);</AS:0> }); } } "; var src2 = @" using System; class C { static void F() { var f = new Action(async () => { <AS:0>Console.WriteLine(1);</AS:0> }); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "()")); } [Fact] public void LambdaToAsyncLambda_WithActiveStatement_NoAwait_Nested() { var src1 = @" class C { static void F() { var f = new Func<int, Func<int, int>>(a => <AS:0>b => 1</AS:0>); } } "; var src2 = @" class C { static void F() { var f = new Func<int, Func<int, int>>(async a => <AS:0>b => 1</AS:0>); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "a")); } [Fact] [WorkItem(37054, "https://github.com/dotnet/roslyn/issues/37054")] public void LocalFunctionToAsyncLocalFunction_BlockBody_WithActiveStatement() { var src1 = @" class C { static void F() { Task<int> f() { <AS:0>Console.WriteLine(1);</AS:0> return Task.FromResult(1); } } } "; var src2 = @" class C { static void F() { async Task<int> f() { <AS:0>Console.WriteLine(1);</AS:0> return await Task.FromResult(1); } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "await", CSharpFeaturesResources.await_expression)); } [Fact] [WorkItem(37054, "https://github.com/dotnet/roslyn/issues/37054")] public void LocalFunctionToAsyncLocalFunction_ExpressionBody_WithActiveStatement() { var src1 = @" class C { static void F() { Task<int> f() => <AS:0>Task.FromResult(1)</AS:0>; } } "; var src2 = @" class C { static void F() { async Task<int> f() => <AS:0>await Task.FromResult(1)</AS:0>; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void AnonymousFunctionToAsyncAnonymousFunction_WithActiveStatement_NoAwait() { var src1 = @" using System.Threading.Tasks; class C { static void F() { var f = new Func<Task>(delegate() { <AS:0>Console.WriteLine(1);</AS:0> return Task.CompletedTask; }); } } "; var src2 = @" using System.Threading.Tasks; class C { static async void F() { var f = new Func<Task>(async delegate() { <AS:0>Console.WriteLine(1);</AS:0> }); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, FeaturesResources.delegate_)); } [Fact] public void AsyncMethodEdit_Semantics() { var src1 = @" using System; using System.Threading.Tasks; class C { static async Task<int> F() { await using var x = new AsyncDisposable(); await foreach (var x in AsyncIter()) { Console.WriteLine(x); } return await Task.FromResult(1); } } "; var src2 = @" using System; using System.Threading.Tasks; class C { static async Task<int> F() { await using var x = new AsyncDisposable(); await foreach (var x in AsyncIter()) { Console.WriteLine(x + 1); } return await Task.FromResult(2); } } "; var edits = GetTopEdits(src1, src2); _ = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void IteratorMethodEdit_Semantics() { var src1 = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> F() { Console.WriteLine(1); yield return 1; } } "; var src2 = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> F() { Console.WriteLine(2); yield return 2; } } "; var edits = GetTopEdits(src1, src2); _ = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void AsyncIteratorMethodEdit_Semantics() { var src1 = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class C { static async IAsyncEnumerable<int> F() { Console.WriteLine(1); await Task.Delay(1); yield return 1; } } "; var src2 = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class C { static async IAsyncEnumerable<int> F() { Console.WriteLine(2); await Task.Delay(2); yield return 2; } } "; var edits = GetTopEdits(src1, src2); _ = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(targetFrameworks: new[] { TargetFramework.NetCoreApp }); } [Fact] public void AsyncMethodToMethod() { var src1 = @" class C { static async void F() { } } "; var src2 = @" class C { static void F() { } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "static void F()", FeaturesResources.method)); } #endregion #region Misplaced AS [Fact] public void MisplacedActiveStatement1() { var src1 = @" <AS:1>class C</AS:1> { public static int F(int a) { <AS:0>return a;</AS:0> <AS:2>return a;</AS:2> } }"; var src2 = @" class C { public static int F(int a) { <AS:0>return a;</AS:0> <AS:2>return a;</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void MisplacedActiveStatement2() { var src1 = @" class C { static <AS:0>void</AS:0> Main(string[] args) { } }"; var src2 = @" class C { static void Main(string[] args) <AS:0>{</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void MisplacedTrackingSpan1() { var src1 = @" class C { static <AS:0>void</AS:0> Main(string[] args) { } }"; var src2 = @" class C { static <TS:0>void</TS:0> Main(string[] args) <AS:0>{</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region C# 7.0 [Fact] public void UpdateAroundActiveStatement_IsPattern() { var src1 = @" class C { static void F(object x) { <AS:0>Console.WriteLine(1);</AS:0> if (x is int i) { Console.WriteLine(""match""); } } } "; var src2 = @" class C { static void F(object x) { <AS:0>Console.WriteLine(1);</AS:0> if (x is string s) { Console.WriteLine(""match""); } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_DeconstructionDeclarationStatement() { var src1 = @" class C { static void F(object x) { <AS:0>Console.WriteLine(1);</AS:0> var (x, y) = (1, 2); } } "; var src2 = @" class C { static void F(object x) { <AS:0>Console.WriteLine(1);</AS:0> var (x, y) = x; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_DeconstructionForEach() { var src1 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> foreach (var (x, y) in new[] { (1, 2) }) { Console.WriteLine(2); } } } "; var src2 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> foreach (var (x, y) in new[] { o }) { Console.WriteLine(2); } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_VarDeconstruction() { var src1 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> for (var (x, y) = o1; ; ) { } } } "; var src2 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> for (var (x, y) = o2; ; ) { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_TypedDeconstruction() { var src1 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> for ((int x, int y) = o1; ; ) { } } } "; var src2 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> for ((int x, int y) = o2; ; ) { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_Tuple() { var src1 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> (int, int) t; } } "; var src2 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> (int, int) t = (1, 2); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_LocalFunction() { var src1 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> void M() { Console.WriteLine(2); } } } "; var src2 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> void M() { Console.WriteLine(3); } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_OutVar() { var src1 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> M(); } } "; var src2 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> M(out var x); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_OutVarRemoved() { var src1 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> M(out var x); } } "; var src2 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_Ref() { var src1 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> ref int i = ref 1; } } "; var src2 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> ref int i = ref 2; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_DeconstructionDeclaration() { var src1 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> var (x, y) = o1; } } "; var src2 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> var (x, y) = o2; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_DeconstructionAssignment() { var src1 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> int x, y; (x, y) = o1; } } "; var src2 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> int x, y; (x, y) = o2; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_SwitchWithPattern() { var src1 = @" class C { static void F(object o1, object o2) { <AS:0>System.Console.WriteLine(1);</AS:0> switch (o1) { case int i: break; } } } "; var src2 = @" class C { static void F(object o1, object o2) { <AS:0>System.Console.WriteLine(1);</AS:0> switch (o2) { case int i: break; } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); edits.VerifySemanticDiagnostics(); } #endregion #region Nullable [Fact] public void ChangeLocalNullableToNonNullable() { var src1 = @" class C { static void F() { <AS:0>string? s = ""a"";</AS:0> } } "; var src2 = @" class C { static void F() { <AS:0>string s = ""a"";</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ChangeLocalNonNullableToNullable() { var src1 = @" class C { static void F() { <AS:0>string s = ""a"";</AS:0> } } "; var src2 = @" class C { static void F() { <AS:0>string? s = ""a"";</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Partial Types [Fact] public void InsertDeleteMethod_Inactive() { // Moving inactive method declaration in a file with active statements. var srcA1 = "partial class C { void F1() { <AS:0>System.Console.WriteLine(1);</AS:0> } }"; var srcB1 = "partial class C { void F2() { } }"; var srcA2 = "partial class C { void F1() { <AS:0>System.Console.WriteLine(1);</AS:0> } void F2() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( activeStatements: GetActiveStatements(srcA1, srcA2, path: "0"), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F2")), }), DocumentResults( activeStatements: GetActiveStatements(srcB1, srcB2, path: "1")) }); } [Fact] [WorkItem(51177, "https://github.com/dotnet/roslyn/issues/51177")] [WorkItem(54758, "https://github.com/dotnet/roslyn/issues/54758")] public void InsertDeleteMethod_Active() { // Moving active method declaration in a file with active statements. // TODO: this is currently a rude edit var srcA1 = "partial class C { }"; var srcB1 = "partial class C { void F() { <AS:0>System.Console.WriteLine(1);</AS:0> } }"; var srcA2 = "partial class C { void F() { System.Console.WriteLine(1); } }"; var srcB2 = "<AS:0>partial class C</AS:0> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( activeStatements: GetActiveStatements(srcA1, srcA2, path: "0"), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")), }), DocumentResults( activeStatements: GetActiveStatements(srcB1, srcB2, path: "1"), // TODO: this is odd AS location https://github.com/dotnet/roslyn/issues/54758 diagnostics: new[] { Diagnostic(RudeEditKind.DeleteActiveStatement, " partial c", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } #endregion #region Records [Fact] public void Record() { var src1 = @" record C(int X) { public int X { get; init; } = <AS:0>1</AS:0>; }"; var src2 = @" record C(int X) { public int X { get; init; } = <AS:0>2</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Record_Constructor() { var src1 = @" record C(int X) { public int X { get; init; } = <AS:0>1</AS:0>; static void Main(string[] args) { <AS:1>var x = new C(1);</AS:1> } }"; var src2 = @" record C(int X) { public int X { get; init; } = <AS:0>2</AS:0>; static void Main(string[] args) { <AS:1>var x = new C(1);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Record_FieldInitializer_Lambda2() { var src1 = @" record C(int X) { Func<int, Func<int>> a = z => () => <AS:0>z + 1</AS:0>; static void Main(string[] args) { <AS:1>new C(1).a(1)();</AS:1> } }"; var src2 = @" record C(int X) { Func<int, Func<int>> a = z => () => <AS:0>z + 2</AS:0>; static void Main(string[] args) { <AS:1>new C(1).a(1)();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Line Mapping /// <summary> /// Validates that changes in #line directives produce semantic updates of the containing method. /// </summary> [Fact] public void LineMapping_ChangeLineNumber_WithinMethod() { var src1 = @" class C { #line 1 ""a"" static void F() { <AS:0>A();</AS:0> #line 5 ""b"" B(1); <AS:1>B();</AS:1> #line 2 ""c"" <AS:2>C();</AS:2> <AS:3>C();</AS:3> #line hidden D(); #line default <AS:4>E();</AS:4> } }"; var src2 = @" class C { #line 1 ""a"" static void F() { <AS:0>A();</AS:0> #line 5 ""b"" B(2); <AS:1>B();</AS:1> #line 9 ""c"" <AS:2>C();</AS:2> <AS:3>C();</AS:3> #line hidden D(); #line default <AS:4>E();</AS:4> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void LineMapping_ChangeFilePath() { var src1 = @" class C { static void F() { <AS:0>A();</AS:0> #line 1 ""a"" <AS:1>B();</AS:1> } }"; var src2 = @" class C { static void F() { <AS:0>A();</AS:0> #line 1 ""b"" <AS:1>B();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "B();", string.Format(FeaturesResources._0_directive, "line"))); } [Fact] public void LineMapping_ExceptionRegions_ChangeLineNumber() { var src1 = @" class C { static void Main() <AS:0>{</AS:0> try { try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line default } #line 20 ""b"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var src2 = @" class C { static void Main() <AS:0>{</AS:0> try { try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line default } #line 30 ""b"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(52971, "https://github.com/dotnet/roslyn/issues/52971")] public void LineMapping_ExceptionRegions_ChangeFilePath() { var src1 = @" class C { static void Main() <AS:0>{</AS:0> try { try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line default } #line 20 ""b"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var src2 = @" class C { static void Main() <AS:0>{</AS:0> try { try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line default } #line 20 ""c"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // TODO: rude edit should be reported edits.VerifyRudeDiagnostics(active); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/52971"), WorkItem(52971, "https://github.com/dotnet/roslyn/issues/52971")] public void LineMapping_ExceptionRegions_LineChange_MultipleMappedFiles() { var src1 = @" class C { static void Main() <AS:0>{</AS:0> try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line 20 ""b"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var src2 = @" class C { static void Main() <AS:0>{</AS:0> try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line 30 ""b"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // TODO: rude edit? edits.VerifyRudeDiagnostics(active); } #endregion #region Misc [Fact] public void Delete_All_SourceText() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @""; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "C"))); } [Fact] public void PartiallyExecutedActiveStatement() { var src1 = @" class C { public static void F() { <AS:0>Console.WriteLine(1);</AS:0> <AS:1>Console.WriteLine(2);</AS:1> <AS:2>Console.WriteLine(3);</AS:2> <AS:3>Console.WriteLine(4);</AS:3> <AS:4>Console.WriteLine(5);</AS:4> } }"; var src2 = @" class C { public static void F() { <AS:0>Console.WriteLine(10);</AS:0> <AS:1>Console.WriteLine(20);</AS:1> <AS:2>Console.WriteLine(30);</AS:2> <AS:3>Console.WriteLine(40);</AS:3> <AS:4>Console.WriteLine(50);</AS:4> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2, flags: new[] { ActiveStatementFlags.PartiallyExecuted | ActiveStatementFlags.IsLeafFrame, ActiveStatementFlags.PartiallyExecuted | ActiveStatementFlags.IsNonLeafFrame, ActiveStatementFlags.IsLeafFrame, ActiveStatementFlags.IsNonLeafFrame, ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.IsLeafFrame }); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.PartiallyExecutedActiveStatementUpdate, "Console.WriteLine(10);"), Diagnostic(RudeEditKind.ActiveStatementUpdate, "Console.WriteLine(20);"), Diagnostic(RudeEditKind.ActiveStatementUpdate, "Console.WriteLine(40);"), Diagnostic(RudeEditKind.ActiveStatementUpdate, "Console.WriteLine(50);")); } [Fact] public void PartiallyExecutedActiveStatement_Deleted1() { var src1 = @" class C { public static void F() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { public static void F() { <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2, flags: new[] { ActiveStatementFlags.PartiallyExecuted | ActiveStatementFlags.IsLeafFrame }); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.PartiallyExecutedActiveStatementDelete, "{", FeaturesResources.code)); } [Fact] public void PartiallyExecutedActiveStatement_Deleted2() { var src1 = @" class C { public static void F() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { public static void F() { <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2, flags: new[] { ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.IsLeafFrame }); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } [Fact] public void Block_Delete() { var src1 = @" class C { public static void F() { G(1); <AS:0>{</AS:0> G(2); } G(3); } } "; var src2 = @" class C { public static void F() { G(1); <AS:0>G(3);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Theory, CombinatorialData] public void MemberBodyInternalError(bool outOfMemory) { var src1 = @" class C { public static void F() { <AS:1>G();</AS:1> } public static void G() { <AS:0>H(1);</AS:0> } public static void H(int x) { } } "; var src2 = @" class C { public static void F() { <AS:1>G();</AS:1> } public static void G() { <AS:0>H(2);</AS:0> } public static void H(int x) { } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); var validator = new CSharpEditAndContinueTestHelpers(faultInjector: node => { if (node.Parent is MethodDeclarationSyntax methodDecl && methodDecl.Identifier.Text == "G") { throw outOfMemory ? new OutOfMemoryException() : new NullReferenceException("NullRef!"); } }); var expectedDiagnostic = outOfMemory ? Diagnostic(RudeEditKind.MemberBodyTooBig, "public static void G()", FeaturesResources.method) : Diagnostic(RudeEditKind.MemberBodyInternalError, "public static void G()", FeaturesResources.method); validator.VerifySemantics( new[] { edits }, TargetFramework.NetCoreApp, new[] { DocumentResults(diagnostics: new[] { expectedDiagnostic }) }); } #endregion #region Top Level Statements [Fact] public void TopLevelStatements_UpdateAroundActiveStatement_LocalFunction() { var src1 = @" using System; <AS:0>Console.WriteLine(1);</AS:0> void M() { Console.WriteLine(2); } "; var src2 = @" using System; <AS:0>Console.WriteLine(1);</AS:0> void M() { Console.WriteLine(3); } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void TopLevelStatements_UpdateAroundActiveStatement_OutVar() { var src1 = @" using System; <AS:0>Console.WriteLine(1);</AS:0> M(); "; var src2 = @" using System; <AS:0>Console.WriteLine(1);</AS:0> M(out var x); "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void TopLevelStatements_Inner() { var src1 = @" using System; <AS:1>Goo(1);</AS:1> static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } "; var src2 = @" using System; while (true) { <AS:1>Goo(2);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "Goo(2);")); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.CSharp.UnitTests; using System.Linq; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { [UseExportProvider] public class ActiveStatementTests : EditingTestBase { #region Update [Fact] public void Update_Inner() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { while (true) { <AS:1>Goo(2);</AS:1> } } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "Goo(2);")); } [Fact] public void Update_Inner_NewCommentAtEndOfActiveStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1>// } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } /// <summary> /// CreateNewOnMetadataUpdate has no effect in presence of active statements (in break mode). /// </summary> [Fact] public void Update_Inner_Reloadable() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C { static void Main() { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C { static void Main() { while (true) { <AS:1>Goo(2);</AS:1> } } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "Goo(2);")); } [Fact] public void Update_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { while (true) { <AS:1>Goo(1);</AS:1> } } static void Goo(int a) { <AS:0>Console.WriteLine(a + 1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Update_Leaf_NewCommentAtEndOfActiveStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0>// } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } /// <summary> /// CreateNewOnMetadataUpdate has no effect in presence of active statements (in break mode). /// </summary> [Fact] public void Update_Leaf_Reloadable() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C { static void Main(string[] args) { while (true) { <AS:1>Goo(1);</AS:1> } } static void Goo(int a) { <AS:0>Console.WriteLine(a + 1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemantics(active, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Goo"), preserveLocalVariables: true) }); } [WorkItem(846588, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/846588")] [Fact] public void Update_Leaf_Block() { var src1 = @" class C : System.IDisposable { public void Dispose() {} static void Main(string[] args) { using (<AS:0>C x = null</AS:0>) {} } }"; var src2 = @" class C : System.IDisposable { public void Dispose() {} static void Main(string[] args) { using (<AS:0>C x = new C()</AS:0>) {} } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Delete in Method Body [Fact] public void Delete_Inner() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { while (true) { } <AS:1>}</AS:1> static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } // TODO (tomat): considering a change [Fact] public void Delete_Inner_MultipleParents() { var src1 = @" class C : IDisposable { unsafe static void Main(string[] args) { { <AS:1>Goo(1);</AS:1> } if (true) { <AS:2>Goo(2);</AS:2> } else { <AS:3>Goo(3);</AS:3> } int x = 1; switch (x) { case 1: case 2: <AS:4>Goo(4);</AS:4> break; default: <AS:5>Goo(5);</AS:5> break; } checked { <AS:6>Goo(4);</AS:6> } unchecked { <AS:7>Goo(7);</AS:7> } while (true) <AS:8>Goo(8);</AS:8> do <AS:9>Goo(9);</AS:9> while (true); for (int i = 0; i < 10; i++) <AS:10>Goo(10);</AS:10> foreach (var i in new[] { 1, 2}) <AS:11>Goo(11);</AS:11> using (var z = new C()) <AS:12>Goo(12);</AS:12> fixed (char* p = ""s"") <AS:13>Goo(13);</AS:13> label: <AS:14>Goo(14);</AS:14> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C : IDisposable { unsafe static void Main(string[] args) { { <AS:1>}</AS:1> if (true) { <AS:2>}</AS:2> else { <AS:3>}</AS:3> int x = 1; switch (x) { case 1: case 2: <AS:4>break;</AS:4> default: <AS:5>break;</AS:5> } checked { <AS:6>}</AS:6> unchecked { <AS:7>}</AS:7> <AS:8>while (true)</AS:8> { } do { } <AS:9>while (true);</AS:9> for (int i = 0; i < 10; <AS:10>i++</AS:10>) { } foreach (var i <AS:11>in</AS:11> new[] { 1, 2 }) { } using (<AS:12>var z = new C()</AS:12>) { } fixed (<AS:13>char* p = ""s""</AS:13>) { } label: <AS:14>{</AS:14> } } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "case 2:", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "default:", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "while (true)", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "do", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "for (int i = 0; i < 10; i++ )", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "foreach (var i in new[] { 1, 2 })", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "using ( var z = new C() )", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "fixed ( char* p = \"s\" )", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "label", FeaturesResources.code)); } [Fact] public void Delete_Leaf1() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>}</AS:0> } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Delete_Leaf2() { var src1 = @" class C { static void Goo(int a) { Console.WriteLine(1); Console.WriteLine(2); <AS:0>Console.WriteLine(3);</AS:0> Console.WriteLine(4); } }"; var src2 = @" class C { static void Goo(int a) { Console.WriteLine(1); Console.WriteLine(2); <AS:0>Console.WriteLine(4);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Delete_Leaf_InTry() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { try { <AS:0>Console.WriteLine(a);</AS:0> } catch { } } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { try { <AS:0>}</AS:0> catch { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Delete_Leaf_InTry2() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { try { try { <AS:0>Console.WriteLine(a);</AS:0> } catch { } } catch { } } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { try { try { <AS:0>}</AS:0> catch { } } catch { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Delete_Inner_CommentActiveStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { //Goo(1); <AS:1>}</AS:1> static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } [WorkItem(755959, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755959")] [Fact] public void Delete_Leaf_CommentActiveStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { //Console.WriteLine(a); <AS:0>}</AS:0> } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Delete_EntireNamespace() { var src1 = @" namespace N { class C { static void Main(String[] args) { <AS:0>Console.WriteLine(1);</AS:0> } } }"; var src2 = @"<AS:0></AS:0>"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.Delete, null, FeaturesResources.namespace_), Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "N.C"))); } #endregion #region Constructors [WorkItem(740949, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/740949")] [Fact] public void Updated_Inner_Constructor() { var src1 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; public Goo(int a) { <AS:0>this.value = a;</AS:0> } }"; var src2 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5*2);</AS:1> } } class Goo { int value; public Goo(int a) { <AS:0>this.value = a;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "Goo f = new Goo(5*2);")); } [WorkItem(741249, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/741249")] [Fact] public void Updated_Leaf_Constructor() { var src1 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; public Goo(int a) { <AS:0>this.value = a;</AS:0> } }"; var src2 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; public Goo(int a) { <AS:0>this.value = a*2;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Fact] public void Updated_Leaf_Constructor_Parameter() { var src1 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; <AS:0>public Goo(int a)</AS:0> { this.value = a; } }"; var src2 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; <AS:0>public Goo(int b)</AS:0> { this.value = b; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Goo..ctor")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Fact] public void Updated_Leaf_Constructor_Parameter_DefaultValue() { var src1 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; <AS:0>public Goo(int a = 5)</AS:0> { this.value = a; } }"; var src2 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; <AS:0>public Goo(int a = 42)</AS:0> { this.value = a; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InitializerUpdate, "int a = 42", FeaturesResources.parameter)); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Fact] public void Updated_Leaf_ConstructorChaining1() { var src1 = @" using System; class Test { static void Main(string[] args) { <AS:1>B b = new B(2, 3);</AS:1> } } class B : A { public B(int x, int y) : <AS:0>base(x + y, x - y)</AS:0> { } } class A { public A(int x, int y) : this(5 + x, y, 0) { } public A(int x, int y, int z) { } }"; var src2 = @" using System; class Test { static void Main(string[] args) { <AS:1>B b = new B(2, 3);</AS:1> } } class B : A { public B(int x, int y) : <AS:0>base(x + y + 5, x - y)</AS:0> { } } class A { public A(int x, int y) : this(x, y, 0) { } public A(int x, int y, int z) { } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Fact] public void Updated_Leaf_ConstructorChaining2() { var src1 = @" using System; class Test { static void Main(string[] args) { <AS:2>B b = new B(2, 3);</AS:2> } } class B : A { public B(int x, int y) : <AS:1>base(x + y, x - y)</AS:1> { } } class A { public A(int x, int y) : <AS:0>this(x, y, 0)</AS:0> { } public A(int x, int y, int z) { } }"; var src2 = @" using System; class Test { static void Main(string[] args) { <AS:2>B b = new B(2, 3);</AS:2> } } class B : A { public B(int x, int y) : <AS:1>base(x + y, x - y)</AS:1> { } } class A { public A(int x, int y) : <AS:0>this(5 + x, y, 0)</AS:0> { } public A(int x, int y, int z) { } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Fact] public void InstanceConstructorWithoutInitializer() { var src1 = @" class C { int a = 5; <AS:0>public C(int a)</AS:0> { } static void Main(string[] args) { <AS:1>C c = new C(3);</AS:1> } }"; var src2 = @" class C { int a = 42; <AS:0>public C(int a)</AS:0> { } static void Main(string[] args) { <AS:1>C c = new C(3);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializer_Internal_Update1() { var src1 = @" class D { public D(int d) {} } class C : D { int a = 5; public C(int a) : <AS:2>this(true)</AS:2> { } public C(bool b) : <AS:1>base(F())</AS:1> {} static int F() { <AS:0>return 1;</AS:0> } static void Main(string[] args) { <AS:3>C c = new C(3);</AS:3> } }"; var src2 = @" class D { public D(int d) {} } class C : D { int a = 5; public C(int a) : <AS:2>this(false)</AS:2> { } public C(bool b) : <AS:1>base(F())</AS:1> {} static int F() { <AS:0>return 1;</AS:0> } static void Main(string[] args) { <AS:3>C c = new C(3);</AS:3> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "this(false)")); } [Fact] public void InstanceConstructorWithInitializer_Internal_Update2() { var src1 = @" class D { public D(int d) {} } class C : D { public C() : <AS:1>base(F())</AS:1> {} static int F() { <AS:0>return 1;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class D { public D(int d) {} } class C : D { <AS:1>public C()</AS:1> {} static int F() { <AS:0>return 1;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "public C()")); } [Fact] public void InstanceConstructorWithInitializer_Internal_Update3() { var src1 = @" class D { public D(int d) <AS:0>{</AS:0> } } class C : D { <AS:1>public C()</AS:1> {} }"; var src2 = @" class D { public D(int d) <AS:0>{</AS:0> } } class C : D { public C() : <AS:1>base(1)</AS:1> {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "base(1)")); } [Fact] public void InstanceConstructorWithInitializer_Leaf_Update1() { var src1 = @" class D { public D(int d) { } } class C : D { public C() : <AS:0>base(1)</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class D { public D(int d) { } } class C : D { public C() : <AS:0>base(2)</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializer_Leaf_Update2() { var src1 = @" class D { public D() { } public D(int d) { } } class C : D { public C() : <AS:0>base(2)</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class D { public D() { } public D(int d) { } } class C : D { <AS:0>public C()</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializer_Leaf_Update3() { var src1 = @" class D { public D() { } public D(int d) { } } class C : D { <AS:0>public C()</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class D { public D() { } public D(int d) { } } class C : D { public C() : <AS:0>base(2)</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializerWithLambda_Update1() { var src1 = @" class C { public C() : this((a, b) => { <AS:0>Console.WriteLine(a + b);</AS:0> }) { } }"; var src2 = @" class C { public C() : base((a, b) => { <AS:0>Console.WriteLine(a - b);</AS:0> }) { } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializerWithLambda_Update2() { var src1 = @" class C { public C() : <AS:1>this((a, b) => { <AS:0>Console.WriteLine(a + b);</AS:0> })</AS:1> { Console.WriteLine(1); } }"; var src2 = @" class C { public C() : <AS:1>this((a, b) => { <AS:0>Console.WriteLine(a + b);</AS:0> })</AS:1> { Console.WriteLine(2); } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializerWithLambda_Update3() { var src1 = @" class C { public C() : <AS:1>this((a, b) => { <AS:0>Console.WriteLine(a + b);</AS:0> })</AS:1> { Console.WriteLine(1); } }"; var src2 = @" class C { public C() : <AS:1>this((a, b) => { <AS:0>Console.WriteLine(a - b);</AS:0> })</AS:1> { Console.WriteLine(1); } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Theory] [InlineData("class ")] [InlineData("struct")] public void InstanceConstructor_DeleteParameterless(string typeKind) { var src1 = "partial " + typeKind + " C { public C() { <AS:0>System.Console.WriteLine(1);</AS:0> } }"; var src2 = "<AS:0>partial " + typeKind + " C</AS:0> { }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "partial " + typeKind + " C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } #endregion #region Field and Property Initializers [Theory] [InlineData("class ")] [InlineData("struct")] public void InstancePropertyInitializer_Leaf_Update(string typeKind) { var src1 = @" " + typeKind + @" C { int a { get; } = <AS:0>1</AS:0>; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" " + typeKind + @" C { int a { get; } = <AS:0>2</AS:0>; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Theory] [InlineData("class ")] [InlineData("struct")] public void InstancePropertyInitializer_Leaf_Update_SynthesizedConstructor(string typeKind) { var src1 = @" " + typeKind + @" C { int a { get; } = <AS:0>1</AS:0>; static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" " + typeKind + @" C { int a { get; } = <AS:0>2</AS:0>; static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Theory] [InlineData("class ")] [InlineData("struct")] public void InstanceFieldInitializer_Leaf_Update1(string typeKind) { var src1 = @" " + typeKind + @" C { <AS:0>int a = 1</AS:0>, b = 2; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" " + typeKind + @" C { <AS:0>int a = 2</AS:0>, b = 2; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Theory] [InlineData("class ")] [InlineData("struct")] public void InstanceFieldInitializer_Leaf_Update1_SynthesizedConstructor(string typeKind) { var src1 = @" " + typeKind + @" C { <AS:0>int a = 1</AS:0>, b = 2; static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" " + typeKind + @" C { <AS:0>int a = 2</AS:0>, b = 2; static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceFieldInitializer_Internal_Update1() { var src1 = @" class C { <AS:1>int a = F(1)</AS:1>, b = F(2); public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class C { <AS:1>int a = F(2)</AS:1>, b = F(2); public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "int a = F(2)")); } [Fact] public void InstanceFieldInitializer_Internal_Update2() { var src1 = @" class C { int a = F(1), <AS:1>b = F(2)</AS:1>; public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class C { int a = F(1), <AS:1>b = F(3)</AS:1>; public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "b = F(3)")); } [Fact] public void InstancePropertyInitializer_Internal_Delete1() { var src1 = @" class C { int a { get; } = <AS:0>1</AS:0>; int b { get; } = 2; }"; var src2 = @" class C { int a { get { return 1; } } int b { get; } = <AS:0>2</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstancePropertyInitializer_Internal_Delete2() { var src1 = @" class C { int a { get; } = <AS:0>1</AS:0>; static int s { get; } = 2; int b { get; } = 2; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class C { int a { get; } static int s { get; } = 2; int b { get; } = <AS:0>3</AS:0>; public C() { } static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceFieldInitializer_Internal_Delete1() { var src1 = @" class C { <AS:1>int a = F(1)</AS:1>, b = F(2); public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class C { int a, <AS:1>b = F(2)</AS:1>; public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceFieldInitializer_Internal_Delete2() { var src1 = @" class C { int a = F(1), <AS:1>b = F(2)</AS:1>; public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class C { <AS:1>int a, b;</AS:1> public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstancePropertyAndFieldInitializers_Delete1() { var src1 = @" class C { int a { get; } = <AS:0>1</AS:0>; static int s { get; } = 2; int b = 2; }"; var src2 = @" class C { int a { get; } static int s { get; } = 2; <AS:0>int b = 3;</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstancePropertyAndFieldInitializers_Delete2() { var src1 = @" class C { int a = <AS:0>1</AS:0>; static int s { get; } = 2; int b { get; } = 2; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class C { int a; static int s { get; } = 2; int b { get; } = <AS:0>3</AS:0>; public C() { } static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceFieldInitializer_SingleDeclarator() { var src1 = @" class C { <AS:1>public static readonly int a = F(1);</AS:1> public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class C { <AS:1>public static readonly int <TS:1>a = F(1)</TS:1>;</AS:1> public C() {} public static int F(int a) { <TS:0><AS:0>return a + 1;</AS:0></TS:0> } static void Main(string[] args) { <TS:2><AS:2>C c = new C();</AS:2></TS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_Lambda1() { var src1 = @" class C { Func<int, int> a = z => <AS:0>z + 1</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1);</AS:1> } }"; var src2 = @" class C { Func<int, int> a = F(z => <AS:0>z + 1</AS:0>); static void Main(string[] args) { <AS:1>new C().a(1);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void PropertyInitializer_Lambda1() { var src1 = @" class C { Func<int, int> a { get; } = z => <AS:0>z + 1</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1);</AS:1> } }"; var src2 = @" class C { Func<int, int> a { get; } = F(z => <AS:0>z + 1</AS:0>); static void Main(string[] args) { <AS:1>new C().a(1);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_Lambda2() { var src1 = @" class C { Func<int, Func<int>> a = z => () => <AS:0>z + 1</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1)();</AS:1> } }"; var src2 = @" class C { Func<int, Func<int>> a = z => () => <AS:0>z + 2</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1)();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void PropertyInitializer_Lambda2() { var src1 = @" class C { Func<int, Func<int>> a { get; } = z => () => <AS:0>z + 1</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1)();</AS:1> } }"; var src2 = @" class C { Func<int, Func<int>> a { get; } = z => () => <AS:0>z + 2</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1)();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_InsertConst1() { var src1 = @" class C { <AS:0>int a = 1</AS:0>; public C() {} }"; var src2 = @" class C { <AS:0>const int a = 1;</AS:0> public C() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a = 1 ;]@24 -> [const int a = 1;]@24"); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ModifiersUpdate, "const int a = 1", FeaturesResources.const_field)); } [Fact] public void LocalInitializer_InsertConst1() { var src1 = @" class C { public void M() { <AS:0>int a = 1</AS:0>; } }"; var src2 = @" class C { public void M() { const int a = 1; <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_InsertConst2() { var src1 = @" class C { int <AS:0>a = 1</AS:0>, b = 2; public C() {} }"; var src2 = @" class C { <AS:0>const int a = 1, b = 2;</AS:0> public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ModifiersUpdate, "const int a = 1, b = 2", FeaturesResources.const_field), Diagnostic(RudeEditKind.ModifiersUpdate, "const int a = 1, b = 2", FeaturesResources.const_field)); } [Fact] public void LocalInitializer_InsertConst2() { var src1 = @" class C { public void M() { int <AS:0>a = 1</AS:0>, b = 2; } }"; var src2 = @" class C { public void M() { const int a = 1, b = 2; <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_Delete1() { var src1 = @" class C { <AS:0>int a = 1;</AS:0> int b = 1; public C() {} }"; var src2 = @" class C { int a; <AS:0>int b = 1;</AS:0> public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void LocalInitializer_Delete1() { var src1 = @" class C { public void M() { <AS:0>int a = 1</AS:0>; } }"; var src2 = @" class C { public void M() { int a; <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_Delete2() { var src1 = @" class C { int b = 1; int c; <AS:0>int a = 1;</AS:0> public C() {} }"; var src2 = @" class C { <AS:0>int b = 1;</AS:0> int c; int a; public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void LocalInitializer_Delete2() { var src1 = @" class C { public void M() { int b = 1; int c; <AS:0>int a = 1;</AS:0> } }"; var src2 = @" class C { public void M() { int b = 1; int c; int a; <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_Delete3() { var src1 = @" class C { int b = 1; int c; <AS:0>int a = 1;</AS:0> public C() {} }"; var src2 = @" class C { <AS:0>int b = 1;</AS:0> int c; public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active, Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.field, "a"))); } [Fact] public void LocalInitializer_Delete3() { var src1 = @" class C { public void M() { int b = 1; int c; <AS:0>int a = 1;</AS:0> } }"; var src2 = @" class C { public void M() { int b = 1; int c; <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_DeleteStaticInstance1() { var src1 = @" class C { <AS:0>int a = 1;</AS:0> static int b = 1; int c = 1; public C() {} }"; var src2 = @" class C { int a; static int b = 1; <AS:0>int c = 1;</AS:0> public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_DeleteStaticInstance2() { var src1 = @" class C { static int c = 1; <AS:0>static int a = 1;</AS:0> int b = 1; public C() {} }"; var src2 = @" class C { <AS:0>static int c = 1;</AS:0> static int a; int b = 1; public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_DeleteStaticInstance3() { var src1 = @" class C { <AS:0>static int a = 1;</AS:0> int b = 1; public C() {} }"; var src2 = @" class C { <AS:0>static int a;</AS:0> int b = 1; public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_DeleteMove1() { var src1 = @" class C { int b = 1; int c; <AS:0>int a = 1;</AS:0> public C() {} }"; var src2 = @" class C { int c; <AS:0>int b = 1;</AS:0> public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active, Diagnostic(RudeEditKind.Move, "int c", FeaturesResources.field), Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.field, "a"))); } [Fact] public void LocalInitializer_DeleteReorder1() { var src1 = @" class C { public void M() { int b = 1; <AS:0>int a = 1;</AS:0> int c; } }"; var src2 = @" class C { public void M() { int c; <AS:0>int b = 1;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldToProperty1() { var src1 = @" class C { int a = <AS:0>1</AS:0>; }"; // The placement of the active statement is not ideal, but acceptable. var src2 = @" <AS:0>class C</AS:0> { int a { get; } = 1; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active, Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.field, "a"))); } [Fact] public void PropertyToField1() { var src1 = @" class C { int a { get; } = <AS:0>1</AS:0>; }"; // The placement of the active statement is not ideal, but acceptable. var src2 = @" <AS:0>class C</AS:0> { int a = 1; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active, Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.auto_property, "a"))); } #endregion #region Lock Statement [Fact] public void LockBody_Update() { var src1 = @" class Test { private static object F() { <AS:0>return new object();</AS:0> } static void Main(string[] args) { <AS:1>lock (F())</AS:1> { System.Console.Write(0); } } }"; var src2 = @" class Test { private static object F() { <AS:0>return new object();</AS:0> } static void Main(string[] args) { <AS:1>lock (F())</AS:1> { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(755749, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755749")] [Fact] public void Lock_Insert_Leaf() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { <AS:0>System.Console.Write(5);</AS:0> } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { <AS:0>System.Console.Write(5);</AS:0> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "lock (lockThis)", CSharpFeaturesResources.lock_statement)); } [WorkItem(755749, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755749")] [Fact] public void Lock_Insert_Leaf2() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { { System.Console.Write(5); <AS:0>}</AS:0> } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { System.Console.Write(5); <AS:0>}</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "lock (lockThis)", CSharpFeaturesResources.lock_statement)); } [Fact] public void Lock_Insert_Leaf3() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { { System.Console.Write(5); } <AS:0>System.Console.Write(10);</AS:0> } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { System.Console.Write(5); } <AS:0>System.Console.Write(5);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lock_Insert_Leaf4() { var src1 = @" class Test { public static object a = new object(); public static object b = new object(); public static object c = new object(); public static object d = new object(); public static object e = new object(); static void Main(string[] args) { lock (a) { lock (b) { lock (c) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static object a = new object(); public static object b = new object(); public static object c = new object(); public static object d = new object(); public static object e = new object(); static void Main(string[] args) { lock (b) { lock (d) { lock (a) { lock (e) { <AS:0>System.Console.Write();</AS:0> } } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "lock (d)", CSharpFeaturesResources.lock_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "lock (e)", CSharpFeaturesResources.lock_statement)); } [Fact] public void Lock_Insert_Leaf5() { var src1 = @" class Test { public static object a = new object(); public static object b = new object(); public static object c = new object(); public static object d = new object(); public static object e = new object(); static void Main(string[] args) { lock (a) { lock (c) { lock (b) { lock (e) { <AS:0>System.Console.Write();</AS:0> } } } } } }"; var src2 = @" class Test { public static object a = new object(); public static object b = new object(); public static object c = new object(); public static object d = new object(); public static object e = new object(); static void Main(string[] args) { lock (b) { lock (d) { lock (a) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "lock (d)", CSharpFeaturesResources.lock_statement)); } [WorkItem(755752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755752")] [Fact] public void Lock_Update_Leaf() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { <AS:0>System.Console.Write(5);</AS:0> } } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (""test"") { <AS:0>System.Console.Write(5);</AS:0> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "lock (\"test\")", CSharpFeaturesResources.lock_statement)); } [Fact] public void Lock_Update_Leaf2() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { System.Console.Write(5); } <AS:0>System.Console.Write(5);</AS:0> } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (""test"") { System.Console.Write(5); } <AS:0>System.Console.Write(5);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lock_Delete_Leaf() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { <AS:0>System.Console.Write(5);</AS:0> } } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { <AS:0>System.Console.Write(5);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lock_Update_Lambda1() { var src1 = @" class C { static void Main(string[] args) { lock (F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static void Main(string[] args) { lock (F(a => a + 1)) { <AS:0>Console.WriteLine(2);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lock_Update_Lambda2() { var src1 = @" class C { static void Main(string[] args) { lock (F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static void Main(string[] args) { lock (G(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "lock (G(a => a))", CSharpFeaturesResources.lock_statement)); } #endregion #region Fixed Statement [Fact] public void FixedBody_Update() { var src1 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { unsafe { char* px2; fixed (<AS:1>char* pj = &F()</AS:1>) { System.Console.WriteLine(0); } } } }"; var src2 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { unsafe { char* px2; fixed (<AS:1>char* pj = &F()</AS:1>) { System.Console.WriteLine(1); } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(755742, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755742")] [Fact] public void Fixed_Insert_Leaf() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; <AS:0>px2 = null;</AS:0> } } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* pj = &value) { <AS:0>px2 = null;</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "fixed (int* pj = &value)", CSharpFeaturesResources.fixed_statement)); } [Fact] public void Fixed_Insert_Leaf2() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; <AS:0>}</AS:0> } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* pj = &value) { px2 = null; } <AS:0>}</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(755742, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755742")] [Fact] public void Fixed_Insert_Leaf3() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; <AS:0>px2 = null;</AS:0> fixed (int* pj = &value) { } } } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* pj = &value) { <AS:0>px2 = null;</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "fixed (int* pj = &value)", CSharpFeaturesResources.fixed_statement)); } [WorkItem(755742, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755742")] [Fact] public void Fixed_Reorder_Leaf1() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* a = &value) { fixed (int* b = &value) { <AS:0>px2 = null;</AS:0> } } } } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* b = &value) { fixed (int* a = &value) { <AS:0>px2 = null;</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(755746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755746")] [Fact] public void Fixed_Update_Leaf1() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* pj = &value) { <AS:0>px2 = null;</AS:0> } } } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* p = &value) { <AS:0>px2 = null;</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "fixed (int* p = &value)", CSharpFeaturesResources.fixed_statement)); } [WorkItem(755746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755746")] [Fact] public void Fixed_Update_Leaf2() { var src1 = @" class Test { public static int value1 = 10; public static int value2 = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* a = &value1) { fixed (int* b = &value1) { fixed (int* c = &value1) { <AS:0>px2 = null;</AS:0> } } } } } }"; var src2 = @" class Test { public static int value1 = 10; public static int value2 = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* c = &value1) { fixed (int* d = &value1) { fixed (int* a = &value2) { fixed (int* e = &value1) { <AS:0>px2 = null;</AS:0> } } } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "fixed (int* a = &value2)", CSharpFeaturesResources.fixed_statement), Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "fixed (int* d = &value1)", CSharpFeaturesResources.fixed_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "fixed (int* e = &value1)", CSharpFeaturesResources.fixed_statement)); } [Fact] public void Fixed_Delete_Leaf() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* pj = &value) { <AS:0>px2 = null;</AS:0> } } } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; <AS:0>px2 = null;</AS:0> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Fixed_Update_Lambda1() { var src1 = @" class C { static unsafe void Main(string[] args) { fixed (byte* p = &F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { fixed (byte* p = &F(a => a + 1)) { <AS:0>Console.WriteLine(2);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Fixed_Update_Lambda2() { var src1 = @" class C { static unsafe void Main(string[] args) { fixed (byte* p = &F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { fixed (byte* p = &G(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "fixed (byte* p = &G(a => a))", CSharpFeaturesResources.fixed_statement)); } #endregion #region ForEach Statement [Fact] public void ForEachBody_Update_ExpressionActive() { var src1 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (char c in <AS:1>F()</AS:1>) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (char c in <AS:1>F()</AS:1>) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariableBody_Update_ExpressionActive() { var src1 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach ((string s, int i) in <AS:1>F()</AS:1>) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach ((string s, int i) in <AS:1>F()</AS:1>) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachBody_Update_InKeywordActive() { var src1 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (char c <AS:1>in</AS:1> F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (char c <AS:1>in</AS:1> F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariableBody_Update_InKeywordActive() { var src1 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach ((string s, int i) <AS:1>in</AS:1> F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach ((string s, int i) <AS:1>in</AS:1> F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachBody_Update_VariableActive() { var src1 = @" class Test { private static string[] F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>string c</AS:1> in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static string[] F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>string c</AS:1> in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariableBody_Update_VariableActive() { var src1 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>(string s, int i)</AS:1> in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>(string s, int i)</AS:1> in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachBody_Update_ForeachKeywordActive() { var src1 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { <AS:1>foreach</AS:1> (char c in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { <AS:1>foreach</AS:1> (char c in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariableBody_Update_ForeachKeywordActive() { var src1 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { <AS:1>foreach</AS:1> ((string s, int i) in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { <AS:1>foreach</AS:1> ((string s, int i) in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_Update() { var src1 = @" class Test { private static string[] F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>string c</AS:1> in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static string[] F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>object c</AS:1> in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // not ideal, but good enough: edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "object c"), Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "foreach ( object c in F())", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEachDeconstructionVariable_Update() { var src1 = @" class Test { private static (int, (bool, double))[] F() { <AS:0>return new[] { (1, (true, 2.0)) };</AS:0> } static void Main(string[] args) { foreach (<AS:1>(int i, (bool b, double d))</AS:1> in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static (int, (bool, double))[] F() { <AS:0>return new[] { (1, (true, 2.0)) };</AS:0> } static void Main(string[] args) { foreach (<AS:1>(int i, (var b, double d))</AS:1> in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "(int i, (var b, double d))"), Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "foreach ( (int i, (var b, double d)) in F())", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEach_Reorder_Leaf() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var b in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var b in e1) { foreach (var c in e1) { foreach (var a in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_Reorder_Leaf() { var src1 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { foreach ((var a1, var a2) in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_Update_Leaf() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { <AS:0>System.Console.Write();</AS:0> } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var b in e1) { foreach (var c in e1) { foreach (var a in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var b in e1)", CSharpFeaturesResources.foreach_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var c in e1)", CSharpFeaturesResources.foreach_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var a in e1)", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEachVariable_Update_Leaf() { var src1 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { <AS:0>System.Console.Write();</AS:0> } }"; var src2 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { foreach ((var a1, var a2) in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var c in e1)", CSharpFeaturesResources.foreach_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach ((int b1, bool b2) in e1)", CSharpFeaturesResources.foreach_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach ((var a1, var a2) in e1)", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEach_Delete_Leaf1() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var b in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var b in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_Delete_Leaf1() { var src1 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach ((int b1, bool b2) in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_Delete_Leaf2() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var b in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var b in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_Delete_Leaf2() { var src1 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_Delete_Leaf3() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var b in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_Delete_Leaf3() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_Lambda1() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { Action a = () => { <AS:0>System.Console.Write();</AS:0> }; <AS:1>a();</AS:1> } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var b in e1) { foreach (var c in e1) { Action a = () => { foreach (var a in e1) { <AS:0>System.Console.Write();</AS:0> } }; } <AS:1>a();</AS:1> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var a in e1)", CSharpFeaturesResources.foreach_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var b in e1)", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEach_Update_Lambda1() { var src1 = @" class C { static unsafe void Main(string[] args) { foreach (var a in F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { foreach (var a in F(a => a + 1)) { <AS:0>Console.WriteLine(2);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_Update_Lambda2() { var src1 = @" class C { static unsafe void Main(string[] args) { foreach (var a in F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { foreach (var a in G(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "foreach (var a in G(a => a))", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEach_Update_Nullable() { var src1 = @" class C { static void F() { var arr = new int?[] { 0 }; foreach (var s in arr) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static void F() { var arr = new int[] { 0 }; foreach (var s in arr) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_DeleteBody() { var src1 = @" class C { static void F() { foreach (var s in new[] { 1 }) <AS:0>G();</AS:0> } } "; var src2 = @" class C { static void F() { foreach (var s in new[] { 1 }) <AS:0>;</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_DeleteBody() { var src1 = @" class C { static void F() { foreach ((var a1, var a2) in new[] { (1,1) }) <AS:0>G();</AS:0> } } "; var src2 = @" class C { static void F() { foreach ((var a1, var a2) in new[] { (1,1) }) <AS:0>;</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region For Statement [Fact] public void ForStatement_Initializer1() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (<AS:1>i = F(1)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (<AS:1>i = F(2)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "i = F(2)")); } [Fact] public void ForStatement_Initializer2() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (<AS:1>i = F(1)</AS:1>, F(1); i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (<AS:1>i = F(1)</AS:1>, F(2); i < 10; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForStatement_Initializer_Delete() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (<AS:1>i = F(1)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (; <AS:1>i < 10</AS:1>; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "for (; i < 10 ; i++)", FeaturesResources.code)); } [Fact] public void ForStatement_Declarator1() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>var i = F(1)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>var i = F(2)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "var i = F(2)")); } [Fact] public void ForStatement_Declarator2() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>int i = F(1)</AS:1>, j = F(1); i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>int i = F(1)</AS:1>, j = F(2); i < 10; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForStatement_Declarator3() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>int i = F(1)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>int i = F(1)</AS:1>, j = F(2); i < 10; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForStatement_Condition1() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; <AS:1>i < F(10)</AS:1>; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; <AS:1>i < F(20)</AS:1>; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "i < F(20)")); } [Fact] public void ForStatement_Condition_Delete() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; <AS:1>i < F(10)</AS:1>; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; ; <AS:1>i++</AS:1>) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "for (int i = 1; ; i++ )", FeaturesResources.code)); } [Fact] public void ForStatement_Incrementors1() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(1)</AS:1>) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(20); <AS:1>F(1)</AS:1>) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForStatement_Incrementors2() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(1)</AS:1>) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(2)</AS:1>) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "F(2)")); } [Fact] public void ForStatement_Incrementors3() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(1)</AS:1>) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(1)</AS:1>, i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForStatement_Incrementors4() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(1)</AS:1>, i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); i++, <AS:1>F(1)</AS:1>) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Using Statement and Local Declaration [Fact] public void UsingStatement_Expression_Update_Leaf() { var src1 = @" class Test { public static System.IDisposable a = null; public static System.IDisposable b = null; public static System.IDisposable c = null; static void Main(string[] args) { using (a) { using (b) { <AS:0>System.Console.Write();</AS:0> } } } }"; var src2 = @" class Test { public static System.IDisposable a = null; public static System.IDisposable b = null; public static System.IDisposable c = null; static void Main(string[] args) { using (a) { using (c) { using (b) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // Using with an expression generates code that stores the value of the expression in a compiler-generated temp. // This temp is not initialized when using is added around an active statement so the disposal is a no-op. // The user might expect that the object the field points to is disposed at the end of the using block, but it isn't. edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "using (c)", CSharpFeaturesResources.using_statement)); } [Fact] public void UsingStatement_Declaration_Update_Leaf() { var src1 = @" class Test { static void Main(string[] args) { using (var a = new Disposable()) { using (var b = new Disposable()) { <AS:0>System.Console.Write();</AS:0> } } } }"; var src2 = @" class Test { static void Main(string[] args) { using (var a = new Disposable()) { using (var c = new Disposable()) { using (var b = new Disposable()) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // Unlike using with an expression, using with a declaration does not introduce compiler-generated temps. // As with other local declarations that are added but not executed, the variable is not initialized and thus // there should be no expectation (or need) for its disposal. Hence we do not report a rude edit. edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingLocalDeclaration_Update_Leaf1() { var src1 = @" class Test { static void Main(string[] args) { using var a = new Disposable(), b = new Disposable(); <AS:0>System.Console.Write();</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { using var a = new Disposable(), c = new Disposable(), b = new Disposable(); <AS:0>System.Console.Write();</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // Unlike using with an expression, using local declaration does not introduce compiler-generated temps. // As with other local declarations that are added but not executed, the variable is not initialized and thus // there should be no expectation (or need) for its disposal. Hence we do not report a rude edit. edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingLocalDeclaration_Update_Leaf2() { var src1 = @" class Test { static void Main(string[] args) { using var a = new Disposable(); using var b = new Disposable(); <AS:0>System.Console.Write();</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { using var a = new Disposable(); using var c = new Disposable(); using var b = new Disposable(); <AS:0>System.Console.Write();</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // Unlike using with an expression, using local declaration does not introduce compiler-generated temps. // As with other local declarations that are added but not executed, the variable is not initialized and thus // there should be no expectation (or need) for its disposal. Hence we do not report a rude edit. edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingStatement_Update_NonLeaf1() { var src1 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (var a = new Disposable(1)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var src2 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (var a = new Disposable(2)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "}")); } [Fact] public void UsingStatement_Update_NonLeaf2() { var src1 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (Disposable a = new Disposable(1), b = Disposable(2)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var src2 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (Disposable a = new Disposable(1)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "}")); } [Fact] public void UsingStatement_Update_NonLeaf_Lambda() { var src1 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (var a = new Disposable(() => 1)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var src2 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (var a = new Disposable(() => 2)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingLocalDeclaration_Update_NonLeaf1() { var src1 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { if (F()) { using Disposable a = new Disposable(1); using Disposable b = new Disposable(2), c = new Disposable(3); <AS:1>}</AS:1> } }"; var src2 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { if (F()) { using Disposable a = new Disposable(1); using Disposable b = new Disposable(20), c = new Disposable(3); <AS:1>}</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "}")); } [Fact] public void UsingLocalDeclaration_Update_NonLeaf_Lambda() { var src1 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { if (F()) { using Disposable a = new Disposable(() => 1); { using var x = new Disposable(1); } using Disposable b = new Disposable(() => 2), c = new Disposable(() => 3); <AS:1>}</AS:1> } }"; var src2 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { if (F()) { using Disposable a = new Disposable(() => 10); { using var x = new Disposable(2); } Console.WriteLine(1); using Disposable b = new Disposable(() => 20), c = new Disposable(() => 30); <AS:1>}</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingStatement_Expression_InLambdaBody1() { var src1 = @" class Test { public static System.IDisposable a = null; public static System.IDisposable b = null; public static System.IDisposable c = null; public static System.IDisposable d = null; static void Main(string[] args) { using (a) { Action a = () => { using (b) { <AS:0>System.Console.Write();</AS:0> } }; } <AS:1>a();</AS:1> } }"; var src2 = @" class Test { public static System.IDisposable a = null; public static System.IDisposable b = null; public static System.IDisposable c = null; public static System.IDisposable d = null; static void Main(string[] args) { using (d) { Action a = () => { using (c) { using (b) { <AS:0>System.Console.Write();</AS:0> } } }; } <AS:1>a();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "using (c)", CSharpFeaturesResources.using_statement)); } [Fact] public void UsingStatement_Expression_Update_Lambda1() { var src1 = @" class C { static unsafe void Main(string[] args) { using (F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { using (F(a => a + 1)) { <AS:0>Console.WriteLine(2);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingStatement_Expression_Update_Lambda2() { var src1 = @" class C { static unsafe void Main(string[] args) { using (F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { using (G(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "using (G(a => a))", CSharpFeaturesResources.using_statement)); } #endregion #region Conditional Block Statements (If, Switch, While, Do) [Fact] public void IfBody_Update1() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>if (B())</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>if (B())</AS:1> { System.Console.WriteLine(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void IfBody_Update2() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>if (B())</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>if (!B())</AS:1> { System.Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "if (!B())")); } [Fact] public void IfBody_Update_Lambda() { var src1 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>if (B(() => 1))</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>if (B(() => 2))</AS:1> { System.Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void WhileBody_Update1() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>while (B())</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>while (B())</AS:1> { System.Console.WriteLine(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void WhileBody_Update2() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>while (B())</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>while (!B())</AS:1> { System.Console.WriteLine(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "while (!B())")); } [Fact] public void WhileBody_Update_Lambda() { var src1 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>while (B(() => 1))</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>while (B(() => 2))</AS:1> { System.Console.WriteLine(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void DoWhileBody_Update1() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { do { System.Console.WriteLine(0); } <AS:1>while (B());</AS:1> } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { do { System.Console.WriteLine(1); } <AS:1>while (B());</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void DoWhileBody_Update2() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { do { System.Console.WriteLine(0); } <AS:1>while (B());</AS:1> } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { do { System.Console.WriteLine(1); } <AS:1>while (!B());</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "while (!B());")); } [Fact] public void DoWhileBody_Update_Lambda() { var src1 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { do { System.Console.WriteLine(0); } <AS:1>while (B(() => 1));</AS:1> } }"; var src2 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { do { System.Console.WriteLine(1); } <AS:1>while (B(() => 2));</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void DoWhileBody_Delete() { var src1 = @" class C { static void F() { do <AS:0>G();</AS:0> while (true); } } "; var src2 = @" class C { static void F() { do <AS:0>;</AS:0> while (true); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void SwitchCase_Update1() { var src1 = @" class C { public static string F() <AS:0>{</AS:0> return null; } public static void Main() { <AS:1>switch (F())</AS:1> { case ""a"": System.Console.WriteLine(0); break; case ""b"": System.Console.WriteLine(1); break; } } }"; var src2 = @" class C { public static string F() <AS:0>{</AS:0> return null; } public static void Main() { <AS:1>switch (F())</AS:1> { case ""a"": System.Console.WriteLine(0); break; case ""b"": System.Console.WriteLine(2); break; } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void SwitchCase_Update_Lambda() { var src1 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>switch (B(() => 1))</AS:1> { case ""a"": System.Console.WriteLine(0); break; case ""b"": System.Console.WriteLine(1); break; } } }"; var src2 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>switch (B(() => 2))</AS:1> { case ""a"": System.Console.WriteLine(0); break; case ""b"": System.Console.WriteLine(2); break; } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Switch Statement When Clauses, Patterns [Fact] public void SwitchWhenClause_PatternUpdate1() { var src1 = @" class C { public static int Main() { switch (F()) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; case byte a when G5(a): return 10; case double b when G2(b): return 20; case C { X: 2 } when G4(9): return 30; case C { X: 2, Y: C { X: 1 } } c1 when G3(c1): return 40; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; case byte a when G5(a): return 10; case double b when G2(b): return 20; case C { X: 2 } when G4(9): return 30; case C { X: 2, Y: C { X: 2 } } c1 when G3(c1): return 40; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F())", CSharpFeaturesResources.switch_statement_case_clause)); } [Fact] public void SwitchWhenClause_PatternInsert() { var src1 = @" class C { public static int Main() { switch (F()) { case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F())", CSharpFeaturesResources.switch_statement_case_clause)); } [Fact] public void SwitchWhenClause_PatternDelete() { var src1 = @" class C { public static int Main() { switch (F()) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F())", CSharpFeaturesResources.switch_statement_case_clause)); } [Fact] public void SwitchWhenClause_WhenDelete() { var src1 = @" class C { public static int Main() { switch (F()) { case byte a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case byte a1: case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F())", CSharpFeaturesResources.switch_statement_case_clause)); } [Fact] public void SwitchWhenClause_WhenAdd() { var src1 = @" class C { public static int Main() { switch (F()) { case byte a1: case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case byte a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F())", CSharpFeaturesResources.switch_statement_case_clause)); } [Fact] public void SwitchWhenClause_WhenUpdate() { var src1 = @" class C { public static int Main() { switch (F()) { case byte a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case byte a1 when G1(a1 * 2): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void SwitchWhenClause_UpdateGoverningExpression() { var src1 = @" class C { public static int Main() { switch (F(1)) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F(2)) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F(2))", CSharpFeaturesResources.switch_statement)); } [Fact] public void Switch_PropertyPattern_Update_NonLeaf() { var src1 = @" class C { public int X { get => <AS:0>1</AS:0>; } public static int F(object obj) { <AS:1>switch (obj)</AS:1> { case C { X: 1 }: return 1; } return 0; } }"; var src2 = @" class C { public int X { get => <AS:0>1</AS:0>; } public static int F(object obj) { <AS:1>switch (obj)</AS:1> { case C { X: 2 }: return 1; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "switch (obj)")); } [Fact] public void Switch_PositionalPattern_Update_NonLeaf() { var src1 = @" class C { public void Deconstruct(out int x) => <AS:0>x = X</AS:0>; public static int F(object obj) { <AS:1>switch (obj)</AS:1> { case C ( x: 1 ): return 1; } return 0; } }"; var src2 = @" class C { public void Deconstruct(out int x) => <AS:0>x = X</AS:0>; public static int F(object obj) { <AS:1>switch (obj)</AS:1> { case C ( x: 2 ): return 1; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "switch (obj)")); } [Fact] public void Switch_VarPattern_Update_NonLeaf() { var src1 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case var (x, y): return 1; case 2: return 2; } return 0; } }"; var src2 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case var (x, y): return 1; case 3: return 2; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "switch (G())")); } [Fact] public void Switch_DiscardPattern_Update_NonLeaf() { var src1 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case bool _: return 1; } return 0; } }"; var src2 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case int _: return 1; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "switch (G())")); } [Fact] public void Switch_NoPatterns_Update_NonLeaf() { var src1 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case 1: return 1; } return 0; } }"; var src2 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case 2: return 1; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Switch Expression [Fact] public void SwitchExpression() { var src1 = @" class C { public static int Main() { Console.WriteLine(1); <AS:4>return F() switch { int a <AS:0>when F1()</AS:0> => <AS:1>F2()</AS:1>, bool b => <AS:2>F3()</AS:2>, _ => <AS:3>F4()</AS:3> };</AS:4> } }"; var src2 = @" class C { public static int Main() { Console.WriteLine(2); <AS:4>return F() switch { int a <AS:0>when F1()</AS:0> => <AS:1>F2()</AS:1>, bool b => <AS:2>F3()</AS:2>, _ => <AS:3>F4()</AS:3> };</AS:4> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void SwitchExpression_Lambda1() { var src1 = @" class C { public static int Main() => <AS:1>F() switch { 0 => new Func<int>(() => <AS:0>1</AS:0>)(), _ => 2}</AS:1>; }"; var src2 = @" class C { public static int Main() => <AS:1>F() switch { 0 => new Func<int>(() => <AS:0>3</AS:0>)(), _ => 2}</AS:1>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void SwitchExpression_Lambda2() { var src1 = @" class C { public static int Main() => <AS:1>F() switch { i => new Func<int>(() => <AS:0>i + 1</AS:0>)(), _ => 2}</AS:1>; }"; var src2 = @" class C { public static int Main() => <AS:1>F() switch { i => new Func<int>(() => <AS:0>i + 3</AS:0>)(), _ => 2}</AS:1>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_MemberExpressionBody() { var src1 = @" class C { public static int Main() => <AS:0>F() switch { 0 => 1, _ => 2}</AS:0>; }"; var src2 = @" class C { public static int Main() => <AS:0>G() switch { 0 => 10, _ => 20}</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_LambdaBody() { var src1 = @" class C { public static Func<int> M() => () => <AS:0>F() switch { 0 => 1, _ => 2}</AS:0>; }"; var src2 = @" class C { public static Func<int> M() => () => <AS:0>G() switch { 0 => 10, _ => 20}</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_QueryLambdaBody() { var src1 = @" class C { public static IEnumerable<int> M() { return from a in new[] { 1 } where <AS:0>F() <AS:1>switch { 0 => true, _ => false}</AS:0>/**/</AS:1> select a; } }"; var src2 = @" class C { public static IEnumerable<int> M() { return from a in new[] { 2 } where <AS:0>F() <AS:1>switch { 0 => true, _ => false}</AS:0>/**/</AS:1> select a; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_NestedInGoverningExpression() { var src1 = @" class C { public static int Main() => <AS:1>(F() switch { 0 => 1, _ => 2 }) switch { 1 => <AS:0>10</AS:0>, _ => 20 }</AS:1>; }"; var src2 = @" class C { public static int Main() => <AS:1>(G() switch { 0 => 10, _ => 20 }) switch { 10 => <AS:0>100</AS:0>, _ => 200 }</AS:1>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "(G() switch { 0 => 10, _ => 20 }) switch { 10 => 100 , _ => 200 }")); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_NestedInArm() { var src1 = @" class C { public static int Main() => F1() switch { 1 when F2() <AS:0>switch { 0 => true, _ => false }</AS:0> => F3() <AS:1>switch { 0 => 1, _ => 2 }</AS:1>, _ => 20 }; }"; var src2 = @" class C { public static int Main() => F1() switch { 1 when F2() <AS:0>switch { 0 => true, _ => false }</AS:0> => F3() <AS:1>switch { 0 => 1, _ => 2 }</AS:1>, _ => 20 }; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_Delete1() { var src1 = @" class C { public static int Main() { return Method() switch { true => G(), _ => F2() switch { 1 => <AS:0>0</AS:0>, _ => 2 } }; } }"; var src2 = @" class C { public static int Main() { return Method() switch { true => G(), _ => <AS:0>1</AS:0> }; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_Delete2() { var src1 = @" class C { public static int Main() { return F1() switch { 1 => 0, _ => F2() switch { 1 => <AS:0>0</AS:0>, _ => 2 } }; } }"; var src2 = @" class C { public static int Main() { return F1() switch { 1 => <AS:0>0</AS:0>, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_Delete3() { var src1 = @" class C { public static int Main() { return F1() switch { 1 when F2() switch { 1 => <AS:0>true</AS:0>, _ => false } => 0, _ => 2 }; } }"; var src2 = @" class C { public static int Main() { return F1() switch { 1 <AS:0>when F3()</AS:0> => 0, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Try [Fact] public void Try_Add_Inner() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } catch { } } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "try", CSharpFeaturesResources.try_block)); } [Fact] public void Try_Add_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { <AS:0>Console.WriteLine(1);</AS:0> } catch { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Try_Delete_Inner() { var src1 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>catch { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Goo();", CSharpFeaturesResources.try_block)); } [Fact] public void Try_Delete_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { <AS:0>Console.WriteLine(1);</AS:0> } catch { } } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Try_Update_Inner() { var src1 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>catch { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>catch (IOException) { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "try", CSharpFeaturesResources.try_block)); } [Fact] public void Try_Update_Inner2() { var src1 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>catch { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>catch { }</ER:1.0> Console.WriteLine(2); } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void TryFinally_Update_Inner() { var src1 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>finally { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>finally { }</ER:1.0> Console.WriteLine(2); } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Try_Update_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { <AS:0>Console.WriteLine(1);</AS:0> } catch { } } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { <AS:0>Console.WriteLine(1);</AS:0> } catch (IOException) { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void TryFinally_DeleteStatement_Inner() { var src1 = @" class C { static void Main() { <AS:0>Console.WriteLine(0);</AS:0> try { <AS:1>Console.WriteLine(1);</AS:1> } <ER:1.0>finally { Console.WriteLine(2); }</ER:1.0> } }"; var src2 = @" class C { static void Main() { <AS:0>Console.WriteLine(0);</AS:0> try { <AS:1>}</AS:1> finally { Console.WriteLine(2); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } [Fact] public void TryFinally_DeleteStatement_Leaf() { var src1 = @" class C { static void Main(string[] args) { <ER:0.0>try { Console.WriteLine(0); } finally { <AS:0>Console.WriteLine(1);</AS:0> }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { try { Console.WriteLine(0); } finally { <AS:0>}</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "finally", CSharpFeaturesResources.finally_clause)); } [Fact] public void Try_DeleteStatement_Inner() { var src1 = @" class C { static void Main() { <AS:0>Console.WriteLine(0);</AS:0> try { <AS:1>Console.WriteLine(1);</AS:1> } <ER:1.0>finally { Console.WriteLine(2); }</ER:1.0> } }"; var src2 = @" class C { static void Main() { <AS:0>Console.WriteLine(0);</AS:0> try { <AS:1>}</AS:1> <ER:1.0>finally { Console.WriteLine(2); }</ER:1.0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } [Fact] public void Try_DeleteStatement_Leaf() { var src1 = @" class C { static void Main() { try { <AS:0>Console.WriteLine(1);</AS:0> } finally { Console.WriteLine(2); } } }"; var src2 = @" class C { static void Main() { try { <AS:0>}</AS:0> finally { Console.WriteLine(2); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Catch [Fact] public void Catch_Add_Inner() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } catch { <AS:1>Goo();</AS:1> } } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Add_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { } catch { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Delete_Inner() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Goo();", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Delete_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { } <ER:0.0>catch { <AS:0>Console.WriteLine(1);</AS:0> }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Console.WriteLine(1);", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Update_Inner() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Update_InFilter_Inner() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) <AS:1>when (Goo(1))</AS:1> { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (Exception) <AS:1>when (Goo(1))</AS:1> { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Update_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { } <ER:0.0>catch { <AS:0>Console.WriteLine(1);</AS:0> }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { } <ER:0.0>catch (IOException) { <AS:0>Console.WriteLine(1);</AS:0> }</ER:0.0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void CatchFilter_Update_Inner() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) <AS:1>when (Goo(1))</AS:1> { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) <AS:1>when (Goo(2))</AS:1> { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "when (Goo(2))"), Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void CatchFilter_Update_Leaf1() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:0.0>catch (IOException) <AS:0>when (Goo(1))</AS:0> { }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:0.0>catch (IOException) <AS:0>when (Goo(2))</AS:0> { }</ER:0.0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void CatchFilter_Update_Leaf2() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:0.0>catch (IOException) <AS:0>when (Goo(1))</AS:0> { }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:0.0>catch (Exception) <AS:0>when (Goo(1))</AS:0> { }<ER:0.0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } #endregion #region Finally [Fact] public void Finally_Add_Inner() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } finally { <AS:1>Goo();</AS:1> } } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "finally", CSharpFeaturesResources.finally_clause)); } [Fact] public void Finally_Add_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { } finally { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "finally", CSharpFeaturesResources.finally_clause)); } [Fact] public void Finally_Delete_Inner() { var src1 = @" class C { static void Main(string[] args) { <ER:1.0>try { } finally { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Goo();", CSharpFeaturesResources.finally_clause)); } [Fact] public void Finally_Delete_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <ER:0.0>try { } finally { <AS:0>Console.WriteLine(1);</AS:0> }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Console.WriteLine(1);", CSharpFeaturesResources.finally_clause)); } #endregion #region Try-Catch-Finally [Fact] public void TryCatchFinally() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) { try { try { try { <AS:1>Goo();</AS:1> } catch { } } catch (Exception) { } } finally { } }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (Exception) { try { try { } finally { try { <AS:1>Goo();</AS:1> } catch { } } } catch (Exception) { } }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause), Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "try", CSharpFeaturesResources.try_block), Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Goo();", CSharpFeaturesResources.try_block), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "finally", CSharpFeaturesResources.finally_clause)); } [Fact, WorkItem(23865, "https://github.com/dotnet/roslyn/issues/23865")] public void TryCatchFinally_Regions() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) { try { try { try { <AS:1>Goo();</AS:1> } catch { } } catch (Exception) { } } finally { } }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) { try { try { try { <AS:1>Goo();</AS:1> } catch { } } catch (Exception) { } } finally { } }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // TODO: this is incorrect, we need to report a rude edit: edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(23865, "https://github.com/dotnet/roslyn/issues/23865")] public void TryCatchFinally2_Regions() { var src1 = @" class C { static void Main(string[] args) { try { try { try { try { <AS:1>Goo();</AS:1> } <ER:1.3>catch { }</ER:1.3> } <ER:1.2>catch (Exception) { }</ER:1.2> } <ER:1.1>finally { }</ER:1.1> } <ER:1.0>catch (IOException) { } finally { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { try { try { try { <AS:1>Goo();</AS:1> } <ER:1.3>catch { }</ER:1.3> } <ER:1.2>catch (Exception) { }</ER:1.2> } <ER:1.1>finally { }</ER:1.1> } <ER:1.0>catch (IOException) { } finally { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // TODO: this is incorrect, we need to report a rude edit since an ER span has been changed (empty line added): edits.VerifyRudeDiagnostics(active); } [Fact] public void TryFilter_Regions1() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException e) when (e == null) { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException e) when (e == null) { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void TryFilter_Regions2() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException e) <AS:1>when (e == null)</AS:1> { Goo(); }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException e) <AS:1>when (e == null)</AS:1> { Goo(); }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Try_Lambda1() { var src1 = @" using System; using System.Linq; class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { Func<int, int> f = null; try { f = x => <AS:1>1 + Goo(x)</AS:1>; } catch { } <AS:2>Console.Write(f(2));</AS:2> } }"; var src2 = @" using System; using System.Linq; class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { Func<int, int> f = null; f = x => <AS:1>1 + Goo(x)</AS:1>; <AS:2>Console.Write(f(2));</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Try_Lambda2() { var src1 = @" using System; using System.Linq; class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { Func<int, int> f = x => { try { <AS:1>return 1 + Goo(x);</AS:1> } <ER:1.0>catch { }</ER:1.0> }; <AS:2>Console.Write(f(2));</AS:2> } }"; var src2 = @" using System; using System.Linq; class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { Func<int, int> f = x => { <AS:1>return 1 + Goo(x);</AS:1> }; <AS:2>Console.Write(f(2));</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "return 1 + Goo(x);", CSharpFeaturesResources.try_block)); } [Fact] public void Try_Query_Join1() { var src1 = @" class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { try { q = from x in xs join y in ys on <AS:1>F()</AS:1> equals G() select 1; } catch { } <AS:2>q.ToArray();</AS:2> } }"; var src2 = @" class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { q = from x in xs join y in ys on <AS:1>F()</AS:1> equals G() select 1; <AS:2>q.ToArray();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Checked/Unchecked [Fact] public void CheckedUnchecked_Insert_Leaf() { var src1 = @" class Test { static void Main(string[] args) { int a = 1, b = 2; <AS:0>Console.WriteLine(a*b);</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { int a = 1, b = 2; checked { <AS:0>Console.WriteLine(a*b);</AS:0> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void CheckedUnchecked_Insert_Internal() { var src1 = @" class Test { static void Main(string[] args) { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { checked { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "checked", CSharpFeaturesResources.checked_statement)); } [Fact] public void CheckedUnchecked_Delete_Internal() { var src1 = @" class Test { static void Main(string[] args) { checked { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "System.Console.WriteLine(5 * M(1, 2));", CSharpFeaturesResources.checked_statement)); } [Fact] public void CheckedUnchecked_Update_Internal() { var src1 = @" class Test { static void Main(string[] args) { unchecked { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { checked { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "checked", CSharpFeaturesResources.checked_statement)); } [Fact] public void CheckedUnchecked_Lambda1() { var src1 = @" class Test { static void Main(string[] args) { unchecked { Action f = () => <AS:1>5 * M(1, 2)</AS:1>; } <AS:2>f();</AS:2> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { checked { Action f = () => <AS:1>5 * M(1, 2)</AS:1>; } <AS:2>f();</AS:2> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "checked", CSharpFeaturesResources.checked_statement)); } [Fact] public void CheckedUnchecked_Query1() { var src1 = @" using System.Collections.Generic; using System.Linq; class Test { static void Main() { IEnumerable<int> f; unchecked { f = from a in new[] { 5 } select <AS:1>M(a, int.MaxValue)</AS:1>; } <AS:2>f.ToArray();</AS:2> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var src2 = @" using System.Collections.Generic; using System.Linq; class Test { static void Main() { IEnumerable<int> f; checked { f = from a in new[] { 5 } select <AS:1>M(a, int.MaxValue)</AS:1>; } <AS:2>f.ToArray();</AS:2> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "checked", CSharpFeaturesResources.checked_statement)); } #endregion #region Lambdas [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_GeneralStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>F(a => <AS:0>1</AS:0>);</AS:1> } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>F(a => <AS:0>2</AS:0>);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_Nested1() { var src1 = @" class C { static void Main(string[] args) { <AS:2>F(b => <AS:1>F(a => <AS:0>1</AS:0>)</AS:1>);</AS:2> } } "; var src2 = @" class C { static void Main(string[] args) { <AS:2>F(b => <AS:1>F(a => <AS:0>2</AS:0>)</AS:1>);</AS:2> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_Nested2() { var src1 = @" class C { static void Main(string[] args) { <AS:2>F(b => <AS:1>F(a => <AS:0>1</AS:0>)</AS:1>);</AS:2> } } "; var src2 = @" class C { static void Main(string[] args) { <AS:2>F(b => <AS:1>G(a => <AS:0>2</AS:0>)</AS:1>);</AS:2> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "G(a => 2 )")); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_IfStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>if (F(a => <AS:0>1</AS:0>))</AS:1> { } } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>if (F(a => <AS:0>2</AS:0>))</AS:1> { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_WhileStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>while (F(a => <AS:0>1</AS:0>))</AS:1> { } } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>while (F(a => <AS:0>2</AS:0>))</AS:1> { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_DoStatement() { var src1 = @" class C { static void Main(string[] args) { do {} <AS:1>while (F(a => <AS:0>1</AS:0>));</AS:1> } } "; var src2 = @" class C { static void Main(string[] args) { do {} <AS:1>while (F(a => <AS:0>2</AS:0>));</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_SwitchStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>switch (F(a => <AS:0>1</AS:0>))</AS:1> { case 0: break; case 1: break; } } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>switch (F(a => <AS:0>2</AS:0>))</AS:1> { case 0: break; case 1: break; } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_LockStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>lock (F(a => <AS:0>1</AS:0>))</AS:1> {} } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>lock (F(a => <AS:0>2</AS:0>))</AS:1> {} } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_UsingStatement1() { var src1 = @" class C { static void Main(string[] args) { <AS:1>using (F(a => <AS:0>1</AS:0>))</AS:1> {} } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>using (F(a => <AS:0>2</AS:0>))</AS:1> {} } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_ExpressionToStatements() { var src1 = @" class C { static void Main(string[] args) { Func<int, int> f = a => <AS:0>1</AS:0>; } } "; var src2 = @" class C { static void Main(string[] args) { <AS:0>Func<int, int> f = a => { return 1; };</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_ExpressionToDelegate() { var src1 = @" using System; class C { static void Main() { Func<int, int> f = a => <AS:0>1</AS:0>; } } "; var src2 = @" using System; class C { static void Main() { <AS:0>Func<int, int> f = delegate(int a) { return 1; };</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_StatementsToExpression() { var src1 = @" class C { static void Main(string[] args) { Func<int, int> f = a => { <AS:0>return 1;</AS:0> }; } } "; var src2 = @" class C { static void Main(string[] args) { <AS:0>Func<int, int> f = a => 1;</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_DelegateToExpression() { var src1 = @" using System; class C { static void Main() { Func<int, int> f = delegate(int a) { <AS:0>return 1;</AS:0> }; } } "; var src2 = @" using System; class C { static void Main() { <AS:0>Func<int, int> f = a => 1;</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_StatementsToDelegate() { var src1 = @" using System; class C { static void Main() { Func<int, int> f = a => { <AS:0>return 1;</AS:0> }; } } "; var src2 = @" using System; class C { static void Main() { Func<int, int> f = delegate(int a) { <AS:0>return 2;</AS:0> }; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_ActiveStatementUpdate() { var src1 = @" using System; class C { static void Main(string[] args) { Func<int, int, int> f = (int a, int b) => <AS:0>a + b + 1</AS:0>; <AS:1>f(2);</AS:1> } }"; var src2 = @" using System; class C { static void Main(string[] args) { Func<int, int, int> f = (_, _) => <AS:0>10</AS:0>; <AS:1>f(2);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Lambdas_ActiveStatementRemoved1() { var src1 = @" class C { static void Main(string[] args) { Func<int, Func<int, int>> f = a => { return b => { <AS:0>return b;</AS:0> }; }; var z = f(1); <AS:1>z(2);</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { Func<int, int> f = b => { <AS:0>return b;</AS:0> }; var z = f; <AS:1>z(2);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "return b;", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_ActiveStatementRemoved2() { var src1 = @" class C { static void Main(string[] args) { Func<int, Func<int, int>> f = a => (b) => <AS:0>b</AS:0>; var z = f(1); <AS:1>z(2);</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { Func<int, int> f = <AS:0>(b)</AS:0> => b; var z = f; <AS:1>z(2);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "(b)", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_ActiveStatementRemoved3() { var src1 = @" class C { static void Main(string[] args) { Func<int, Func<int, int>> f = a => { Func<int, int> z; F(b => { <AS:0>return b;</AS:0> }, out z); return z; }; var z = f(1); <AS:1>z(2);</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { Func<int, int> f = b => { <AS:0>F(b);</AS:0> return 1; }; var z = f; <AS:1>z(2);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "F(b);", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_ActiveStatementRemoved4() { var src1 = @" class C { static void Main(string[] args) { Func<int, Func<int, int>> f = a => { <AS:1>z(2);</AS:1> return b => { <AS:0>return b;</AS:0> }; }; } }"; var src2 = @" class C { static void Main(string[] args) <AS:0,1>{</AS:0,1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "{", CSharpFeaturesResources.lambda), Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "{", CSharpFeaturesResources.lambda)); } [Fact] public void Queries_ActiveStatementRemoved_WhereClause() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b where <AS:0>b.goo</AS:0> select b.bar; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select b.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.where_clause)); } [Fact] public void Queries_ActiveStatementRemoved_LetClause() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b let x = <AS:0>b.goo</AS:0> select x; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select a.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.let_clause)); } [Fact] public void Queries_ActiveStatementRemoved_JoinClauseLeft() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b join c in d on <AS:0>a.goo</AS:0> equals c.bar select a.bar; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select a.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.join_clause)); } [Fact] public void Queries_ActiveStatementRemoved_OrderBy1() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b orderby <AS:0>a.x</AS:0>, a.y descending, a.z ascending select a; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select a.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.orderby_clause)); } [Fact] public void Queries_ActiveStatementRemoved_OrderBy2() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b orderby a.x, <AS:0>a.y</AS:0> descending, a.z ascending select a; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select a.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.orderby_clause)); } [Fact] public void Queries_ActiveStatementRemoved_OrderBy3() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b orderby a.x, a.y descending, <AS:0>a.z</AS:0> ascending select a; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select a.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.orderby_clause)); } [Fact] public void Queries_Remove_JoinInto1() { var src1 = @" class C { static void Main() { var q = from x in xs join y in ys on F() equals G() into g select <AS:0>1</AS:0>; } }"; var src2 = @" class C { static void Main() { var q = from x in xs join y in ys on F() equals G() select <AS:0>1</AS:0>; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Queries_Remove_QueryContinuation1() { var src1 = @" class C { static void Main() { var q = from x in xs group x by x.F() into g where <AS:0>g.F()</AS:0> select 1; } }"; var src2 = @" class C { static void Main() { var q = from x in xs group x by x.F() <AS:0>into</AS:0> g select 1; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "into", CSharpFeaturesResources.where_clause)); } [Fact] public void Queries_Remove_QueryContinuation2() { var src1 = @" class C { static void Main() { var q = from x in xs group x by x.F() into g select <AS:0>1</AS:0>; } }"; var src2 = @" class C { static void Main() { var q = from x in xs <AS:0>join</AS:0> y in ys on F() equals G() into g select 1; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "join", CSharpFeaturesResources.select_clause)); } [Fact] public void Queries_Select_Reduced1() { var src1 = @" class C { static void Main() { var q = from a in array where a > 0 select <AS:0>a + 1</AS:0>; } }"; var src2 = @" class C { static void Main() { var q = from a in array where a > 0 <AS:0>select</AS:0> a; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "select", CSharpFeaturesResources.select_clause)); } [Fact] public void Queries_Select_Reduced2() { var src1 = @" class C { static int F(IEnumerable<int> e) => <AS:0>1</AS:0>; static void Main() { <AS:1>F(from a in array where a > 0 select a + 1);</AS:1> } }"; var src2 = @" class C { static int F(IEnumerable<int> e) => <AS:0>1</AS:0>; static void Main() { <AS:1>F(from a in array where a > 0 select a);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "F(from a in array where a > 0 select a);")); } [Fact] public void Queries_GroupBy_Reduced1() { var src1 = @" class C { static void Main() { var q = from a in array group <AS:0>a + 1</AS:0> by a; } }"; var src2 = @" class C { static void Main() { var q = from a in array <AS:0>group</AS:0> a by a; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "group", CSharpFeaturesResources.groupby_clause)); } [Fact] public void Queries_GroupBy_Reduced2() { var src1 = @" class C { static int F(IEnumerable<IGrouping<int, int>> e) => <AS:0>1</AS:0>; static void Main() { <AS:1>F(from a in array group a by a);</AS:1> } }"; var src2 = @" class C { static int F(IEnumerable<IGrouping<int, int>> e) => <AS:0>1</AS:0>; static void Main() { <AS:1>F(from a in array group a + 1 by a);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "F(from a in array group a + 1 by a);")); } #endregion #region State Machines [Fact] public void MethodToIteratorMethod_WithActiveStatement() { var src1 = @" class C { static IEnumerable<int> F() { <AS:0>Console.WriteLine(1);</AS:0> return new[] { 1, 2, 3 }; } } "; var src2 = @" class C { static IEnumerable<int> F() { <AS:0>Console.WriteLine(1);</AS:0> yield return 1; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "yield return 1;", CSharpFeaturesResources.yield_return_statement)); } [Fact] public void MethodToIteratorMethod_WithActiveStatementInLambda() { var src1 = @" class C { static IEnumerable<int> F() { var f = new Action(() => { <AS:0>Console.WriteLine(1);</AS:0> }); return new[] { 1, 2, 3 }; } } "; var src2 = @" class C { static IEnumerable<int> F() { var f = new Action(() => { <AS:0>Console.WriteLine(1);</AS:0> }); yield return 1; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // should not contain RUDE_EDIT_INSERT_AROUND edits.VerifyRudeDiagnostics(active); } [Fact] public void MethodToIteratorMethod_WithoutActiveStatement() { var src1 = @" class C { static IEnumerable<int> F() { Console.WriteLine(1); return new[] { 1, 2, 3 }; } } "; var src2 = @" class C { static IEnumerable<int> F() { Console.WriteLine(1); yield return 1; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void MethodToAsyncMethod_WithActiveStatement_AwaitExpression() { var src1 = @" class C { static Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> return Task.FromResult(1); } } "; var src2 = @" class C { static async Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> return await Task.FromResult(1); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void MethodToAsyncMethod_WithActiveStatement_AwaitForEach() { var src1 = @" class C { static Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> return Task.FromResult(1); } } "; var src2 = @" class C { static async Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> await foreach (var x in AsyncIter()) { } return 1; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "await foreach (var x in AsyncIter())", CSharpFeaturesResources.asynchronous_foreach_statement)); } [Fact] public void MethodToAsyncMethod_WithActiveStatement_AwaitUsing() { var src1 = @" class C { static Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> return Task.FromResult(1); } } "; var src2 = @" class C { static async Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> await using IAsyncDisposable x = new AsyncDisposable(), y = new AsyncDisposable(); return 1; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "x = new AsyncDisposable()", CSharpFeaturesResources.asynchronous_using_declaration), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "y = new AsyncDisposable()", CSharpFeaturesResources.asynchronous_using_declaration)); } [Fact] public void MethodToAsyncMethod_WithActiveStatement_NoAwait1() { var src1 = @" class C { static void F() <AS:0>{</AS:0> Console.WriteLine(1); } } "; var src2 = @" class C { static async void F() <AS:0>{</AS:0> Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "static async void F()")); } [Fact] public void MethodToAsyncMethod_WithActiveStatement_NoAwait2() { var src1 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var src2 = @" class C { static async void F() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "static async void F()")); } [Fact] public void MethodToAsyncMethod_WithActiveStatementInLambda1() { var src1 = @" class C { static Task<int> F() { var f = new Action(() => { <AS:0>Console.WriteLine(1);</AS:0> }); return Task.FromResult(1); } } "; var src2 = @" class C { static async Task<int> F() { var f = new Action(() => { <AS:0>Console.WriteLine(1);</AS:0> }); return await Task.FromResult(1); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // should not contain RUDE_EDIT_INSERT_AROUND edits.VerifyRudeDiagnostics(active); } [Fact] public void MethodToAsyncMethod_WithActiveStatementInLambda_2() { var src1 = @" class C { static void F() { var f = new Action(() => { <AS:1>Console.WriteLine(1);</AS:1> }); <AS:0>f();</AS:0> } } "; var src2 = @" class C { static async void F() { var f = new Action(() => { <AS:1>Console.WriteLine(1);</AS:1> }); <AS:0>f();</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "static async void F()")); } [Fact] public void MethodToAsyncMethod_WithLambda() { var src1 = @" class C { static void F() <AS:0>{</AS:0> var f = new Action(() => { Console.WriteLine(1); }); f(); } } "; var src2 = @" class C { static async void F() <AS:0>{</AS:0> var f = new Action(() => { Console.WriteLine(1); }); f(); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "static async void F()")); } [Fact] public void MethodToAsyncMethod_WithoutActiveStatement_1() { var src1 = @" class C { static Task<int> F() { Console.WriteLine(1); return Task.FromResult(1); } } "; var src2 = @" class C { static async Task<int> F() { Console.WriteLine(1); return await Task.FromResult(1); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void MethodToAsyncMethod_WithoutActiveStatement_2() { var src1 = @" class C { static void F() { Console.WriteLine(1); } } "; var src2 = @" class C { static async void F() { Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void LambdaToAsyncLambda_WithActiveStatement() { var src1 = @" using System; using System.Threading.Tasks; class C { static void F() { var f = new Func<Task<int>>(() => { <AS:0>Console.WriteLine(1);</AS:0> return Task.FromResult(1); }); } } "; var src2 = @" using System; using System.Threading.Tasks; class C { static void F() { var f = new Func<Task<int>>(async () => { <AS:0>Console.WriteLine(1);</AS:0> return await Task.FromResult(1); }); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void LambdaToAsyncLambda_WithActiveStatement_NoAwait() { var src1 = @" using System; class C { static void F() { var f = new Action(() => { <AS:0>Console.WriteLine(1);</AS:0> }); } } "; var src2 = @" using System; class C { static void F() { var f = new Action(async () => { <AS:0>Console.WriteLine(1);</AS:0> }); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "()")); } [Fact] public void LambdaToAsyncLambda_WithActiveStatement_NoAwait_Nested() { var src1 = @" class C { static void F() { var f = new Func<int, Func<int, int>>(a => <AS:0>b => 1</AS:0>); } } "; var src2 = @" class C { static void F() { var f = new Func<int, Func<int, int>>(async a => <AS:0>b => 1</AS:0>); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "a")); } [Fact] [WorkItem(37054, "https://github.com/dotnet/roslyn/issues/37054")] public void LocalFunctionToAsyncLocalFunction_BlockBody_WithActiveStatement() { var src1 = @" class C { static void F() { Task<int> f() { <AS:0>Console.WriteLine(1);</AS:0> return Task.FromResult(1); } } } "; var src2 = @" class C { static void F() { async Task<int> f() { <AS:0>Console.WriteLine(1);</AS:0> return await Task.FromResult(1); } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "await", CSharpFeaturesResources.await_expression)); } [Fact] [WorkItem(37054, "https://github.com/dotnet/roslyn/issues/37054")] public void LocalFunctionToAsyncLocalFunction_ExpressionBody_WithActiveStatement() { var src1 = @" class C { static void F() { Task<int> f() => <AS:0>Task.FromResult(1)</AS:0>; } } "; var src2 = @" class C { static void F() { async Task<int> f() => <AS:0>await Task.FromResult(1)</AS:0>; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void AnonymousFunctionToAsyncAnonymousFunction_WithActiveStatement_NoAwait() { var src1 = @" using System.Threading.Tasks; class C { static void F() { var f = new Func<Task>(delegate() { <AS:0>Console.WriteLine(1);</AS:0> return Task.CompletedTask; }); } } "; var src2 = @" using System.Threading.Tasks; class C { static async void F() { var f = new Func<Task>(async delegate() { <AS:0>Console.WriteLine(1);</AS:0> }); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, FeaturesResources.delegate_)); } [Fact] public void AsyncMethodEdit_Semantics() { var src1 = @" using System; using System.Threading.Tasks; class C { static async Task<int> F() { await using var x = new AsyncDisposable(); await foreach (var x in AsyncIter()) { Console.WriteLine(x); } return await Task.FromResult(1); } } "; var src2 = @" using System; using System.Threading.Tasks; class C { static async Task<int> F() { await using var x = new AsyncDisposable(); await foreach (var x in AsyncIter()) { Console.WriteLine(x + 1); } return await Task.FromResult(2); } } "; var edits = GetTopEdits(src1, src2); _ = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void IteratorMethodEdit_Semantics() { var src1 = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> F() { Console.WriteLine(1); yield return 1; } } "; var src2 = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> F() { Console.WriteLine(2); yield return 2; } } "; var edits = GetTopEdits(src1, src2); _ = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void AsyncIteratorMethodEdit_Semantics() { var src1 = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class C { static async IAsyncEnumerable<int> F() { Console.WriteLine(1); await Task.Delay(1); yield return 1; } } "; var src2 = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class C { static async IAsyncEnumerable<int> F() { Console.WriteLine(2); await Task.Delay(2); yield return 2; } } "; var edits = GetTopEdits(src1, src2); _ = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(targetFrameworks: new[] { TargetFramework.NetCoreApp }); } [Fact] public void AsyncMethodToMethod() { var src1 = @" class C { static async void F() { } } "; var src2 = @" class C { static void F() { } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "static void F()", FeaturesResources.method)); } #endregion #region Misplaced AS [Fact] public void MisplacedActiveStatement1() { var src1 = @" <AS:1>class C</AS:1> { public static int F(int a) { <AS:0>return a;</AS:0> <AS:2>return a;</AS:2> } }"; var src2 = @" class C { public static int F(int a) { <AS:0>return a;</AS:0> <AS:2>return a;</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void MisplacedActiveStatement2() { var src1 = @" class C { static <AS:0>void</AS:0> Main(string[] args) { } }"; var src2 = @" class C { static void Main(string[] args) <AS:0>{</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void MisplacedTrackingSpan1() { var src1 = @" class C { static <AS:0>void</AS:0> Main(string[] args) { } }"; var src2 = @" class C { static <TS:0>void</TS:0> Main(string[] args) <AS:0>{</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region C# 7.0 [Fact] public void UpdateAroundActiveStatement_IsPattern() { var src1 = @" class C { static void F(object x) { <AS:0>Console.WriteLine(1);</AS:0> if (x is int i) { Console.WriteLine(""match""); } } } "; var src2 = @" class C { static void F(object x) { <AS:0>Console.WriteLine(1);</AS:0> if (x is string s) { Console.WriteLine(""match""); } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_DeconstructionDeclarationStatement() { var src1 = @" class C { static void F(object x) { <AS:0>Console.WriteLine(1);</AS:0> var (x, y) = (1, 2); } } "; var src2 = @" class C { static void F(object x) { <AS:0>Console.WriteLine(1);</AS:0> var (x, y) = x; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_DeconstructionForEach() { var src1 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> foreach (var (x, y) in new[] { (1, 2) }) { Console.WriteLine(2); } } } "; var src2 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> foreach (var (x, y) in new[] { o }) { Console.WriteLine(2); } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_VarDeconstruction() { var src1 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> for (var (x, y) = o1; ; ) { } } } "; var src2 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> for (var (x, y) = o2; ; ) { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_TypedDeconstruction() { var src1 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> for ((int x, int y) = o1; ; ) { } } } "; var src2 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> for ((int x, int y) = o2; ; ) { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_Tuple() { var src1 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> (int, int) t; } } "; var src2 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> (int, int) t = (1, 2); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_LocalFunction() { var src1 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> void M() { Console.WriteLine(2); } } } "; var src2 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> void M() { Console.WriteLine(3); } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_OutVar() { var src1 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> M(); } } "; var src2 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> M(out var x); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_OutVarRemoved() { var src1 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> M(out var x); } } "; var src2 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_Ref() { var src1 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> ref int i = ref 1; } } "; var src2 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> ref int i = ref 2; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_DeconstructionDeclaration() { var src1 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> var (x, y) = o1; } } "; var src2 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> var (x, y) = o2; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_DeconstructionAssignment() { var src1 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> int x, y; (x, y) = o1; } } "; var src2 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> int x, y; (x, y) = o2; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_SwitchWithPattern() { var src1 = @" class C { static void F(object o1, object o2) { <AS:0>System.Console.WriteLine(1);</AS:0> switch (o1) { case int i: break; } } } "; var src2 = @" class C { static void F(object o1, object o2) { <AS:0>System.Console.WriteLine(1);</AS:0> switch (o2) { case int i: break; } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); edits.VerifySemanticDiagnostics(); } #endregion #region Nullable [Fact] public void ChangeLocalNullableToNonNullable() { var src1 = @" class C { static void F() { <AS:0>string? s = ""a"";</AS:0> } } "; var src2 = @" class C { static void F() { <AS:0>string s = ""a"";</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ChangeLocalNonNullableToNullable() { var src1 = @" class C { static void F() { <AS:0>string s = ""a"";</AS:0> } } "; var src2 = @" class C { static void F() { <AS:0>string? s = ""a"";</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Partial Types [Fact] public void InsertDeleteMethod_Inactive() { // Moving inactive method declaration in a file with active statements. var srcA1 = "partial class C { void F1() { <AS:0>System.Console.WriteLine(1);</AS:0> } }"; var srcB1 = "partial class C { void F2() { } }"; var srcA2 = "partial class C { void F1() { <AS:0>System.Console.WriteLine(1);</AS:0> } void F2() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( activeStatements: GetActiveStatements(srcA1, srcA2, path: "0"), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F2")), }), DocumentResults( activeStatements: GetActiveStatements(srcB1, srcB2, path: "1")) }); } [Fact] [WorkItem(51177, "https://github.com/dotnet/roslyn/issues/51177")] [WorkItem(54758, "https://github.com/dotnet/roslyn/issues/54758")] public void InsertDeleteMethod_Active() { // Moving active method declaration in a file with active statements. // TODO: this is currently a rude edit var srcA1 = "partial class C { }"; var srcB1 = "partial class C { void F() { <AS:0>System.Console.WriteLine(1);</AS:0> } }"; var srcA2 = "partial class C { void F() { System.Console.WriteLine(1); } }"; var srcB2 = "<AS:0>partial class C</AS:0> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( activeStatements: GetActiveStatements(srcA1, srcA2, path: "0"), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")), }), DocumentResults( activeStatements: GetActiveStatements(srcB1, srcB2, path: "1"), // TODO: this is odd AS location https://github.com/dotnet/roslyn/issues/54758 diagnostics: new[] { Diagnostic(RudeEditKind.DeleteActiveStatement, " partial c", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } #endregion #region Records [Fact] public void Record() { var src1 = @" record C(int X) { public int X { get; init; } = <AS:0>1</AS:0>; }"; var src2 = @" record C(int X) { public int X { get; init; } = <AS:0>2</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Record_Constructor() { var src1 = @" record C(int X) { public int X { get; init; } = <AS:0>1</AS:0>; static void Main(string[] args) { <AS:1>var x = new C(1);</AS:1> } }"; var src2 = @" record C(int X) { public int X { get; init; } = <AS:0>2</AS:0>; static void Main(string[] args) { <AS:1>var x = new C(1);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Record_FieldInitializer_Lambda2() { var src1 = @" record C(int X) { Func<int, Func<int>> a = z => () => <AS:0>z + 1</AS:0>; static void Main(string[] args) { <AS:1>new C(1).a(1)();</AS:1> } }"; var src2 = @" record C(int X) { Func<int, Func<int>> a = z => () => <AS:0>z + 2</AS:0>; static void Main(string[] args) { <AS:1>new C(1).a(1)();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Line Mapping /// <summary> /// Validates that changes in #line directives produce semantic updates of the containing method. /// </summary> [Fact] public void LineMapping_ChangeLineNumber_WithinMethod() { var src1 = @" class C { #line 1 ""a"" static void F() { <AS:0>A();</AS:0> #line 5 ""b"" B(1); <AS:1>B();</AS:1> #line 2 ""c"" <AS:2>C();</AS:2> <AS:3>C();</AS:3> #line hidden D(); #line default <AS:4>E();</AS:4> } }"; var src2 = @" class C { #line 1 ""a"" static void F() { <AS:0>A();</AS:0> #line 5 ""b"" B(2); <AS:1>B();</AS:1> #line 9 ""c"" <AS:2>C();</AS:2> <AS:3>C();</AS:3> #line hidden D(); #line default <AS:4>E();</AS:4> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void LineMapping_ChangeFilePath() { var src1 = @" class C { static void F() { <AS:0>A();</AS:0> #line 1 ""a"" <AS:1>B();</AS:1> } }"; var src2 = @" class C { static void F() { <AS:0>A();</AS:0> #line 1 ""b"" <AS:1>B();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "B();", string.Format(FeaturesResources._0_directive, "line"))); } [Fact] public void LineMapping_ExceptionRegions_ChangeLineNumber() { var src1 = @" class C { static void Main() <AS:0>{</AS:0> try { try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line default } #line 20 ""b"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var src2 = @" class C { static void Main() <AS:0>{</AS:0> try { try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line default } #line 30 ""b"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(52971, "https://github.com/dotnet/roslyn/issues/52971")] public void LineMapping_ExceptionRegions_ChangeFilePath() { var src1 = @" class C { static void Main() <AS:0>{</AS:0> try { try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line default } #line 20 ""b"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var src2 = @" class C { static void Main() <AS:0>{</AS:0> try { try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line default } #line 20 ""c"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // TODO: rude edit should be reported edits.VerifyRudeDiagnostics(active); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/52971"), WorkItem(52971, "https://github.com/dotnet/roslyn/issues/52971")] public void LineMapping_ExceptionRegions_LineChange_MultipleMappedFiles() { var src1 = @" class C { static void Main() <AS:0>{</AS:0> try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line 20 ""b"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var src2 = @" class C { static void Main() <AS:0>{</AS:0> try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line 30 ""b"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // TODO: rude edit? edits.VerifyRudeDiagnostics(active); } #endregion #region Misc [Fact] public void Delete_All_SourceText() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @""; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "C"))); } [Fact] public void PartiallyExecutedActiveStatement() { var src1 = @" class C { public static void F() { <AS:0>Console.WriteLine(1);</AS:0> <AS:1>Console.WriteLine(2);</AS:1> <AS:2>Console.WriteLine(3);</AS:2> <AS:3>Console.WriteLine(4);</AS:3> <AS:4>Console.WriteLine(5);</AS:4> } }"; var src2 = @" class C { public static void F() { <AS:0>Console.WriteLine(10);</AS:0> <AS:1>Console.WriteLine(20);</AS:1> <AS:2>Console.WriteLine(30);</AS:2> <AS:3>Console.WriteLine(40);</AS:3> <AS:4>Console.WriteLine(50);</AS:4> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2, flags: new[] { ActiveStatementFlags.PartiallyExecuted | ActiveStatementFlags.IsLeafFrame, ActiveStatementFlags.PartiallyExecuted | ActiveStatementFlags.IsNonLeafFrame, ActiveStatementFlags.IsLeafFrame, ActiveStatementFlags.IsNonLeafFrame, ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.IsLeafFrame }); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.PartiallyExecutedActiveStatementUpdate, "Console.WriteLine(10);"), Diagnostic(RudeEditKind.ActiveStatementUpdate, "Console.WriteLine(20);"), Diagnostic(RudeEditKind.ActiveStatementUpdate, "Console.WriteLine(40);"), Diagnostic(RudeEditKind.ActiveStatementUpdate, "Console.WriteLine(50);")); } [Fact] public void PartiallyExecutedActiveStatement_Deleted1() { var src1 = @" class C { public static void F() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { public static void F() { <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2, flags: new[] { ActiveStatementFlags.PartiallyExecuted | ActiveStatementFlags.IsLeafFrame }); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.PartiallyExecutedActiveStatementDelete, "{", FeaturesResources.code)); } [Fact] public void PartiallyExecutedActiveStatement_Deleted2() { var src1 = @" class C { public static void F() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { public static void F() { <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2, flags: new[] { ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.IsLeafFrame }); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } [Fact] public void Block_Delete() { var src1 = @" class C { public static void F() { G(1); <AS:0>{</AS:0> G(2); } G(3); } } "; var src2 = @" class C { public static void F() { G(1); <AS:0>G(3);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Theory, CombinatorialData] public void MemberBodyInternalError(bool outOfMemory) { var src1 = @" class C { public static void F() { <AS:1>G();</AS:1> } public static void G() { <AS:0>H(1);</AS:0> } public static void H(int x) { } } "; var src2 = @" class C { public static void F() { <AS:1>G();</AS:1> } public static void G() { <AS:0>H(2);</AS:0> } public static void H(int x) { } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); var validator = new CSharpEditAndContinueTestHelpers(faultInjector: node => { if (node.Parent is MethodDeclarationSyntax methodDecl && methodDecl.Identifier.Text == "G") { throw outOfMemory ? new OutOfMemoryException() : new NullReferenceException("NullRef!"); } }); var expectedDiagnostic = outOfMemory ? Diagnostic(RudeEditKind.MemberBodyTooBig, "public static void G()", FeaturesResources.method) : Diagnostic(RudeEditKind.MemberBodyInternalError, "public static void G()", FeaturesResources.method); validator.VerifySemantics( new[] { edits }, TargetFramework.NetCoreApp, new[] { DocumentResults(diagnostics: new[] { expectedDiagnostic }) }); } #endregion #region Top Level Statements [Fact] public void TopLevelStatements_UpdateAroundActiveStatement_LocalFunction() { var src1 = @" using System; <AS:0>Console.WriteLine(1);</AS:0> void M() { Console.WriteLine(2); } "; var src2 = @" using System; <AS:0>Console.WriteLine(1);</AS:0> void M() { Console.WriteLine(3); } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void TopLevelStatements_UpdateAroundActiveStatement_OutVar() { var src1 = @" using System; <AS:0>Console.WriteLine(1);</AS:0> M(); "; var src2 = @" using System; <AS:0>Console.WriteLine(1);</AS:0> M(out var x); "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void TopLevelStatements_Inner() { var src1 = @" using System; <AS:1>Goo(1);</AS:1> static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } "; var src2 = @" using System; while (true) { <AS:1>Goo(2);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "Goo(2);")); } #endregion } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/EditorFeatures/VisualBasicTest/Wrapping/AbstractParameterWrappingTests.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.CodeActions Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.Formatting Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Wrapping Public MustInherit Class AbstractWrappingTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function MassageActions(actions As ImmutableArray(Of CodeAction)) As ImmutableArray(Of CodeAction) Return FlattenActions(actions) End Function Private Protected Function GetIndentionColumn(column As Integer) As OptionsCollection Return New OptionsCollection(GetLanguage()) From { {FormattingOptions2.PreferredWrappingColumn, column} } End Function Protected Function TestAllWrappingCasesAsync( input As String, ParamArray outputs As String()) As Task Return TestAllWrappingCasesAsync(input, options:=Nothing, outputs) End Function Private Protected Function TestAllWrappingCasesAsync( input As String, options As OptionsCollection, ParamArray outputs As String()) As Task Dim parameters = New TestParameters(options:=options) Return TestAllInRegularAndScriptAsync(input, parameters, outputs) 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.CodeActions Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.Formatting Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Wrapping Public MustInherit Class AbstractWrappingTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function MassageActions(actions As ImmutableArray(Of CodeAction)) As ImmutableArray(Of CodeAction) Return FlattenActions(actions) End Function Private Protected Function GetIndentionColumn(column As Integer) As OptionsCollection Return New OptionsCollection(GetLanguage()) From { {FormattingOptions2.PreferredWrappingColumn, column} } End Function Protected Function TestAllWrappingCasesAsync( input As String, ParamArray outputs As String()) As Task Return TestAllWrappingCasesAsync(input, options:=Nothing, outputs) End Function Private Protected Function TestAllWrappingCasesAsync( input As String, options As OptionsCollection, ParamArray outputs As String()) As Task Dim parameters = New TestParameters(options:=options) Return TestAllInRegularAndScriptAsync(input, parameters, outputs) End Function End Class End Namespace
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Features/Core/Portable/Structure/BlockTypes.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.Structure { internal static class BlockTypes { // Basic types. public const string Nonstructural = nameof(Nonstructural); // Trivia public const string Comment = nameof(Comment); public const string PreprocessorRegion = nameof(PreprocessorRegion); // Top level declarations. public const string Imports = nameof(Imports); public const string Namespace = nameof(Namespace); public const string Type = nameof(Type); public const string Member = nameof(Member); // Statements and expressions. public const string Statement = nameof(Statement); public const string Conditional = nameof(Conditional); public const string Loop = nameof(Loop); public const string Expression = nameof(Expression); internal static bool IsCommentOrPreprocessorRegion(string type) { switch (type) { case Comment: case PreprocessorRegion: return true; } return false; } internal static bool IsExpressionLevelConstruct(string type) => type == Expression; internal static bool IsStatementLevelConstruct(string type) { switch (type) { case Statement: case Conditional: case Loop: return true; } return false; } internal static bool IsCodeLevelConstruct(string type) => IsExpressionLevelConstruct(type) || IsStatementLevelConstruct(type); internal static bool IsDeclarationLevelConstruct(string type) => !IsCodeLevelConstruct(type) && !IsCommentOrPreprocessorRegion(type); } }
// Licensed to the .NET Foundation under one or more 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.Structure { internal static class BlockTypes { // Basic types. public const string Nonstructural = nameof(Nonstructural); // Trivia public const string Comment = nameof(Comment); public const string PreprocessorRegion = nameof(PreprocessorRegion); // Top level declarations. public const string Imports = nameof(Imports); public const string Namespace = nameof(Namespace); public const string Type = nameof(Type); public const string Member = nameof(Member); // Statements and expressions. public const string Statement = nameof(Statement); public const string Conditional = nameof(Conditional); public const string Loop = nameof(Loop); public const string Expression = nameof(Expression); internal static bool IsCommentOrPreprocessorRegion(string type) { switch (type) { case Comment: case PreprocessorRegion: return true; } return false; } internal static bool IsExpressionLevelConstruct(string type) => type == Expression; internal static bool IsStatementLevelConstruct(string type) { switch (type) { case Statement: case Conditional: case Loop: return true; } return false; } internal static bool IsCodeLevelConstruct(string type) => IsExpressionLevelConstruct(type) || IsStatementLevelConstruct(type); internal static bool IsDeclarationLevelConstruct(string type) => !IsCodeLevelConstruct(type) && !IsCommentOrPreprocessorRegion(type); } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/VisualStudio/VisualBasic/Impl/CodeModel/Interop/IVBCodeTypeLocation.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.Runtime.InteropServices Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Interop <ComImport> <InterfaceType(ComInterfaceType.InterfaceIsDual)> <Guid("69A529CD-84E3-4ee8-9918-A540CB827993")> Friend Interface IVBCodeTypeLocation ReadOnly Property ExternalLocation As String End Interface 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.Runtime.InteropServices Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Interop <ComImport> <InterfaceType(ComInterfaceType.InterfaceIsDual)> <Guid("69A529CD-84E3-4ee8-9918-A540CB827993")> Friend Interface IVBCodeTypeLocation ReadOnly Property ExternalLocation As String End Interface End Namespace
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/ValueUsageInfo.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 { [Flags] internal enum ValueUsageInfo { /// <summary> /// Represents default value indicating no usage. /// </summary> None = 0x0, /// <summary> /// Represents a value read. /// For example, reading the value of a local/field/parameter. /// </summary> Read = 0x1, /// <summary> /// Represents a value write. /// For example, assigning a value to a local/field/parameter. /// </summary> Write = 0x2, /// <summary> /// Represents a reference being taken for the symbol. /// For example, passing an argument to an "in", "ref" or "out" parameter. /// </summary> Reference = 0x4, /// <summary> /// Represents a name-only reference that neither reads nor writes the underlying value. /// For example, 'nameof(x)' or reference to a symbol 'x' in a documentation comment /// does not read or write the underlying value stored in 'x'. /// </summary> Name = 0x8, /// <summary> /// Represents a value read and/or write. /// For example, an increment or compound assignment operation. /// </summary> ReadWrite = Read | Write, /// <summary> /// Represents a readable reference being taken to the value. /// For example, passing an argument to an "in" or "ref readonly" parameter. /// </summary> ReadableReference = Read | Reference, /// <summary> /// Represents a readable reference being taken to the value. /// For example, passing an argument to an "out" parameter. /// </summary> WritableReference = Write | Reference, /// <summary> /// Represents a value read or write. /// For example, passing an argument to a "ref" parameter. /// </summary> ReadableWritableReference = Read | Write | Reference } internal static class ValueUsageInfoExtensions { public static bool IsReadFrom(this ValueUsageInfo valueUsageInfo) => (valueUsageInfo & ValueUsageInfo.Read) != 0; public static bool IsWrittenTo(this ValueUsageInfo valueUsageInfo) => (valueUsageInfo & ValueUsageInfo.Write) != 0; public static bool IsNameOnly(this ValueUsageInfo valueUsageInfo) => (valueUsageInfo & ValueUsageInfo.Name) != 0; public static bool IsReference(this ValueUsageInfo valueUsageInfo) => (valueUsageInfo & ValueUsageInfo.Reference) != 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. using System; namespace Microsoft.CodeAnalysis { [Flags] internal enum ValueUsageInfo { /// <summary> /// Represents default value indicating no usage. /// </summary> None = 0x0, /// <summary> /// Represents a value read. /// For example, reading the value of a local/field/parameter. /// </summary> Read = 0x1, /// <summary> /// Represents a value write. /// For example, assigning a value to a local/field/parameter. /// </summary> Write = 0x2, /// <summary> /// Represents a reference being taken for the symbol. /// For example, passing an argument to an "in", "ref" or "out" parameter. /// </summary> Reference = 0x4, /// <summary> /// Represents a name-only reference that neither reads nor writes the underlying value. /// For example, 'nameof(x)' or reference to a symbol 'x' in a documentation comment /// does not read or write the underlying value stored in 'x'. /// </summary> Name = 0x8, /// <summary> /// Represents a value read and/or write. /// For example, an increment or compound assignment operation. /// </summary> ReadWrite = Read | Write, /// <summary> /// Represents a readable reference being taken to the value. /// For example, passing an argument to an "in" or "ref readonly" parameter. /// </summary> ReadableReference = Read | Reference, /// <summary> /// Represents a readable reference being taken to the value. /// For example, passing an argument to an "out" parameter. /// </summary> WritableReference = Write | Reference, /// <summary> /// Represents a value read or write. /// For example, passing an argument to a "ref" parameter. /// </summary> ReadableWritableReference = Read | Write | Reference } internal static class ValueUsageInfoExtensions { public static bool IsReadFrom(this ValueUsageInfo valueUsageInfo) => (valueUsageInfo & ValueUsageInfo.Read) != 0; public static bool IsWrittenTo(this ValueUsageInfo valueUsageInfo) => (valueUsageInfo & ValueUsageInfo.Write) != 0; public static bool IsNameOnly(this ValueUsageInfo valueUsageInfo) => (valueUsageInfo & ValueUsageInfo.Name) != 0; public static bool IsReference(this ValueUsageInfo valueUsageInfo) => (valueUsageInfo & ValueUsageInfo.Reference) != 0; } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IMethodReferenceOperation.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.Operations Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics <CompilerTrait(CompilerFeature.IOperation)> Partial Public Class IOperationTests Inherits SemanticModelTestBase <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub MethodReference_NoControlFlow() ' Verify method references with different kinds of instance references. Dim source = <![CDATA[ Imports System Friend Class C Public Overridable Function M1_Method() As Integer Return 0 End Function Public Shared Function M2_Method() As Integer Return 0 End Function Public Sub M(c As C, m1 As Func(Of Integer), m2 As Func(Of Integer), m3 As Func(Of Integer)) 'BIND:"Public Sub M(c As C, m1 As Func(Of Integer), m2 As Func(Of Integer), m3 As Func(Of Integer))" m1 = AddressOf Me.M1_Method m2 = AddressOf c.M1_Method m3 = AddressOf M2_Method End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (3) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'm1 = Addres ... e.M1_Method') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Func(Of System.Int32), IsImplicit) (Syntax: 'm1 = Addres ... e.M1_Method') Left: IParameterReferenceOperation: m1 (OperationKind.ParameterReference, Type: System.Func(Of System.Int32)) (Syntax: 'm1') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32), IsImplicit) (Syntax: 'AddressOf Me.M1_Method') Target: IMethodReferenceOperation: Function C.M1_Method() As System.Int32 (IsVirtual) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf Me.M1_Method') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'm2 = Addres ... c.M1_Method') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Func(Of System.Int32), IsImplicit) (Syntax: 'm2 = Addres ... c.M1_Method') Left: IParameterReferenceOperation: m2 (OperationKind.ParameterReference, Type: System.Func(Of System.Int32)) (Syntax: 'm2') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32), IsImplicit) (Syntax: 'AddressOf c.M1_Method') Target: IMethodReferenceOperation: Function C.M1_Method() As System.Int32 (IsVirtual) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf c.M1_Method') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'm3 = AddressOf M2_Method') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Func(Of System.Int32), IsImplicit) (Syntax: 'm3 = AddressOf M2_Method') Left: IParameterReferenceOperation: m3 (OperationKind.ParameterReference, Type: System.Func(Of System.Int32)) (Syntax: 'm3') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32), IsImplicit) (Syntax: 'AddressOf M2_Method') Target: IMethodReferenceOperation: Function C.M2_Method() As System.Int32 (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M2_Method') Instance Receiver: null Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub MethodReference_ControlFlowInReceiver() Dim source = <![CDATA[ Imports System Friend Class C Public Function M1() As Integer Return 0 End Function Public Sub M(c1 As C, c2 As C, m As Func(Of Integer))'BIND:"Public Sub M(c1 As C, c2 As C, m As Func(Of Integer))" m = AddressOf If(c1, c2).M1 End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'm') Value: IParameterReferenceOperation: m (OperationKind.ParameterReference, Type: System.Func(Of System.Int32)) (Syntax: 'm') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'm = Address ... (c1, c2).M1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Func(Of System.Int32), IsImplicit) (Syntax: 'm = Address ... (c1, c2).M1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Func(Of System.Int32), IsImplicit) (Syntax: 'm') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32), IsImplicit) (Syntax: 'AddressOf If(c1, c2).M1') Target: IMethodReferenceOperation: Function C.M1() As System.Int32 (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf If(c1, c2).M1') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub MethodReference_ControlFlowInReceiver_StaticMethod() Dim source = <![CDATA[ Imports System Friend Class C Public Shared Function M1() As Integer Return 0 End Function Public Sub M(c1 As C, c2 As C, m1 As Func(Of Integer), m2 As Func(Of Integer))'BIND:"Public Sub M(c1 As C, c2 As C, m1 As Func(Of Integer), m2 As Func(Of Integer))" m1 = AddressOf c1.M1 m2 = AddressOf If(c1, c2).M1 End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'm1 = AddressOf c1.M1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Func(Of System.Int32), IsImplicit) (Syntax: 'm1 = AddressOf c1.M1') Left: IParameterReferenceOperation: m1 (OperationKind.ParameterReference, Type: System.Func(Of System.Int32)) (Syntax: 'm1') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32), IsImplicit) (Syntax: 'AddressOf c1.M1') Target: IMethodReferenceOperation: Function C.M1() As System.Int32 (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf c1.M1') Instance Receiver: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'm2 = Addres ... (c1, c2).M1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Func(Of System.Int32), IsImplicit) (Syntax: 'm2 = Addres ... (c1, c2).M1') Left: IParameterReferenceOperation: m2 (OperationKind.ParameterReference, Type: System.Func(Of System.Int32)) (Syntax: 'm2') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32), IsImplicit) (Syntax: 'AddressOf If(c1, c2).M1') Target: IMethodReferenceOperation: Function C.M1() As System.Int32 (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf If(c1, c2).M1') Instance Receiver: null Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. m1 = AddressOf c1.M1 ~~~~~~~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. m2 = AddressOf If(c1, c2).M1 ~~~~~~~~~~~~~~~~~~~~~~~ ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) 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 Microsoft.CodeAnalysis.Operations Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics <CompilerTrait(CompilerFeature.IOperation)> Partial Public Class IOperationTests Inherits SemanticModelTestBase <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub MethodReference_NoControlFlow() ' Verify method references with different kinds of instance references. Dim source = <![CDATA[ Imports System Friend Class C Public Overridable Function M1_Method() As Integer Return 0 End Function Public Shared Function M2_Method() As Integer Return 0 End Function Public Sub M(c As C, m1 As Func(Of Integer), m2 As Func(Of Integer), m3 As Func(Of Integer)) 'BIND:"Public Sub M(c As C, m1 As Func(Of Integer), m2 As Func(Of Integer), m3 As Func(Of Integer))" m1 = AddressOf Me.M1_Method m2 = AddressOf c.M1_Method m3 = AddressOf M2_Method End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (3) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'm1 = Addres ... e.M1_Method') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Func(Of System.Int32), IsImplicit) (Syntax: 'm1 = Addres ... e.M1_Method') Left: IParameterReferenceOperation: m1 (OperationKind.ParameterReference, Type: System.Func(Of System.Int32)) (Syntax: 'm1') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32), IsImplicit) (Syntax: 'AddressOf Me.M1_Method') Target: IMethodReferenceOperation: Function C.M1_Method() As System.Int32 (IsVirtual) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf Me.M1_Method') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'm2 = Addres ... c.M1_Method') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Func(Of System.Int32), IsImplicit) (Syntax: 'm2 = Addres ... c.M1_Method') Left: IParameterReferenceOperation: m2 (OperationKind.ParameterReference, Type: System.Func(Of System.Int32)) (Syntax: 'm2') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32), IsImplicit) (Syntax: 'AddressOf c.M1_Method') Target: IMethodReferenceOperation: Function C.M1_Method() As System.Int32 (IsVirtual) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf c.M1_Method') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'm3 = AddressOf M2_Method') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Func(Of System.Int32), IsImplicit) (Syntax: 'm3 = AddressOf M2_Method') Left: IParameterReferenceOperation: m3 (OperationKind.ParameterReference, Type: System.Func(Of System.Int32)) (Syntax: 'm3') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32), IsImplicit) (Syntax: 'AddressOf M2_Method') Target: IMethodReferenceOperation: Function C.M2_Method() As System.Int32 (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf M2_Method') Instance Receiver: null Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub MethodReference_ControlFlowInReceiver() Dim source = <![CDATA[ Imports System Friend Class C Public Function M1() As Integer Return 0 End Function Public Sub M(c1 As C, c2 As C, m As Func(Of Integer))'BIND:"Public Sub M(c1 As C, c2 As C, m As Func(Of Integer))" m = AddressOf If(c1, c2).M1 End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'm') Value: IParameterReferenceOperation: m (OperationKind.ParameterReference, Type: System.Func(Of System.Int32)) (Syntax: 'm') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'm = Address ... (c1, c2).M1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Func(Of System.Int32), IsImplicit) (Syntax: 'm = Address ... (c1, c2).M1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Func(Of System.Int32), IsImplicit) (Syntax: 'm') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32), IsImplicit) (Syntax: 'AddressOf If(c1, c2).M1') Target: IMethodReferenceOperation: Function C.M1() As System.Int32 (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf If(c1, c2).M1') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub MethodReference_ControlFlowInReceiver_StaticMethod() Dim source = <![CDATA[ Imports System Friend Class C Public Shared Function M1() As Integer Return 0 End Function Public Sub M(c1 As C, c2 As C, m1 As Func(Of Integer), m2 As Func(Of Integer))'BIND:"Public Sub M(c1 As C, c2 As C, m1 As Func(Of Integer), m2 As Func(Of Integer))" m1 = AddressOf c1.M1 m2 = AddressOf If(c1, c2).M1 End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'm1 = AddressOf c1.M1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Func(Of System.Int32), IsImplicit) (Syntax: 'm1 = AddressOf c1.M1') Left: IParameterReferenceOperation: m1 (OperationKind.ParameterReference, Type: System.Func(Of System.Int32)) (Syntax: 'm1') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32), IsImplicit) (Syntax: 'AddressOf c1.M1') Target: IMethodReferenceOperation: Function C.M1() As System.Int32 (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf c1.M1') Instance Receiver: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'm2 = Addres ... (c1, c2).M1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Func(Of System.Int32), IsImplicit) (Syntax: 'm2 = Addres ... (c1, c2).M1') Left: IParameterReferenceOperation: m2 (OperationKind.ParameterReference, Type: System.Func(Of System.Int32)) (Syntax: 'm2') Right: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func(Of System.Int32), IsImplicit) (Syntax: 'AddressOf If(c1, c2).M1') Target: IMethodReferenceOperation: Function C.M1() As System.Int32 (Static) (OperationKind.MethodReference, Type: null) (Syntax: 'AddressOf If(c1, c2).M1') Instance Receiver: null Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. m1 = AddressOf c1.M1 ~~~~~~~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. m2 = AddressOf If(c1, c2).M1 ~~~~~~~~~~~~~~~~~~~~~~~ ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub End Class End Namespace
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/EditorFeatures/Core.Cocoa/Snippets/CSharpSnippets/SnippetFunctions/SnippetFunctionGenerateSwitchCases.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.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.Snippets.SnippetFunctions; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; using TextSpan = Microsoft.CodeAnalysis.Text.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Snippets.SnippetFunctions { internal sealed class SnippetFunctionGenerateSwitchCases : AbstractSnippetFunctionGenerateSwitchCases { public SnippetFunctionGenerateSwitchCases(SnippetExpansionClient snippetExpansionClient, ITextBuffer subjectBuffer, string caseGenerationLocationField, string switchExpressionField) : base(snippetExpansionClient, subjectBuffer, caseGenerationLocationField, switchExpressionField) { } protected override string CaseFormat { get { return @"case {0}.{1}: break; "; } } protected override string DefaultCase { get { return @"default: break;"; } } protected override bool TryGetEnumTypeSymbol(CancellationToken cancellationToken, [NotNullWhen(returnValue: true)] out ITypeSymbol? typeSymbol) { typeSymbol = null; if (!TryGetDocument(out var document)) { return false; } Contract.ThrowIfNull(_snippetExpansionClient.ExpansionSession); var subjectBufferFieldSpan = _snippetExpansionClient.ExpansionSession.GetFieldSpan(SwitchExpressionField); var expressionSpan = subjectBufferFieldSpan.Span.ToTextSpan(); var syntaxTree = document.GetRequiredSyntaxTreeSynchronously(cancellationToken); var token = syntaxTree.FindTokenOnRightOfPosition(expressionSpan.Start, cancellationToken); var expressionNode = token.GetAncestor(n => n.Span == expressionSpan); if (expressionNode == null) { return false; } var model = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken); typeSymbol = model?.GetTypeInfo(expressionNode, cancellationToken).Type; return typeSymbol != null; } protected override bool TryGetSimplifiedTypeNameInCaseContext(Document document, string fullyQualifiedTypeName, string firstEnumMemberName, int startPosition, int endPosition, CancellationToken cancellationToken, out string simplifiedTypeName) { simplifiedTypeName = string.Empty; var typeAnnotation = new SyntaxAnnotation(); var str = "case " + fullyQualifiedTypeName + "." + firstEnumMemberName + ":" + Environment.NewLine + " break;"; var textChange = new TextChange(new TextSpan(startPosition, endPosition - startPosition), str); var typeSpanToAnnotate = new TextSpan(startPosition + "case ".Length, fullyQualifiedTypeName.Length); var textWithCaseAdded = document.GetTextSynchronously(cancellationToken).WithChanges(textChange); var documentWithCaseAdded = document.WithText(textWithCaseAdded); var syntaxRoot = documentWithCaseAdded.GetRequiredSyntaxRootSynchronously(cancellationToken); var nodeToReplace = syntaxRoot.DescendantNodes().FirstOrDefault(n => n.Span == typeSpanToAnnotate); if (nodeToReplace == null) { return false; } var updatedRoot = syntaxRoot.ReplaceNode(nodeToReplace, nodeToReplace.WithAdditionalAnnotations(typeAnnotation, Simplifier.Annotation)); var documentWithAnnotations = documentWithCaseAdded.WithSyntaxRoot(updatedRoot); var simplifiedDocument = Simplifier.ReduceAsync(documentWithAnnotations, cancellationToken: cancellationToken).Result; simplifiedTypeName = simplifiedDocument.GetRequiredSyntaxRootSynchronously(cancellationToken).GetAnnotatedNodesAndTokens(typeAnnotation).Single().ToString(); 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. using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.Snippets.SnippetFunctions; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; using TextSpan = Microsoft.CodeAnalysis.Text.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Snippets.SnippetFunctions { internal sealed class SnippetFunctionGenerateSwitchCases : AbstractSnippetFunctionGenerateSwitchCases { public SnippetFunctionGenerateSwitchCases(SnippetExpansionClient snippetExpansionClient, ITextBuffer subjectBuffer, string caseGenerationLocationField, string switchExpressionField) : base(snippetExpansionClient, subjectBuffer, caseGenerationLocationField, switchExpressionField) { } protected override string CaseFormat { get { return @"case {0}.{1}: break; "; } } protected override string DefaultCase { get { return @"default: break;"; } } protected override bool TryGetEnumTypeSymbol(CancellationToken cancellationToken, [NotNullWhen(returnValue: true)] out ITypeSymbol? typeSymbol) { typeSymbol = null; if (!TryGetDocument(out var document)) { return false; } Contract.ThrowIfNull(_snippetExpansionClient.ExpansionSession); var subjectBufferFieldSpan = _snippetExpansionClient.ExpansionSession.GetFieldSpan(SwitchExpressionField); var expressionSpan = subjectBufferFieldSpan.Span.ToTextSpan(); var syntaxTree = document.GetRequiredSyntaxTreeSynchronously(cancellationToken); var token = syntaxTree.FindTokenOnRightOfPosition(expressionSpan.Start, cancellationToken); var expressionNode = token.GetAncestor(n => n.Span == expressionSpan); if (expressionNode == null) { return false; } var model = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken); typeSymbol = model?.GetTypeInfo(expressionNode, cancellationToken).Type; return typeSymbol != null; } protected override bool TryGetSimplifiedTypeNameInCaseContext(Document document, string fullyQualifiedTypeName, string firstEnumMemberName, int startPosition, int endPosition, CancellationToken cancellationToken, out string simplifiedTypeName) { simplifiedTypeName = string.Empty; var typeAnnotation = new SyntaxAnnotation(); var str = "case " + fullyQualifiedTypeName + "." + firstEnumMemberName + ":" + Environment.NewLine + " break;"; var textChange = new TextChange(new TextSpan(startPosition, endPosition - startPosition), str); var typeSpanToAnnotate = new TextSpan(startPosition + "case ".Length, fullyQualifiedTypeName.Length); var textWithCaseAdded = document.GetTextSynchronously(cancellationToken).WithChanges(textChange); var documentWithCaseAdded = document.WithText(textWithCaseAdded); var syntaxRoot = documentWithCaseAdded.GetRequiredSyntaxRootSynchronously(cancellationToken); var nodeToReplace = syntaxRoot.DescendantNodes().FirstOrDefault(n => n.Span == typeSpanToAnnotate); if (nodeToReplace == null) { return false; } var updatedRoot = syntaxRoot.ReplaceNode(nodeToReplace, nodeToReplace.WithAdditionalAnnotations(typeAnnotation, Simplifier.Annotation)); var documentWithAnnotations = documentWithCaseAdded.WithSyntaxRoot(updatedRoot); var simplifiedDocument = Simplifier.ReduceAsync(documentWithAnnotations, cancellationToken: cancellationToken).Result; simplifiedTypeName = simplifiedDocument.GetRequiredSyntaxRootSynchronously(cancellationToken).GetAnnotatedNodesAndTokens(typeAnnotation).Single().ToString(); return true; } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Extensions/CallStatementSyntaxExtensions.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.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions Friend Module CallStatementSyntaxExtensions <Extension> Public Function CanRemoveCallKeyword(callStatement As CallStatementSyntax) As Boolean Dim nextToken = callStatement.CallKeyword.GetNextToken() If (nextToken.IsKindOrHasMatchingText(SyntaxKind.IdentifierToken) OrElse nextToken.Parent.IsKind(SyntaxKind.PredefinedType)) AndAlso Not SyntaxFacts.GetContextualKeywordKind(nextToken.ToString()) = SyntaxKind.MidKeyword Then Return True End If ' Only keywords starting "invocable" expressions If nextToken.IsKindOrHasMatchingText(SyntaxKind.CBoolKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.CCharKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.CDateKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.CDblKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.CDecKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.CIntKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.CLngKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.CObjKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.CSByteKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.CShortKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.CSngKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.CStrKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.CTypeKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.CUIntKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.CULngKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.CUShortKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.DirectCastKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.GetTypeKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.GetXmlNamespaceKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.MeKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.MyBaseKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.MyClassKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.TryCastKeyword) Then Return True End If Return False End Function End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions Friend Module CallStatementSyntaxExtensions <Extension> Public Function CanRemoveCallKeyword(callStatement As CallStatementSyntax) As Boolean Dim nextToken = callStatement.CallKeyword.GetNextToken() If (nextToken.IsKindOrHasMatchingText(SyntaxKind.IdentifierToken) OrElse nextToken.Parent.IsKind(SyntaxKind.PredefinedType)) AndAlso Not SyntaxFacts.GetContextualKeywordKind(nextToken.ToString()) = SyntaxKind.MidKeyword Then Return True End If ' Only keywords starting "invocable" expressions If nextToken.IsKindOrHasMatchingText(SyntaxKind.CBoolKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.CCharKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.CDateKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.CDblKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.CDecKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.CIntKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.CLngKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.CObjKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.CSByteKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.CShortKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.CSngKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.CStrKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.CTypeKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.CUIntKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.CULngKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.CUShortKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.DirectCastKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.GetTypeKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.GetXmlNamespaceKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.MeKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.MyBaseKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.MyClassKeyword) OrElse nextToken.IsKindOrHasMatchingText(SyntaxKind.TryCastKeyword) Then Return True End If Return False End Function End Module End Namespace
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/Core/Portable/AssemblyUtilities.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.Reflection.Metadata; using System.Reflection.PortableExecutable; using Microsoft.CodeAnalysis; namespace Roslyn.Utilities { internal static class AssemblyUtilities { /// <summary> /// Given a path to an assembly, identifies files in the same directory /// that could satisfy the assembly's dependencies. May throw. /// </summary> /// <remarks> /// Dependencies are identified by simply checking the name of an assembly /// reference against a file name; if they match the file is considered a /// dependency. Other factors, such as version, culture, public key, etc., /// are not considered, and so the returned collection may include items that /// cannot in fact satisfy the original assembly's dependencies. /// </remarks> /// <exception cref="IOException">If the file at <paramref name="filePath"/> does not exist or cannot be accessed.</exception> /// <exception cref="BadImageFormatException">If the file is not an assembly or is somehow corrupted.</exception> public static ImmutableArray<string> FindAssemblySet(string filePath) { RoslynDebug.Assert(PathUtilities.IsAbsolute(filePath)); Queue<string> workList = new Queue<string>(); HashSet<string> assemblySet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); workList.Enqueue(filePath); while (workList.Count > 0) { string assemblyPath = workList.Dequeue(); if (!assemblySet.Add(assemblyPath)) { continue; } var directory = Path.GetDirectoryName(assemblyPath); using (var reader = new PEReader(FileUtilities.OpenRead(assemblyPath))) { var metadataReader = reader.GetMetadataReader(); var assemblyReferenceHandles = metadataReader.AssemblyReferences; foreach (var handle in assemblyReferenceHandles) { var reference = metadataReader.GetAssemblyReference(handle); var referenceName = metadataReader.GetString(reference.Name); // Suppression is questionable because Path.GetDirectoryName returns null on root directories https://github.com/dotnet/roslyn/issues/41636 string referencePath = Path.Combine(directory!, referenceName + ".dll"); if (!assemblySet.Contains(referencePath) && File.Exists(referencePath)) { workList.Enqueue(referencePath); } } } } return ImmutableArray.CreateRange(assemblySet); } /// <summary> /// Given a path to an assembly, returns its MVID (Module Version ID). /// May throw. /// </summary> /// <exception cref="IOException">If the file at <paramref name="filePath"/> does not exist or cannot be accessed.</exception> /// <exception cref="BadImageFormatException">If the file is not an assembly or is somehow corrupted.</exception> public static Guid ReadMvid(string filePath) { RoslynDebug.Assert(PathUtilities.IsAbsolute(filePath)); using (var reader = new PEReader(FileUtilities.OpenRead(filePath))) { var metadataReader = reader.GetMetadataReader(); var mvidHandle = metadataReader.GetModuleDefinition().Mvid; var fileMvid = metadataReader.GetGuid(mvidHandle); return fileMvid; } } /// <summary> /// Given a path to an assembly, finds the paths to all of its satellite /// assemblies. /// </summary> /// <exception cref="IOException">If the file at <paramref name="filePath"/> does not exist or cannot be accessed.</exception> /// <exception cref="BadImageFormatException">If the file is not an assembly or is somehow corrupted.</exception> public static ImmutableArray<string> FindSatelliteAssemblies(string filePath) { Debug.Assert(PathUtilities.IsAbsolute(filePath)); var builder = ImmutableArray.CreateBuilder<string>(); string? directory = Path.GetDirectoryName(filePath); RoslynDebug.AssertNotNull(directory); string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath); string resourcesNameWithoutExtension = fileNameWithoutExtension + ".resources"; string resourcesNameWithExtension = resourcesNameWithoutExtension + ".dll"; foreach (var subDirectory in Directory.EnumerateDirectories(directory, "*", SearchOption.TopDirectoryOnly)) { string satelliteAssemblyPath = Path.Combine(subDirectory, resourcesNameWithExtension); if (File.Exists(satelliteAssemblyPath)) { builder.Add(satelliteAssemblyPath); } satelliteAssemblyPath = Path.Combine(subDirectory, resourcesNameWithoutExtension, resourcesNameWithExtension); if (File.Exists(satelliteAssemblyPath)) { builder.Add(satelliteAssemblyPath); } } return builder.ToImmutable(); } /// <summary> /// Given a path to an assembly and a set of paths to possible dependencies, /// identifies which of the assembly's references are missing. May throw. /// </summary> /// <exception cref="IOException">If the files does not exist or cannot be accessed.</exception> /// <exception cref="BadImageFormatException">If one of the files is not an assembly or is somehow corrupted.</exception> public static ImmutableArray<AssemblyIdentity> IdentifyMissingDependencies(string assemblyPath, IEnumerable<string> dependencyFilePaths) { RoslynDebug.Assert(PathUtilities.IsAbsolute(assemblyPath)); RoslynDebug.Assert(dependencyFilePaths != null); HashSet<AssemblyIdentity> assemblyDefinitions = new HashSet<AssemblyIdentity>(); foreach (var potentialDependency in dependencyFilePaths) { using (var reader = new PEReader(FileUtilities.OpenRead(potentialDependency))) { var metadataReader = reader.GetMetadataReader(); var assemblyDefinition = metadataReader.ReadAssemblyIdentityOrThrow(); assemblyDefinitions.Add(assemblyDefinition); } } HashSet<AssemblyIdentity> assemblyReferences = new HashSet<AssemblyIdentity>(); using (var reader = new PEReader(FileUtilities.OpenRead(assemblyPath))) { var metadataReader = reader.GetMetadataReader(); var references = metadataReader.GetReferencedAssembliesOrThrow(); assemblyReferences.AddAll(references); } assemblyReferences.ExceptWith(assemblyDefinitions); return ImmutableArray.CreateRange(assemblyReferences); } /// <summary> /// Given a path to an assembly, returns the <see cref="AssemblyIdentity"/> for the assembly. /// May throw. /// </summary> /// <exception cref="IOException">If the file at <paramref name="assemblyPath"/> does not exist or cannot be accessed.</exception> /// <exception cref="BadImageFormatException">If the file is not an assembly or is somehow corrupted.</exception> public static AssemblyIdentity GetAssemblyIdentity(string assemblyPath) { Debug.Assert(PathUtilities.IsAbsolute(assemblyPath)); using (var reader = new PEReader(FileUtilities.OpenRead(assemblyPath))) { var metadataReader = reader.GetMetadataReader(); var assemblyIdentity = metadataReader.ReadAssemblyIdentityOrThrow(); return assemblyIdentity; } } } }
// Licensed to the .NET Foundation under one or more 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.Reflection.Metadata; using System.Reflection.PortableExecutable; using Microsoft.CodeAnalysis; namespace Roslyn.Utilities { internal static class AssemblyUtilities { /// <summary> /// Given a path to an assembly, identifies files in the same directory /// that could satisfy the assembly's dependencies. May throw. /// </summary> /// <remarks> /// Dependencies are identified by simply checking the name of an assembly /// reference against a file name; if they match the file is considered a /// dependency. Other factors, such as version, culture, public key, etc., /// are not considered, and so the returned collection may include items that /// cannot in fact satisfy the original assembly's dependencies. /// </remarks> /// <exception cref="IOException">If the file at <paramref name="filePath"/> does not exist or cannot be accessed.</exception> /// <exception cref="BadImageFormatException">If the file is not an assembly or is somehow corrupted.</exception> public static ImmutableArray<string> FindAssemblySet(string filePath) { RoslynDebug.Assert(PathUtilities.IsAbsolute(filePath)); Queue<string> workList = new Queue<string>(); HashSet<string> assemblySet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); workList.Enqueue(filePath); while (workList.Count > 0) { string assemblyPath = workList.Dequeue(); if (!assemblySet.Add(assemblyPath)) { continue; } var directory = Path.GetDirectoryName(assemblyPath); using (var reader = new PEReader(FileUtilities.OpenRead(assemblyPath))) { var metadataReader = reader.GetMetadataReader(); var assemblyReferenceHandles = metadataReader.AssemblyReferences; foreach (var handle in assemblyReferenceHandles) { var reference = metadataReader.GetAssemblyReference(handle); var referenceName = metadataReader.GetString(reference.Name); // Suppression is questionable because Path.GetDirectoryName returns null on root directories https://github.com/dotnet/roslyn/issues/41636 string referencePath = Path.Combine(directory!, referenceName + ".dll"); if (!assemblySet.Contains(referencePath) && File.Exists(referencePath)) { workList.Enqueue(referencePath); } } } } return ImmutableArray.CreateRange(assemblySet); } /// <summary> /// Given a path to an assembly, returns its MVID (Module Version ID). /// May throw. /// </summary> /// <exception cref="IOException">If the file at <paramref name="filePath"/> does not exist or cannot be accessed.</exception> /// <exception cref="BadImageFormatException">If the file is not an assembly or is somehow corrupted.</exception> public static Guid ReadMvid(string filePath) { RoslynDebug.Assert(PathUtilities.IsAbsolute(filePath)); using (var reader = new PEReader(FileUtilities.OpenRead(filePath))) { var metadataReader = reader.GetMetadataReader(); var mvidHandle = metadataReader.GetModuleDefinition().Mvid; var fileMvid = metadataReader.GetGuid(mvidHandle); return fileMvid; } } /// <summary> /// Given a path to an assembly, finds the paths to all of its satellite /// assemblies. /// </summary> /// <exception cref="IOException">If the file at <paramref name="filePath"/> does not exist or cannot be accessed.</exception> /// <exception cref="BadImageFormatException">If the file is not an assembly or is somehow corrupted.</exception> public static ImmutableArray<string> FindSatelliteAssemblies(string filePath) { Debug.Assert(PathUtilities.IsAbsolute(filePath)); var builder = ImmutableArray.CreateBuilder<string>(); string? directory = Path.GetDirectoryName(filePath); RoslynDebug.AssertNotNull(directory); string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath); string resourcesNameWithoutExtension = fileNameWithoutExtension + ".resources"; string resourcesNameWithExtension = resourcesNameWithoutExtension + ".dll"; foreach (var subDirectory in Directory.EnumerateDirectories(directory, "*", SearchOption.TopDirectoryOnly)) { string satelliteAssemblyPath = Path.Combine(subDirectory, resourcesNameWithExtension); if (File.Exists(satelliteAssemblyPath)) { builder.Add(satelliteAssemblyPath); } satelliteAssemblyPath = Path.Combine(subDirectory, resourcesNameWithoutExtension, resourcesNameWithExtension); if (File.Exists(satelliteAssemblyPath)) { builder.Add(satelliteAssemblyPath); } } return builder.ToImmutable(); } /// <summary> /// Given a path to an assembly and a set of paths to possible dependencies, /// identifies which of the assembly's references are missing. May throw. /// </summary> /// <exception cref="IOException">If the files does not exist or cannot be accessed.</exception> /// <exception cref="BadImageFormatException">If one of the files is not an assembly or is somehow corrupted.</exception> public static ImmutableArray<AssemblyIdentity> IdentifyMissingDependencies(string assemblyPath, IEnumerable<string> dependencyFilePaths) { RoslynDebug.Assert(PathUtilities.IsAbsolute(assemblyPath)); RoslynDebug.Assert(dependencyFilePaths != null); HashSet<AssemblyIdentity> assemblyDefinitions = new HashSet<AssemblyIdentity>(); foreach (var potentialDependency in dependencyFilePaths) { using (var reader = new PEReader(FileUtilities.OpenRead(potentialDependency))) { var metadataReader = reader.GetMetadataReader(); var assemblyDefinition = metadataReader.ReadAssemblyIdentityOrThrow(); assemblyDefinitions.Add(assemblyDefinition); } } HashSet<AssemblyIdentity> assemblyReferences = new HashSet<AssemblyIdentity>(); using (var reader = new PEReader(FileUtilities.OpenRead(assemblyPath))) { var metadataReader = reader.GetMetadataReader(); var references = metadataReader.GetReferencedAssembliesOrThrow(); assemblyReferences.AddAll(references); } assemblyReferences.ExceptWith(assemblyDefinitions); return ImmutableArray.CreateRange(assemblyReferences); } /// <summary> /// Given a path to an assembly, returns the <see cref="AssemblyIdentity"/> for the assembly. /// May throw. /// </summary> /// <exception cref="IOException">If the file at <paramref name="assemblyPath"/> does not exist or cannot be accessed.</exception> /// <exception cref="BadImageFormatException">If the file is not an assembly or is somehow corrupted.</exception> public static AssemblyIdentity GetAssemblyIdentity(string assemblyPath) { Debug.Assert(PathUtilities.IsAbsolute(assemblyPath)); using (var reader = new PEReader(FileUtilities.OpenRead(assemblyPath))) { var metadataReader = reader.GetMetadataReader(); var assemblyIdentity = metadataReader.ReadAssemblyIdentityOrThrow(); return assemblyIdentity; } } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Features/CSharp/Portable/SignatureHelp/AbstractOrdinaryMethodSignatureHelpProvider.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 Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SignatureHelp; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp { internal abstract class AbstractOrdinaryMethodSignatureHelpProvider : AbstractCSharpSignatureHelpProvider { internal static SignatureHelpItem ConvertMethodGroupMethod( Document document, IMethodSymbol method, int position, SemanticModel semanticModel) { return ConvertMethodGroupMethod(document, method, position, semanticModel, descriptionParts: null); } internal static SignatureHelpItem ConvertMethodGroupMethod( Document document, IMethodSymbol method, int position, SemanticModel semanticModel, IList<SymbolDisplayPart>? descriptionParts) { var anonymousTypeDisplayService = document.GetRequiredLanguageService<IAnonymousTypeDisplayService>(); var documentationCommentFormattingService = document.GetRequiredLanguageService<IDocumentationCommentFormattingService>(); return CreateItemImpl( method, semanticModel, position, anonymousTypeDisplayService, method.IsParams(), c => method.OriginalDefinition.GetDocumentationParts(semanticModel, position, documentationCommentFormattingService, c), GetMethodGroupPreambleParts(method, semanticModel, position), GetSeparatorParts(), GetMethodGroupPostambleParts(), method.Parameters.Select(p => Convert(p, semanticModel, position, documentationCommentFormattingService)).ToList(), descriptionParts: descriptionParts); } private static IList<SymbolDisplayPart> GetMethodGroupPreambleParts( IMethodSymbol method, SemanticModel semanticModel, int position) { var result = new List<SymbolDisplayPart>(); var awaitable = method.GetOriginalUnreducedDefinition().IsAwaitableNonDynamic(semanticModel, position); var extension = method.GetOriginalUnreducedDefinition().IsExtensionMethod(); if (awaitable && extension) { result.Add(Punctuation(SyntaxKind.OpenParenToken)); result.Add(Text(CSharpFeaturesResources.awaitable)); result.Add(Punctuation(SyntaxKind.CommaToken)); result.Add(Text(CSharpFeaturesResources.extension)); result.Add(Punctuation(SyntaxKind.CloseParenToken)); result.Add(Space()); } else if (awaitable) { result.Add(Punctuation(SyntaxKind.OpenParenToken)); result.Add(Text(CSharpFeaturesResources.awaitable)); result.Add(Punctuation(SyntaxKind.CloseParenToken)); result.Add(Space()); } else if (extension) { result.Add(Punctuation(SyntaxKind.OpenParenToken)); result.Add(Text(CSharpFeaturesResources.extension)); result.Add(Punctuation(SyntaxKind.CloseParenToken)); result.Add(Space()); } result.AddRange(method.ToMinimalDisplayParts(semanticModel, position, MinimallyQualifiedWithoutParametersFormat)); result.Add(Punctuation(SyntaxKind.OpenParenToken)); return result; } private static IList<SymbolDisplayPart> GetMethodGroupPostambleParts() => SpecializedCollections.SingletonList(Punctuation(SyntaxKind.CloseParenToken)); } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SignatureHelp; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp { internal abstract class AbstractOrdinaryMethodSignatureHelpProvider : AbstractCSharpSignatureHelpProvider { internal static SignatureHelpItem ConvertMethodGroupMethod( Document document, IMethodSymbol method, int position, SemanticModel semanticModel) { return ConvertMethodGroupMethod(document, method, position, semanticModel, descriptionParts: null); } internal static SignatureHelpItem ConvertMethodGroupMethod( Document document, IMethodSymbol method, int position, SemanticModel semanticModel, IList<SymbolDisplayPart>? descriptionParts) { var anonymousTypeDisplayService = document.GetRequiredLanguageService<IAnonymousTypeDisplayService>(); var documentationCommentFormattingService = document.GetRequiredLanguageService<IDocumentationCommentFormattingService>(); return CreateItemImpl( method, semanticModel, position, anonymousTypeDisplayService, method.IsParams(), c => method.OriginalDefinition.GetDocumentationParts(semanticModel, position, documentationCommentFormattingService, c), GetMethodGroupPreambleParts(method, semanticModel, position), GetSeparatorParts(), GetMethodGroupPostambleParts(), method.Parameters.Select(p => Convert(p, semanticModel, position, documentationCommentFormattingService)).ToList(), descriptionParts: descriptionParts); } private static IList<SymbolDisplayPart> GetMethodGroupPreambleParts( IMethodSymbol method, SemanticModel semanticModel, int position) { var result = new List<SymbolDisplayPart>(); var awaitable = method.GetOriginalUnreducedDefinition().IsAwaitableNonDynamic(semanticModel, position); var extension = method.GetOriginalUnreducedDefinition().IsExtensionMethod(); if (awaitable && extension) { result.Add(Punctuation(SyntaxKind.OpenParenToken)); result.Add(Text(CSharpFeaturesResources.awaitable)); result.Add(Punctuation(SyntaxKind.CommaToken)); result.Add(Text(CSharpFeaturesResources.extension)); result.Add(Punctuation(SyntaxKind.CloseParenToken)); result.Add(Space()); } else if (awaitable) { result.Add(Punctuation(SyntaxKind.OpenParenToken)); result.Add(Text(CSharpFeaturesResources.awaitable)); result.Add(Punctuation(SyntaxKind.CloseParenToken)); result.Add(Space()); } else if (extension) { result.Add(Punctuation(SyntaxKind.OpenParenToken)); result.Add(Text(CSharpFeaturesResources.extension)); result.Add(Punctuation(SyntaxKind.CloseParenToken)); result.Add(Space()); } result.AddRange(method.ToMinimalDisplayParts(semanticModel, position, MinimallyQualifiedWithoutParametersFormat)); result.Add(Punctuation(SyntaxKind.OpenParenToken)); return result; } private static IList<SymbolDisplayPart> GetMethodGroupPostambleParts() => SpecializedCollections.SingletonList(Punctuation(SyntaxKind.CloseParenToken)); } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Scripting/VisualBasicTest/My Project/launchSettings.json
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
{ "profiles": { "xUnit.net Console (32-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" }, "xUnit.net Console (64-bit)": { "commandName": "Executable", "executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe", "commandLineArgs": "$(TargetPath) -noshadow -verbose" } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/VisualStudio/VisualBasic/Impl/Options/AutomationObject/AutomationObject.ExtractMethod.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.ExtractMethod Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options Partial Public Class AutomationObject Public Property ExtractMethod_AllowBestEffort As Boolean Get Return GetBooleanOption(ExtractMethodOptions.AllowBestEffort) End Get Set(value As Boolean) SetBooleanOption(ExtractMethodOptions.AllowBestEffort, value) End Set End Property Public Property ExtractMethod_DoNotPutOutOrRefOnStruct As Boolean Get Return GetBooleanOption(ExtractMethodOptions.DontPutOutOrRefOnStruct) End Get Set(value As Boolean) SetBooleanOption(ExtractMethodOptions.DontPutOutOrRefOnStruct, value) End Set End Property 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.ExtractMethod Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options Partial Public Class AutomationObject Public Property ExtractMethod_AllowBestEffort As Boolean Get Return GetBooleanOption(ExtractMethodOptions.AllowBestEffort) End Get Set(value As Boolean) SetBooleanOption(ExtractMethodOptions.AllowBestEffort, value) End Set End Property Public Property ExtractMethod_DoNotPutOutOrRefOnStruct As Boolean Get Return GetBooleanOption(ExtractMethodOptions.DontPutOutOrRefOnStruct) End Get Set(value As Boolean) SetBooleanOption(ExtractMethodOptions.DontPutOutOrRefOnStruct, value) End Set End Property End Class End Namespace
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/Test/Core/Platform/Desktop/ErrorDiagnostics.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #if NET472 using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Roslyn.Test.Utilities { public sealed class ErrorDiagnostics { public enum WellKnownDll { PlatformVsEditor, PlatformEditor, TextLogic, TextUI, TextWpf, TextData, UIUndo, StandardClassification } public enum DllVersion { Unknown, Beta2, RC } public static List<string> DiagnoseMefProblems() { var list = new List<string>(); var dllList = GetWellKnownDllsWithVersion().ToList(); foreach (var tuple in dllList) { if (tuple.Item3 == DllVersion.RC) { var assembly = tuple.Item1; list.Add(string.Format("Loaded RC version of assembly {0} instead of beta2: {1} - {2}", assembly.GetName().Name, assembly.CodeBase, assembly.Location)); } } return list; } public static IEnumerable<Tuple<Assembly, WellKnownDll>> GetWellKnownDlls() { var list = AppDomain.CurrentDomain.GetAssemblies().ToList(); foreach (var assembly in list) { switch (assembly.GetName().Name) { case "Microsoft.VisualStudio.Platform.VSEditor": yield return Tuple.Create(assembly, WellKnownDll.PlatformVsEditor); break; case "Microsoft.VisualStudio.Platform.Editor": yield return Tuple.Create(assembly, WellKnownDll.PlatformEditor); break; case "Microsoft.VisualStudio.Text.Logic": yield return Tuple.Create(assembly, WellKnownDll.TextLogic); break; case "Microsoft.VisualStudio.Text.UI": yield return Tuple.Create(assembly, WellKnownDll.TextUI); break; case "Microsoft.VisualStudio.Text.Data": yield return Tuple.Create(assembly, WellKnownDll.TextData); break; case "Microsoft.VisualStudio.Text.UI.Wpf": yield return Tuple.Create(assembly, WellKnownDll.TextWpf); break; case "Microsoft.VisualStudio.UI.Undo": yield return Tuple.Create(assembly, WellKnownDll.UIUndo); break; case "Microsoft.VisualStudio.Language.StandardClassification": yield return Tuple.Create(assembly, WellKnownDll.StandardClassification); break; } } } private static IEnumerable<Tuple<Assembly, WellKnownDll, DllVersion>> GetWellKnownDllsWithVersion() { foreach (var pair in GetWellKnownDlls()) { switch (pair.Item2) { case WellKnownDll.PlatformVsEditor: { var type = pair.Item1.GetType("Microsoft.VisualStudio.Text.Implementation.BaseSnapshot"); var ct = type.GetProperty("ContentType"); var version = ct == null ? DllVersion.Beta2 : DllVersion.RC; yield return Tuple.Create(pair.Item1, pair.Item2, version); } break; case WellKnownDll.TextData: { var type = pair.Item1.GetType("Microsoft.VisualStudio.Text.ITextSnapshot"); var ct = type.GetProperty("ContentType"); var version = ct == null ? DllVersion.Beta2 : DllVersion.RC; yield return Tuple.Create(pair.Item1, pair.Item2, version); } break; default: yield return Tuple.Create(pair.Item1, pair.Item2, DllVersion.Unknown); break; } } } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #if NET472 using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Roslyn.Test.Utilities { public sealed class ErrorDiagnostics { public enum WellKnownDll { PlatformVsEditor, PlatformEditor, TextLogic, TextUI, TextWpf, TextData, UIUndo, StandardClassification } public enum DllVersion { Unknown, Beta2, RC } public static List<string> DiagnoseMefProblems() { var list = new List<string>(); var dllList = GetWellKnownDllsWithVersion().ToList(); foreach (var tuple in dllList) { if (tuple.Item3 == DllVersion.RC) { var assembly = tuple.Item1; list.Add(string.Format("Loaded RC version of assembly {0} instead of beta2: {1} - {2}", assembly.GetName().Name, assembly.CodeBase, assembly.Location)); } } return list; } public static IEnumerable<Tuple<Assembly, WellKnownDll>> GetWellKnownDlls() { var list = AppDomain.CurrentDomain.GetAssemblies().ToList(); foreach (var assembly in list) { switch (assembly.GetName().Name) { case "Microsoft.VisualStudio.Platform.VSEditor": yield return Tuple.Create(assembly, WellKnownDll.PlatformVsEditor); break; case "Microsoft.VisualStudio.Platform.Editor": yield return Tuple.Create(assembly, WellKnownDll.PlatformEditor); break; case "Microsoft.VisualStudio.Text.Logic": yield return Tuple.Create(assembly, WellKnownDll.TextLogic); break; case "Microsoft.VisualStudio.Text.UI": yield return Tuple.Create(assembly, WellKnownDll.TextUI); break; case "Microsoft.VisualStudio.Text.Data": yield return Tuple.Create(assembly, WellKnownDll.TextData); break; case "Microsoft.VisualStudio.Text.UI.Wpf": yield return Tuple.Create(assembly, WellKnownDll.TextWpf); break; case "Microsoft.VisualStudio.UI.Undo": yield return Tuple.Create(assembly, WellKnownDll.UIUndo); break; case "Microsoft.VisualStudio.Language.StandardClassification": yield return Tuple.Create(assembly, WellKnownDll.StandardClassification); break; } } } private static IEnumerable<Tuple<Assembly, WellKnownDll, DllVersion>> GetWellKnownDllsWithVersion() { foreach (var pair in GetWellKnownDlls()) { switch (pair.Item2) { case WellKnownDll.PlatformVsEditor: { var type = pair.Item1.GetType("Microsoft.VisualStudio.Text.Implementation.BaseSnapshot"); var ct = type.GetProperty("ContentType"); var version = ct == null ? DllVersion.Beta2 : DllVersion.RC; yield return Tuple.Create(pair.Item1, pair.Item2, version); } break; case WellKnownDll.TextData: { var type = pair.Item1.GetType("Microsoft.VisualStudio.Text.ITextSnapshot"); var ct = type.GetProperty("ContentType"); var version = ct == null ? DllVersion.Beta2 : DllVersion.RC; yield return Tuple.Create(pair.Item1, pair.Item2, version); } break; default: yield return Tuple.Create(pair.Item1, pair.Item2, DllVersion.Unknown); break; } } } } } #endif
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/CSharp/Portable/Utilities/ValueSetFactory.UIntTC.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 UIntTC : INumericTC<uint> { uint INumericTC<uint>.MinValue => uint.MinValue; uint INumericTC<uint>.MaxValue => uint.MaxValue; uint INumericTC<uint>.Zero => 0; public bool Related(BinaryOperatorKind relation, uint left, uint 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"); } } uint INumericTC<uint>.Next(uint value) { Debug.Assert(value != uint.MaxValue); return value + 1; } public uint FromConstantValue(ConstantValue constantValue) => constantValue.IsBad ? (uint)0 : constantValue.UInt32Value; public ConstantValue ToConstantValue(uint value) => ConstantValue.Create(value); string INumericTC<uint>.ToString(uint value) => value.ToString(); uint INumericTC<uint>.Prev(uint value) { Debug.Assert(value != uint.MinValue); return value - 1; } public uint Random(Random random) { return (uint)((random.Next() << 10) ^ 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 UIntTC : INumericTC<uint> { uint INumericTC<uint>.MinValue => uint.MinValue; uint INumericTC<uint>.MaxValue => uint.MaxValue; uint INumericTC<uint>.Zero => 0; public bool Related(BinaryOperatorKind relation, uint left, uint 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"); } } uint INumericTC<uint>.Next(uint value) { Debug.Assert(value != uint.MaxValue); return value + 1; } public uint FromConstantValue(ConstantValue constantValue) => constantValue.IsBad ? (uint)0 : constantValue.UInt32Value; public ConstantValue ToConstantValue(uint value) => ConstantValue.Create(value); string INumericTC<uint>.ToString(uint value) => value.ToString(); uint INumericTC<uint>.Prev(uint value) { Debug.Assert(value != uint.MinValue); return value - 1; } public uint Random(Random random) { return (uint)((random.Next() << 10) ^ random.Next()); } } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Features/VisualBasic/Portable/PublicAPI.Unshipped.txt
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenStaticLocals.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 Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenStaticInitializer Inherits BasicTestBase <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub CodeGen_SimpleStaticLocal() 'TODO: get the correct IL CompileAndVerify( <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() StaticLocalInSub() StaticLocalInSub() End Sub Sub StaticLocalInSub() <Obsolete> Static SLItem1 = 1 Console.WriteLine("StaticLocalInSub") Console.WriteLine(SLItem1.GetType.ToString) 'Type Inferred Console.WriteLine(SLItem1.ToString) 'Value SLItem1 += 1 End Sub End Module ]]> </file> </compilation>). VerifyIL("Module1.StaticLocalInSub", <![CDATA[ { // Code size 187 (0xbb) .maxstack 3 .locals init (Boolean V_0) IL_0000: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0005: brtrue.s IL_0018 IL_0007: ldsflda "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_000c: newobj "Sub Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag..ctor()" IL_0011: ldnull IL_0012: call "Function System.Threading.Interlocked.CompareExchange(Of Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag)(ByRef Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag, Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag, Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag) As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0017: pop IL_0018: ldc.i4.0 IL_0019: stloc.0 .try { IL_001a: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_001f: ldloca.s V_0 IL_0021: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0026: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_002b: ldfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_0030: brtrue.s IL_004a IL_0032: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0037: ldc.i4.2 IL_0038: stfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_003d: ldc.i4.1 IL_003e: box "Integer" IL_0043: stsfld "Module1.SLItem1 As Object" IL_0048: leave.s IL_0078 IL_004a: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_004f: ldfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_0054: ldc.i4.2 IL_0055: bne.un.s IL_005d IL_0057: newobj "Sub Microsoft.VisualBasic.CompilerServices.IncompleteInitialization..ctor()" IL_005c: throw IL_005d: leave.s IL_0078 } finally { IL_005f: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0064: ldc.i4.1 IL_0065: stfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_006a: ldloc.0 IL_006b: brfalse.s IL_0077 IL_006d: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0072: call "Sub System.Threading.Monitor.Exit(Object)" IL_0077: endfinally } IL_0078: ldstr "StaticLocalInSub" IL_007d: call "Sub System.Console.WriteLine(String)" IL_0082: ldsfld "Module1.SLItem1 As Object" IL_0087: callvirt "Function Object.GetType() As System.Type" IL_008c: callvirt "Function System.Type.ToString() As String" IL_0091: call "Sub System.Console.WriteLine(String)" IL_0096: ldsfld "Module1.SLItem1 As Object" IL_009b: callvirt "Function Object.ToString() As String" IL_00a0: call "Sub System.Console.WriteLine(String)" IL_00a5: ldsfld "Module1.SLItem1 As Object" IL_00aa: ldc.i4.1 IL_00ab: box "Integer" IL_00b0: call "Function Microsoft.VisualBasic.CompilerServices.Operators.AddObject(Object, Object) As Object" IL_00b5: stsfld "Module1.SLItem1 As Object" IL_00ba: ret } ]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub CodeGen_DoubleStaticLocalWithSameNameDifferentScopes() 'TODO: get the correct IL CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() Goo() Bar() Goo() Bar() End Sub Sub Goo() Static SLItem1 = 1 Console.WriteLine("StaticLocalInSub") Console.WriteLine(SLItem1.GetType.ToString) 'Type Inferred Console.WriteLine(SLItem1.ToString) 'Value SLItem1 += 1 End Sub Sub Bar() Static SLItem1 = 1 Console.WriteLine("StaticLocalInSub") Console.WriteLine(SLItem1.GetType.ToString) 'Type Inferred Console.WriteLine(SLItem1.ToString) 'Value SLItem1 += 1 End Sub End Module </file> </compilation>). VerifyIL("Module1.Goo", <![CDATA[ { // Code size 187 (0xbb) .maxstack 3 .locals init (Boolean V_0) IL_0000: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0005: brtrue.s IL_0018 IL_0007: ldsflda "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_000c: newobj "Sub Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag..ctor()" IL_0011: ldnull IL_0012: call "Function System.Threading.Interlocked.CompareExchange(Of Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag)(ByRef Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag, Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag, Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag) As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0017: pop IL_0018: ldc.i4.0 IL_0019: stloc.0 .try { IL_001a: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_001f: ldloca.s V_0 IL_0021: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0026: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_002b: ldfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_0030: brtrue.s IL_004a IL_0032: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0037: ldc.i4.2 IL_0038: stfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_003d: ldc.i4.1 IL_003e: box "Integer" IL_0043: stsfld "Module1.SLItem1 As Object" IL_0048: leave.s IL_0078 IL_004a: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_004f: ldfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_0054: ldc.i4.2 IL_0055: bne.un.s IL_005d IL_0057: newobj "Sub Microsoft.VisualBasic.CompilerServices.IncompleteInitialization..ctor()" IL_005c: throw IL_005d: leave.s IL_0078 } finally { IL_005f: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0064: ldc.i4.1 IL_0065: stfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_006a: ldloc.0 IL_006b: brfalse.s IL_0077 IL_006d: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0072: call "Sub System.Threading.Monitor.Exit(Object)" IL_0077: endfinally } IL_0078: ldstr "StaticLocalInSub" IL_007d: call "Sub System.Console.WriteLine(String)" IL_0082: ldsfld "Module1.SLItem1 As Object" IL_0087: callvirt "Function Object.GetType() As System.Type" IL_008c: callvirt "Function System.Type.ToString() As String" IL_0091: call "Sub System.Console.WriteLine(String)" IL_0096: ldsfld "Module1.SLItem1 As Object" IL_009b: callvirt "Function Object.ToString() As String" IL_00a0: call "Sub System.Console.WriteLine(String)" IL_00a5: ldsfld "Module1.SLItem1 As Object" IL_00aa: ldc.i4.1 IL_00ab: box "Integer" IL_00b0: call "Function Microsoft.VisualBasic.CompilerServices.Operators.AddObject(Object, Object) As Object" IL_00b5: stsfld "Module1.SLItem1 As Object" IL_00ba: ret } ]]>) CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() Goo() Bar() Goo() Bar() End Sub Sub Goo() Static SLItem1 = 1 Console.WriteLine("StaticLocalInSub") Console.WriteLine(SLItem1.GetType.ToString) 'Type Inferred Console.WriteLine(SLItem1.ToString) 'Value SLItem1 += 1 End Sub Sub Bar() Static SLItem1 = 1 Console.WriteLine("StaticLocalInSub") Console.WriteLine(SLItem1.GetType.ToString) 'Type Inferred Console.WriteLine(SLItem1.ToString) 'Value SLItem1 += 1 End Sub End Module </file> </compilation>). VerifyIL("Module1.Bar", <![CDATA[ { // Code size 187 (0xbb) .maxstack 3 .locals init (Boolean V_0) IL_0000: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0005: brtrue.s IL_0018 IL_0007: ldsflda "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_000c: newobj "Sub Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag..ctor()" IL_0011: ldnull IL_0012: call "Function System.Threading.Interlocked.CompareExchange(Of Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag)(ByRef Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag, Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag, Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag) As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0017: pop IL_0018: ldc.i4.0 IL_0019: stloc.0 .try { IL_001a: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_001f: ldloca.s V_0 IL_0021: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0026: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_002b: ldfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_0030: brtrue.s IL_004a IL_0032: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0037: ldc.i4.2 IL_0038: stfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_003d: ldc.i4.1 IL_003e: box "Integer" IL_0043: stsfld "Module1.SLItem1 As Object" IL_0048: leave.s IL_0078 IL_004a: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_004f: ldfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_0054: ldc.i4.2 IL_0055: bne.un.s IL_005d IL_0057: newobj "Sub Microsoft.VisualBasic.CompilerServices.IncompleteInitialization..ctor()" IL_005c: throw IL_005d: leave.s IL_0078 } finally { IL_005f: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0064: ldc.i4.1 IL_0065: stfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_006a: ldloc.0 IL_006b: brfalse.s IL_0077 IL_006d: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0072: call "Sub System.Threading.Monitor.Exit(Object)" IL_0077: endfinally } IL_0078: ldstr "StaticLocalInSub" IL_007d: call "Sub System.Console.WriteLine(String)" IL_0082: ldsfld "Module1.SLItem1 As Object" IL_0087: callvirt "Function Object.GetType() As System.Type" IL_008c: callvirt "Function System.Type.ToString() As String" IL_0091: call "Sub System.Console.WriteLine(String)" IL_0096: ldsfld "Module1.SLItem1 As Object" IL_009b: callvirt "Function Object.ToString() As String" IL_00a0: call "Sub System.Console.WriteLine(String)" IL_00a5: ldsfld "Module1.SLItem1 As Object" IL_00aa: ldc.i4.1 IL_00ab: box "Integer" IL_00b0: call "Function Microsoft.VisualBasic.CompilerServices.Operators.AddObject(Object, Object) As Object" IL_00b5: stsfld "Module1.SLItem1 As Object" IL_00ba: ret } ]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub CodeGen_DoubleStaticLocalWithSameNameDifferentOverloads() 'TODO: get the correct IL CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() Goo() Goo(1) Goo() Goo(2) End Sub Sub Goo() Static SLItem1 = 1 Console.WriteLine("StaticLocalInSub") Console.WriteLine(SLItem1.GetType.ToString) 'Type Inferred Console.WriteLine(SLItem1.ToString) 'Value SLItem1 += 1 End Sub Sub goo(x as Integer) Static SLItem1 = 1 Console.WriteLine("StaticLocalInSub") Console.WriteLine(SLItem1.GetType.ToString) 'Type Inferred Console.WriteLine(SLItem1.ToString) 'Value SLItem1 += 1 End Sub End Module </file> </compilation>). VerifyIL("Module1.Goo", <![CDATA[ { // Code size 187 (0xbb) .maxstack 3 .locals init (Boolean V_0) IL_0000: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0005: brtrue.s IL_0018 IL_0007: ldsflda "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_000c: newobj "Sub Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag..ctor()" IL_0011: ldnull IL_0012: call "Function System.Threading.Interlocked.CompareExchange(Of Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag)(ByRef Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag, Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag, Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag) As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0017: pop IL_0018: ldc.i4.0 IL_0019: stloc.0 .try { IL_001a: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_001f: ldloca.s V_0 IL_0021: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0026: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_002b: ldfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_0030: brtrue.s IL_004a IL_0032: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0037: ldc.i4.2 IL_0038: stfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_003d: ldc.i4.1 IL_003e: box "Integer" IL_0043: stsfld "Module1.SLItem1 As Object" IL_0048: leave.s IL_0078 IL_004a: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_004f: ldfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_0054: ldc.i4.2 IL_0055: bne.un.s IL_005d IL_0057: newobj "Sub Microsoft.VisualBasic.CompilerServices.IncompleteInitialization..ctor()" IL_005c: throw IL_005d: leave.s IL_0078 } finally { IL_005f: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0064: ldc.i4.1 IL_0065: stfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_006a: ldloc.0 IL_006b: brfalse.s IL_0077 IL_006d: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0072: call "Sub System.Threading.Monitor.Exit(Object)" IL_0077: endfinally } IL_0078: ldstr "StaticLocalInSub" IL_007d: call "Sub System.Console.WriteLine(String)" IL_0082: ldsfld "Module1.SLItem1 As Object" IL_0087: callvirt "Function Object.GetType() As System.Type" IL_008c: callvirt "Function System.Type.ToString() As String" IL_0091: call "Sub System.Console.WriteLine(String)" IL_0096: ldsfld "Module1.SLItem1 As Object" IL_009b: callvirt "Function Object.ToString() As String" IL_00a0: call "Sub System.Console.WriteLine(String)" IL_00a5: ldsfld "Module1.SLItem1 As Object" IL_00aa: ldc.i4.1 IL_00ab: box "Integer" IL_00b0: call "Function Microsoft.VisualBasic.CompilerServices.Operators.AddObject(Object, Object) As Object" IL_00b5: stsfld "Module1.SLItem1 As Object" IL_00ba: ret } ]]>) CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() Goo() Goo(1) Goo() Goo(2) End Sub Sub goo(x as Integer) Static SLItem1 = 1 Console.WriteLine("StaticLocalInSub") Console.WriteLine(SLItem1.GetType.ToString) 'Type Inferred Console.WriteLine(SLItem1.ToString) 'Value SLItem1 += 1 End Sub Sub Goo() Static SLItem1 = 1 Console.WriteLine("StaticLocalInSub") Console.WriteLine(SLItem1.GetType.ToString) 'Type Inferred Console.WriteLine(SLItem1.ToString) 'Value SLItem1 += 1 End Sub End Module </file> </compilation>). VerifyIL("Module1.goo", <![CDATA[ { // Code size 187 (0xbb) .maxstack 3 .locals init (Boolean V_0) IL_0000: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0005: brtrue.s IL_0018 IL_0007: ldsflda "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_000c: newobj "Sub Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag..ctor()" IL_0011: ldnull IL_0012: call "Function System.Threading.Interlocked.CompareExchange(Of Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag)(ByRef Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag, Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag, Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag) As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0017: pop IL_0018: ldc.i4.0 IL_0019: stloc.0 .try { IL_001a: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_001f: ldloca.s V_0 IL_0021: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0026: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_002b: ldfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_0030: brtrue.s IL_004a IL_0032: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0037: ldc.i4.2 IL_0038: stfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_003d: ldc.i4.1 IL_003e: box "Integer" IL_0043: stsfld "Module1.SLItem1 As Object" IL_0048: leave.s IL_0078 IL_004a: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_004f: ldfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_0054: ldc.i4.2 IL_0055: bne.un.s IL_005d IL_0057: newobj "Sub Microsoft.VisualBasic.CompilerServices.IncompleteInitialization..ctor()" IL_005c: throw IL_005d: leave.s IL_0078 } finally { IL_005f: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0064: ldc.i4.1 IL_0065: stfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_006a: ldloc.0 IL_006b: brfalse.s IL_0077 IL_006d: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0072: call "Sub System.Threading.Monitor.Exit(Object)" IL_0077: endfinally } IL_0078: ldstr "StaticLocalInSub" IL_007d: call "Sub System.Console.WriteLine(String)" IL_0082: ldsfld "Module1.SLItem1 As Object" IL_0087: callvirt "Function Object.GetType() As System.Type" IL_008c: callvirt "Function System.Type.ToString() As String" IL_0091: call "Sub System.Console.WriteLine(String)" IL_0096: ldsfld "Module1.SLItem1 As Object" IL_009b: callvirt "Function Object.ToString() As String" IL_00a0: call "Sub System.Console.WriteLine(String)" IL_00a5: ldsfld "Module1.SLItem1 As Object" IL_00aa: ldc.i4.1 IL_00ab: box "Integer" IL_00b0: call "Function Microsoft.VisualBasic.CompilerServices.Operators.AddObject(Object, Object) As Object" IL_00b5: stsfld "Module1.SLItem1 As Object" IL_00ba: ret } ]]>) 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 Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenStaticInitializer Inherits BasicTestBase <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub CodeGen_SimpleStaticLocal() 'TODO: get the correct IL CompileAndVerify( <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 Sub Main() StaticLocalInSub() StaticLocalInSub() End Sub Sub StaticLocalInSub() <Obsolete> Static SLItem1 = 1 Console.WriteLine("StaticLocalInSub") Console.WriteLine(SLItem1.GetType.ToString) 'Type Inferred Console.WriteLine(SLItem1.ToString) 'Value SLItem1 += 1 End Sub End Module ]]> </file> </compilation>). VerifyIL("Module1.StaticLocalInSub", <![CDATA[ { // Code size 187 (0xbb) .maxstack 3 .locals init (Boolean V_0) IL_0000: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0005: brtrue.s IL_0018 IL_0007: ldsflda "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_000c: newobj "Sub Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag..ctor()" IL_0011: ldnull IL_0012: call "Function System.Threading.Interlocked.CompareExchange(Of Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag)(ByRef Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag, Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag, Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag) As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0017: pop IL_0018: ldc.i4.0 IL_0019: stloc.0 .try { IL_001a: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_001f: ldloca.s V_0 IL_0021: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0026: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_002b: ldfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_0030: brtrue.s IL_004a IL_0032: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0037: ldc.i4.2 IL_0038: stfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_003d: ldc.i4.1 IL_003e: box "Integer" IL_0043: stsfld "Module1.SLItem1 As Object" IL_0048: leave.s IL_0078 IL_004a: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_004f: ldfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_0054: ldc.i4.2 IL_0055: bne.un.s IL_005d IL_0057: newobj "Sub Microsoft.VisualBasic.CompilerServices.IncompleteInitialization..ctor()" IL_005c: throw IL_005d: leave.s IL_0078 } finally { IL_005f: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0064: ldc.i4.1 IL_0065: stfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_006a: ldloc.0 IL_006b: brfalse.s IL_0077 IL_006d: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0072: call "Sub System.Threading.Monitor.Exit(Object)" IL_0077: endfinally } IL_0078: ldstr "StaticLocalInSub" IL_007d: call "Sub System.Console.WriteLine(String)" IL_0082: ldsfld "Module1.SLItem1 As Object" IL_0087: callvirt "Function Object.GetType() As System.Type" IL_008c: callvirt "Function System.Type.ToString() As String" IL_0091: call "Sub System.Console.WriteLine(String)" IL_0096: ldsfld "Module1.SLItem1 As Object" IL_009b: callvirt "Function Object.ToString() As String" IL_00a0: call "Sub System.Console.WriteLine(String)" IL_00a5: ldsfld "Module1.SLItem1 As Object" IL_00aa: ldc.i4.1 IL_00ab: box "Integer" IL_00b0: call "Function Microsoft.VisualBasic.CompilerServices.Operators.AddObject(Object, Object) As Object" IL_00b5: stsfld "Module1.SLItem1 As Object" IL_00ba: ret } ]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub CodeGen_DoubleStaticLocalWithSameNameDifferentScopes() 'TODO: get the correct IL CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() Goo() Bar() Goo() Bar() End Sub Sub Goo() Static SLItem1 = 1 Console.WriteLine("StaticLocalInSub") Console.WriteLine(SLItem1.GetType.ToString) 'Type Inferred Console.WriteLine(SLItem1.ToString) 'Value SLItem1 += 1 End Sub Sub Bar() Static SLItem1 = 1 Console.WriteLine("StaticLocalInSub") Console.WriteLine(SLItem1.GetType.ToString) 'Type Inferred Console.WriteLine(SLItem1.ToString) 'Value SLItem1 += 1 End Sub End Module </file> </compilation>). VerifyIL("Module1.Goo", <![CDATA[ { // Code size 187 (0xbb) .maxstack 3 .locals init (Boolean V_0) IL_0000: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0005: brtrue.s IL_0018 IL_0007: ldsflda "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_000c: newobj "Sub Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag..ctor()" IL_0011: ldnull IL_0012: call "Function System.Threading.Interlocked.CompareExchange(Of Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag)(ByRef Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag, Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag, Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag) As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0017: pop IL_0018: ldc.i4.0 IL_0019: stloc.0 .try { IL_001a: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_001f: ldloca.s V_0 IL_0021: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0026: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_002b: ldfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_0030: brtrue.s IL_004a IL_0032: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0037: ldc.i4.2 IL_0038: stfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_003d: ldc.i4.1 IL_003e: box "Integer" IL_0043: stsfld "Module1.SLItem1 As Object" IL_0048: leave.s IL_0078 IL_004a: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_004f: ldfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_0054: ldc.i4.2 IL_0055: bne.un.s IL_005d IL_0057: newobj "Sub Microsoft.VisualBasic.CompilerServices.IncompleteInitialization..ctor()" IL_005c: throw IL_005d: leave.s IL_0078 } finally { IL_005f: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0064: ldc.i4.1 IL_0065: stfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_006a: ldloc.0 IL_006b: brfalse.s IL_0077 IL_006d: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0072: call "Sub System.Threading.Monitor.Exit(Object)" IL_0077: endfinally } IL_0078: ldstr "StaticLocalInSub" IL_007d: call "Sub System.Console.WriteLine(String)" IL_0082: ldsfld "Module1.SLItem1 As Object" IL_0087: callvirt "Function Object.GetType() As System.Type" IL_008c: callvirt "Function System.Type.ToString() As String" IL_0091: call "Sub System.Console.WriteLine(String)" IL_0096: ldsfld "Module1.SLItem1 As Object" IL_009b: callvirt "Function Object.ToString() As String" IL_00a0: call "Sub System.Console.WriteLine(String)" IL_00a5: ldsfld "Module1.SLItem1 As Object" IL_00aa: ldc.i4.1 IL_00ab: box "Integer" IL_00b0: call "Function Microsoft.VisualBasic.CompilerServices.Operators.AddObject(Object, Object) As Object" IL_00b5: stsfld "Module1.SLItem1 As Object" IL_00ba: ret } ]]>) CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() Goo() Bar() Goo() Bar() End Sub Sub Goo() Static SLItem1 = 1 Console.WriteLine("StaticLocalInSub") Console.WriteLine(SLItem1.GetType.ToString) 'Type Inferred Console.WriteLine(SLItem1.ToString) 'Value SLItem1 += 1 End Sub Sub Bar() Static SLItem1 = 1 Console.WriteLine("StaticLocalInSub") Console.WriteLine(SLItem1.GetType.ToString) 'Type Inferred Console.WriteLine(SLItem1.ToString) 'Value SLItem1 += 1 End Sub End Module </file> </compilation>). VerifyIL("Module1.Bar", <![CDATA[ { // Code size 187 (0xbb) .maxstack 3 .locals init (Boolean V_0) IL_0000: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0005: brtrue.s IL_0018 IL_0007: ldsflda "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_000c: newobj "Sub Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag..ctor()" IL_0011: ldnull IL_0012: call "Function System.Threading.Interlocked.CompareExchange(Of Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag)(ByRef Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag, Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag, Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag) As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0017: pop IL_0018: ldc.i4.0 IL_0019: stloc.0 .try { IL_001a: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_001f: ldloca.s V_0 IL_0021: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0026: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_002b: ldfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_0030: brtrue.s IL_004a IL_0032: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0037: ldc.i4.2 IL_0038: stfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_003d: ldc.i4.1 IL_003e: box "Integer" IL_0043: stsfld "Module1.SLItem1 As Object" IL_0048: leave.s IL_0078 IL_004a: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_004f: ldfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_0054: ldc.i4.2 IL_0055: bne.un.s IL_005d IL_0057: newobj "Sub Microsoft.VisualBasic.CompilerServices.IncompleteInitialization..ctor()" IL_005c: throw IL_005d: leave.s IL_0078 } finally { IL_005f: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0064: ldc.i4.1 IL_0065: stfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_006a: ldloc.0 IL_006b: brfalse.s IL_0077 IL_006d: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0072: call "Sub System.Threading.Monitor.Exit(Object)" IL_0077: endfinally } IL_0078: ldstr "StaticLocalInSub" IL_007d: call "Sub System.Console.WriteLine(String)" IL_0082: ldsfld "Module1.SLItem1 As Object" IL_0087: callvirt "Function Object.GetType() As System.Type" IL_008c: callvirt "Function System.Type.ToString() As String" IL_0091: call "Sub System.Console.WriteLine(String)" IL_0096: ldsfld "Module1.SLItem1 As Object" IL_009b: callvirt "Function Object.ToString() As String" IL_00a0: call "Sub System.Console.WriteLine(String)" IL_00a5: ldsfld "Module1.SLItem1 As Object" IL_00aa: ldc.i4.1 IL_00ab: box "Integer" IL_00b0: call "Function Microsoft.VisualBasic.CompilerServices.Operators.AddObject(Object, Object) As Object" IL_00b5: stsfld "Module1.SLItem1 As Object" IL_00ba: ret } ]]>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub CodeGen_DoubleStaticLocalWithSameNameDifferentOverloads() 'TODO: get the correct IL CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() Goo() Goo(1) Goo() Goo(2) End Sub Sub Goo() Static SLItem1 = 1 Console.WriteLine("StaticLocalInSub") Console.WriteLine(SLItem1.GetType.ToString) 'Type Inferred Console.WriteLine(SLItem1.ToString) 'Value SLItem1 += 1 End Sub Sub goo(x as Integer) Static SLItem1 = 1 Console.WriteLine("StaticLocalInSub") Console.WriteLine(SLItem1.GetType.ToString) 'Type Inferred Console.WriteLine(SLItem1.ToString) 'Value SLItem1 += 1 End Sub End Module </file> </compilation>). VerifyIL("Module1.Goo", <![CDATA[ { // Code size 187 (0xbb) .maxstack 3 .locals init (Boolean V_0) IL_0000: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0005: brtrue.s IL_0018 IL_0007: ldsflda "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_000c: newobj "Sub Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag..ctor()" IL_0011: ldnull IL_0012: call "Function System.Threading.Interlocked.CompareExchange(Of Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag)(ByRef Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag, Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag, Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag) As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0017: pop IL_0018: ldc.i4.0 IL_0019: stloc.0 .try { IL_001a: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_001f: ldloca.s V_0 IL_0021: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0026: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_002b: ldfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_0030: brtrue.s IL_004a IL_0032: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0037: ldc.i4.2 IL_0038: stfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_003d: ldc.i4.1 IL_003e: box "Integer" IL_0043: stsfld "Module1.SLItem1 As Object" IL_0048: leave.s IL_0078 IL_004a: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_004f: ldfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_0054: ldc.i4.2 IL_0055: bne.un.s IL_005d IL_0057: newobj "Sub Microsoft.VisualBasic.CompilerServices.IncompleteInitialization..ctor()" IL_005c: throw IL_005d: leave.s IL_0078 } finally { IL_005f: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0064: ldc.i4.1 IL_0065: stfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_006a: ldloc.0 IL_006b: brfalse.s IL_0077 IL_006d: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0072: call "Sub System.Threading.Monitor.Exit(Object)" IL_0077: endfinally } IL_0078: ldstr "StaticLocalInSub" IL_007d: call "Sub System.Console.WriteLine(String)" IL_0082: ldsfld "Module1.SLItem1 As Object" IL_0087: callvirt "Function Object.GetType() As System.Type" IL_008c: callvirt "Function System.Type.ToString() As String" IL_0091: call "Sub System.Console.WriteLine(String)" IL_0096: ldsfld "Module1.SLItem1 As Object" IL_009b: callvirt "Function Object.ToString() As String" IL_00a0: call "Sub System.Console.WriteLine(String)" IL_00a5: ldsfld "Module1.SLItem1 As Object" IL_00aa: ldc.i4.1 IL_00ab: box "Integer" IL_00b0: call "Function Microsoft.VisualBasic.CompilerServices.Operators.AddObject(Object, Object) As Object" IL_00b5: stsfld "Module1.SLItem1 As Object" IL_00ba: ret } ]]>) CompileAndVerify( <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() Goo() Goo(1) Goo() Goo(2) End Sub Sub goo(x as Integer) Static SLItem1 = 1 Console.WriteLine("StaticLocalInSub") Console.WriteLine(SLItem1.GetType.ToString) 'Type Inferred Console.WriteLine(SLItem1.ToString) 'Value SLItem1 += 1 End Sub Sub Goo() Static SLItem1 = 1 Console.WriteLine("StaticLocalInSub") Console.WriteLine(SLItem1.GetType.ToString) 'Type Inferred Console.WriteLine(SLItem1.ToString) 'Value SLItem1 += 1 End Sub End Module </file> </compilation>). VerifyIL("Module1.goo", <![CDATA[ { // Code size 187 (0xbb) .maxstack 3 .locals init (Boolean V_0) IL_0000: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0005: brtrue.s IL_0018 IL_0007: ldsflda "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_000c: newobj "Sub Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag..ctor()" IL_0011: ldnull IL_0012: call "Function System.Threading.Interlocked.CompareExchange(Of Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag)(ByRef Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag, Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag, Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag) As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0017: pop IL_0018: ldc.i4.0 IL_0019: stloc.0 .try { IL_001a: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_001f: ldloca.s V_0 IL_0021: call "Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)" IL_0026: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_002b: ldfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_0030: brtrue.s IL_004a IL_0032: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0037: ldc.i4.2 IL_0038: stfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_003d: ldc.i4.1 IL_003e: box "Integer" IL_0043: stsfld "Module1.SLItem1 As Object" IL_0048: leave.s IL_0078 IL_004a: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_004f: ldfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_0054: ldc.i4.2 IL_0055: bne.un.s IL_005d IL_0057: newobj "Sub Microsoft.VisualBasic.CompilerServices.IncompleteInitialization..ctor()" IL_005c: throw IL_005d: leave.s IL_0078 } finally { IL_005f: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0064: ldc.i4.1 IL_0065: stfld "Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag.State As Short" IL_006a: ldloc.0 IL_006b: brfalse.s IL_0077 IL_006d: ldsfld "Module1.SLItem1$Init As Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag" IL_0072: call "Sub System.Threading.Monitor.Exit(Object)" IL_0077: endfinally } IL_0078: ldstr "StaticLocalInSub" IL_007d: call "Sub System.Console.WriteLine(String)" IL_0082: ldsfld "Module1.SLItem1 As Object" IL_0087: callvirt "Function Object.GetType() As System.Type" IL_008c: callvirt "Function System.Type.ToString() As String" IL_0091: call "Sub System.Console.WriteLine(String)" IL_0096: ldsfld "Module1.SLItem1 As Object" IL_009b: callvirt "Function Object.ToString() As String" IL_00a0: call "Sub System.Console.WriteLine(String)" IL_00a5: ldsfld "Module1.SLItem1 As Object" IL_00aa: ldc.i4.1 IL_00ab: box "Integer" IL_00b0: call "Function Microsoft.VisualBasic.CompilerServices.Operators.AddObject(Object, Object) As Object" IL_00b5: stsfld "Module1.SLItem1 As Object" IL_00ba: ret } ]]>) End Sub End Class End Namespace
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Statements/WhenKeywordRecommender.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.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Statements ''' <summary> ''' Recommends the "When" keyword for a Catch filter ''' </summary> Friend Class WhenKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("When", VBFeaturesResources.Adds_a_conditional_test_to_a_Catch_statement_Exceptions_are_caught_by_that_Catch_statement_only_when_the_conditional_test_that_follows_the_When_keyword_evaluates_to_True)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If context.FollowsEndOfStatement Then Return ImmutableArray(Of RecommendedKeyword).Empty End If Dim targetToken = context.TargetToken If targetToken.IsFromIdentifierNode(Of CatchStatementSyntax)(Function(catchStatement) catchStatement.IdentifierName) Then Return s_keywords End If If context.SyntaxTree.IsFollowingCompleteExpression(Of SimpleAsClauseSyntax)(context.Position, context.TargetToken, childGetter:=Function(asClause) If(TypeOf asClause.Parent Is CatchStatementSyntax, asClause.Type, Nothing), cancellationToken:=cancellationToken) Then Return s_keywords 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.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Statements ''' <summary> ''' Recommends the "When" keyword for a Catch filter ''' </summary> Friend Class WhenKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword("When", VBFeaturesResources.Adds_a_conditional_test_to_a_Catch_statement_Exceptions_are_caught_by_that_Catch_statement_only_when_the_conditional_test_that_follows_the_When_keyword_evaluates_to_True)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) If context.FollowsEndOfStatement Then Return ImmutableArray(Of RecommendedKeyword).Empty End If Dim targetToken = context.TargetToken If targetToken.IsFromIdentifierNode(Of CatchStatementSyntax)(Function(catchStatement) catchStatement.IdentifierName) Then Return s_keywords End If If context.SyntaxTree.IsFollowingCompleteExpression(Of SimpleAsClauseSyntax)(context.Position, context.TargetToken, childGetter:=Function(asClause) If(TypeOf asClause.Parent Is CatchStatementSyntax, asClause.Type, Nothing), cancellationToken:=cancellationToken) Then Return s_keywords End If Return ImmutableArray(Of RecommendedKeyword).Empty End Function End Class End Namespace
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Dependencies/PooledObjects/PooledDictionary.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; namespace Microsoft.CodeAnalysis.PooledObjects { // Dictionary that can be recycled via an object pool // NOTE: these dictionaries always have the default comparer. internal sealed partial class PooledDictionary<K, V> : Dictionary<K, V> where K : notnull { private readonly ObjectPool<PooledDictionary<K, V>> _pool; private PooledDictionary(ObjectPool<PooledDictionary<K, V>> pool, IEqualityComparer<K> keyComparer) : base(keyComparer) { _pool = pool; } public ImmutableDictionary<K, V> ToImmutableDictionaryAndFree() { var result = this.ToImmutableDictionary(this.Comparer); this.Free(); return result; } public ImmutableDictionary<K, V> ToImmutableDictionary() => this.ToImmutableDictionary(this.Comparer); public void Free() { this.Clear(); _pool?.Free(this); } // global pool private static readonly ObjectPool<PooledDictionary<K, V>> s_poolInstance = CreatePool(EqualityComparer<K>.Default); // if someone needs to create a pool; public static ObjectPool<PooledDictionary<K, V>> CreatePool(IEqualityComparer<K> keyComparer) { ObjectPool<PooledDictionary<K, V>>? pool = null; pool = new ObjectPool<PooledDictionary<K, V>>(() => new PooledDictionary<K, V>(pool!, keyComparer), 128); return pool; } public static PooledDictionary<K, V> GetInstance() { var instance = s_poolInstance.Allocate(); Debug.Assert(instance.Count == 0); return instance; } } }
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.CodeAnalysis.PooledObjects { // Dictionary that can be recycled via an object pool // NOTE: these dictionaries always have the default comparer. internal sealed partial class PooledDictionary<K, V> : Dictionary<K, V> where K : notnull { private readonly ObjectPool<PooledDictionary<K, V>> _pool; private PooledDictionary(ObjectPool<PooledDictionary<K, V>> pool, IEqualityComparer<K> keyComparer) : base(keyComparer) { _pool = pool; } public ImmutableDictionary<K, V> ToImmutableDictionaryAndFree() { var result = this.ToImmutableDictionary(this.Comparer); this.Free(); return result; } public ImmutableDictionary<K, V> ToImmutableDictionary() => this.ToImmutableDictionary(this.Comparer); public void Free() { this.Clear(); _pool?.Free(this); } // global pool private static readonly ObjectPool<PooledDictionary<K, V>> s_poolInstance = CreatePool(EqualityComparer<K>.Default); // if someone needs to create a pool; public static ObjectPool<PooledDictionary<K, V>> CreatePool(IEqualityComparer<K> keyComparer) { ObjectPool<PooledDictionary<K, V>>? pool = null; pool = new ObjectPool<PooledDictionary<K, V>>(() => new PooledDictionary<K, V>(pool!, keyComparer), 128); return pool; } public static PooledDictionary<K, V> GetInstance() { var instance = s_poolInstance.Allocate(); Debug.Assert(instance.Count == 0); return instance; } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Scripting/CSharpTest/InteractiveSessionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.Scripting.Hosting; using Microsoft.CodeAnalysis.Scripting.Test; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests { using static TestCompilationFactory; public class HostModel { public readonly int Goo; } public class InteractiveSessionTests : TestBase { internal static readonly Assembly HostAssembly = typeof(InteractiveSessionTests).GetTypeInfo().Assembly; #region Namespaces, Types [Fact(Skip = "https://github.com/dotnet/roslyn/issues/17869")] public void CompilationChain_NestedTypesClass() { var script = CSharpScript.Create(@" static string outerStr = null; public static void Goo(string str) { outerStr = str; } class InnerClass { public string innerStr = null; public void Goo() { Goo(""test""); innerStr = outerStr; } } ").ContinueWith(@" InnerClass iC = new InnerClass(); iC.Goo(); ").ContinueWith(@" System.Console.WriteLine(iC.innerStr); "); ScriptingTestHelpers.RunScriptWithOutput(script, "test"); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/17869")] public void CompilationChain_NestedTypesStruct() { var script = CSharpScript.Create(@" static string outerStr = null; public static void Goo(string str) { outerStr = str; } struct InnerStruct { public string innerStr; public void Goo() { Goo(""test""); innerStr = outerStr; } } ").ContinueWith(@" InnerStruct iS = new InnerStruct(); iS.Goo(); ").ContinueWith(@" System.Console.WriteLine(iS.innerStr); "); ScriptingTestHelpers.RunScriptWithOutput(script, "test"); } [Fact] public async Task CompilationChain_InterfaceTypes() { var script = CSharpScript.Create(@" interface I1 { int Goo();} class InnerClass : I1 { public int Goo() { return 1; } }").ContinueWith(@" I1 iC = new InnerClass(); ").ContinueWith(@" iC.Goo() "); Assert.Equal(1, await script.EvaluateAsync()); } [Fact] public void ScriptMemberAccessFromNestedClass() { var script = CSharpScript.Create(@" object field; object Property { get; set; } void Method() { } ").ContinueWith(@" class C { public void Goo() { object f = field; object p = Property; Method(); } } "); ScriptingTestHelpers.AssertCompilationError(script, // (6,20): error CS0120: An object reference is required for the non-static field, method, or property 'field' Diagnostic(ErrorCode.ERR_ObjectRequired, "field").WithArguments("field"), // (7,20): error CS0120: An object reference is required for the non-static field, method, or property 'Property' Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("Property"), // (8,9): error CS0120: An object reference is required for the non-static field, method, or property 'Method()' Diagnostic(ErrorCode.ERR_ObjectRequired, "Method").WithArguments("Method()")); } #region Anonymous Types [Fact] public void AnonymousTypes_TopLevel_MultipleSubmissions() { var script = CSharpScript.Create(@" var a = new { f = 1 }; ").ContinueWith(@" var b = new { g = 1 }; ").ContinueWith<Array>(@" var c = new { f = 1 }; var d = new { g = 1 }; new object[] { new[] { a, c }, new[] { b, d } } "); var result = script.EvaluateAsync().Result; Assert.Equal(2, result.Length); Assert.Equal(2, ((Array)result.GetValue(0)).Length); Assert.Equal(2, ((Array)result.GetValue(1)).Length); } [Fact] public void AnonymousTypes_TopLevel_MultipleSubmissions2() { var script = CSharpScript.Create(@" var a = new { f = 1 }; ").ContinueWith(@" var b = new { g = 1 }; ").ContinueWith(@" var c = new { f = 1 }; var d = new { g = 1 }; object.ReferenceEquals(a.GetType(), c.GetType()).ToString() + "" "" + object.ReferenceEquals(a.GetType(), b.GetType()).ToString() + "" "" + object.ReferenceEquals(b.GetType(), d.GetType()).ToString() "); Assert.Equal("True False True", script.EvaluateAsync().Result.ToString()); } [WorkItem(543863, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543863")] [Fact] public void AnonymousTypes_Redefinition() { var script = CSharpScript.Create(@" var x = new { Goo = ""goo"" }; ").ContinueWith(@" var x = new { Goo = ""goo"" }; ").ContinueWith(@" x.Goo "); var result = script.EvaluateAsync().Result; Assert.Equal("goo", result); } [Fact] public void AnonymousTypes_TopLevel_Empty() { var script = CSharpScript.Create(@" var a = new { }; ").ContinueWith(@" var b = new { }; ").ContinueWith<Array>(@" var c = new { }; var d = new { }; new object[] { new[] { a, c }, new[] { b, d } } "); var result = script.EvaluateAsync().Result; Assert.Equal(2, result.Length); Assert.Equal(2, ((Array)result.GetValue(0)).Length); Assert.Equal(2, ((Array)result.GetValue(1)).Length); } #endregion #region Dynamic [Fact] public void Dynamic_Expando() { var options = ScriptOptions.Default. AddReferences( typeof(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException).GetTypeInfo().Assembly, typeof(System.Dynamic.ExpandoObject).GetTypeInfo().Assembly). AddImports( "System.Dynamic"); var script = CSharpScript.Create(@" dynamic expando = new ExpandoObject(); ", options).ContinueWith(@" expando.goo = 1; ").ContinueWith(@" expando.goo "); Assert.Equal(1, script.EvaluateAsync().Result); } #endregion [Fact] public void Enums() { var script = CSharpScript.Create(@" public enum Enum1 { A, B, C } Enum1 E = Enum1.C; E "); var e = script.EvaluateAsync().Result; Assert.True(e.GetType().GetTypeInfo().IsEnum, "Expected enum"); Assert.Equal(typeof(int), Enum.GetUnderlyingType(e.GetType())); } #endregion #region Attributes [Fact] public void PInvoke() { var source = @" using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [DllImport(""goo"", EntryPoint = ""bar"", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = true, SetLastError = true, BestFitMapping = true, ThrowOnUnmappableChar = true)] public static extern void M(); class C { } typeof(C) "; Type c = CSharpScript.EvaluateAsync<Type>(source).Result; var m = c.DeclaringType.GetTypeInfo().GetDeclaredMethod("M"); Assert.Equal(MethodImplAttributes.PreserveSig, m.MethodImplementationFlags); // Reflection synthesizes DllImportAttribute var dllImport = (DllImportAttribute)m.GetCustomAttributes(typeof(DllImportAttribute), inherit: false).Single(); Assert.True(dllImport.BestFitMapping); Assert.Equal(CallingConvention.Cdecl, dllImport.CallingConvention); Assert.Equal(CharSet.Unicode, dllImport.CharSet); Assert.True(dllImport.ExactSpelling); Assert.True(dllImport.SetLastError); Assert.True(dllImport.PreserveSig); Assert.True(dllImport.ThrowOnUnmappableChar); Assert.Equal("bar", dllImport.EntryPoint); Assert.Equal("goo", dllImport.Value); } #endregion // extension methods - must be private, can be top level #region Modifiers and Visibility [Fact] public void PrivateTopLevel() { var script = CSharpScript.Create<int>(@" private int goo() { return 1; } private static int bar() { return 10; } private static int f = 100; goo() + bar() + f "); Assert.Equal(111, script.EvaluateAsync().Result); script = script.ContinueWith<int>(@" goo() + bar() + f "); Assert.Equal(111, script.EvaluateAsync().Result); script = script.ContinueWith<int>(@" class C { public static int baz() { return bar() + f; } } C.baz() "); Assert.Equal(110, script.EvaluateAsync().Result); } [Fact] public void NestedVisibility() { var script = CSharpScript.Create(@" private class C { internal class D { internal static int goo() { return 1; } } private class E { internal static int goo() { return 1; } } public class F { internal protected static int goo() { return 1; } } internal protected class G { internal static int goo() { return 1; } } } "); Assert.Equal(1, script.ContinueWith<int>("C.D.goo()").EvaluateAsync().Result); Assert.Equal(1, script.ContinueWith<int>("C.F.goo()").EvaluateAsync().Result); Assert.Equal(1, script.ContinueWith<int>("C.G.goo()").EvaluateAsync().Result); ScriptingTestHelpers.AssertCompilationError(script.ContinueWith<int>(@"C.E.goo()"), // error CS0122: 'C.E' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "E").WithArguments("C.E")); } [Fact] public void Fields_Visibility() { var script = CSharpScript.Create(@" private int i = 2; // test comment; public int j = 2; protected int k = 2; internal protected int l = 2; internal int pi = 2; ").ContinueWith(@" i = i + i; j = j + j; k = k + k; l = l + l; ").ContinueWith(@" pi = i + j + k + l; "); Assert.Equal(4, script.ContinueWith<int>("i").EvaluateAsync().Result); Assert.Equal(4, script.ContinueWith<int>("j").EvaluateAsync().Result); Assert.Equal(4, script.ContinueWith<int>("k").EvaluateAsync().Result); Assert.Equal(4, script.ContinueWith<int>("l").EvaluateAsync().Result); Assert.Equal(16, script.ContinueWith<int>("pi").EvaluateAsync().Result); } [WorkItem(100639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/100639")] [Fact] public void ExternDestructor() { var script = CSharpScript.Create( @"class C { extern ~C(); }"); Assert.Null(script.EvaluateAsync().Result); } #endregion #region Chaining [Fact] public void CompilationChain_BasicFields() { var script = CSharpScript.Create("var x = 1;").ContinueWith("x"); Assert.Equal(1, script.EvaluateAsync().Result); } [Fact] public void CompilationChain_GlobalNamespaceAndUsings() { var result = CSharpScript.Create("using InteractiveFixtures.C;", ScriptOptions.Default.AddReferences(HostAssembly)). ContinueWith("using InteractiveFixtures.C;"). ContinueWith("System.Environment.ProcessorCount"). EvaluateAsync().Result; Assert.Equal(Environment.ProcessorCount, result); } [Fact] public void CompilationChain_CurrentSubmissionUsings() { var s0 = CSharpScript.RunAsync("", ScriptOptions.Default.AddReferences(HostAssembly)); var state = s0. ContinueWith("class X { public int goo() { return 1; } }"). ContinueWith("class X { public int goo() { return 1; } }"). ContinueWith("using InteractiveFixtures.A;"). ContinueWith("new X().goo()"); Assert.Equal(1, state.Result.ReturnValue); state = s0. ContinueWith("class X { public int goo() { return 1; } }"). ContinueWith(@" using InteractiveFixtures.A; new X().goo() "); Assert.Equal(1, state.Result.ReturnValue); } [Fact] public void CompilationChain_UsingDuplicates() { var script = CSharpScript.Create(@" using System; using System; ").ContinueWith(@" using System; using System; ").ContinueWith(@" Environment.ProcessorCount "); Assert.Equal(Environment.ProcessorCount, script.EvaluateAsync().Result); } [Fact] public void CompilationChain_GlobalImports() { var options = ScriptOptions.Default.AddImports("System"); var state = CSharpScript.RunAsync("Environment.ProcessorCount", options); Assert.Equal(Environment.ProcessorCount, state.Result.ReturnValue); state = state.ContinueWith("Environment.ProcessorCount"); Assert.Equal(Environment.ProcessorCount, state.Result.ReturnValue); } [Fact] public void CompilationChain_Accessibility() { // Submissions have internal and protected access to one another. var state1 = CSharpScript.RunAsync("internal class C1 { } protected int X; 1"); var compilation1 = state1.Result.Script.GetCompilation(); compilation1.VerifyDiagnostics( // (1,39): warning CS0628: 'X': new protected member declared in sealed type // internal class C1 { } protected int X; 1 Diagnostic(ErrorCode.WRN_ProtectedInSealed, "X").WithArguments("X").WithLocation(1, 39) ); Assert.Equal(1, state1.Result.ReturnValue); var state2 = state1.ContinueWith("internal class C2 : C1 { } 2"); var compilation2 = state2.Result.Script.GetCompilation(); compilation2.VerifyDiagnostics(); Assert.Equal(2, state2.Result.ReturnValue); var c2C2 = (INamedTypeSymbol)lookupMember(compilation2, "Submission#1", "C2"); var c2C1 = c2C2.BaseType; var c2X = lookupMember(compilation1, "Submission#0", "X"); Assert.True(compilation2.IsSymbolAccessibleWithin(c2C1, c2C2)); Assert.True(compilation2.IsSymbolAccessibleWithin(c2C2, c2C1)); Assert.True(compilation2.IsSymbolAccessibleWithin(c2X, c2C2)); // access not enforced among submission symbols var state3 = state2.ContinueWith("private class C3 : C2 { } 3"); var compilation3 = state3.Result.Script.GetCompilation(); compilation3.VerifyDiagnostics(); Assert.Equal(3, state3.Result.ReturnValue); var c3C3 = (INamedTypeSymbol)lookupMember(compilation3, "Submission#2", "C3"); var c3C1 = c3C3.BaseType; Assert.Throws<ArgumentException>(() => compilation2.IsSymbolAccessibleWithin(c3C3, c3C1)); Assert.True(compilation3.IsSymbolAccessibleWithin(c3C3, c3C1)); INamedTypeSymbol lookupType(Compilation c, string name) { return c.GlobalNamespace.GetMembers(name).Single() as INamedTypeSymbol; } ISymbol lookupMember(Compilation c, string typeName, string memberName) { return lookupType(c, typeName).GetMembers(memberName).Single(); } } [Fact] public void CompilationChain_SubmissionSlotResize() { var state = CSharpScript.RunAsync(""); for (int i = 0; i < 17; i++) { state = state.ContinueWith(@"public int i = 1;"); } ScriptingTestHelpers.ContinueRunScriptWithOutput(state, @"System.Console.WriteLine(i);", "1"); } [Fact] public void CompilationChain_UsingNotHidingPreviousSubmission() { int result1 = CSharpScript.Create("using System;"). ContinueWith("int Environment = 1;"). ContinueWith<int>("Environment"). EvaluateAsync().Result; Assert.Equal(1, result1); int result2 = CSharpScript.Create("int Environment = 1;"). ContinueWith("using System;"). ContinueWith<int>("Environment"). EvaluateAsync().Result; Assert.Equal(1, result2); } [Fact] public void CompilationChain_DefinitionHidesGlobal() { var result = CSharpScript.Create("int System = 1;"). ContinueWith("System"). EvaluateAsync().Result; Assert.Equal(1, result); } public class C1 { public readonly int System = 1; public readonly int Environment = 2; } /// <summary> /// Symbol declaration in host object model hides global definition. /// </summary> [Fact] public void CompilationChain_HostObjectMembersHidesGlobal() { var result = CSharpScript.RunAsync("System", globals: new C1()). Result.ReturnValue; Assert.Equal(1, result); } [Fact] public void CompilationChain_UsingNotHidingHostObjectMembers() { var result = CSharpScript.RunAsync("using System;", globals: new C1()). ContinueWith("Environment"). Result.ReturnValue; Assert.Equal(2, result); } [Fact] public void CompilationChain_DefinitionHidesHostObjectMembers() { var result = CSharpScript.RunAsync("int System = 2;", globals: new C1()). ContinueWith("System"). Result.ReturnValue; Assert.Equal(2, result); } [Fact] public void Submissions_ExecutionOrder1() { var s0 = CSharpScript.Create("int x = 1;"); var s1 = s0.ContinueWith("int y = 2;"); var s2 = s1.ContinueWith<int>("x + y"); Assert.Equal(3, s2.EvaluateAsync().Result); Assert.Null(s1.EvaluateAsync().Result); Assert.Null(s0.EvaluateAsync().Result); Assert.Equal(3, s2.EvaluateAsync().Result); Assert.Null(s1.EvaluateAsync().Result); Assert.Null(s0.EvaluateAsync().Result); Assert.Equal(3, s2.EvaluateAsync().Result); Assert.Equal(3, s2.EvaluateAsync().Result); } [Fact] public async Task Submissions_ExecutionOrder2() { var s0 = await CSharpScript.RunAsync("int x = 1;"); Assert.Throws<CompilationErrorException>(() => s0.ContinueWithAsync("invalid$syntax").Result); var s1 = await s0.ContinueWithAsync("x = 2; x = 10"); Assert.Throws<CompilationErrorException>(() => s1.ContinueWithAsync("invalid$syntax").Result); Assert.Throws<CompilationErrorException>(() => s1.ContinueWithAsync("x = undefined_symbol").Result); var s2 = await s1.ContinueWithAsync("int y = 2;"); Assert.Null(s2.ReturnValue); var s3 = await s2.ContinueWithAsync("x + y"); Assert.Equal(12, s3.ReturnValue); } public class HostObjectWithOverrides { public override bool Equals(object obj) => true; public override int GetHashCode() => 1234567; public override string ToString() => "HostObjectToString impl"; } [Fact] public async Task ObjectOverrides1() { var state0 = await CSharpScript.RunAsync("", globals: new HostObjectWithOverrides()); var state1 = await state0.ContinueWithAsync<bool>("Equals(null)"); Assert.True(state1.ReturnValue); var state2 = await state1.ContinueWithAsync<int>("GetHashCode()"); Assert.Equal(1234567, state2.ReturnValue); var state3 = await state2.ContinueWithAsync<string>("ToString()"); Assert.Equal("HostObjectToString impl", state3.ReturnValue); } [Fact] public async Task ObjectOverrides2() { var state0 = await CSharpScript.RunAsync("", globals: new object()); var state1 = await state0.ContinueWithAsync<bool>(@" object x = 1; object y = x; ReferenceEquals(x, y)"); Assert.True(state1.ReturnValue); var state2 = await state1.ContinueWithAsync<string>("ToString()"); Assert.Equal("System.Object", state2.ReturnValue); var state3 = await state2.ContinueWithAsync<bool>("Equals(null)"); Assert.False(state3.ReturnValue); } [Fact] public void ObjectOverrides3() { var state0 = CSharpScript.RunAsync(""); var src1 = @" Equals(null); GetHashCode(); ToString(); ReferenceEquals(null, null);"; ScriptingTestHelpers.AssertCompilationError(state0, src1, // (2,1): error CS0103: The name 'Equals' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "Equals").WithArguments("Equals"), // (3,1): error CS0103: The name 'GetHashCode' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "GetHashCode").WithArguments("GetHashCode"), // (4,1): error CS0103: The name 'ToString' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "ToString").WithArguments("ToString"), // (5,1): error CS0103: The name 'ReferenceEquals' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "ReferenceEquals").WithArguments("ReferenceEquals")); var src2 = @" public override string ToString() { return null; } "; ScriptingTestHelpers.AssertCompilationError(state0, src2, // (1,24): error CS0115: 'ToString()': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "ToString").WithArguments("ToString()")); } #endregion #region Generics [Fact, WorkItem(201759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/201759")] public void CompilationChain_GenericTypes() { var script = CSharpScript.Create(@" class InnerClass<T> { public int method(int value) { return value + 1; } public int field = 2; }").ContinueWith(@" InnerClass<int> iC = new InnerClass<int>(); ").ContinueWith(@" iC.method(iC.field) "); Assert.Equal(3, script.EvaluateAsync().Result); } [WorkItem(529243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529243")] [Fact] public void RecursiveBaseType() { CSharpScript.EvaluateAsync(@" class A<T> { } class B<T> : A<B<B<T>>> { } "); } [WorkItem(5378, "DevDiv_Projects/Roslyn")] [Fact] public void CompilationChain_GenericMethods() { var s0 = CSharpScript.Create(@" public int goo<T, R>(T arg) { return 1; } public static T bar<T>(T i) { return i; } "); Assert.Equal(1, s0.ContinueWith(@"goo<int, int>(1)").EvaluateAsync().Result); Assert.Equal(5, s0.ContinueWith(@"bar(5)").EvaluateAsync().Result); } /// <summary> /// Tests that we emit ldftn and ldvirtftn instructions correctly. /// </summary> [Fact] public void CompilationChain_Ldftn() { var state = CSharpScript.RunAsync(@" public class C { public static int f() { return 1; } public int g() { return 10; } public virtual int h() { return 100; } public static int gf<T>() { return 2; } public int gg<T>() { return 20; } public virtual int gh<T>() { return 200; } } "); state = state.ContinueWith(@" new System.Func<int>(C.f)() + new System.Func<int>(new C().g)() + new System.Func<int>(new C().h)()" ); Assert.Equal(111, state.Result.ReturnValue); state = state.ContinueWith(@" new System.Func<int>(C.gf<int>)() + new System.Func<int>(new C().gg<object>)() + new System.Func<int>(new C().gh<bool>)() "); Assert.Equal(222, state.Result.ReturnValue); } /// <summary> /// Tests that we emit ldftn and ldvirtftn instructions correctly. /// </summary> [Fact] public void CompilationChain_Ldftn_GenericType() { var state = CSharpScript.RunAsync(@" public class C<S> { public static int f() { return 1; } public int g() { return 10; } public virtual int h() { return 100; } public static int gf<T>() { return 2; } public int gg<T>() { return 20; } public virtual int gh<T>() { return 200; } } "); state = state.ContinueWith(@" new System.Func<int>(C<byte>.f)() + new System.Func<int>(new C<byte>().g)() + new System.Func<int>(new C<byte>().h)() "); Assert.Equal(111, state.Result.ReturnValue); state = state.ContinueWith(@" new System.Func<int>(C<byte>.gf<int>)() + new System.Func<int>(new C<byte>().gg<object>)() + new System.Func<int>(new C<byte>().gh<bool>)() "); Assert.Equal(222, state.Result.ReturnValue); } #endregion #region Statements and Expressions [Fact] public void IfStatement() { var result = CSharpScript.EvaluateAsync<int>(@" using static System.Console; int x; if (true) { x = 5; } else { x = 6; } x ").Result; Assert.Equal(5, result); } [Fact] public void ExprStmtParenthesesUsedToOverrideDefaultEval() { Assert.Equal(18, CSharpScript.EvaluateAsync<int>("(4 + 5) * 2").Result); Assert.Equal(1, CSharpScript.EvaluateAsync<long>("6 / (2 * 3)").Result); } [WorkItem(5397, "DevDiv_Projects/Roslyn")] [Fact] public void TopLevelLambda() { var s = CSharpScript.RunAsync(@" using System; delegate void TestDelegate(string s); "); s = s.ContinueWith(@" TestDelegate testDelB = delegate (string s) { Console.WriteLine(s); }; "); ScriptingTestHelpers.ContinueRunScriptWithOutput(s, @"testDelB(""hello"");", "hello"); } [Fact] public void Closure() { var f = CSharpScript.EvaluateAsync<Func<int, int>>(@" int Goo(int arg) { return arg + 1; } System.Func<int, int> f = (arg) => { return Goo(arg); }; f ").Result; Assert.Equal(3, f(2)); } [Fact] public void Closure2() { var result = CSharpScript.EvaluateAsync<List<string>>(@" #r ""System.Core"" using System; using System.Linq; using System.Collections.Generic; List<string> result = new List<string>(); string s = ""hello""; Enumerable.ToList(Enumerable.Range(1, 2)).ForEach(x => result.Add(s)); result ").Result; AssertEx.Equal(new[] { "hello", "hello" }, result); } [Fact] public void UseDelegateMixStaticAndDynamic() { var f = CSharpScript.RunAsync("using System;"). ContinueWith("int Sqr(int x) {return x*x;}"). ContinueWith<Func<int, int>>("new Func<int,int>(Sqr)").Result.ReturnValue; Assert.Equal(4, f(2)); } [WorkItem(9229, "DevDiv_Projects/Roslyn")] [Fact] public void Arrays() { var s = CSharpScript.RunAsync(@" int[] arr_1 = { 1, 2, 3 }; int[] arr_2 = new int[] { 1, 2, 3 }; int[] arr_3 = new int[5]; ").ContinueWith(@" arr_2[0] = 5; "); Assert.Equal(3, s.ContinueWith(@"arr_1[2]").Result.ReturnValue); Assert.Equal(5, s.ContinueWith(@"arr_2[0]").Result.ReturnValue); Assert.Equal(0, s.ContinueWith(@"arr_3[0]").Result.ReturnValue); } [Fact] public void FieldInitializers() { var result = CSharpScript.EvaluateAsync<List<int>>(@" using System.Collections.Generic; static List<int> result = new List<int>(); int b = 2; int a; int x = 1, y = b; static int g = 1; static int f = g + 1; a = x + y; result.Add(a); int z = 4 + f; result.Add(z); result.Add(a * z); result ").Result; Assert.Equal(3, result.Count); Assert.Equal(3, result[0]); Assert.Equal(6, result[1]); Assert.Equal(18, result[2]); } [Fact] public void FieldInitializersWithBlocks() { var result = CSharpScript.EvaluateAsync<List<int>>(@" using System.Collections.Generic; static List<int> result = new List<int>(); const int constant = 1; { int x = constant; result.Add(x); } int field = 2; { int x = field; result.Add(x); } result.Add(constant); result.Add(field); result ").Result; Assert.Equal(4, result.Count); Assert.Equal(1, result[0]); Assert.Equal(2, result[1]); Assert.Equal(1, result[2]); Assert.Equal(2, result[3]); } [Fact] public void TestInteractiveClosures() { var result = CSharpScript.RunAsync(@" using System.Collections.Generic; static List<int> result = new List<int>();"). ContinueWith("int x = 1;"). ContinueWith("System.Func<int> f = () => x++;"). ContinueWith("result.Add(f());"). ContinueWith("result.Add(x);"). ContinueWith<List<int>>("result").Result.ReturnValue; Assert.Equal(2, result.Count); Assert.Equal(1, result[0]); Assert.Equal(2, result[1]); } [Fact] public void ExtensionMethods() { var options = ScriptOptions.Default.AddReferences( typeof(Enumerable).GetTypeInfo().Assembly); var result = CSharpScript.EvaluateAsync<int>(@" using System.Linq; string[] fruit = { ""banana"", ""orange"", ""lime"", ""apple"", ""kiwi"" }; fruit.Skip(1).Where(s => s.Length > 4).Count()", options).Result; Assert.Equal(2, result); } [Fact] public void ImplicitlyTypedFields() { var result = CSharpScript.EvaluateAsync<object[]>(@" var x = 1; var y = x; var z = goo(x); string goo(int a) { return null; } int goo(string a) { return 0; } new object[] { x, y, z } ").Result; AssertEx.Equal(new object[] { 1, 1, null }, result); } /// <summary> /// Name of PrivateImplementationDetails type needs to be unique across submissions. /// The compiler should suffix it with a MVID of the current submission module so we should be fine. /// </summary> [WorkItem(949559, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/949559")] [WorkItem(540237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540237")] [WorkItem(9229, "DevDiv_Projects/Roslyn")] [WorkItem(2721, "https://github.com/dotnet/roslyn/issues/2721")] [Fact] public async Task PrivateImplementationDetailsType() { var result1 = await CSharpScript.EvaluateAsync<int[]>("new int[] { 1,2,3,4 }"); AssertEx.Equal(new[] { 1, 2, 3, 4 }, result1); var result2 = await CSharpScript.EvaluateAsync<int[]>("new int[] { 1,2,3,4,5 }"); AssertEx.Equal(new[] { 1, 2, 3, 4, 5 }, result2); var s1 = await CSharpScript.RunAsync<int[]>("new int[] { 1,2,3,4,5,6 }"); AssertEx.Equal(new[] { 1, 2, 3, 4, 5, 6 }, s1.ReturnValue); var s2 = await s1.ContinueWithAsync<int[]>("new int[] { 1,2,3,4,5,6,7 }"); AssertEx.Equal(new[] { 1, 2, 3, 4, 5, 6, 7 }, s2.ReturnValue); var s3 = await s2.ContinueWithAsync<int[]>("new int[] { 1,2,3,4,5,6,7,8 }"); AssertEx.Equal(new[] { 1, 2, 3, 4, 5, 6, 7, 8 }, s3.ReturnValue); } [Fact] public void NoAwait() { // No await. The return value is Task<int> rather than int. var result = CSharpScript.EvaluateAsync("System.Threading.Tasks.Task.FromResult(1)").Result; Assert.Equal(1, ((Task<int>)result).Result); } /// <summary> /// 'await' expression at top-level. /// </summary> [Fact] public void Await() { Assert.Equal(2, CSharpScript.EvaluateAsync("await System.Threading.Tasks.Task.FromResult(2)").Result); } /// <summary> /// 'await' in sub-expression. /// </summary> [Fact] public void AwaitSubExpression() { Assert.Equal(3, CSharpScript.EvaluateAsync<int>("0 + await System.Threading.Tasks.Task.FromResult(3)").Result); } [Fact] public void AwaitVoid() { var task = CSharpScript.EvaluateAsync<object>("await System.Threading.Tasks.Task.Run(() => { })"); Assert.Null(task.Result); Assert.Equal(TaskStatus.RanToCompletion, task.Status); } /// <summary> /// 'await' in lambda should be ignored. /// </summary> [Fact] public async Task AwaitInLambda() { var s0 = await CSharpScript.RunAsync(@" using System; using System.Threading.Tasks; static T F<T>(Func<Task<T>> f) { return f().Result; } static T G<T>(T t, Func<T, Task<T>> f) { return f(t).Result; }"); var s1 = await s0.ContinueWithAsync("F(async () => await Task.FromResult(4))"); Assert.Equal(4, s1.ReturnValue); var s2 = await s1.ContinueWithAsync("G(5, async x => await Task.FromResult(x))"); Assert.Equal(5, s2.ReturnValue); } [Fact] public void AwaitChain1() { var options = ScriptOptions.Default. AddReferences(typeof(Task).GetTypeInfo().Assembly). AddImports("System.Threading.Tasks"); var state = CSharpScript.RunAsync("int i = 0;", options). ContinueWith("await Task.Delay(1); i++;"). ContinueWith("await Task.Delay(1); i++;"). ContinueWith("await Task.Delay(1); i++;"). ContinueWith("i"). Result; Assert.Equal(3, state.ReturnValue); } [Fact] public void AwaitChain2() { var options = ScriptOptions.Default. AddReferences(typeof(Task).GetTypeInfo().Assembly). AddImports("System.Threading.Tasks"); var state = CSharpScript.Create("int i = 0;", options). ContinueWith("await Task.Delay(1); i++;"). ContinueWith("await Task.Delay(1); i++;"). RunAsync(). ContinueWith("await Task.Delay(1); i++;"). ContinueWith("i"). Result; Assert.Equal(3, state.ReturnValue); } [Fact, WorkItem(39548, "https://github.com/dotnet/roslyn/issues/39548")] public async Task PatternVariableDeclaration() { var state = await CSharpScript.RunAsync("var x = (false, 4);"); state = await state.ContinueWithAsync("x is (false, var y)"); Assert.Equal(true, state.ReturnValue); } [Fact, WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] public async Task CSharp9PatternForms() { var options = ScriptOptions.Default.WithLanguageVersion(MessageID.IDS_FeatureAndPattern.RequiredVersion()); var state = await CSharpScript.RunAsync("object x = 1;", options: options); state = await state.ContinueWithAsync("x is long or int", options: options); Assert.Equal(true, state.ReturnValue); state = await state.ContinueWithAsync("x is int and < 10", options: options); Assert.Equal(true, state.ReturnValue); state = await state.ContinueWithAsync("x is (long or < 10L)", options: options); Assert.Equal(false, state.ReturnValue); state = await state.ContinueWithAsync("x is not > 100", options: options); Assert.Equal(true, state.ReturnValue); } #endregion #region References [Fact(Skip = "https://github.com/dotnet/roslyn/issues/53391")] [WorkItem(15860, "https://github.com/dotnet/roslyn/issues/53391")] public void ReferenceDirective_FileWithDependencies() { var file1 = Temp.CreateFile(); var file2 = Temp.CreateFile(); var lib1 = CreateCSharpCompilationWithCorlib(@" public interface I { int F(); }"); lib1.Emit(file1.Path); var lib2 = CreateCSharpCompilation(@" public class C : I { public int F() => 1; }", new MetadataReference[] { TestReferences.NetStandard13.SystemRuntime, lib1.ToMetadataReference() }); lib2.Emit(file2.Path); object result = CSharpScript.EvaluateAsync($@" #r ""{file1.Path}"" #r ""{file2.Path}"" new C() ").Result; Assert.NotNull(result); } [ConditionalFact(typeof(WindowsOnly)), WorkItem(15860, "https://github.com/dotnet/roslyn/issues/15860")] public void ReferenceDirective_RelativeToBaseParent() { var file = Temp.CreateFile(); var lib = CreateCSharpCompilationWithCorlib("public class C {}"); lib.Emit(file.Path); string dir = Path.Combine(Path.GetDirectoryName(file.Path), "subdir"); string libFileName = Path.GetFileName(file.Path); string scriptPath = Path.Combine(dir, "a.csx"); var script = CSharpScript.Create( $@"#r ""{Path.Combine("..", libFileName)}""", ScriptOptions.Default.WithFilePath(scriptPath)); script.GetCompilation().VerifyDiagnostics(); } [ConditionalFact(typeof(WindowsOnly)), WorkItem(15860, "https://github.com/dotnet/roslyn/issues/15860")] public void ReferenceDirective_RelativeToBaseRoot() { var file = Temp.CreateFile(); var lib = CreateCSharpCompilationWithCorlib("public class C {}"); lib.Emit(file.Path); string root = Path.GetPathRoot(file.Path); string unrooted = file.Path.Substring(root.Length); string dir = Path.Combine(root, "goo", "bar", "baz"); string scriptPath = Path.Combine(dir, "a.csx"); var script = CSharpScript.Create( $@"#r ""\{unrooted}""", ScriptOptions.Default.WithFilePath(scriptPath)); script.GetCompilation().VerifyDiagnostics(); } [Fact] public void ExtensionPriority1() { string mainName = "Main_" + Guid.NewGuid(); string libName = "Lib_" + Guid.NewGuid(); var libExe = CreateCSharpCompilationWithCorlib(@"public class C { public string F = ""exe""; }", libName); var libDll = CreateCSharpCompilationWithCorlib(@"public class C { public string F = ""dll""; }", libName); var libWinmd = CreateCSharpCompilationWithCorlib(@"public class C { public string F = ""winmd""; }", libName); var main = CreateCSharpCompilation( @"public static class M { public static readonly C X = new C(); }", new MetadataReference[] { TestReferences.NetStandard13.SystemRuntime, libExe.ToMetadataReference() }, mainName); var exeImage = libExe.EmitToArray(); var dllImage = libDll.EmitToArray(); var winmdImage = libWinmd.EmitToArray(); var mainImage = main.EmitToArray(); var dir = Temp.CreateDirectory(); var fileMain = dir.CreateFile(mainName + ".dll").WriteAllBytes(mainImage); dir.CreateFile(libName + ".exe").WriteAllBytes(exeImage); dir.CreateFile(libName + ".winmd").WriteAllBytes(winmdImage); var r2 = CSharpScript.Create($@"#r ""{fileMain.Path}""").ContinueWith($@"M.X.F").RunAsync().Result.ReturnValue; Assert.Equal("exe", r2); } [Fact] public void ExtensionPriority2() { string mainName = "Main_" + Guid.NewGuid(); string libName = "Lib_" + Guid.NewGuid(); var libExe = CreateCSharpCompilationWithCorlib(@"public class C { public string F = ""exe""; }", libName); var libDll = CreateCSharpCompilationWithCorlib(@"public class C { public string F = ""dll""; }", libName); var libWinmd = CreateCSharpCompilationWithCorlib(@"public class C { public string F = ""winmd""; }", libName); var main = CreateCSharpCompilation( @"public static class M { public static readonly C X = new C(); }", new MetadataReference[] { TestReferences.NetStandard13.SystemRuntime, libExe.ToMetadataReference() }, mainName); var exeImage = libExe.EmitToArray(); var dllImage = libDll.EmitToArray(); var winmdImage = libWinmd.EmitToArray(); var mainImage = main.EmitToArray(); var dir = Temp.CreateDirectory(); var fileMain = dir.CreateFile(mainName + ".dll").WriteAllBytes(mainImage); dir.CreateFile(libName + ".exe").WriteAllBytes(exeImage); dir.CreateFile(libName + ".dll").WriteAllBytes(dllImage); dir.CreateFile(libName + ".winmd").WriteAllBytes(winmdImage); var r2 = CSharpScript.Create($@"#r ""{fileMain.Path}""").ContinueWith($@"M.X.F").RunAsync().Result.ReturnValue; Assert.Equal("dll", r2); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/6015")] public void UsingExternalAliasesForHiding() { string source = @" namespace N { public class C { } } public class D { } public class E { } "; var libRef = CreateCSharpCompilationWithCorlib(source, "lib").EmitToImageReference(); var script = CSharpScript.Create(@"new C()", ScriptOptions.Default.WithReferences(libRef.WithAliases(new[] { "Hidden" })).WithImports("Hidden::N")); script.Compile().Verify(); } #endregion #region UsingDeclarations [Fact] public void UsingAlias() { object result = CSharpScript.EvaluateAsync(@" using D = System.Collections.Generic.Dictionary<string, int>; D d = new D(); d ").Result; Assert.True(result is Dictionary<string, int>, "Expected Dictionary<string, int>"); } [WorkItem(9229, "DevDiv_Projects/Roslyn")] [Fact] public void Usings1() { var options = ScriptOptions.Default. AddImports("System", "System.Linq"). AddReferences(typeof(Enumerable).GetTypeInfo().Assembly); object result = CSharpScript.EvaluateAsync("new int[] { 1, 2, 3 }.First()", options).Result; Assert.Equal(1, result); } [WorkItem(9229, "DevDiv_Projects/Roslyn")] [Fact] public void Usings2() { var options = ScriptOptions.Default. AddImports("System", "System.Linq"). AddReferences(typeof(Enumerable).GetTypeInfo().Assembly); var s1 = CSharpScript.RunAsync("new int[] { 1, 2, 3 }.First()", options); Assert.Equal(1, s1.Result.ReturnValue); var s2 = s1.ContinueWith("new List<int>()", options.AddImports("System.Collections.Generic")); Assert.IsType<List<int>>(s2.Result.ReturnValue); } [Fact] public void AddNamespaces_Errors() { // no immediate error, error is reported if the namespace can't be found when compiling: var options = ScriptOptions.Default.AddImports("?1", "?2"); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("1", options), // error CS0246: The type or namespace name '?1' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound).WithArguments("?1"), // error CS0246: The type or namespace name '?2' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound).WithArguments("?2")); options = ScriptOptions.Default.AddImports(""); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("1", options), // error CS7088: Invalid 'Usings' value: ''. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "")); options = ScriptOptions.Default.AddImports(".abc"); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("1", options), // error CS7088: Invalid 'Usings' value: '.abc'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", ".abc")); options = ScriptOptions.Default.AddImports("a\0bc"); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("1", options), // error CS7088: Invalid 'Usings' value: '.abc'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "a\0bc")); } #endregion #region Host Object Binding and Conversions public class C<T> { } [Fact] public void Submission_HostConversions() { Assert.Equal(2, CSharpScript.EvaluateAsync<int>("1+1").Result); Assert.Null(CSharpScript.EvaluateAsync<string>("null").Result); try { CSharpScript.RunAsync<C<int>>("null"); Assert.True(false, "Expected an exception"); } catch (CompilationErrorException e) { // error CS0400: The type or namespace name 'Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Source.InteractiveSessionTests+C`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], Roslyn.Compilers.CSharp.Emit.UnitTests, Version=42.42.42.42, Culture=neutral, PublicKeyToken=fc793a00266884fb' could not be found in the global namespace (are you missing an assembly reference?) Assert.Equal(ErrorCode.ERR_GlobalSingleTypeNameNotFound, (ErrorCode)e.Diagnostics.Single().Code); // Can't use Verify() because the version number of the test dll is different in the build lab. } var options = ScriptOptions.Default.AddReferences(HostAssembly); var cint = CSharpScript.EvaluateAsync<C<int>>("null", options).Result; Assert.Null(cint); Assert.Null(CSharpScript.EvaluateAsync<int?>("null", options).Result); try { CSharpScript.RunAsync<int>("null"); Assert.True(false, "Expected an exception"); } catch (CompilationErrorException e) { e.Diagnostics.Verify( // (1,1): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // null Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int")); } try { CSharpScript.RunAsync<string>("1+1"); Assert.True(false, "Expected an exception"); } catch (CompilationErrorException e) { e.Diagnostics.Verify( // (1,1): error CS0029: Cannot implicitly convert type 'int' to 'string' // 1+1 Diagnostic(ErrorCode.ERR_NoImplicitConv, "1+1").WithArguments("int", "string")); } } [Fact] public void Submission_HostVarianceConversions() { var value = CSharpScript.EvaluateAsync<IEnumerable<Exception>>(@" using System; using System.Collections.Generic; new List<ArgumentException>() ").Result; Assert.Null(value.FirstOrDefault()); } public class B { public int x = 1, w = 4; } public class C : B, I { public static readonly int StaticField = 123; public int Y => 2; public string N { get; set; } = "2"; public int Z() => 3; public override int GetHashCode() => 123; } public interface I { string N { get; set; } int Z(); } private class PrivateClass : I { public string N { get; set; } = null; public int Z() => 3; } public class M<T> { private int F() => 3; public T G() => default(T); } [Fact] public void HostObjectBinding_PublicClassMembers() { var c = new C(); var s0 = CSharpScript.RunAsync<int>("x + Y + Z()", globals: c); Assert.Equal(6, s0.Result.ReturnValue); var s1 = s0.ContinueWith<int>("x"); Assert.Equal(1, s1.Result.ReturnValue); var s2 = s1.ContinueWith<int>("int x = 20;"); var s3 = s2.ContinueWith<int>("x"); Assert.Equal(20, s3.Result.ReturnValue); } [Fact] public void HostObjectBinding_PublicGenericClassMembers() { var m = new M<string>(); var result = CSharpScript.EvaluateAsync<string>("G()", globals: m); Assert.Null(result.Result); } [Fact] public async Task HostObjectBinding_Interface() { var c = new C(); var s0 = await CSharpScript.RunAsync<int>("Z()", globals: c, globalsType: typeof(I)); Assert.Equal(3, s0.ReturnValue); ScriptingTestHelpers.AssertCompilationError(s0, @"x + Y", // The name '{0}' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x"), Diagnostic(ErrorCode.ERR_NameNotInContext, "Y").WithArguments("Y")); var s1 = await s0.ContinueWithAsync<string>("N"); Assert.Equal("2", s1.ReturnValue); } [Fact] public void HostObjectBinding_PrivateClass() { var c = new PrivateClass(); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("Z()", globals: c), // (1,1): error CS0122: '<Fully Qualified Name of PrivateClass>.Z()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "Z").WithArguments(typeof(PrivateClass).FullName.Replace("+", ".") + ".Z()")); } [Fact] public void HostObjectBinding_PrivateMembers() { object c = new M<int>(); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("Z()", globals: c), // (1,1): error CS0103: The name 'z' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "Z").WithArguments("Z")); } [Fact] public void HostObjectBinding_PrivateClassImplementingPublicInterface() { var c = new PrivateClass(); var result = CSharpScript.EvaluateAsync<int>("Z()", globals: c, globalsType: typeof(I)); Assert.Equal(3, result.Result); } [Fact] public void HostObjectBinding_StaticMembers() { var s0 = CSharpScript.RunAsync("static int goo = StaticField;", globals: new C()); var s1 = s0.ContinueWith("static int bar { get { return goo; } }"); var s2 = s1.ContinueWith("class C { public static int baz() { return bar; } }"); var s3 = s2.ContinueWith("C.baz()"); Assert.Equal(123, s3.Result.ReturnValue); } public class D { public int goo(int a) { return 0; } } /// <summary> /// Host object members don't form a method group with submission members. /// </summary> [Fact] public void HostObjectBinding_Overloads() { var s0 = CSharpScript.RunAsync("int goo(double a) { return 2; }", globals: new D()); var s1 = s0.ContinueWith("goo(1)"); Assert.Equal(2, s1.Result.ReturnValue); var s2 = s1.ContinueWith("goo(1.0)"); Assert.Equal(2, s2.Result.ReturnValue); } [Fact] public void HostObjectInRootNamespace() { var obj = new InteractiveFixtures_TopLevelHostObject { X = 1, Y = 2, Z = 3 }; var r0 = CSharpScript.EvaluateAsync<int>("X + Y + Z", globals: obj); Assert.Equal(6, r0.Result); obj = new InteractiveFixtures_TopLevelHostObject { X = 1, Y = 2, Z = 3 }; var r1 = CSharpScript.EvaluateAsync<int>("X", globals: obj); Assert.Equal(1, r1.Result); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30303")] public void HostObjectAssemblyReference1() { var scriptCompilation = CSharpScript.Create( "nameof(Microsoft.CodeAnalysis.Scripting)", ScriptOptions.Default.WithMetadataResolver(TestRuntimeMetadataReferenceResolver.Instance), globalsType: typeof(CommandLineScriptGlobals)).GetCompilation(); scriptCompilation.VerifyDiagnostics( // (1,8): error CS0234: The type or namespace name 'CodeAnalysis' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?) // nameof(Microsoft.CodeAnalysis.Scripting) Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "Microsoft.CodeAnalysis").WithArguments("CodeAnalysis", "Microsoft").WithLocation(1, 8)); string corAssemblyName = typeof(object).GetTypeInfo().Assembly.GetName().Name; string hostObjectAssemblyName = scriptCompilation.ScriptCompilationInfo.GlobalsType.GetTypeInfo().Assembly.GetName().Name; // The host adds // 1) a reference to typeof(object).Assembly // 2) a reference to GlobalsType with alias <host> applied recursively. // References returned from ResolveMissingAssembly have <implicit> alias. foreach (var (assembly, aliases) in scriptCompilation.GetBoundReferenceManager().GetReferencedAssemblyAliases()) { string name = assembly.Identity.Name; switch (name) { case "Microsoft.CodeAnalysis.CSharp.Scripting": case "Microsoft.CodeAnalysis.CSharp": // assemblies not referenced Assert.False(true); break; case "Microsoft.CodeAnalysis": case "System.Collections.Immutable": // Microsoft.CodeAnalysis.Scripting contains host object and is thus referenced recursively with <host> alias. // The script doesn't reference the assemblies explicitly. AssertEx.SetEqual(new[] { "<implicit>", "<host>" }, aliases); break; default: if (name == corAssemblyName) { // Host object depends on System.Object, thus <host> is applied on CorLib. AssertEx.SetEqual(new[] { "<host>", "global" }, aliases); } else if (name == hostObjectAssemblyName) { // Host object is only referenced by the host and thus the assembly is hidden behind <host> alias. AssertEx.SetEqual(new[] { "<host>" }, aliases); } break; } } } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/dotnet/roslyn/issues/30303")] public void HostObjectAssemblyReference2() { var scriptCompilation = CSharpScript.Create( "typeof(Microsoft.CodeAnalysis.Scripting.Script)", options: ScriptOptions.Default. WithMetadataResolver(TestRuntimeMetadataReferenceResolver.Instance). WithReferences(typeof(CSharpScript).GetTypeInfo().Assembly), globalsType: typeof(CommandLineScriptGlobals)).GetCompilation(); scriptCompilation.VerifyDiagnostics(); string corAssemblyName = typeof(object).GetTypeInfo().Assembly.GetName().Name; string hostObjectAssemblyName = scriptCompilation.ScriptCompilationInfo.GlobalsType.GetTypeInfo().Assembly.GetName().Name; // The host adds // 1) a reference to typeof(object).Assembly // 2) a reference to GlobalsType with alias <host> applied recursively. // References returned from ResolveMissingAssembly have <implicit> alias. foreach (var (assembly, aliases) in scriptCompilation.GetBoundReferenceManager().GetReferencedAssemblyAliases()) { string name = assembly.Identity.Name; switch (name) { case "Microsoft.CodeAnalysis.CSharp.Scripting": // we have an explicit reference to CSharpScript assembly: AssertEx.SetEqual(Array.Empty<string>(), aliases); break; case "Microsoft.CodeAnalysis.CSharp": // The script has a recursive reference to Microsoft.CodeAnalysis.CSharp.Scripting, which references these assemblies. // The script doesn't reference the assembly explicitly. AssertEx.SetEqual(new[] { "<implicit>", "global" }, aliases); break; case "Microsoft.CodeAnalysis": case "System.Collections.Immutable": // The script has a recursive reference to Microsoft.CodeAnalysis.CSharp.Scripting, which references these assemblies. // Microsoft.CodeAnalysis.Scripting contains host object and is thus referenced recursively with <host> alias. // The script doesn't reference the assemblies explicitly. AssertEx.SetEqual(new[] { "<implicit>", "<host>", "global" }, aliases); break; default: if (name == corAssemblyName) { // Host object depends on System.Object, thus <host> is applied on CorLib. AssertEx.SetEqual(new[] { "<host>", "global" }, aliases); } else if (name == hostObjectAssemblyName) { // Host object is defined in an assembly that CSharpScript depends on. // CSharpScript assembly was references (recursively) hence host object assembly is // available to the script (global alias). AssertEx.SetEqual(new[] { "<host>", "global" }, aliases); } break; } } } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/dotnet/roslyn/issues/30303")] public void HostObjectAssemblyReference3() { string source = $@" #r ""{typeof(CSharpScript).GetTypeInfo().Assembly.ManifestModule.FullyQualifiedName}"" typeof(Microsoft.CodeAnalysis.Scripting.Script) "; var scriptCompilation = CSharpScript.Create( source, ScriptOptions.Default.WithMetadataResolver(TestRuntimeMetadataReferenceResolver.Instance), globalsType: typeof(CommandLineScriptGlobals)).GetCompilation(); scriptCompilation.VerifyDiagnostics(); string corAssemblyName = typeof(object).GetTypeInfo().Assembly.GetName().Name; string hostObjectAssemblyName = scriptCompilation.ScriptCompilationInfo.GlobalsType.GetTypeInfo().Assembly.GetName().Name; // The host adds // 1) a reference to typeof(object).Assembly // 2) a reference to GlobalsType with alias <host> applied recursively. // References returned from ResolveMissingAssembly have <implicit> alias. foreach (var (assembly, aliases) in scriptCompilation.GetBoundReferenceManager().GetReferencedAssemblyAliases()) { string name = assembly.Identity.Name; switch (name) { case "Microsoft.CodeAnalysis.CSharp.Scripting": // we have an explicit reference to CSharpScript assembly: AssertEx.SetEqual(Array.Empty<string>(), aliases); break; case "Microsoft.CodeAnalysis.CSharp": // The script has a recursive reference to Microsoft.CodeAnalysis.CSharp.Scripting, which references these assemblies. // The script doesn't reference the assembly explicitly. AssertEx.SetEqual(new[] { "<implicit>", "global" }, aliases); break; case "Microsoft.CodeAnalysis": case "System.Collections.Immutable": // The script has a recursive reference to Microsoft.CodeAnalysis.CSharp.Scripting, which references these assemblies. // Microsoft.CodeAnalysis.Scripting contains host object and is thus referenced recursively with <host> alias. // The script doesn't reference the assemblies explicitly. AssertEx.SetEqual(new[] { "<implicit>", "<host>", "global" }, aliases); break; default: if (name == corAssemblyName) { // Host object depends on System.Object, thus <host> is applied on CorLib. AssertEx.SetEqual(new[] { "<host>", "global" }, aliases); } else if (name == hostObjectAssemblyName) { // Host object is defined in an assembly that CSharpScript depends on. // CSharpScript assembly was references (recursively) hence host object assembly is // available to the script (global alias). AssertEx.SetEqual(new[] { "<host>", "global" }, aliases); } break; } } } public class E { public bool TryGetValue(out object obj) { obj = new object(); return true; } } [Fact] [WorkItem(39565, "https://github.com/dotnet/roslyn/issues/39565")] public async Task MethodCallWithImplicitReceiverAndOutVar() { var code = @" if(TryGetValue(out var result)){ _ = result; } return true; "; var result = await CSharpScript.EvaluateAsync<bool>(code, globalsType: typeof(E), globals: new E()); Assert.True(result); } public class F { public bool Value = true; } [Fact] public void StaticMethodCannotAccessGlobalInstance() { var code = @" static bool M() { return Value; } return M(); "; var script = CSharpScript.Create<bool>(code, globalsType: typeof(F)); ScriptingTestHelpers.AssertCompilationError(() => script.RunAsync(new F()).Wait(), // (4,9): error CS0120: An object reference is required for the non-static field, method, or property 'InteractiveSessionTests.F.Value' // return Value; Diagnostic(ErrorCode.ERR_ObjectRequired, "Value").WithArguments("Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests.InteractiveSessionTests.F.Value").WithLocation(4, 9)); } [Fact] [WorkItem(39581, "https://github.com/dotnet/roslyn/issues/39581")] public void StaticLocalFunctionCannotAccessGlobalInstance() { var code = @" bool M() { return Inner(); static bool Inner() { return Value; } } return M(); "; var script = CSharpScript.Create<bool>(code, globalsType: typeof(F)); ScriptingTestHelpers.AssertCompilationError(() => script.RunAsync(new F()).Wait(), // (7,10): error CS0120: An object reference is required for the non-static field, method, or property 'InteractiveSessionTests.F.Value' // return Value; Diagnostic(ErrorCode.ERR_ObjectRequired, "Value").WithArguments("Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests.InteractiveSessionTests.F.Value").WithLocation(7, 10)); } [Fact] public async Task LocalFunctionCanAccessGlobalInstance() { var code = @" bool M() { return Inner(); bool Inner() { return Value; } } return M(); "; var result = await CSharpScript.EvaluateAsync<bool>(code, globalsType: typeof(F), globals: new F()); Assert.True(result); } #endregion #region Exceptions [Fact] [WorkItem(6580, "https://github.com/dotnet/roslyn/issues/6580")] [WorkItem(10883, "https://github.com/dotnet/roslyn/issues/10883")] public async Task PreservingDeclarationsOnException1() { var s0 = CSharpScript.Create(@" int i = 10; throw new System.Exception(""Bang!""); int j = 2; "); var s1 = s0.ContinueWith(@" int F() => i + j; "); var state1 = await s1.RunAsync(catchException: e => true); Assert.Equal("Bang!", state1.Exception.Message); var state2 = await state1.ContinueWithAsync<int>("F()"); Assert.Equal(10, state2.ReturnValue); } [Fact] [WorkItem(6580, "https://github.com/dotnet/roslyn/issues/6580")] [WorkItem(10883, "https://github.com/dotnet/roslyn/issues/10883")] public async Task PreservingDeclarationsOnException2() { var s0 = CSharpScript.Create(@" int i = 100; "); var s1 = s0.ContinueWith(@" int j = 20; throw new System.Exception(""Bang!""); int k = 3; "); var s2 = s1.ContinueWith(@" int F() => i + j + k; "); var state2 = await s2.RunAsync(catchException: e => true); Assert.Equal("Bang!", state2.Exception.Message); var state3 = await state2.ContinueWithAsync<int>("F()"); Assert.Equal(120, state3.ReturnValue); } [Fact] [WorkItem(6580, "https://github.com/dotnet/roslyn/issues/6580")] [WorkItem(10883, "https://github.com/dotnet/roslyn/issues/10883")] public async Task PreservingDeclarationsOnException3() { var s0 = CSharpScript.Create(@" int i = 1000; "); var s1 = s0.ContinueWith(@" int j = 200; throw new System.Exception(""Bang!""); int k = 30; "); var s2 = s1.ContinueWith(@" int l = 4; "); var s3 = s2.ContinueWith(@" int F() => i + j + k + l; "); var state3 = await s3.RunAsync(catchException: e => true); Assert.Equal("Bang!", state3.Exception.Message); var state4 = await state3.ContinueWithAsync<int>("F()"); Assert.Equal(1200, state4.ReturnValue); } [Fact] [WorkItem(6580, "https://github.com/dotnet/roslyn/issues/6580")] [WorkItem(10883, "https://github.com/dotnet/roslyn/issues/10883")] public async Task PreservingDeclarationsOnException4() { var state0 = await CSharpScript.RunAsync(@" int i = 1000; "); var state1 = await state0.ContinueWithAsync(@" int j = 200; throw new System.Exception(""Bang 1!""); int k = 30; ", catchException: e => true); Assert.Equal("Bang 1!", state1.Exception.Message); var state2 = await state1.ContinueWithAsync<int>(@" int l = 4; throw new System.Exception(""Bang 2!""); 1 ", catchException: e => true); Assert.Equal("Bang 2!", state2.Exception.Message); var state4 = await state2.ContinueWithAsync(@" i + j + k + l "); Assert.Equal(1204, state4.ReturnValue); } [Fact] public async Task PreservingDeclarationsOnCancellation1() { var cancellationSource = new CancellationTokenSource(); var globals = new StrongBox<CancellationTokenSource>(); globals.Value = cancellationSource; var s0 = CSharpScript.Create(@" int i = 1000; ", globalsType: globals.GetType()); var s1 = s0.ContinueWith(@" int j = 200; Value.Cancel(); int k = 30; "); // cancellation exception is thrown just before we start evaluating s2: var s2 = s1.ContinueWith(@" int l = 4; "); var s3 = s2.ContinueWith(@" int F() => i + j + k + l; "); var state3 = await s3.RunAsync(globals, catchException: e => true, cancellationToken: cancellationSource.Token); Assert.IsType<OperationCanceledException>(state3.Exception); var state4 = await state3.ContinueWithAsync<int>("F()"); Assert.Equal(1230, state4.ReturnValue); } [Fact] public async Task PreservingDeclarationsOnCancellation2() { var cancellationSource = new CancellationTokenSource(); var globals = new StrongBox<CancellationTokenSource>(); globals.Value = cancellationSource; var s0 = CSharpScript.Create(@" int i = 1000; ", globalsType: globals.GetType()); var s1 = s0.ContinueWith(@" int j = 200; int k = 30; "); var s2 = s1.ContinueWith(@" int l = 4; Value.Cancel(); "); // cancellation exception is thrown just before we start evaluating s3: var s3 = s2.ContinueWith(@" int F() => i + j + k + l; "); var state3 = await s3.RunAsync(globals, catchException: e => true, cancellationToken: cancellationSource.Token); Assert.IsType<OperationCanceledException>(state3.Exception); var state4 = await state3.ContinueWithAsync<int>("F()"); Assert.Equal(1234, state4.ReturnValue); } [Fact] public async Task PreservingDeclarationsOnCancellation3() { var cancellationSource = new CancellationTokenSource(); var globals = new StrongBox<CancellationTokenSource>(); globals.Value = cancellationSource; var s0 = CSharpScript.Create(@" int i = 1000; ", globalsType: globals.GetType()); var s1 = s0.ContinueWith(@" int j = 200; Value.Cancel(); int k = 30; "); // cancellation exception is thrown just before we start evaluating s2: var s2 = s1.ContinueWith(@" int l = 4; "); var s3 = s2.ContinueWith(@" int F() => i + j + k + l; "); await Assert.ThrowsAsync<OperationCanceledException>(() => s3.RunAsync(globals, catchException: e => !(e is OperationCanceledException), cancellationToken: cancellationSource.Token)); } #endregion #region Local Functions [Fact] public void LocalFunction_PreviousSubmissionAndGlobal() { var result = CSharpScript.RunAsync( @"int InInitialSubmission() { return LocalFunction(); int LocalFunction() => Y; }", globals: new C()). ContinueWith( @"var lambda = new System.Func<int>(() => { return LocalFunction(); int LocalFunction() => Y + InInitialSubmission(); }); lambda.Invoke()"). Result.ReturnValue; Assert.Equal(4, result); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.Scripting.Hosting; using Microsoft.CodeAnalysis.Scripting.Test; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests { using static TestCompilationFactory; public class HostModel { public readonly int Goo; } public class InteractiveSessionTests : TestBase { internal static readonly Assembly HostAssembly = typeof(InteractiveSessionTests).GetTypeInfo().Assembly; #region Namespaces, Types [Fact(Skip = "https://github.com/dotnet/roslyn/issues/17869")] public void CompilationChain_NestedTypesClass() { var script = CSharpScript.Create(@" static string outerStr = null; public static void Goo(string str) { outerStr = str; } class InnerClass { public string innerStr = null; public void Goo() { Goo(""test""); innerStr = outerStr; } } ").ContinueWith(@" InnerClass iC = new InnerClass(); iC.Goo(); ").ContinueWith(@" System.Console.WriteLine(iC.innerStr); "); ScriptingTestHelpers.RunScriptWithOutput(script, "test"); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/17869")] public void CompilationChain_NestedTypesStruct() { var script = CSharpScript.Create(@" static string outerStr = null; public static void Goo(string str) { outerStr = str; } struct InnerStruct { public string innerStr; public void Goo() { Goo(""test""); innerStr = outerStr; } } ").ContinueWith(@" InnerStruct iS = new InnerStruct(); iS.Goo(); ").ContinueWith(@" System.Console.WriteLine(iS.innerStr); "); ScriptingTestHelpers.RunScriptWithOutput(script, "test"); } [Fact] public async Task CompilationChain_InterfaceTypes() { var script = CSharpScript.Create(@" interface I1 { int Goo();} class InnerClass : I1 { public int Goo() { return 1; } }").ContinueWith(@" I1 iC = new InnerClass(); ").ContinueWith(@" iC.Goo() "); Assert.Equal(1, await script.EvaluateAsync()); } [Fact] public void ScriptMemberAccessFromNestedClass() { var script = CSharpScript.Create(@" object field; object Property { get; set; } void Method() { } ").ContinueWith(@" class C { public void Goo() { object f = field; object p = Property; Method(); } } "); ScriptingTestHelpers.AssertCompilationError(script, // (6,20): error CS0120: An object reference is required for the non-static field, method, or property 'field' Diagnostic(ErrorCode.ERR_ObjectRequired, "field").WithArguments("field"), // (7,20): error CS0120: An object reference is required for the non-static field, method, or property 'Property' Diagnostic(ErrorCode.ERR_ObjectRequired, "Property").WithArguments("Property"), // (8,9): error CS0120: An object reference is required for the non-static field, method, or property 'Method()' Diagnostic(ErrorCode.ERR_ObjectRequired, "Method").WithArguments("Method()")); } #region Anonymous Types [Fact] public void AnonymousTypes_TopLevel_MultipleSubmissions() { var script = CSharpScript.Create(@" var a = new { f = 1 }; ").ContinueWith(@" var b = new { g = 1 }; ").ContinueWith<Array>(@" var c = new { f = 1 }; var d = new { g = 1 }; new object[] { new[] { a, c }, new[] { b, d } } "); var result = script.EvaluateAsync().Result; Assert.Equal(2, result.Length); Assert.Equal(2, ((Array)result.GetValue(0)).Length); Assert.Equal(2, ((Array)result.GetValue(1)).Length); } [Fact] public void AnonymousTypes_TopLevel_MultipleSubmissions2() { var script = CSharpScript.Create(@" var a = new { f = 1 }; ").ContinueWith(@" var b = new { g = 1 }; ").ContinueWith(@" var c = new { f = 1 }; var d = new { g = 1 }; object.ReferenceEquals(a.GetType(), c.GetType()).ToString() + "" "" + object.ReferenceEquals(a.GetType(), b.GetType()).ToString() + "" "" + object.ReferenceEquals(b.GetType(), d.GetType()).ToString() "); Assert.Equal("True False True", script.EvaluateAsync().Result.ToString()); } [WorkItem(543863, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543863")] [Fact] public void AnonymousTypes_Redefinition() { var script = CSharpScript.Create(@" var x = new { Goo = ""goo"" }; ").ContinueWith(@" var x = new { Goo = ""goo"" }; ").ContinueWith(@" x.Goo "); var result = script.EvaluateAsync().Result; Assert.Equal("goo", result); } [Fact] public void AnonymousTypes_TopLevel_Empty() { var script = CSharpScript.Create(@" var a = new { }; ").ContinueWith(@" var b = new { }; ").ContinueWith<Array>(@" var c = new { }; var d = new { }; new object[] { new[] { a, c }, new[] { b, d } } "); var result = script.EvaluateAsync().Result; Assert.Equal(2, result.Length); Assert.Equal(2, ((Array)result.GetValue(0)).Length); Assert.Equal(2, ((Array)result.GetValue(1)).Length); } #endregion #region Dynamic [Fact] public void Dynamic_Expando() { var options = ScriptOptions.Default. AddReferences( typeof(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException).GetTypeInfo().Assembly, typeof(System.Dynamic.ExpandoObject).GetTypeInfo().Assembly). AddImports( "System.Dynamic"); var script = CSharpScript.Create(@" dynamic expando = new ExpandoObject(); ", options).ContinueWith(@" expando.goo = 1; ").ContinueWith(@" expando.goo "); Assert.Equal(1, script.EvaluateAsync().Result); } #endregion [Fact] public void Enums() { var script = CSharpScript.Create(@" public enum Enum1 { A, B, C } Enum1 E = Enum1.C; E "); var e = script.EvaluateAsync().Result; Assert.True(e.GetType().GetTypeInfo().IsEnum, "Expected enum"); Assert.Equal(typeof(int), Enum.GetUnderlyingType(e.GetType())); } #endregion #region Attributes [Fact] public void PInvoke() { var source = @" using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [DllImport(""goo"", EntryPoint = ""bar"", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = true, SetLastError = true, BestFitMapping = true, ThrowOnUnmappableChar = true)] public static extern void M(); class C { } typeof(C) "; Type c = CSharpScript.EvaluateAsync<Type>(source).Result; var m = c.DeclaringType.GetTypeInfo().GetDeclaredMethod("M"); Assert.Equal(MethodImplAttributes.PreserveSig, m.MethodImplementationFlags); // Reflection synthesizes DllImportAttribute var dllImport = (DllImportAttribute)m.GetCustomAttributes(typeof(DllImportAttribute), inherit: false).Single(); Assert.True(dllImport.BestFitMapping); Assert.Equal(CallingConvention.Cdecl, dllImport.CallingConvention); Assert.Equal(CharSet.Unicode, dllImport.CharSet); Assert.True(dllImport.ExactSpelling); Assert.True(dllImport.SetLastError); Assert.True(dllImport.PreserveSig); Assert.True(dllImport.ThrowOnUnmappableChar); Assert.Equal("bar", dllImport.EntryPoint); Assert.Equal("goo", dllImport.Value); } #endregion // extension methods - must be private, can be top level #region Modifiers and Visibility [Fact] public void PrivateTopLevel() { var script = CSharpScript.Create<int>(@" private int goo() { return 1; } private static int bar() { return 10; } private static int f = 100; goo() + bar() + f "); Assert.Equal(111, script.EvaluateAsync().Result); script = script.ContinueWith<int>(@" goo() + bar() + f "); Assert.Equal(111, script.EvaluateAsync().Result); script = script.ContinueWith<int>(@" class C { public static int baz() { return bar() + f; } } C.baz() "); Assert.Equal(110, script.EvaluateAsync().Result); } [Fact] public void NestedVisibility() { var script = CSharpScript.Create(@" private class C { internal class D { internal static int goo() { return 1; } } private class E { internal static int goo() { return 1; } } public class F { internal protected static int goo() { return 1; } } internal protected class G { internal static int goo() { return 1; } } } "); Assert.Equal(1, script.ContinueWith<int>("C.D.goo()").EvaluateAsync().Result); Assert.Equal(1, script.ContinueWith<int>("C.F.goo()").EvaluateAsync().Result); Assert.Equal(1, script.ContinueWith<int>("C.G.goo()").EvaluateAsync().Result); ScriptingTestHelpers.AssertCompilationError(script.ContinueWith<int>(@"C.E.goo()"), // error CS0122: 'C.E' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "E").WithArguments("C.E")); } [Fact] public void Fields_Visibility() { var script = CSharpScript.Create(@" private int i = 2; // test comment; public int j = 2; protected int k = 2; internal protected int l = 2; internal int pi = 2; ").ContinueWith(@" i = i + i; j = j + j; k = k + k; l = l + l; ").ContinueWith(@" pi = i + j + k + l; "); Assert.Equal(4, script.ContinueWith<int>("i").EvaluateAsync().Result); Assert.Equal(4, script.ContinueWith<int>("j").EvaluateAsync().Result); Assert.Equal(4, script.ContinueWith<int>("k").EvaluateAsync().Result); Assert.Equal(4, script.ContinueWith<int>("l").EvaluateAsync().Result); Assert.Equal(16, script.ContinueWith<int>("pi").EvaluateAsync().Result); } [WorkItem(100639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/100639")] [Fact] public void ExternDestructor() { var script = CSharpScript.Create( @"class C { extern ~C(); }"); Assert.Null(script.EvaluateAsync().Result); } #endregion #region Chaining [Fact] public void CompilationChain_BasicFields() { var script = CSharpScript.Create("var x = 1;").ContinueWith("x"); Assert.Equal(1, script.EvaluateAsync().Result); } [Fact] public void CompilationChain_GlobalNamespaceAndUsings() { var result = CSharpScript.Create("using InteractiveFixtures.C;", ScriptOptions.Default.AddReferences(HostAssembly)). ContinueWith("using InteractiveFixtures.C;"). ContinueWith("System.Environment.ProcessorCount"). EvaluateAsync().Result; Assert.Equal(Environment.ProcessorCount, result); } [Fact] public void CompilationChain_CurrentSubmissionUsings() { var s0 = CSharpScript.RunAsync("", ScriptOptions.Default.AddReferences(HostAssembly)); var state = s0. ContinueWith("class X { public int goo() { return 1; } }"). ContinueWith("class X { public int goo() { return 1; } }"). ContinueWith("using InteractiveFixtures.A;"). ContinueWith("new X().goo()"); Assert.Equal(1, state.Result.ReturnValue); state = s0. ContinueWith("class X { public int goo() { return 1; } }"). ContinueWith(@" using InteractiveFixtures.A; new X().goo() "); Assert.Equal(1, state.Result.ReturnValue); } [Fact] public void CompilationChain_UsingDuplicates() { var script = CSharpScript.Create(@" using System; using System; ").ContinueWith(@" using System; using System; ").ContinueWith(@" Environment.ProcessorCount "); Assert.Equal(Environment.ProcessorCount, script.EvaluateAsync().Result); } [Fact] public void CompilationChain_GlobalImports() { var options = ScriptOptions.Default.AddImports("System"); var state = CSharpScript.RunAsync("Environment.ProcessorCount", options); Assert.Equal(Environment.ProcessorCount, state.Result.ReturnValue); state = state.ContinueWith("Environment.ProcessorCount"); Assert.Equal(Environment.ProcessorCount, state.Result.ReturnValue); } [Fact] public void CompilationChain_Accessibility() { // Submissions have internal and protected access to one another. var state1 = CSharpScript.RunAsync("internal class C1 { } protected int X; 1"); var compilation1 = state1.Result.Script.GetCompilation(); compilation1.VerifyDiagnostics( // (1,39): warning CS0628: 'X': new protected member declared in sealed type // internal class C1 { } protected int X; 1 Diagnostic(ErrorCode.WRN_ProtectedInSealed, "X").WithArguments("X").WithLocation(1, 39) ); Assert.Equal(1, state1.Result.ReturnValue); var state2 = state1.ContinueWith("internal class C2 : C1 { } 2"); var compilation2 = state2.Result.Script.GetCompilation(); compilation2.VerifyDiagnostics(); Assert.Equal(2, state2.Result.ReturnValue); var c2C2 = (INamedTypeSymbol)lookupMember(compilation2, "Submission#1", "C2"); var c2C1 = c2C2.BaseType; var c2X = lookupMember(compilation1, "Submission#0", "X"); Assert.True(compilation2.IsSymbolAccessibleWithin(c2C1, c2C2)); Assert.True(compilation2.IsSymbolAccessibleWithin(c2C2, c2C1)); Assert.True(compilation2.IsSymbolAccessibleWithin(c2X, c2C2)); // access not enforced among submission symbols var state3 = state2.ContinueWith("private class C3 : C2 { } 3"); var compilation3 = state3.Result.Script.GetCompilation(); compilation3.VerifyDiagnostics(); Assert.Equal(3, state3.Result.ReturnValue); var c3C3 = (INamedTypeSymbol)lookupMember(compilation3, "Submission#2", "C3"); var c3C1 = c3C3.BaseType; Assert.Throws<ArgumentException>(() => compilation2.IsSymbolAccessibleWithin(c3C3, c3C1)); Assert.True(compilation3.IsSymbolAccessibleWithin(c3C3, c3C1)); INamedTypeSymbol lookupType(Compilation c, string name) { return c.GlobalNamespace.GetMembers(name).Single() as INamedTypeSymbol; } ISymbol lookupMember(Compilation c, string typeName, string memberName) { return lookupType(c, typeName).GetMembers(memberName).Single(); } } [Fact] public void CompilationChain_SubmissionSlotResize() { var state = CSharpScript.RunAsync(""); for (int i = 0; i < 17; i++) { state = state.ContinueWith(@"public int i = 1;"); } ScriptingTestHelpers.ContinueRunScriptWithOutput(state, @"System.Console.WriteLine(i);", "1"); } [Fact] public void CompilationChain_UsingNotHidingPreviousSubmission() { int result1 = CSharpScript.Create("using System;"). ContinueWith("int Environment = 1;"). ContinueWith<int>("Environment"). EvaluateAsync().Result; Assert.Equal(1, result1); int result2 = CSharpScript.Create("int Environment = 1;"). ContinueWith("using System;"). ContinueWith<int>("Environment"). EvaluateAsync().Result; Assert.Equal(1, result2); } [Fact] public void CompilationChain_DefinitionHidesGlobal() { var result = CSharpScript.Create("int System = 1;"). ContinueWith("System"). EvaluateAsync().Result; Assert.Equal(1, result); } public class C1 { public readonly int System = 1; public readonly int Environment = 2; } /// <summary> /// Symbol declaration in host object model hides global definition. /// </summary> [Fact] public void CompilationChain_HostObjectMembersHidesGlobal() { var result = CSharpScript.RunAsync("System", globals: new C1()). Result.ReturnValue; Assert.Equal(1, result); } [Fact] public void CompilationChain_UsingNotHidingHostObjectMembers() { var result = CSharpScript.RunAsync("using System;", globals: new C1()). ContinueWith("Environment"). Result.ReturnValue; Assert.Equal(2, result); } [Fact] public void CompilationChain_DefinitionHidesHostObjectMembers() { var result = CSharpScript.RunAsync("int System = 2;", globals: new C1()). ContinueWith("System"). Result.ReturnValue; Assert.Equal(2, result); } [Fact] public void Submissions_ExecutionOrder1() { var s0 = CSharpScript.Create("int x = 1;"); var s1 = s0.ContinueWith("int y = 2;"); var s2 = s1.ContinueWith<int>("x + y"); Assert.Equal(3, s2.EvaluateAsync().Result); Assert.Null(s1.EvaluateAsync().Result); Assert.Null(s0.EvaluateAsync().Result); Assert.Equal(3, s2.EvaluateAsync().Result); Assert.Null(s1.EvaluateAsync().Result); Assert.Null(s0.EvaluateAsync().Result); Assert.Equal(3, s2.EvaluateAsync().Result); Assert.Equal(3, s2.EvaluateAsync().Result); } [Fact] public async Task Submissions_ExecutionOrder2() { var s0 = await CSharpScript.RunAsync("int x = 1;"); Assert.Throws<CompilationErrorException>(() => s0.ContinueWithAsync("invalid$syntax").Result); var s1 = await s0.ContinueWithAsync("x = 2; x = 10"); Assert.Throws<CompilationErrorException>(() => s1.ContinueWithAsync("invalid$syntax").Result); Assert.Throws<CompilationErrorException>(() => s1.ContinueWithAsync("x = undefined_symbol").Result); var s2 = await s1.ContinueWithAsync("int y = 2;"); Assert.Null(s2.ReturnValue); var s3 = await s2.ContinueWithAsync("x + y"); Assert.Equal(12, s3.ReturnValue); } public class HostObjectWithOverrides { public override bool Equals(object obj) => true; public override int GetHashCode() => 1234567; public override string ToString() => "HostObjectToString impl"; } [Fact] public async Task ObjectOverrides1() { var state0 = await CSharpScript.RunAsync("", globals: new HostObjectWithOverrides()); var state1 = await state0.ContinueWithAsync<bool>("Equals(null)"); Assert.True(state1.ReturnValue); var state2 = await state1.ContinueWithAsync<int>("GetHashCode()"); Assert.Equal(1234567, state2.ReturnValue); var state3 = await state2.ContinueWithAsync<string>("ToString()"); Assert.Equal("HostObjectToString impl", state3.ReturnValue); } [Fact] public async Task ObjectOverrides2() { var state0 = await CSharpScript.RunAsync("", globals: new object()); var state1 = await state0.ContinueWithAsync<bool>(@" object x = 1; object y = x; ReferenceEquals(x, y)"); Assert.True(state1.ReturnValue); var state2 = await state1.ContinueWithAsync<string>("ToString()"); Assert.Equal("System.Object", state2.ReturnValue); var state3 = await state2.ContinueWithAsync<bool>("Equals(null)"); Assert.False(state3.ReturnValue); } [Fact] public void ObjectOverrides3() { var state0 = CSharpScript.RunAsync(""); var src1 = @" Equals(null); GetHashCode(); ToString(); ReferenceEquals(null, null);"; ScriptingTestHelpers.AssertCompilationError(state0, src1, // (2,1): error CS0103: The name 'Equals' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "Equals").WithArguments("Equals"), // (3,1): error CS0103: The name 'GetHashCode' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "GetHashCode").WithArguments("GetHashCode"), // (4,1): error CS0103: The name 'ToString' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "ToString").WithArguments("ToString"), // (5,1): error CS0103: The name 'ReferenceEquals' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "ReferenceEquals").WithArguments("ReferenceEquals")); var src2 = @" public override string ToString() { return null; } "; ScriptingTestHelpers.AssertCompilationError(state0, src2, // (1,24): error CS0115: 'ToString()': no suitable method found to override Diagnostic(ErrorCode.ERR_OverrideNotExpected, "ToString").WithArguments("ToString()")); } #endregion #region Generics [Fact, WorkItem(201759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/201759")] public void CompilationChain_GenericTypes() { var script = CSharpScript.Create(@" class InnerClass<T> { public int method(int value) { return value + 1; } public int field = 2; }").ContinueWith(@" InnerClass<int> iC = new InnerClass<int>(); ").ContinueWith(@" iC.method(iC.field) "); Assert.Equal(3, script.EvaluateAsync().Result); } [WorkItem(529243, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529243")] [Fact] public void RecursiveBaseType() { CSharpScript.EvaluateAsync(@" class A<T> { } class B<T> : A<B<B<T>>> { } "); } [WorkItem(5378, "DevDiv_Projects/Roslyn")] [Fact] public void CompilationChain_GenericMethods() { var s0 = CSharpScript.Create(@" public int goo<T, R>(T arg) { return 1; } public static T bar<T>(T i) { return i; } "); Assert.Equal(1, s0.ContinueWith(@"goo<int, int>(1)").EvaluateAsync().Result); Assert.Equal(5, s0.ContinueWith(@"bar(5)").EvaluateAsync().Result); } /// <summary> /// Tests that we emit ldftn and ldvirtftn instructions correctly. /// </summary> [Fact] public void CompilationChain_Ldftn() { var state = CSharpScript.RunAsync(@" public class C { public static int f() { return 1; } public int g() { return 10; } public virtual int h() { return 100; } public static int gf<T>() { return 2; } public int gg<T>() { return 20; } public virtual int gh<T>() { return 200; } } "); state = state.ContinueWith(@" new System.Func<int>(C.f)() + new System.Func<int>(new C().g)() + new System.Func<int>(new C().h)()" ); Assert.Equal(111, state.Result.ReturnValue); state = state.ContinueWith(@" new System.Func<int>(C.gf<int>)() + new System.Func<int>(new C().gg<object>)() + new System.Func<int>(new C().gh<bool>)() "); Assert.Equal(222, state.Result.ReturnValue); } /// <summary> /// Tests that we emit ldftn and ldvirtftn instructions correctly. /// </summary> [Fact] public void CompilationChain_Ldftn_GenericType() { var state = CSharpScript.RunAsync(@" public class C<S> { public static int f() { return 1; } public int g() { return 10; } public virtual int h() { return 100; } public static int gf<T>() { return 2; } public int gg<T>() { return 20; } public virtual int gh<T>() { return 200; } } "); state = state.ContinueWith(@" new System.Func<int>(C<byte>.f)() + new System.Func<int>(new C<byte>().g)() + new System.Func<int>(new C<byte>().h)() "); Assert.Equal(111, state.Result.ReturnValue); state = state.ContinueWith(@" new System.Func<int>(C<byte>.gf<int>)() + new System.Func<int>(new C<byte>().gg<object>)() + new System.Func<int>(new C<byte>().gh<bool>)() "); Assert.Equal(222, state.Result.ReturnValue); } #endregion #region Statements and Expressions [Fact] public void IfStatement() { var result = CSharpScript.EvaluateAsync<int>(@" using static System.Console; int x; if (true) { x = 5; } else { x = 6; } x ").Result; Assert.Equal(5, result); } [Fact] public void ExprStmtParenthesesUsedToOverrideDefaultEval() { Assert.Equal(18, CSharpScript.EvaluateAsync<int>("(4 + 5) * 2").Result); Assert.Equal(1, CSharpScript.EvaluateAsync<long>("6 / (2 * 3)").Result); } [WorkItem(5397, "DevDiv_Projects/Roslyn")] [Fact] public void TopLevelLambda() { var s = CSharpScript.RunAsync(@" using System; delegate void TestDelegate(string s); "); s = s.ContinueWith(@" TestDelegate testDelB = delegate (string s) { Console.WriteLine(s); }; "); ScriptingTestHelpers.ContinueRunScriptWithOutput(s, @"testDelB(""hello"");", "hello"); } [Fact] public void Closure() { var f = CSharpScript.EvaluateAsync<Func<int, int>>(@" int Goo(int arg) { return arg + 1; } System.Func<int, int> f = (arg) => { return Goo(arg); }; f ").Result; Assert.Equal(3, f(2)); } [Fact] public void Closure2() { var result = CSharpScript.EvaluateAsync<List<string>>(@" #r ""System.Core"" using System; using System.Linq; using System.Collections.Generic; List<string> result = new List<string>(); string s = ""hello""; Enumerable.ToList(Enumerable.Range(1, 2)).ForEach(x => result.Add(s)); result ").Result; AssertEx.Equal(new[] { "hello", "hello" }, result); } [Fact] public void UseDelegateMixStaticAndDynamic() { var f = CSharpScript.RunAsync("using System;"). ContinueWith("int Sqr(int x) {return x*x;}"). ContinueWith<Func<int, int>>("new Func<int,int>(Sqr)").Result.ReturnValue; Assert.Equal(4, f(2)); } [WorkItem(9229, "DevDiv_Projects/Roslyn")] [Fact] public void Arrays() { var s = CSharpScript.RunAsync(@" int[] arr_1 = { 1, 2, 3 }; int[] arr_2 = new int[] { 1, 2, 3 }; int[] arr_3 = new int[5]; ").ContinueWith(@" arr_2[0] = 5; "); Assert.Equal(3, s.ContinueWith(@"arr_1[2]").Result.ReturnValue); Assert.Equal(5, s.ContinueWith(@"arr_2[0]").Result.ReturnValue); Assert.Equal(0, s.ContinueWith(@"arr_3[0]").Result.ReturnValue); } [Fact] public void FieldInitializers() { var result = CSharpScript.EvaluateAsync<List<int>>(@" using System.Collections.Generic; static List<int> result = new List<int>(); int b = 2; int a; int x = 1, y = b; static int g = 1; static int f = g + 1; a = x + y; result.Add(a); int z = 4 + f; result.Add(z); result.Add(a * z); result ").Result; Assert.Equal(3, result.Count); Assert.Equal(3, result[0]); Assert.Equal(6, result[1]); Assert.Equal(18, result[2]); } [Fact] public void FieldInitializersWithBlocks() { var result = CSharpScript.EvaluateAsync<List<int>>(@" using System.Collections.Generic; static List<int> result = new List<int>(); const int constant = 1; { int x = constant; result.Add(x); } int field = 2; { int x = field; result.Add(x); } result.Add(constant); result.Add(field); result ").Result; Assert.Equal(4, result.Count); Assert.Equal(1, result[0]); Assert.Equal(2, result[1]); Assert.Equal(1, result[2]); Assert.Equal(2, result[3]); } [Fact] public void TestInteractiveClosures() { var result = CSharpScript.RunAsync(@" using System.Collections.Generic; static List<int> result = new List<int>();"). ContinueWith("int x = 1;"). ContinueWith("System.Func<int> f = () => x++;"). ContinueWith("result.Add(f());"). ContinueWith("result.Add(x);"). ContinueWith<List<int>>("result").Result.ReturnValue; Assert.Equal(2, result.Count); Assert.Equal(1, result[0]); Assert.Equal(2, result[1]); } [Fact] public void ExtensionMethods() { var options = ScriptOptions.Default.AddReferences( typeof(Enumerable).GetTypeInfo().Assembly); var result = CSharpScript.EvaluateAsync<int>(@" using System.Linq; string[] fruit = { ""banana"", ""orange"", ""lime"", ""apple"", ""kiwi"" }; fruit.Skip(1).Where(s => s.Length > 4).Count()", options).Result; Assert.Equal(2, result); } [Fact] public void ImplicitlyTypedFields() { var result = CSharpScript.EvaluateAsync<object[]>(@" var x = 1; var y = x; var z = goo(x); string goo(int a) { return null; } int goo(string a) { return 0; } new object[] { x, y, z } ").Result; AssertEx.Equal(new object[] { 1, 1, null }, result); } /// <summary> /// Name of PrivateImplementationDetails type needs to be unique across submissions. /// The compiler should suffix it with a MVID of the current submission module so we should be fine. /// </summary> [WorkItem(949559, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/949559")] [WorkItem(540237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540237")] [WorkItem(9229, "DevDiv_Projects/Roslyn")] [WorkItem(2721, "https://github.com/dotnet/roslyn/issues/2721")] [Fact] public async Task PrivateImplementationDetailsType() { var result1 = await CSharpScript.EvaluateAsync<int[]>("new int[] { 1,2,3,4 }"); AssertEx.Equal(new[] { 1, 2, 3, 4 }, result1); var result2 = await CSharpScript.EvaluateAsync<int[]>("new int[] { 1,2,3,4,5 }"); AssertEx.Equal(new[] { 1, 2, 3, 4, 5 }, result2); var s1 = await CSharpScript.RunAsync<int[]>("new int[] { 1,2,3,4,5,6 }"); AssertEx.Equal(new[] { 1, 2, 3, 4, 5, 6 }, s1.ReturnValue); var s2 = await s1.ContinueWithAsync<int[]>("new int[] { 1,2,3,4,5,6,7 }"); AssertEx.Equal(new[] { 1, 2, 3, 4, 5, 6, 7 }, s2.ReturnValue); var s3 = await s2.ContinueWithAsync<int[]>("new int[] { 1,2,3,4,5,6,7,8 }"); AssertEx.Equal(new[] { 1, 2, 3, 4, 5, 6, 7, 8 }, s3.ReturnValue); } [Fact] public void NoAwait() { // No await. The return value is Task<int> rather than int. var result = CSharpScript.EvaluateAsync("System.Threading.Tasks.Task.FromResult(1)").Result; Assert.Equal(1, ((Task<int>)result).Result); } /// <summary> /// 'await' expression at top-level. /// </summary> [Fact] public void Await() { Assert.Equal(2, CSharpScript.EvaluateAsync("await System.Threading.Tasks.Task.FromResult(2)").Result); } /// <summary> /// 'await' in sub-expression. /// </summary> [Fact] public void AwaitSubExpression() { Assert.Equal(3, CSharpScript.EvaluateAsync<int>("0 + await System.Threading.Tasks.Task.FromResult(3)").Result); } [Fact] public void AwaitVoid() { var task = CSharpScript.EvaluateAsync<object>("await System.Threading.Tasks.Task.Run(() => { })"); Assert.Null(task.Result); Assert.Equal(TaskStatus.RanToCompletion, task.Status); } /// <summary> /// 'await' in lambda should be ignored. /// </summary> [Fact] public async Task AwaitInLambda() { var s0 = await CSharpScript.RunAsync(@" using System; using System.Threading.Tasks; static T F<T>(Func<Task<T>> f) { return f().Result; } static T G<T>(T t, Func<T, Task<T>> f) { return f(t).Result; }"); var s1 = await s0.ContinueWithAsync("F(async () => await Task.FromResult(4))"); Assert.Equal(4, s1.ReturnValue); var s2 = await s1.ContinueWithAsync("G(5, async x => await Task.FromResult(x))"); Assert.Equal(5, s2.ReturnValue); } [Fact] public void AwaitChain1() { var options = ScriptOptions.Default. AddReferences(typeof(Task).GetTypeInfo().Assembly). AddImports("System.Threading.Tasks"); var state = CSharpScript.RunAsync("int i = 0;", options). ContinueWith("await Task.Delay(1); i++;"). ContinueWith("await Task.Delay(1); i++;"). ContinueWith("await Task.Delay(1); i++;"). ContinueWith("i"). Result; Assert.Equal(3, state.ReturnValue); } [Fact] public void AwaitChain2() { var options = ScriptOptions.Default. AddReferences(typeof(Task).GetTypeInfo().Assembly). AddImports("System.Threading.Tasks"); var state = CSharpScript.Create("int i = 0;", options). ContinueWith("await Task.Delay(1); i++;"). ContinueWith("await Task.Delay(1); i++;"). RunAsync(). ContinueWith("await Task.Delay(1); i++;"). ContinueWith("i"). Result; Assert.Equal(3, state.ReturnValue); } [Fact, WorkItem(39548, "https://github.com/dotnet/roslyn/issues/39548")] public async Task PatternVariableDeclaration() { var state = await CSharpScript.RunAsync("var x = (false, 4);"); state = await state.ContinueWithAsync("x is (false, var y)"); Assert.Equal(true, state.ReturnValue); } [Fact, WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")] public async Task CSharp9PatternForms() { var options = ScriptOptions.Default.WithLanguageVersion(MessageID.IDS_FeatureAndPattern.RequiredVersion()); var state = await CSharpScript.RunAsync("object x = 1;", options: options); state = await state.ContinueWithAsync("x is long or int", options: options); Assert.Equal(true, state.ReturnValue); state = await state.ContinueWithAsync("x is int and < 10", options: options); Assert.Equal(true, state.ReturnValue); state = await state.ContinueWithAsync("x is (long or < 10L)", options: options); Assert.Equal(false, state.ReturnValue); state = await state.ContinueWithAsync("x is not > 100", options: options); Assert.Equal(true, state.ReturnValue); } #endregion #region References [Fact(Skip = "https://github.com/dotnet/roslyn/issues/53391")] [WorkItem(15860, "https://github.com/dotnet/roslyn/issues/53391")] public void ReferenceDirective_FileWithDependencies() { var file1 = Temp.CreateFile(); var file2 = Temp.CreateFile(); var lib1 = CreateCSharpCompilationWithCorlib(@" public interface I { int F(); }"); lib1.Emit(file1.Path); var lib2 = CreateCSharpCompilation(@" public class C : I { public int F() => 1; }", new MetadataReference[] { TestReferences.NetStandard13.SystemRuntime, lib1.ToMetadataReference() }); lib2.Emit(file2.Path); object result = CSharpScript.EvaluateAsync($@" #r ""{file1.Path}"" #r ""{file2.Path}"" new C() ").Result; Assert.NotNull(result); } [ConditionalFact(typeof(WindowsOnly)), WorkItem(15860, "https://github.com/dotnet/roslyn/issues/15860")] public void ReferenceDirective_RelativeToBaseParent() { var file = Temp.CreateFile(); var lib = CreateCSharpCompilationWithCorlib("public class C {}"); lib.Emit(file.Path); string dir = Path.Combine(Path.GetDirectoryName(file.Path), "subdir"); string libFileName = Path.GetFileName(file.Path); string scriptPath = Path.Combine(dir, "a.csx"); var script = CSharpScript.Create( $@"#r ""{Path.Combine("..", libFileName)}""", ScriptOptions.Default.WithFilePath(scriptPath)); script.GetCompilation().VerifyDiagnostics(); } [ConditionalFact(typeof(WindowsOnly)), WorkItem(15860, "https://github.com/dotnet/roslyn/issues/15860")] public void ReferenceDirective_RelativeToBaseRoot() { var file = Temp.CreateFile(); var lib = CreateCSharpCompilationWithCorlib("public class C {}"); lib.Emit(file.Path); string root = Path.GetPathRoot(file.Path); string unrooted = file.Path.Substring(root.Length); string dir = Path.Combine(root, "goo", "bar", "baz"); string scriptPath = Path.Combine(dir, "a.csx"); var script = CSharpScript.Create( $@"#r ""\{unrooted}""", ScriptOptions.Default.WithFilePath(scriptPath)); script.GetCompilation().VerifyDiagnostics(); } [Fact] public void ExtensionPriority1() { string mainName = "Main_" + Guid.NewGuid(); string libName = "Lib_" + Guid.NewGuid(); var libExe = CreateCSharpCompilationWithCorlib(@"public class C { public string F = ""exe""; }", libName); var libDll = CreateCSharpCompilationWithCorlib(@"public class C { public string F = ""dll""; }", libName); var libWinmd = CreateCSharpCompilationWithCorlib(@"public class C { public string F = ""winmd""; }", libName); var main = CreateCSharpCompilation( @"public static class M { public static readonly C X = new C(); }", new MetadataReference[] { TestReferences.NetStandard13.SystemRuntime, libExe.ToMetadataReference() }, mainName); var exeImage = libExe.EmitToArray(); var dllImage = libDll.EmitToArray(); var winmdImage = libWinmd.EmitToArray(); var mainImage = main.EmitToArray(); var dir = Temp.CreateDirectory(); var fileMain = dir.CreateFile(mainName + ".dll").WriteAllBytes(mainImage); dir.CreateFile(libName + ".exe").WriteAllBytes(exeImage); dir.CreateFile(libName + ".winmd").WriteAllBytes(winmdImage); var r2 = CSharpScript.Create($@"#r ""{fileMain.Path}""").ContinueWith($@"M.X.F").RunAsync().Result.ReturnValue; Assert.Equal("exe", r2); } [Fact] public void ExtensionPriority2() { string mainName = "Main_" + Guid.NewGuid(); string libName = "Lib_" + Guid.NewGuid(); var libExe = CreateCSharpCompilationWithCorlib(@"public class C { public string F = ""exe""; }", libName); var libDll = CreateCSharpCompilationWithCorlib(@"public class C { public string F = ""dll""; }", libName); var libWinmd = CreateCSharpCompilationWithCorlib(@"public class C { public string F = ""winmd""; }", libName); var main = CreateCSharpCompilation( @"public static class M { public static readonly C X = new C(); }", new MetadataReference[] { TestReferences.NetStandard13.SystemRuntime, libExe.ToMetadataReference() }, mainName); var exeImage = libExe.EmitToArray(); var dllImage = libDll.EmitToArray(); var winmdImage = libWinmd.EmitToArray(); var mainImage = main.EmitToArray(); var dir = Temp.CreateDirectory(); var fileMain = dir.CreateFile(mainName + ".dll").WriteAllBytes(mainImage); dir.CreateFile(libName + ".exe").WriteAllBytes(exeImage); dir.CreateFile(libName + ".dll").WriteAllBytes(dllImage); dir.CreateFile(libName + ".winmd").WriteAllBytes(winmdImage); var r2 = CSharpScript.Create($@"#r ""{fileMain.Path}""").ContinueWith($@"M.X.F").RunAsync().Result.ReturnValue; Assert.Equal("dll", r2); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/6015")] public void UsingExternalAliasesForHiding() { string source = @" namespace N { public class C { } } public class D { } public class E { } "; var libRef = CreateCSharpCompilationWithCorlib(source, "lib").EmitToImageReference(); var script = CSharpScript.Create(@"new C()", ScriptOptions.Default.WithReferences(libRef.WithAliases(new[] { "Hidden" })).WithImports("Hidden::N")); script.Compile().Verify(); } #endregion #region UsingDeclarations [Fact] public void UsingAlias() { object result = CSharpScript.EvaluateAsync(@" using D = System.Collections.Generic.Dictionary<string, int>; D d = new D(); d ").Result; Assert.True(result is Dictionary<string, int>, "Expected Dictionary<string, int>"); } [WorkItem(9229, "DevDiv_Projects/Roslyn")] [Fact] public void Usings1() { var options = ScriptOptions.Default. AddImports("System", "System.Linq"). AddReferences(typeof(Enumerable).GetTypeInfo().Assembly); object result = CSharpScript.EvaluateAsync("new int[] { 1, 2, 3 }.First()", options).Result; Assert.Equal(1, result); } [WorkItem(9229, "DevDiv_Projects/Roslyn")] [Fact] public void Usings2() { var options = ScriptOptions.Default. AddImports("System", "System.Linq"). AddReferences(typeof(Enumerable).GetTypeInfo().Assembly); var s1 = CSharpScript.RunAsync("new int[] { 1, 2, 3 }.First()", options); Assert.Equal(1, s1.Result.ReturnValue); var s2 = s1.ContinueWith("new List<int>()", options.AddImports("System.Collections.Generic")); Assert.IsType<List<int>>(s2.Result.ReturnValue); } [Fact] public void AddNamespaces_Errors() { // no immediate error, error is reported if the namespace can't be found when compiling: var options = ScriptOptions.Default.AddImports("?1", "?2"); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("1", options), // error CS0246: The type or namespace name '?1' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound).WithArguments("?1"), // error CS0246: The type or namespace name '?2' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound).WithArguments("?2")); options = ScriptOptions.Default.AddImports(""); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("1", options), // error CS7088: Invalid 'Usings' value: ''. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "")); options = ScriptOptions.Default.AddImports(".abc"); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("1", options), // error CS7088: Invalid 'Usings' value: '.abc'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", ".abc")); options = ScriptOptions.Default.AddImports("a\0bc"); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("1", options), // error CS7088: Invalid 'Usings' value: '.abc'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "a\0bc")); } #endregion #region Host Object Binding and Conversions public class C<T> { } [Fact] public void Submission_HostConversions() { Assert.Equal(2, CSharpScript.EvaluateAsync<int>("1+1").Result); Assert.Null(CSharpScript.EvaluateAsync<string>("null").Result); try { CSharpScript.RunAsync<C<int>>("null"); Assert.True(false, "Expected an exception"); } catch (CompilationErrorException e) { // error CS0400: The type or namespace name 'Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Source.InteractiveSessionTests+C`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], Roslyn.Compilers.CSharp.Emit.UnitTests, Version=42.42.42.42, Culture=neutral, PublicKeyToken=fc793a00266884fb' could not be found in the global namespace (are you missing an assembly reference?) Assert.Equal(ErrorCode.ERR_GlobalSingleTypeNameNotFound, (ErrorCode)e.Diagnostics.Single().Code); // Can't use Verify() because the version number of the test dll is different in the build lab. } var options = ScriptOptions.Default.AddReferences(HostAssembly); var cint = CSharpScript.EvaluateAsync<C<int>>("null", options).Result; Assert.Null(cint); Assert.Null(CSharpScript.EvaluateAsync<int?>("null", options).Result); try { CSharpScript.RunAsync<int>("null"); Assert.True(false, "Expected an exception"); } catch (CompilationErrorException e) { e.Diagnostics.Verify( // (1,1): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // null Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int")); } try { CSharpScript.RunAsync<string>("1+1"); Assert.True(false, "Expected an exception"); } catch (CompilationErrorException e) { e.Diagnostics.Verify( // (1,1): error CS0029: Cannot implicitly convert type 'int' to 'string' // 1+1 Diagnostic(ErrorCode.ERR_NoImplicitConv, "1+1").WithArguments("int", "string")); } } [Fact] public void Submission_HostVarianceConversions() { var value = CSharpScript.EvaluateAsync<IEnumerable<Exception>>(@" using System; using System.Collections.Generic; new List<ArgumentException>() ").Result; Assert.Null(value.FirstOrDefault()); } public class B { public int x = 1, w = 4; } public class C : B, I { public static readonly int StaticField = 123; public int Y => 2; public string N { get; set; } = "2"; public int Z() => 3; public override int GetHashCode() => 123; } public interface I { string N { get; set; } int Z(); } private class PrivateClass : I { public string N { get; set; } = null; public int Z() => 3; } public class M<T> { private int F() => 3; public T G() => default(T); } [Fact] public void HostObjectBinding_PublicClassMembers() { var c = new C(); var s0 = CSharpScript.RunAsync<int>("x + Y + Z()", globals: c); Assert.Equal(6, s0.Result.ReturnValue); var s1 = s0.ContinueWith<int>("x"); Assert.Equal(1, s1.Result.ReturnValue); var s2 = s1.ContinueWith<int>("int x = 20;"); var s3 = s2.ContinueWith<int>("x"); Assert.Equal(20, s3.Result.ReturnValue); } [Fact] public void HostObjectBinding_PublicGenericClassMembers() { var m = new M<string>(); var result = CSharpScript.EvaluateAsync<string>("G()", globals: m); Assert.Null(result.Result); } [Fact] public async Task HostObjectBinding_Interface() { var c = new C(); var s0 = await CSharpScript.RunAsync<int>("Z()", globals: c, globalsType: typeof(I)); Assert.Equal(3, s0.ReturnValue); ScriptingTestHelpers.AssertCompilationError(s0, @"x + Y", // The name '{0}' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x"), Diagnostic(ErrorCode.ERR_NameNotInContext, "Y").WithArguments("Y")); var s1 = await s0.ContinueWithAsync<string>("N"); Assert.Equal("2", s1.ReturnValue); } [Fact] public void HostObjectBinding_PrivateClass() { var c = new PrivateClass(); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("Z()", globals: c), // (1,1): error CS0122: '<Fully Qualified Name of PrivateClass>.Z()' is inaccessible due to its protection level Diagnostic(ErrorCode.ERR_BadAccess, "Z").WithArguments(typeof(PrivateClass).FullName.Replace("+", ".") + ".Z()")); } [Fact] public void HostObjectBinding_PrivateMembers() { object c = new M<int>(); ScriptingTestHelpers.AssertCompilationError(() => CSharpScript.EvaluateAsync("Z()", globals: c), // (1,1): error CS0103: The name 'z' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, "Z").WithArguments("Z")); } [Fact] public void HostObjectBinding_PrivateClassImplementingPublicInterface() { var c = new PrivateClass(); var result = CSharpScript.EvaluateAsync<int>("Z()", globals: c, globalsType: typeof(I)); Assert.Equal(3, result.Result); } [Fact] public void HostObjectBinding_StaticMembers() { var s0 = CSharpScript.RunAsync("static int goo = StaticField;", globals: new C()); var s1 = s0.ContinueWith("static int bar { get { return goo; } }"); var s2 = s1.ContinueWith("class C { public static int baz() { return bar; } }"); var s3 = s2.ContinueWith("C.baz()"); Assert.Equal(123, s3.Result.ReturnValue); } public class D { public int goo(int a) { return 0; } } /// <summary> /// Host object members don't form a method group with submission members. /// </summary> [Fact] public void HostObjectBinding_Overloads() { var s0 = CSharpScript.RunAsync("int goo(double a) { return 2; }", globals: new D()); var s1 = s0.ContinueWith("goo(1)"); Assert.Equal(2, s1.Result.ReturnValue); var s2 = s1.ContinueWith("goo(1.0)"); Assert.Equal(2, s2.Result.ReturnValue); } [Fact] public void HostObjectInRootNamespace() { var obj = new InteractiveFixtures_TopLevelHostObject { X = 1, Y = 2, Z = 3 }; var r0 = CSharpScript.EvaluateAsync<int>("X + Y + Z", globals: obj); Assert.Equal(6, r0.Result); obj = new InteractiveFixtures_TopLevelHostObject { X = 1, Y = 2, Z = 3 }; var r1 = CSharpScript.EvaluateAsync<int>("X", globals: obj); Assert.Equal(1, r1.Result); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30303")] public void HostObjectAssemblyReference1() { var scriptCompilation = CSharpScript.Create( "nameof(Microsoft.CodeAnalysis.Scripting)", ScriptOptions.Default.WithMetadataResolver(TestRuntimeMetadataReferenceResolver.Instance), globalsType: typeof(CommandLineScriptGlobals)).GetCompilation(); scriptCompilation.VerifyDiagnostics( // (1,8): error CS0234: The type or namespace name 'CodeAnalysis' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?) // nameof(Microsoft.CodeAnalysis.Scripting) Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "Microsoft.CodeAnalysis").WithArguments("CodeAnalysis", "Microsoft").WithLocation(1, 8)); string corAssemblyName = typeof(object).GetTypeInfo().Assembly.GetName().Name; string hostObjectAssemblyName = scriptCompilation.ScriptCompilationInfo.GlobalsType.GetTypeInfo().Assembly.GetName().Name; // The host adds // 1) a reference to typeof(object).Assembly // 2) a reference to GlobalsType with alias <host> applied recursively. // References returned from ResolveMissingAssembly have <implicit> alias. foreach (var (assembly, aliases) in scriptCompilation.GetBoundReferenceManager().GetReferencedAssemblyAliases()) { string name = assembly.Identity.Name; switch (name) { case "Microsoft.CodeAnalysis.CSharp.Scripting": case "Microsoft.CodeAnalysis.CSharp": // assemblies not referenced Assert.False(true); break; case "Microsoft.CodeAnalysis": case "System.Collections.Immutable": // Microsoft.CodeAnalysis.Scripting contains host object and is thus referenced recursively with <host> alias. // The script doesn't reference the assemblies explicitly. AssertEx.SetEqual(new[] { "<implicit>", "<host>" }, aliases); break; default: if (name == corAssemblyName) { // Host object depends on System.Object, thus <host> is applied on CorLib. AssertEx.SetEqual(new[] { "<host>", "global" }, aliases); } else if (name == hostObjectAssemblyName) { // Host object is only referenced by the host and thus the assembly is hidden behind <host> alias. AssertEx.SetEqual(new[] { "<host>" }, aliases); } break; } } } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/dotnet/roslyn/issues/30303")] public void HostObjectAssemblyReference2() { var scriptCompilation = CSharpScript.Create( "typeof(Microsoft.CodeAnalysis.Scripting.Script)", options: ScriptOptions.Default. WithMetadataResolver(TestRuntimeMetadataReferenceResolver.Instance). WithReferences(typeof(CSharpScript).GetTypeInfo().Assembly), globalsType: typeof(CommandLineScriptGlobals)).GetCompilation(); scriptCompilation.VerifyDiagnostics(); string corAssemblyName = typeof(object).GetTypeInfo().Assembly.GetName().Name; string hostObjectAssemblyName = scriptCompilation.ScriptCompilationInfo.GlobalsType.GetTypeInfo().Assembly.GetName().Name; // The host adds // 1) a reference to typeof(object).Assembly // 2) a reference to GlobalsType with alias <host> applied recursively. // References returned from ResolveMissingAssembly have <implicit> alias. foreach (var (assembly, aliases) in scriptCompilation.GetBoundReferenceManager().GetReferencedAssemblyAliases()) { string name = assembly.Identity.Name; switch (name) { case "Microsoft.CodeAnalysis.CSharp.Scripting": // we have an explicit reference to CSharpScript assembly: AssertEx.SetEqual(Array.Empty<string>(), aliases); break; case "Microsoft.CodeAnalysis.CSharp": // The script has a recursive reference to Microsoft.CodeAnalysis.CSharp.Scripting, which references these assemblies. // The script doesn't reference the assembly explicitly. AssertEx.SetEqual(new[] { "<implicit>", "global" }, aliases); break; case "Microsoft.CodeAnalysis": case "System.Collections.Immutable": // The script has a recursive reference to Microsoft.CodeAnalysis.CSharp.Scripting, which references these assemblies. // Microsoft.CodeAnalysis.Scripting contains host object and is thus referenced recursively with <host> alias. // The script doesn't reference the assemblies explicitly. AssertEx.SetEqual(new[] { "<implicit>", "<host>", "global" }, aliases); break; default: if (name == corAssemblyName) { // Host object depends on System.Object, thus <host> is applied on CorLib. AssertEx.SetEqual(new[] { "<host>", "global" }, aliases); } else if (name == hostObjectAssemblyName) { // Host object is defined in an assembly that CSharpScript depends on. // CSharpScript assembly was references (recursively) hence host object assembly is // available to the script (global alias). AssertEx.SetEqual(new[] { "<host>", "global" }, aliases); } break; } } } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/dotnet/roslyn/issues/30303")] public void HostObjectAssemblyReference3() { string source = $@" #r ""{typeof(CSharpScript).GetTypeInfo().Assembly.ManifestModule.FullyQualifiedName}"" typeof(Microsoft.CodeAnalysis.Scripting.Script) "; var scriptCompilation = CSharpScript.Create( source, ScriptOptions.Default.WithMetadataResolver(TestRuntimeMetadataReferenceResolver.Instance), globalsType: typeof(CommandLineScriptGlobals)).GetCompilation(); scriptCompilation.VerifyDiagnostics(); string corAssemblyName = typeof(object).GetTypeInfo().Assembly.GetName().Name; string hostObjectAssemblyName = scriptCompilation.ScriptCompilationInfo.GlobalsType.GetTypeInfo().Assembly.GetName().Name; // The host adds // 1) a reference to typeof(object).Assembly // 2) a reference to GlobalsType with alias <host> applied recursively. // References returned from ResolveMissingAssembly have <implicit> alias. foreach (var (assembly, aliases) in scriptCompilation.GetBoundReferenceManager().GetReferencedAssemblyAliases()) { string name = assembly.Identity.Name; switch (name) { case "Microsoft.CodeAnalysis.CSharp.Scripting": // we have an explicit reference to CSharpScript assembly: AssertEx.SetEqual(Array.Empty<string>(), aliases); break; case "Microsoft.CodeAnalysis.CSharp": // The script has a recursive reference to Microsoft.CodeAnalysis.CSharp.Scripting, which references these assemblies. // The script doesn't reference the assembly explicitly. AssertEx.SetEqual(new[] { "<implicit>", "global" }, aliases); break; case "Microsoft.CodeAnalysis": case "System.Collections.Immutable": // The script has a recursive reference to Microsoft.CodeAnalysis.CSharp.Scripting, which references these assemblies. // Microsoft.CodeAnalysis.Scripting contains host object and is thus referenced recursively with <host> alias. // The script doesn't reference the assemblies explicitly. AssertEx.SetEqual(new[] { "<implicit>", "<host>", "global" }, aliases); break; default: if (name == corAssemblyName) { // Host object depends on System.Object, thus <host> is applied on CorLib. AssertEx.SetEqual(new[] { "<host>", "global" }, aliases); } else if (name == hostObjectAssemblyName) { // Host object is defined in an assembly that CSharpScript depends on. // CSharpScript assembly was references (recursively) hence host object assembly is // available to the script (global alias). AssertEx.SetEqual(new[] { "<host>", "global" }, aliases); } break; } } } public class E { public bool TryGetValue(out object obj) { obj = new object(); return true; } } [Fact] [WorkItem(39565, "https://github.com/dotnet/roslyn/issues/39565")] public async Task MethodCallWithImplicitReceiverAndOutVar() { var code = @" if(TryGetValue(out var result)){ _ = result; } return true; "; var result = await CSharpScript.EvaluateAsync<bool>(code, globalsType: typeof(E), globals: new E()); Assert.True(result); } public class F { public bool Value = true; } [Fact] public void StaticMethodCannotAccessGlobalInstance() { var code = @" static bool M() { return Value; } return M(); "; var script = CSharpScript.Create<bool>(code, globalsType: typeof(F)); ScriptingTestHelpers.AssertCompilationError(() => script.RunAsync(new F()).Wait(), // (4,9): error CS0120: An object reference is required for the non-static field, method, or property 'InteractiveSessionTests.F.Value' // return Value; Diagnostic(ErrorCode.ERR_ObjectRequired, "Value").WithArguments("Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests.InteractiveSessionTests.F.Value").WithLocation(4, 9)); } [Fact] [WorkItem(39581, "https://github.com/dotnet/roslyn/issues/39581")] public void StaticLocalFunctionCannotAccessGlobalInstance() { var code = @" bool M() { return Inner(); static bool Inner() { return Value; } } return M(); "; var script = CSharpScript.Create<bool>(code, globalsType: typeof(F)); ScriptingTestHelpers.AssertCompilationError(() => script.RunAsync(new F()).Wait(), // (7,10): error CS0120: An object reference is required for the non-static field, method, or property 'InteractiveSessionTests.F.Value' // return Value; Diagnostic(ErrorCode.ERR_ObjectRequired, "Value").WithArguments("Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests.InteractiveSessionTests.F.Value").WithLocation(7, 10)); } [Fact] public async Task LocalFunctionCanAccessGlobalInstance() { var code = @" bool M() { return Inner(); bool Inner() { return Value; } } return M(); "; var result = await CSharpScript.EvaluateAsync<bool>(code, globalsType: typeof(F), globals: new F()); Assert.True(result); } #endregion #region Exceptions [Fact] [WorkItem(6580, "https://github.com/dotnet/roslyn/issues/6580")] [WorkItem(10883, "https://github.com/dotnet/roslyn/issues/10883")] public async Task PreservingDeclarationsOnException1() { var s0 = CSharpScript.Create(@" int i = 10; throw new System.Exception(""Bang!""); int j = 2; "); var s1 = s0.ContinueWith(@" int F() => i + j; "); var state1 = await s1.RunAsync(catchException: e => true); Assert.Equal("Bang!", state1.Exception.Message); var state2 = await state1.ContinueWithAsync<int>("F()"); Assert.Equal(10, state2.ReturnValue); } [Fact] [WorkItem(6580, "https://github.com/dotnet/roslyn/issues/6580")] [WorkItem(10883, "https://github.com/dotnet/roslyn/issues/10883")] public async Task PreservingDeclarationsOnException2() { var s0 = CSharpScript.Create(@" int i = 100; "); var s1 = s0.ContinueWith(@" int j = 20; throw new System.Exception(""Bang!""); int k = 3; "); var s2 = s1.ContinueWith(@" int F() => i + j + k; "); var state2 = await s2.RunAsync(catchException: e => true); Assert.Equal("Bang!", state2.Exception.Message); var state3 = await state2.ContinueWithAsync<int>("F()"); Assert.Equal(120, state3.ReturnValue); } [Fact] [WorkItem(6580, "https://github.com/dotnet/roslyn/issues/6580")] [WorkItem(10883, "https://github.com/dotnet/roslyn/issues/10883")] public async Task PreservingDeclarationsOnException3() { var s0 = CSharpScript.Create(@" int i = 1000; "); var s1 = s0.ContinueWith(@" int j = 200; throw new System.Exception(""Bang!""); int k = 30; "); var s2 = s1.ContinueWith(@" int l = 4; "); var s3 = s2.ContinueWith(@" int F() => i + j + k + l; "); var state3 = await s3.RunAsync(catchException: e => true); Assert.Equal("Bang!", state3.Exception.Message); var state4 = await state3.ContinueWithAsync<int>("F()"); Assert.Equal(1200, state4.ReturnValue); } [Fact] [WorkItem(6580, "https://github.com/dotnet/roslyn/issues/6580")] [WorkItem(10883, "https://github.com/dotnet/roslyn/issues/10883")] public async Task PreservingDeclarationsOnException4() { var state0 = await CSharpScript.RunAsync(@" int i = 1000; "); var state1 = await state0.ContinueWithAsync(@" int j = 200; throw new System.Exception(""Bang 1!""); int k = 30; ", catchException: e => true); Assert.Equal("Bang 1!", state1.Exception.Message); var state2 = await state1.ContinueWithAsync<int>(@" int l = 4; throw new System.Exception(""Bang 2!""); 1 ", catchException: e => true); Assert.Equal("Bang 2!", state2.Exception.Message); var state4 = await state2.ContinueWithAsync(@" i + j + k + l "); Assert.Equal(1204, state4.ReturnValue); } [Fact] public async Task PreservingDeclarationsOnCancellation1() { var cancellationSource = new CancellationTokenSource(); var globals = new StrongBox<CancellationTokenSource>(); globals.Value = cancellationSource; var s0 = CSharpScript.Create(@" int i = 1000; ", globalsType: globals.GetType()); var s1 = s0.ContinueWith(@" int j = 200; Value.Cancel(); int k = 30; "); // cancellation exception is thrown just before we start evaluating s2: var s2 = s1.ContinueWith(@" int l = 4; "); var s3 = s2.ContinueWith(@" int F() => i + j + k + l; "); var state3 = await s3.RunAsync(globals, catchException: e => true, cancellationToken: cancellationSource.Token); Assert.IsType<OperationCanceledException>(state3.Exception); var state4 = await state3.ContinueWithAsync<int>("F()"); Assert.Equal(1230, state4.ReturnValue); } [Fact] public async Task PreservingDeclarationsOnCancellation2() { var cancellationSource = new CancellationTokenSource(); var globals = new StrongBox<CancellationTokenSource>(); globals.Value = cancellationSource; var s0 = CSharpScript.Create(@" int i = 1000; ", globalsType: globals.GetType()); var s1 = s0.ContinueWith(@" int j = 200; int k = 30; "); var s2 = s1.ContinueWith(@" int l = 4; Value.Cancel(); "); // cancellation exception is thrown just before we start evaluating s3: var s3 = s2.ContinueWith(@" int F() => i + j + k + l; "); var state3 = await s3.RunAsync(globals, catchException: e => true, cancellationToken: cancellationSource.Token); Assert.IsType<OperationCanceledException>(state3.Exception); var state4 = await state3.ContinueWithAsync<int>("F()"); Assert.Equal(1234, state4.ReturnValue); } [Fact] public async Task PreservingDeclarationsOnCancellation3() { var cancellationSource = new CancellationTokenSource(); var globals = new StrongBox<CancellationTokenSource>(); globals.Value = cancellationSource; var s0 = CSharpScript.Create(@" int i = 1000; ", globalsType: globals.GetType()); var s1 = s0.ContinueWith(@" int j = 200; Value.Cancel(); int k = 30; "); // cancellation exception is thrown just before we start evaluating s2: var s2 = s1.ContinueWith(@" int l = 4; "); var s3 = s2.ContinueWith(@" int F() => i + j + k + l; "); await Assert.ThrowsAsync<OperationCanceledException>(() => s3.RunAsync(globals, catchException: e => !(e is OperationCanceledException), cancellationToken: cancellationSource.Token)); } #endregion #region Local Functions [Fact] public void LocalFunction_PreviousSubmissionAndGlobal() { var result = CSharpScript.RunAsync( @"int InInitialSubmission() { return LocalFunction(); int LocalFunction() => Y; }", globals: new C()). ContinueWith( @"var lambda = new System.Func<int>(() => { return LocalFunction(); int LocalFunction() => Y + InInitialSubmission(); }); lambda.Invoke()"). Result.ReturnValue; Assert.Equal(4, result); } #endregion } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Features/LanguageServer/Protocol/Handler/Highlights/DocumentHighlightHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.DocumentHighlighting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { [ExportRoslynLanguagesLspRequestHandlerProvider, Shared] [ProvidesMethod(Methods.TextDocumentDocumentHighlightName)] internal class DocumentHighlightsHandler : AbstractStatelessRequestHandler<TextDocumentPositionParams, DocumentHighlight[]> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DocumentHighlightsHandler() { } public override string Method => Methods.TextDocumentDocumentHighlightName; public override bool MutatesSolutionState => false; public override bool RequiresLSPSolution => true; public override TextDocumentIdentifier? GetTextDocumentIdentifier(TextDocumentPositionParams request) => request.TextDocument; public override async Task<DocumentHighlight[]> HandleRequestAsync(TextDocumentPositionParams request, RequestContext context, CancellationToken cancellationToken) { var document = context.Document; if (document == null) { return Array.Empty<DocumentHighlight>(); } var documentHighlightService = document.Project.LanguageServices.GetRequiredService<IDocumentHighlightsService>(); var position = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(request.Position), cancellationToken).ConfigureAwait(false); var highlights = await documentHighlightService.GetDocumentHighlightsAsync( document, position, ImmutableHashSet.Create(document), cancellationToken).ConfigureAwait(false); if (!highlights.IsDefaultOrEmpty) { // LSP requests are only for a single document. So just get the highlights for the requested document. var highlightsForDocument = highlights.FirstOrDefault(h => h.Document.Id == document.Id); var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); return highlightsForDocument.HighlightSpans.Select(h => new DocumentHighlight { Range = ProtocolConversions.TextSpanToRange(h.TextSpan, text), Kind = ProtocolConversions.HighlightSpanKindToDocumentHighlightKind(h.Kind), }).ToArray(); } return Array.Empty<DocumentHighlight>(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.DocumentHighlighting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { [ExportRoslynLanguagesLspRequestHandlerProvider, Shared] [ProvidesMethod(Methods.TextDocumentDocumentHighlightName)] internal class DocumentHighlightsHandler : AbstractStatelessRequestHandler<TextDocumentPositionParams, DocumentHighlight[]> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DocumentHighlightsHandler() { } public override string Method => Methods.TextDocumentDocumentHighlightName; public override bool MutatesSolutionState => false; public override bool RequiresLSPSolution => true; public override TextDocumentIdentifier? GetTextDocumentIdentifier(TextDocumentPositionParams request) => request.TextDocument; public override async Task<DocumentHighlight[]> HandleRequestAsync(TextDocumentPositionParams request, RequestContext context, CancellationToken cancellationToken) { var document = context.Document; if (document == null) { return Array.Empty<DocumentHighlight>(); } var documentHighlightService = document.Project.LanguageServices.GetRequiredService<IDocumentHighlightsService>(); var position = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(request.Position), cancellationToken).ConfigureAwait(false); var highlights = await documentHighlightService.GetDocumentHighlightsAsync( document, position, ImmutableHashSet.Create(document), cancellationToken).ConfigureAwait(false); if (!highlights.IsDefaultOrEmpty) { // LSP requests are only for a single document. So just get the highlights for the requested document. var highlightsForDocument = highlights.FirstOrDefault(h => h.Document.Id == document.Id); var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); return highlightsForDocument.HighlightSpans.Select(h => new DocumentHighlight { Range = ProtocolConversions.TextSpanToRange(h.TextSpan, text), Kind = ProtocolConversions.HighlightSpanKindToDocumentHighlightKind(h.Kind), }).ToArray(); } return Array.Empty<DocumentHighlight>(); } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/CSharp/Test/Semantic/Semantics/AnonymousFunctionTests.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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [WorkItem(275, "https://github.com/dotnet/csharplang/issues/275")] [CompilerTrait(CompilerFeature.AnonymousFunctions)] public class AnonymousFunctionTests : CSharpTestBase { public static CSharpCompilation VerifyInPreview(string source, params DiagnosticDescription[] expected) => CreateCompilation(source, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics(expected); internal CompilationVerifier VerifyInPreview(CSharpTestSource source, string expectedOutput, Action<ModuleSymbol>? symbolValidator = null, params DiagnosticDescription[] expected) => CompileAndVerify( source, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.RegularPreview, symbolValidator: symbolValidator, expectedOutput: expectedOutput) .VerifyDiagnostics(expected); internal void VerifyInPreview(string source, string expectedOutput, string metadataName, string expectedIL) { verify(source); verify(source.Replace("static (", "(")); void verify(string source) { var verifier = CompileAndVerify( source, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.RegularPreview, symbolValidator: symbolValidator, expectedOutput: expectedOutput) .VerifyDiagnostics(); verifier.VerifyIL(metadataName, expectedIL); } void symbolValidator(ModuleSymbol module) { var method = module.GlobalNamespace.GetMember<MethodSymbol>(metadataName); // note that static anonymous functions do not guarantee that the lowered method will be static. Assert.False(method.IsStatic); } } [Fact] public void DisallowInNonPreview() { var source = @" using System; public class C { public static int a; public void F() { Func<int> f = static () => a; } }"; CreateCompilation(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (10,23): error CS8400: Feature 'static anonymous function' is not available in C# 8.0. Please use language version 9.0 or greater. // Func<int> f = static () => a; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "static").WithArguments("static anonymous function", "9.0").WithLocation(10, 23)); } [Fact] public void StaticLambdaCanReferenceStaticField() { var source = @" using System; public class C { public static int a; public static void Main() { Func<int> f = static () => a; a = 42; Console.Write(f()); } }"; VerifyInPreview( source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__1_0", expectedIL: @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldsfld ""int C.a"" IL_0005: ret } "); } [Fact] public void StaticLambdaCanReferenceStaticProperty() { var source = @" using System; public class C { static int A { get; set; } public static void Main() { Func<int> f = static () => A; A = 42; Console.Write(f()); } }"; VerifyInPreview( source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__4_0", expectedIL: @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""int C.A.get"" IL_0005: ret }"); } [Fact] public void StaticLambdaCanReferenceConstField() { var source = @" using System; public class C { public const int a = 42; public static void Main() { Func<int> f = static () => a; Console.Write(f()); } }"; VerifyInPreview( source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__1_0", expectedIL: @" { // Code size 3 (0x3) .maxstack 1 IL_0000: ldc.i4.s 42 IL_0002: ret }"); } [Fact] public void StaticLambdaCanReferenceConstLocal() { var source = @" using System; public class C { public static void Main() { const int a = 42; Func<int> f = static () => a; Console.Write(f()); } }"; VerifyInPreview( source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @" { // Code size 3 (0x3) .maxstack 1 IL_0000: ldc.i4.s 42 IL_0002: ret }"); } [Fact] public void StaticLambdaCanReturnConstLocal() { var source = @" using System; public class C { public static void Main() { Func<int> f = static () => { const int a = 42; return a; }; Console.Write(f()); } }"; VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @" { // Code size 8 (0x8) .maxstack 1 .locals init (int V_0) IL_0000: nop IL_0001: ldc.i4.s 42 IL_0003: stloc.0 IL_0004: br.s IL_0006 IL_0006: ldloc.0 IL_0007: ret }"); } [Fact] public void StaticLambdaCannotCaptureInstanceField() { var source = @" using System; public class C { public int a; public void F() { Func<int> f = static () => a; } }"; VerifyInPreview(source, // (10,36): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'. // Func<int> f = static () => a; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "a").WithLocation(10, 36)); } [Fact] public void StaticLambdaCannotCaptureInstanceProperty() { var source = @" using System; public class C { int A { get; } public void F() { Func<int> f = static () => A; } }"; VerifyInPreview(source, // (10,36): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'. // Func<int> f = static () => A; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "A").WithLocation(10, 36)); } [Fact] public void StaticLambdaCannotCaptureParameter() { var source = @" using System; public class C { public void F(int a) { Func<int> f = static () => a; } }"; VerifyInPreview(source, // (8,36): error CS8427: A static anonymous function cannot contain a reference to 'a'. // Func<int> f = static () => a; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "a").WithArguments("a").WithLocation(8, 36)); } [Fact] public void StaticLambdaCannotCaptureOuterLocal() { var source = @" using System; public class C { public void F() { int a; Func<int> f = static () => a; } }"; VerifyInPreview(source, // (9,36): error CS8427: A static anonymous function cannot contain a reference to 'a'. // Func<int> f = static () => a; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "a").WithArguments("a").WithLocation(9, 36), // (9,36): error CS0165: Use of unassigned local variable 'a' // Func<int> f = static () => a; Diagnostic(ErrorCode.ERR_UseDefViolation, "a").WithArguments("a").WithLocation(9, 36)); } [Fact] public void StaticLambdaCanReturnInnerLocal() { var source = @" using System; public class C { public static void Main() { Func<int> f = static () => { int a = 42; return a; }; Console.Write(f()); } }"; VerifyInPreview( source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @" { // Code size 10 (0xa) .maxstack 1 .locals init (int V_0, //a int V_1) IL_0000: nop IL_0001: ldc.i4.s 42 IL_0003: stloc.0 IL_0004: ldloc.0 IL_0005: stloc.1 IL_0006: br.s IL_0008 IL_0008: ldloc.1 IL_0009: ret }"); } [Fact] public void StaticLambdaCannotReferenceThis() { var source = @" using System; public class C { public void F() { Func<int> f = static () => { this.F(); return 0; }; } }"; VerifyInPreview(source, // (10,13): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'. // this.F(); Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "this").WithLocation(10, 13)); } [Fact] public void StaticLambdaCannotReferenceBase() { var source = @" using System; public class B { public virtual void F() { } } public class C : B { public override void F() { Func<int> f = static () => { base.F(); return 0; }; } }"; VerifyInPreview(source, // (15,13): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'. // base.F(); Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "base").WithLocation(15, 13)); } [Fact] public void StaticLambdaCannotReferenceInstanceLocalFunction() { var source = @" using System; public class C { public void F() { Func<int> f = static () => { F(); return 0; }; void F() {} } }"; VerifyInPreview(source, // (10,13): error CS8427: A static anonymous function cannot contain a reference to 'F'. // F(); Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "F()").WithArguments("F").WithLocation(10, 13)); } [Fact] public void StaticLambdaCanReferenceStaticLocalFunction() { var source = @" using System; public class C { public static void Main() { Func<int> f = static () => local(); Console.WriteLine(f()); static int local() => 42; } }"; VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""int C.<Main>g__local|0_1()"" IL_0005: ret }"); } [Fact] public void StaticLambdaCanHaveLocalsCapturedByInnerInstanceLambda() { var source = @" using System; public class C { public static void Main() { Func<int> f = static () => { int i = 42; Func<int> g = () => i; return g(); }; Console.Write(f()); } }"; VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @" { // Code size 39 (0x27) .maxstack 2 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 System.Func<int> V_1, //g int V_2) IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: nop IL_0007: ldloc.0 IL_0008: ldc.i4.s 42 IL_000a: stfld ""int C.<>c__DisplayClass0_0.i"" IL_000f: ldloc.0 IL_0010: ldftn ""int C.<>c__DisplayClass0_0.<Main>b__1()"" IL_0016: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001b: stloc.1 IL_001c: ldloc.1 IL_001d: callvirt ""int System.Func<int>.Invoke()"" IL_0022: stloc.2 IL_0023: br.s IL_0025 IL_0025: ldloc.2 IL_0026: ret }"); } [Fact] public void StaticLambdaCannotHaveLocalsCapturedByInnerStaticLambda() { var source = @" using System; public class C { public void F() { Func<int> f = static () => { int i = 0; Func<int> g = static () => i; return 0; }; } }"; VerifyInPreview(source, // (11,40): error CS8427: A static anonymous function cannot contain a reference to 'i'. // Func<int> g = static () => i; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 40)); } [Fact] public void InstanceLambdaCannotHaveLocalsCapturedByInnerStaticLambda() { var source = @" using System; public class C { public void F() { Func<int> f = () => { int i = 0; Func<int> g = static () => i; return 0; }; } }"; VerifyInPreview(source, // (11,40): error CS8427: A static anonymous function cannot contain a reference to 'i'. // Func<int> g = static () => i; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 40)); } [Fact] public void StaticLambdaCanHaveLocalsCapturedByInnerInstanceLocalFunction() { var source = @" using System; public class C { public static void Main() { Func<int> f = static () => { int i = 42; int g() => i; return g(); }; Console.Write(f()); } }"; VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @" { // Code size 23 (0x17) .maxstack 2 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 int V_1) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.s 42 IL_0005: stfld ""int C.<>c__DisplayClass0_0.i"" IL_000a: nop IL_000b: ldloca.s V_0 IL_000d: call ""int C.<Main>g__g|0_1(ref C.<>c__DisplayClass0_0)"" IL_0012: stloc.1 IL_0013: br.s IL_0015 IL_0015: ldloc.1 IL_0016: ret }"); } [Fact] public void StaticLambdaCannotHaveLocalsCapturedByInnerStaticLocalFunction() { var source = @" using System; public class C { public void F() { Func<int> f = static () => { int i = 0; static int g() => i; return g(); }; } }"; VerifyInPreview(source, // (11,31): error CS8421: A static local function cannot contain a reference to 'i'. // static int g() => i; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 31)); } [Fact] public void InstanceLambdaCannotHaveLocalsCapturedByInnerStaticLocalFunction() { var source = @" using System; public class C { public void F() { Func<int> f = () => { int i = 0; static int g() => i; return g(); }; } }"; VerifyInPreview(source, // (11,31): error CS8421: A static local function cannot contain a reference to 'i'. // static int g() => i; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 31)); } [Fact] public void StaticLocalFunctionCanHaveLocalsCapturedByInnerInstanceLocalFunction() { var source = @" using System; public class C { public static void Main() { static int f() { int i = 42; int g() => i; return g(); }; Console.Write(f()); } }"; var verifier = VerifyInPreview( source, expectedOutput: "42", symbolValidator); const string metadataName = "C.<Main>g__f|0_0"; if (RuntimeUtilities.IsCoreClrRuntime) { verifier.VerifyIL(metadataName, @" { // Code size 23 (0x17) .maxstack 2 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 int V_1) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.s 42 IL_0005: stfld ""int C.<>c__DisplayClass0_0.i"" IL_000a: nop IL_000b: ldloca.s V_0 IL_000d: call ""int C.<Main>g__g|0_1(ref C.<>c__DisplayClass0_0)"" IL_0012: stloc.1 IL_0013: br.s IL_0015 IL_0015: ldloc.1 IL_0016: ret }"); } void symbolValidator(ModuleSymbol module) { var method = module.GlobalNamespace.GetMember<MethodSymbol>(metadataName); Assert.True(method.IsStatic); } } [Fact] public void StaticLocalFunctionCannotHaveLocalsCapturedByInnerStaticLocalFunction() { var source = @" public class C { public void F() { static int f() { int i = 0; static int g() => i; return g(); }; } }"; VerifyInPreview(source, // (8,20): warning CS8321: The local function 'f' is declared but never used // static int f() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(8, 20), // (11,31): error CS8421: A static local function cannot contain a reference to 'i'. // static int g() => i; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 31)); } [Fact] public void InstanceLocalFunctionCannotHaveLocalsCapturedByInnerStaticLocalFunction() { var source = @" public class C { public void F() { int f() { int i = 0; static int g() => i; return g(); }; } }"; VerifyInPreview(source, // (8,13): warning CS8321: The local function 'f' is declared but never used // int f() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(8, 13), // (11,31): error CS8421: A static local function cannot contain a reference to 'i'. // static int g() => i; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 31)); } [Fact] public void StaticLocalFunctionCanHaveLocalsCapturedByInnerInstanceLambda() { var source = @" using System; public class C { public void F() { static int f() { int i = 0; Func<int> g = () => i; return g(); }; } }"; VerifyInPreview(source, // (8,20): warning CS8321: The local function 'f' is declared but never used // static int f() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(8, 20)); } [Fact] public void StaticLocalFunctionCannotHaveLocalsCapturedByInnerStaticLambda() { var source = @" using System; public class C { public void F() { static int f() { int i = 0; Func<int> g = static () => i; return g(); }; } }"; VerifyInPreview(source, // (8,20): warning CS8321: The local function 'f' is declared but never used // static int f() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(8, 20), // (11,40): error CS8427: A static anonymous function cannot contain a reference to 'i'. // Func<int> g = static () => i; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 40)); } [Fact] public void InstanceLocalFunctionCannotHaveLocalsCapturedByInnerStaticLambda() { var source = @" using System; public class C { public void F() { int f() { int i = 0; Func<int> g = static () => i; return g(); }; } }"; VerifyInPreview(source, // (8,13): warning CS8321: The local function 'f' is declared but never used // int f() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(8, 13), // (11,40): error CS8427: A static anonymous function cannot contain a reference to 'i'. // Func<int> g = static () => i; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 40)); } [Fact] public void StaticLambdaCanCallStaticMethod() { var source = @" using System; public class C { public static void Main() { Func<int> f = static () => M(); Console.Write(f()); } static int M() => 42; }"; VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""int C.M()"" IL_0005: ret } "); } [Fact] public void QueryInStaticLambdaCannotAccessThis() { var source = @" using System; using System.Linq; public class C { public static string[] args; public void F() { Func<int> f = static () => { var q = from a in args select M(a); return 0; }; } int M(string a) => 0; }"; VerifyInPreview(source, // (14,28): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'. // select M(a); Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "M").WithLocation(14, 28)); } [Fact] public void QueryInStaticLambdaCanReferenceStatic() { var source = @" using System; using System.Linq; using System.Collections.Generic; public class C { public static string[] args; public static void Main() { args = new[] { """" }; Func<IEnumerable<int>> f = static () => { var q = from a in args select M(a); return q; }; foreach (var x in f()) { Console.Write(x); } } static int M(string a) => 42; }"; VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__1_0", expectedIL: @" { // Code size 49 (0x31) .maxstack 3 .locals init (System.Collections.Generic.IEnumerable<int> V_0, //q System.Collections.Generic.IEnumerable<int> V_1) IL_0000: nop IL_0001: ldsfld ""string[] C.args"" IL_0006: ldsfld ""System.Func<string, int> C.<>c.<>9__1_1"" IL_000b: dup IL_000c: brtrue.s IL_0025 IL_000e: pop IL_000f: ldsfld ""C.<>c C.<>c.<>9"" IL_0014: ldftn ""int C.<>c.<Main>b__1_1(string)"" IL_001a: newobj ""System.Func<string, int>..ctor(object, System.IntPtr)"" IL_001f: dup IL_0020: stsfld ""System.Func<string, int> C.<>c.<>9__1_1"" IL_0025: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<string, int>(System.Collections.Generic.IEnumerable<string>, System.Func<string, int>)"" IL_002a: stloc.0 IL_002b: ldloc.0 IL_002c: stloc.1 IL_002d: br.s IL_002f IL_002f: ldloc.1 IL_0030: ret } "); } [Fact] public void InstanceLambdaInStaticLambdaCannotReferenceThis() { var source = @" using System; public class C { public void F() { Func<int> f = static () => { Func<int> g = () => { this.F(); return 0; }; return g(); }; } }"; VerifyInPreview(source, // (12,17): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'. // this.F(); Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "this").WithLocation(12, 17)); } [Fact] public void TestStaticAnonymousFunctions() { var source = @" using System; public class C { public void F() { Action<int> a = static delegate(int i) { }; Action<int> b = static a => { }; Action<int> c = static (a) => { }; } }"; var compilation = CreateCompilation(source); var syntaxTree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(syntaxTree); var root = syntaxTree.GetRoot(); var anonymousMethodSyntax = root.DescendantNodes().OfType<AnonymousMethodExpressionSyntax>().Single(); var simpleLambdaSyntax = root.DescendantNodes().OfType<SimpleLambdaExpressionSyntax>().Single(); var parenthesizedLambdaSyntax = root.DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var anonymousMethod = (IMethodSymbol)semanticModel.GetSymbolInfo(anonymousMethodSyntax).Symbol!; var simpleLambda = (IMethodSymbol)semanticModel.GetSymbolInfo(simpleLambdaSyntax).Symbol!; var parenthesizedLambda = (IMethodSymbol)semanticModel.GetSymbolInfo(parenthesizedLambdaSyntax).Symbol!; Assert.True(anonymousMethod.IsStatic); Assert.True(simpleLambda.IsStatic); Assert.True(parenthesizedLambda.IsStatic); } [Fact] public void TestNonStaticAnonymousFunctions() { var source = @" using System; public class C { public void F() { Action<int> a = delegate(int i) { }; Action<int> b = a => { }; Action<int> c = (a) => { }; } }"; var compilation = CreateCompilation(source); var syntaxTree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(syntaxTree); var root = syntaxTree.GetRoot(); var anonymousMethodSyntax = root.DescendantNodes().OfType<AnonymousMethodExpressionSyntax>().Single(); var simpleLambdaSyntax = root.DescendantNodes().OfType<SimpleLambdaExpressionSyntax>().Single(); var parenthesizedLambdaSyntax = root.DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var anonymousMethod = (IMethodSymbol)semanticModel.GetSymbolInfo(anonymousMethodSyntax).Symbol!; var simpleLambda = (IMethodSymbol)semanticModel.GetSymbolInfo(simpleLambdaSyntax).Symbol!; var parenthesizedLambda = (IMethodSymbol)semanticModel.GetSymbolInfo(parenthesizedLambdaSyntax).Symbol!; Assert.False(anonymousMethod.IsStatic); Assert.False(simpleLambda.IsStatic); Assert.False(parenthesizedLambda.IsStatic); } [Fact] public void TestStaticLambdaCallArgument() { var source = @" using System; public class C { public static void F(Func<string> fn) { Console.WriteLine(fn()); } public static void Main() { F(static () => ""hello""); } }"; VerifyInPreview(source, expectedOutput: "hello", metadataName: "C.<>c.<Main>b__1_0", expectedIL: @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldstr ""hello"" IL_0005: ret }"); } [Fact] public void TestStaticLambdaIndexerArgument() { var source = @" using System; public class C { public object this[Func<object> fn] { get { Console.WriteLine(fn()); return null; } } public static void Main() { _ = new C()[static () => ""hello""]; } }"; VerifyInPreview(source, expectedOutput: "hello", metadataName: "C.<>c.<Main>b__2_0", expectedIL: @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldstr ""hello"" IL_0005: ret }"); } [Fact] public void TestStaticDelegateCallArgument() { var source = @" using System; public class C { public static void F(Func<string> fn) { Console.WriteLine(fn()); } public static void Main() { F(static delegate() { return ""hello""; }); } }"; VerifyInPreview(source, expectedOutput: "hello", metadataName: "C.<>c.<Main>b__1_0", expectedIL: @" { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""hello"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret }"); } [Fact] public void StaticLambdaNameof() { var source = @" using System; public class C { public int w; public static int x; public static void F(Func<int, string> fn) { Console.WriteLine(fn(0)); } public static void Main() { int y = 0; F(static (int z) => { return nameof(w) + nameof(x) + nameof(y) + nameof(z); }); } }"; VerifyInPreview(source, expectedOutput: "wxyz", metadataName: "C.<>c.<Main>b__3_0", expectedIL: @" { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""wxyz"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret }"); } [Fact] public void StaticLambdaTypeParams() { var source = @" using System; public class C<T> { public static void F(Func<int, string> fn) { Console.WriteLine(fn(0)); } public static void M<U>() { F(static (int x) => { return default(T).ToString() + default(U).ToString(); }); } } public class Program { public static void Main() { C<int>.M<bool>(); } }"; verify(source); verify(source.Replace("static (", "(")); void verify(string source) { var verifier = CompileAndVerify( source, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular9, symbolValidator: symbolValidator, expectedOutput: "0False") .VerifyDiagnostics(); verifier.VerifyIL("C<T>.<>c__1<U>.<M>b__1_0", @" { // Code size 51 (0x33) .maxstack 3 .locals init (T V_0, U V_1, string V_2) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: dup IL_0004: initobj ""T"" IL_000a: constrained. ""T"" IL_0010: callvirt ""string object.ToString()"" IL_0015: ldloca.s V_1 IL_0017: dup IL_0018: initobj ""U"" IL_001e: constrained. ""U"" IL_0024: callvirt ""string object.ToString()"" IL_0029: call ""string string.Concat(string, string)"" IL_002e: stloc.2 IL_002f: br.s IL_0031 IL_0031: ldloc.2 IL_0032: ret }"); } void symbolValidator(ModuleSymbol module) { var method = module.GlobalNamespace.GetMember<MethodSymbol>("C.<>c__1.<M>b__1_0"); // note that static anonymous functions do not guarantee that the lowered method will be static. Assert.False(method.IsStatic); } } [Fact] public void StaticLambda_Nint() { var source = @" using System; local(static x => x + 1); void local(Func<nint, nint> fn) { Console.WriteLine(fn(0)); }"; VerifyInPreview(source, expectedOutput: "1", metadataName: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + ".<>c.<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">b__0_0", expectedIL: @" { // Code size 5 (0x5) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldc.i4.1 IL_0002: conv.i IL_0003: add IL_0004: ret }"); } [Fact] public void StaticLambda_ExpressionTree() { var source = @" using System; using System.Linq.Expressions; class C { static void Main() { local(static x => x + 1); static void local(Expression<Func<int, int>> fn) { Console.WriteLine(fn.Compile()(0)); } } }"; var verifier = VerifyInPreview(source, expectedOutput: "1"); verifier.VerifyIL("C.Main", @" { // Code size 72 (0x48) .maxstack 5 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: nop IL_0001: ldtoken ""int"" IL_0006: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000b: ldstr ""x"" IL_0010: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0015: stloc.0 IL_0016: ldloc.0 IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: ldtoken ""int"" IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0027: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_002c: call ""System.Linq.Expressions.BinaryExpression System.Linq.Expressions.Expression.Add(System.Linq.Expressions.Expression, System.Linq.Expressions.Expression)"" IL_0031: ldc.i4.1 IL_0032: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0037: dup IL_0038: ldc.i4.0 IL_0039: ldloc.0 IL_003a: stelem.ref IL_003b: call ""System.Linq.Expressions.Expression<System.Func<int, int>> System.Linq.Expressions.Expression.Lambda<System.Func<int, int>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0040: call ""void C.<Main>g__local|0_1(System.Linq.Expressions.Expression<System.Func<int, int>>)"" IL_0045: nop IL_0046: nop IL_0047: ret }"); } [Fact] public void StaticLambda_FunctionPointer_01() { var source = @" class C { unsafe void M() { delegate*<void> ptr = &static () => { }; ptr(); } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,32): error CS1525: Invalid expression term 'static' // delegate*<void> ptr = &static () => { }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "static").WithArguments("static").WithLocation(6, 32), // (6,32): error CS1002: ; expected // delegate*<void> ptr = &static () => { }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "static").WithLocation(6, 32), // (6,32): error CS0106: The modifier 'static' is not valid for this item // delegate*<void> ptr = &static () => { }; Diagnostic(ErrorCode.ERR_BadMemberFlag, "static").WithArguments("static").WithLocation(6, 32), // (6,40): error CS8124: Tuple must contain at least two elements. // delegate*<void> ptr = &static () => { }; Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(6, 40), // (6,42): error CS1001: Identifier expected // delegate*<void> ptr = &static () => { }; Diagnostic(ErrorCode.ERR_IdentifierExpected, "=>").WithLocation(6, 42), // (6,42): error CS1003: Syntax error, ',' expected // delegate*<void> ptr = &static () => { }; Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(6, 42), // (6,45): error CS1002: ; expected // delegate*<void> ptr = &static () => { }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(6, 45) ); } [Fact] public void StaticLambda_FunctionPointer_02() { var source = @" class C { unsafe void M() { delegate*<void> ptr = static () => { }; ptr(); } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,31): error CS1660: Cannot convert lambda expression to type 'delegate*<void>' because it is not a delegate type // delegate*<void> ptr = static () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "static () => { }").WithArguments("lambda expression", "delegate*<void>").WithLocation(6, 31) ); } [Fact] public void StaticAnonymousMethod_FunctionPointer_01() { var source = @" class C { unsafe void M() { delegate*<void> ptr = &static delegate() { }; ptr(); } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,32): error CS0211: Cannot take the address of the given expression // delegate*<void> ptr = &static delegate() { }; Diagnostic(ErrorCode.ERR_InvalidAddrOp, "static delegate() { }").WithLocation(6, 32) ); } [Fact] public void StaticAnonymousMethod_FunctionPointer_02() { var source = @" class C { unsafe void M() { delegate*<void> ptr = static delegate() { }; ptr(); } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,31): error CS1660: Cannot convert anonymous method to type 'delegate*<void>' because it is not a delegate type // delegate*<void> ptr = static delegate() { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "static delegate() { }").WithArguments("anonymous method", "delegate*<void>").WithLocation(6, 31) ); } [Fact] public void ConditionalExpr() { var source = @" using static System.Console; class C { static void M(bool b, System.Action a) { a = b ? () => Write(1) : a; a(); a = b ? static () => Write(2) : a; a(); a = b ? () => { Write(3); } : a; a(); a = b ? static () => { Write(4); } : a; a(); a = b ? a : () => { }; a = b ? a : static () => { }; a = b ? delegate() { Write(5); } : a; a(); a = b ? static delegate() { Write(6); } : a; a(); a = b ? a : delegate() { }; a = b ? a : static delegate() { }; } static void Main() { M(true, () => { }); } } "; CompileAndVerify(source, expectedOutput: "123456", parseOptions: TestOptions.Regular9); } [Fact] public void RefConditionalExpr() { var source = @" using static System.Console; class C { static void M(bool b, ref System.Action a) { a = ref b ? ref () => Write(1) : ref a; a(); a = ref b ? ref static () => Write(2) : ref a; a(); a = ref b ? ref () => { Write(3); } : ref a; a(); a = ref b ? ref static () => { Write(4); } : ref a; a(); a = ref b ? ref a : ref () => { }; a = ref b ? ref a : ref static () => { }; a = ref b ? ref delegate() { Write(5); } : ref a; a(); a = ref b ? ref static delegate() { Write(6); } : ref a; a(); a = ref b ? ref a : ref delegate() { }; a = b ? ref a : ref static delegate() { }; } } "; VerifyInPreview(source, // (8,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref () => Write(1) : ref a; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "() => Write(1)").WithLocation(8, 25), // (11,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref static () => Write(2) : ref a; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "static () => Write(2)").WithLocation(11, 25), // (14,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref () => { Write(3); } : ref a; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "() => { Write(3); }").WithLocation(14, 25), // (17,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref static () => { Write(4); } : ref a; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "static () => { Write(4); }").WithLocation(17, 25), // (20,33): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref a : ref () => { }; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "() => { }").WithLocation(20, 33), // (21,33): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref a : ref static () => { }; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "static () => { }").WithLocation(21, 33), // (23,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref delegate() { Write(5); } : ref a; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "delegate() { Write(5); }").WithLocation(23, 25), // (26,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref static delegate() { Write(6); } : ref a; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "static delegate() { Write(6); }").WithLocation(26, 25), // (29,33): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref a : ref delegate() { }; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "delegate() { }").WithLocation(29, 33), // (30,29): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = b ? ref a : ref static delegate() { }; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "static delegate() { }").WithLocation(30, 29) ); } [Fact] public void SwitchExpr() { var source = @" using static System.Console; class C { static void M(bool b, System.Action a) { a = b switch { true => () => Write(1), false => a }; a(); a = b switch { true => static () => Write(2), false => a }; a(); a = b switch { true => () => { Write(3); }, false => a }; a(); a = b switch { true => static () => { Write(4); }, false => a }; a(); a = b switch { true => a , false => () => { Write(0); } }; a = b switch { true => a , false => static () => { Write(0); } }; a = b switch { true => delegate() { Write(5); }, false => a }; a(); a = b switch { true => static delegate() { Write(6); }, false => a }; a(); a = b switch { true => a , false => delegate() { Write(0); } }; a = b switch { true => a , false => static delegate() { Write(0); } }; } static void Main() { M(true, () => { }); } } "; CompileAndVerify(source, expectedOutput: "123456", parseOptions: TestOptions.Regular9); } [Fact] public void DiscardParams() { var source = @" using System; class C { static void Main() { Action<int, int, string> fn = static (_, _, z) => Console.Write(z); fn(1, 2, ""hello""); fn = static delegate(int _, int _, string z) { Console.Write(z); }; fn(3, 4, "" world""); } } "; CompileAndVerify(source, expectedOutput: "hello world", parseOptions: TestOptions.Regular9); } [Fact] public void PrivateMemberAccessibility() { var source = @" using System; class C { private static void M1(int i) { Console.Write(i); } class Inner { static void Main() { Action a = static () => M1(1); a(); a = static delegate() { M1(2); }; a(); } } } "; verify(source); verify(source.Replace("static (", "(")); void verify(string source) { CompileAndVerify(source, expectedOutput: "12", parseOptions: TestOptions.Regular9); } } } }
 // Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [WorkItem(275, "https://github.com/dotnet/csharplang/issues/275")] [CompilerTrait(CompilerFeature.AnonymousFunctions)] public class AnonymousFunctionTests : CSharpTestBase { public static CSharpCompilation VerifyInPreview(string source, params DiagnosticDescription[] expected) => CreateCompilation(source, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics(expected); internal CompilationVerifier VerifyInPreview(CSharpTestSource source, string expectedOutput, Action<ModuleSymbol>? symbolValidator = null, params DiagnosticDescription[] expected) => CompileAndVerify( source, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.RegularPreview, symbolValidator: symbolValidator, expectedOutput: expectedOutput) .VerifyDiagnostics(expected); internal void VerifyInPreview(string source, string expectedOutput, string metadataName, string expectedIL) { verify(source); verify(source.Replace("static (", "(")); void verify(string source) { var verifier = CompileAndVerify( source, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.RegularPreview, symbolValidator: symbolValidator, expectedOutput: expectedOutput) .VerifyDiagnostics(); verifier.VerifyIL(metadataName, expectedIL); } void symbolValidator(ModuleSymbol module) { var method = module.GlobalNamespace.GetMember<MethodSymbol>(metadataName); // note that static anonymous functions do not guarantee that the lowered method will be static. Assert.False(method.IsStatic); } } [Fact] public void DisallowInNonPreview() { var source = @" using System; public class C { public static int a; public void F() { Func<int> f = static () => a; } }"; CreateCompilation(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (10,23): error CS8400: Feature 'static anonymous function' is not available in C# 8.0. Please use language version 9.0 or greater. // Func<int> f = static () => a; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "static").WithArguments("static anonymous function", "9.0").WithLocation(10, 23)); } [Fact] public void StaticLambdaCanReferenceStaticField() { var source = @" using System; public class C { public static int a; public static void Main() { Func<int> f = static () => a; a = 42; Console.Write(f()); } }"; VerifyInPreview( source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__1_0", expectedIL: @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldsfld ""int C.a"" IL_0005: ret } "); } [Fact] public void StaticLambdaCanReferenceStaticProperty() { var source = @" using System; public class C { static int A { get; set; } public static void Main() { Func<int> f = static () => A; A = 42; Console.Write(f()); } }"; VerifyInPreview( source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__4_0", expectedIL: @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""int C.A.get"" IL_0005: ret }"); } [Fact] public void StaticLambdaCanReferenceConstField() { var source = @" using System; public class C { public const int a = 42; public static void Main() { Func<int> f = static () => a; Console.Write(f()); } }"; VerifyInPreview( source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__1_0", expectedIL: @" { // Code size 3 (0x3) .maxstack 1 IL_0000: ldc.i4.s 42 IL_0002: ret }"); } [Fact] public void StaticLambdaCanReferenceConstLocal() { var source = @" using System; public class C { public static void Main() { const int a = 42; Func<int> f = static () => a; Console.Write(f()); } }"; VerifyInPreview( source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @" { // Code size 3 (0x3) .maxstack 1 IL_0000: ldc.i4.s 42 IL_0002: ret }"); } [Fact] public void StaticLambdaCanReturnConstLocal() { var source = @" using System; public class C { public static void Main() { Func<int> f = static () => { const int a = 42; return a; }; Console.Write(f()); } }"; VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @" { // Code size 8 (0x8) .maxstack 1 .locals init (int V_0) IL_0000: nop IL_0001: ldc.i4.s 42 IL_0003: stloc.0 IL_0004: br.s IL_0006 IL_0006: ldloc.0 IL_0007: ret }"); } [Fact] public void StaticLambdaCannotCaptureInstanceField() { var source = @" using System; public class C { public int a; public void F() { Func<int> f = static () => a; } }"; VerifyInPreview(source, // (10,36): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'. // Func<int> f = static () => a; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "a").WithLocation(10, 36)); } [Fact] public void StaticLambdaCannotCaptureInstanceProperty() { var source = @" using System; public class C { int A { get; } public void F() { Func<int> f = static () => A; } }"; VerifyInPreview(source, // (10,36): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'. // Func<int> f = static () => A; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "A").WithLocation(10, 36)); } [Fact] public void StaticLambdaCannotCaptureParameter() { var source = @" using System; public class C { public void F(int a) { Func<int> f = static () => a; } }"; VerifyInPreview(source, // (8,36): error CS8427: A static anonymous function cannot contain a reference to 'a'. // Func<int> f = static () => a; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "a").WithArguments("a").WithLocation(8, 36)); } [Fact] public void StaticLambdaCannotCaptureOuterLocal() { var source = @" using System; public class C { public void F() { int a; Func<int> f = static () => a; } }"; VerifyInPreview(source, // (9,36): error CS8427: A static anonymous function cannot contain a reference to 'a'. // Func<int> f = static () => a; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "a").WithArguments("a").WithLocation(9, 36), // (9,36): error CS0165: Use of unassigned local variable 'a' // Func<int> f = static () => a; Diagnostic(ErrorCode.ERR_UseDefViolation, "a").WithArguments("a").WithLocation(9, 36)); } [Fact] public void StaticLambdaCanReturnInnerLocal() { var source = @" using System; public class C { public static void Main() { Func<int> f = static () => { int a = 42; return a; }; Console.Write(f()); } }"; VerifyInPreview( source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @" { // Code size 10 (0xa) .maxstack 1 .locals init (int V_0, //a int V_1) IL_0000: nop IL_0001: ldc.i4.s 42 IL_0003: stloc.0 IL_0004: ldloc.0 IL_0005: stloc.1 IL_0006: br.s IL_0008 IL_0008: ldloc.1 IL_0009: ret }"); } [Fact] public void StaticLambdaCannotReferenceThis() { var source = @" using System; public class C { public void F() { Func<int> f = static () => { this.F(); return 0; }; } }"; VerifyInPreview(source, // (10,13): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'. // this.F(); Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "this").WithLocation(10, 13)); } [Fact] public void StaticLambdaCannotReferenceBase() { var source = @" using System; public class B { public virtual void F() { } } public class C : B { public override void F() { Func<int> f = static () => { base.F(); return 0; }; } }"; VerifyInPreview(source, // (15,13): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'. // base.F(); Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "base").WithLocation(15, 13)); } [Fact] public void StaticLambdaCannotReferenceInstanceLocalFunction() { var source = @" using System; public class C { public void F() { Func<int> f = static () => { F(); return 0; }; void F() {} } }"; VerifyInPreview(source, // (10,13): error CS8427: A static anonymous function cannot contain a reference to 'F'. // F(); Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "F()").WithArguments("F").WithLocation(10, 13)); } [Fact] public void StaticLambdaCanReferenceStaticLocalFunction() { var source = @" using System; public class C { public static void Main() { Func<int> f = static () => local(); Console.WriteLine(f()); static int local() => 42; } }"; VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""int C.<Main>g__local|0_1()"" IL_0005: ret }"); } [Fact] public void StaticLambdaCanHaveLocalsCapturedByInnerInstanceLambda() { var source = @" using System; public class C { public static void Main() { Func<int> f = static () => { int i = 42; Func<int> g = () => i; return g(); }; Console.Write(f()); } }"; VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @" { // Code size 39 (0x27) .maxstack 2 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 System.Func<int> V_1, //g int V_2) IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: nop IL_0007: ldloc.0 IL_0008: ldc.i4.s 42 IL_000a: stfld ""int C.<>c__DisplayClass0_0.i"" IL_000f: ldloc.0 IL_0010: ldftn ""int C.<>c__DisplayClass0_0.<Main>b__1()"" IL_0016: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001b: stloc.1 IL_001c: ldloc.1 IL_001d: callvirt ""int System.Func<int>.Invoke()"" IL_0022: stloc.2 IL_0023: br.s IL_0025 IL_0025: ldloc.2 IL_0026: ret }"); } [Fact] public void StaticLambdaCannotHaveLocalsCapturedByInnerStaticLambda() { var source = @" using System; public class C { public void F() { Func<int> f = static () => { int i = 0; Func<int> g = static () => i; return 0; }; } }"; VerifyInPreview(source, // (11,40): error CS8427: A static anonymous function cannot contain a reference to 'i'. // Func<int> g = static () => i; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 40)); } [Fact] public void InstanceLambdaCannotHaveLocalsCapturedByInnerStaticLambda() { var source = @" using System; public class C { public void F() { Func<int> f = () => { int i = 0; Func<int> g = static () => i; return 0; }; } }"; VerifyInPreview(source, // (11,40): error CS8427: A static anonymous function cannot contain a reference to 'i'. // Func<int> g = static () => i; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 40)); } [Fact] public void StaticLambdaCanHaveLocalsCapturedByInnerInstanceLocalFunction() { var source = @" using System; public class C { public static void Main() { Func<int> f = static () => { int i = 42; int g() => i; return g(); }; Console.Write(f()); } }"; VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @" { // Code size 23 (0x17) .maxstack 2 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 int V_1) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.s 42 IL_0005: stfld ""int C.<>c__DisplayClass0_0.i"" IL_000a: nop IL_000b: ldloca.s V_0 IL_000d: call ""int C.<Main>g__g|0_1(ref C.<>c__DisplayClass0_0)"" IL_0012: stloc.1 IL_0013: br.s IL_0015 IL_0015: ldloc.1 IL_0016: ret }"); } [Fact] public void StaticLambdaCannotHaveLocalsCapturedByInnerStaticLocalFunction() { var source = @" using System; public class C { public void F() { Func<int> f = static () => { int i = 0; static int g() => i; return g(); }; } }"; VerifyInPreview(source, // (11,31): error CS8421: A static local function cannot contain a reference to 'i'. // static int g() => i; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 31)); } [Fact] public void InstanceLambdaCannotHaveLocalsCapturedByInnerStaticLocalFunction() { var source = @" using System; public class C { public void F() { Func<int> f = () => { int i = 0; static int g() => i; return g(); }; } }"; VerifyInPreview(source, // (11,31): error CS8421: A static local function cannot contain a reference to 'i'. // static int g() => i; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 31)); } [Fact] public void StaticLocalFunctionCanHaveLocalsCapturedByInnerInstanceLocalFunction() { var source = @" using System; public class C { public static void Main() { static int f() { int i = 42; int g() => i; return g(); }; Console.Write(f()); } }"; var verifier = VerifyInPreview( source, expectedOutput: "42", symbolValidator); const string metadataName = "C.<Main>g__f|0_0"; if (RuntimeUtilities.IsCoreClrRuntime) { verifier.VerifyIL(metadataName, @" { // Code size 23 (0x17) .maxstack 2 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 int V_1) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.s 42 IL_0005: stfld ""int C.<>c__DisplayClass0_0.i"" IL_000a: nop IL_000b: ldloca.s V_0 IL_000d: call ""int C.<Main>g__g|0_1(ref C.<>c__DisplayClass0_0)"" IL_0012: stloc.1 IL_0013: br.s IL_0015 IL_0015: ldloc.1 IL_0016: ret }"); } void symbolValidator(ModuleSymbol module) { var method = module.GlobalNamespace.GetMember<MethodSymbol>(metadataName); Assert.True(method.IsStatic); } } [Fact] public void StaticLocalFunctionCannotHaveLocalsCapturedByInnerStaticLocalFunction() { var source = @" public class C { public void F() { static int f() { int i = 0; static int g() => i; return g(); }; } }"; VerifyInPreview(source, // (8,20): warning CS8321: The local function 'f' is declared but never used // static int f() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(8, 20), // (11,31): error CS8421: A static local function cannot contain a reference to 'i'. // static int g() => i; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 31)); } [Fact] public void InstanceLocalFunctionCannotHaveLocalsCapturedByInnerStaticLocalFunction() { var source = @" public class C { public void F() { int f() { int i = 0; static int g() => i; return g(); }; } }"; VerifyInPreview(source, // (8,13): warning CS8321: The local function 'f' is declared but never used // int f() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(8, 13), // (11,31): error CS8421: A static local function cannot contain a reference to 'i'. // static int g() => i; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 31)); } [Fact] public void StaticLocalFunctionCanHaveLocalsCapturedByInnerInstanceLambda() { var source = @" using System; public class C { public void F() { static int f() { int i = 0; Func<int> g = () => i; return g(); }; } }"; VerifyInPreview(source, // (8,20): warning CS8321: The local function 'f' is declared but never used // static int f() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(8, 20)); } [Fact] public void StaticLocalFunctionCannotHaveLocalsCapturedByInnerStaticLambda() { var source = @" using System; public class C { public void F() { static int f() { int i = 0; Func<int> g = static () => i; return g(); }; } }"; VerifyInPreview(source, // (8,20): warning CS8321: The local function 'f' is declared but never used // static int f() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(8, 20), // (11,40): error CS8427: A static anonymous function cannot contain a reference to 'i'. // Func<int> g = static () => i; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 40)); } [Fact] public void InstanceLocalFunctionCannotHaveLocalsCapturedByInnerStaticLambda() { var source = @" using System; public class C { public void F() { int f() { int i = 0; Func<int> g = static () => i; return g(); }; } }"; VerifyInPreview(source, // (8,13): warning CS8321: The local function 'f' is declared but never used // int f() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(8, 13), // (11,40): error CS8427: A static anonymous function cannot contain a reference to 'i'. // Func<int> g = static () => i; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "i").WithArguments("i").WithLocation(11, 40)); } [Fact] public void StaticLambdaCanCallStaticMethod() { var source = @" using System; public class C { public static void Main() { Func<int> f = static () => M(); Console.Write(f()); } static int M() => 42; }"; VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__0_0", expectedIL: @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""int C.M()"" IL_0005: ret } "); } [Fact] public void QueryInStaticLambdaCannotAccessThis() { var source = @" using System; using System.Linq; public class C { public static string[] args; public void F() { Func<int> f = static () => { var q = from a in args select M(a); return 0; }; } int M(string a) => 0; }"; VerifyInPreview(source, // (14,28): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'. // select M(a); Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "M").WithLocation(14, 28)); } [Fact] public void QueryInStaticLambdaCanReferenceStatic() { var source = @" using System; using System.Linq; using System.Collections.Generic; public class C { public static string[] args; public static void Main() { args = new[] { """" }; Func<IEnumerable<int>> f = static () => { var q = from a in args select M(a); return q; }; foreach (var x in f()) { Console.Write(x); } } static int M(string a) => 42; }"; VerifyInPreview(source, expectedOutput: "42", metadataName: "C.<>c.<Main>b__1_0", expectedIL: @" { // Code size 49 (0x31) .maxstack 3 .locals init (System.Collections.Generic.IEnumerable<int> V_0, //q System.Collections.Generic.IEnumerable<int> V_1) IL_0000: nop IL_0001: ldsfld ""string[] C.args"" IL_0006: ldsfld ""System.Func<string, int> C.<>c.<>9__1_1"" IL_000b: dup IL_000c: brtrue.s IL_0025 IL_000e: pop IL_000f: ldsfld ""C.<>c C.<>c.<>9"" IL_0014: ldftn ""int C.<>c.<Main>b__1_1(string)"" IL_001a: newobj ""System.Func<string, int>..ctor(object, System.IntPtr)"" IL_001f: dup IL_0020: stsfld ""System.Func<string, int> C.<>c.<>9__1_1"" IL_0025: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<string, int>(System.Collections.Generic.IEnumerable<string>, System.Func<string, int>)"" IL_002a: stloc.0 IL_002b: ldloc.0 IL_002c: stloc.1 IL_002d: br.s IL_002f IL_002f: ldloc.1 IL_0030: ret } "); } [Fact] public void InstanceLambdaInStaticLambdaCannotReferenceThis() { var source = @" using System; public class C { public void F() { Func<int> f = static () => { Func<int> g = () => { this.F(); return 0; }; return g(); }; } }"; VerifyInPreview(source, // (12,17): error CS8428: A static anonymous function cannot contain a reference to 'this' or 'base'. // this.F(); Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureThis, "this").WithLocation(12, 17)); } [Fact] public void TestStaticAnonymousFunctions() { var source = @" using System; public class C { public void F() { Action<int> a = static delegate(int i) { }; Action<int> b = static a => { }; Action<int> c = static (a) => { }; } }"; var compilation = CreateCompilation(source); var syntaxTree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(syntaxTree); var root = syntaxTree.GetRoot(); var anonymousMethodSyntax = root.DescendantNodes().OfType<AnonymousMethodExpressionSyntax>().Single(); var simpleLambdaSyntax = root.DescendantNodes().OfType<SimpleLambdaExpressionSyntax>().Single(); var parenthesizedLambdaSyntax = root.DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var anonymousMethod = (IMethodSymbol)semanticModel.GetSymbolInfo(anonymousMethodSyntax).Symbol!; var simpleLambda = (IMethodSymbol)semanticModel.GetSymbolInfo(simpleLambdaSyntax).Symbol!; var parenthesizedLambda = (IMethodSymbol)semanticModel.GetSymbolInfo(parenthesizedLambdaSyntax).Symbol!; Assert.True(anonymousMethod.IsStatic); Assert.True(simpleLambda.IsStatic); Assert.True(parenthesizedLambda.IsStatic); } [Fact] public void TestNonStaticAnonymousFunctions() { var source = @" using System; public class C { public void F() { Action<int> a = delegate(int i) { }; Action<int> b = a => { }; Action<int> c = (a) => { }; } }"; var compilation = CreateCompilation(source); var syntaxTree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(syntaxTree); var root = syntaxTree.GetRoot(); var anonymousMethodSyntax = root.DescendantNodes().OfType<AnonymousMethodExpressionSyntax>().Single(); var simpleLambdaSyntax = root.DescendantNodes().OfType<SimpleLambdaExpressionSyntax>().Single(); var parenthesizedLambdaSyntax = root.DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); var anonymousMethod = (IMethodSymbol)semanticModel.GetSymbolInfo(anonymousMethodSyntax).Symbol!; var simpleLambda = (IMethodSymbol)semanticModel.GetSymbolInfo(simpleLambdaSyntax).Symbol!; var parenthesizedLambda = (IMethodSymbol)semanticModel.GetSymbolInfo(parenthesizedLambdaSyntax).Symbol!; Assert.False(anonymousMethod.IsStatic); Assert.False(simpleLambda.IsStatic); Assert.False(parenthesizedLambda.IsStatic); } [Fact] public void TestStaticLambdaCallArgument() { var source = @" using System; public class C { public static void F(Func<string> fn) { Console.WriteLine(fn()); } public static void Main() { F(static () => ""hello""); } }"; VerifyInPreview(source, expectedOutput: "hello", metadataName: "C.<>c.<Main>b__1_0", expectedIL: @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldstr ""hello"" IL_0005: ret }"); } [Fact] public void TestStaticLambdaIndexerArgument() { var source = @" using System; public class C { public object this[Func<object> fn] { get { Console.WriteLine(fn()); return null; } } public static void Main() { _ = new C()[static () => ""hello""]; } }"; VerifyInPreview(source, expectedOutput: "hello", metadataName: "C.<>c.<Main>b__2_0", expectedIL: @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldstr ""hello"" IL_0005: ret }"); } [Fact] public void TestStaticDelegateCallArgument() { var source = @" using System; public class C { public static void F(Func<string> fn) { Console.WriteLine(fn()); } public static void Main() { F(static delegate() { return ""hello""; }); } }"; VerifyInPreview(source, expectedOutput: "hello", metadataName: "C.<>c.<Main>b__1_0", expectedIL: @" { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""hello"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret }"); } [Fact] public void StaticLambdaNameof() { var source = @" using System; public class C { public int w; public static int x; public static void F(Func<int, string> fn) { Console.WriteLine(fn(0)); } public static void Main() { int y = 0; F(static (int z) => { return nameof(w) + nameof(x) + nameof(y) + nameof(z); }); } }"; VerifyInPreview(source, expectedOutput: "wxyz", metadataName: "C.<>c.<Main>b__3_0", expectedIL: @" { // Code size 11 (0xb) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldstr ""wxyz"" IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret }"); } [Fact] public void StaticLambdaTypeParams() { var source = @" using System; public class C<T> { public static void F(Func<int, string> fn) { Console.WriteLine(fn(0)); } public static void M<U>() { F(static (int x) => { return default(T).ToString() + default(U).ToString(); }); } } public class Program { public static void Main() { C<int>.M<bool>(); } }"; verify(source); verify(source.Replace("static (", "(")); void verify(string source) { var verifier = CompileAndVerify( source, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular9, symbolValidator: symbolValidator, expectedOutput: "0False") .VerifyDiagnostics(); verifier.VerifyIL("C<T>.<>c__1<U>.<M>b__1_0", @" { // Code size 51 (0x33) .maxstack 3 .locals init (T V_0, U V_1, string V_2) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: dup IL_0004: initobj ""T"" IL_000a: constrained. ""T"" IL_0010: callvirt ""string object.ToString()"" IL_0015: ldloca.s V_1 IL_0017: dup IL_0018: initobj ""U"" IL_001e: constrained. ""U"" IL_0024: callvirt ""string object.ToString()"" IL_0029: call ""string string.Concat(string, string)"" IL_002e: stloc.2 IL_002f: br.s IL_0031 IL_0031: ldloc.2 IL_0032: ret }"); } void symbolValidator(ModuleSymbol module) { var method = module.GlobalNamespace.GetMember<MethodSymbol>("C.<>c__1.<M>b__1_0"); // note that static anonymous functions do not guarantee that the lowered method will be static. Assert.False(method.IsStatic); } } [Fact] public void StaticLambda_Nint() { var source = @" using System; local(static x => x + 1); void local(Func<nint, nint> fn) { Console.WriteLine(fn(0)); }"; VerifyInPreview(source, expectedOutput: "1", metadataName: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + ".<>c.<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">b__0_0", expectedIL: @" { // Code size 5 (0x5) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldc.i4.1 IL_0002: conv.i IL_0003: add IL_0004: ret }"); } [Fact] public void StaticLambda_ExpressionTree() { var source = @" using System; using System.Linq.Expressions; class C { static void Main() { local(static x => x + 1); static void local(Expression<Func<int, int>> fn) { Console.WriteLine(fn.Compile()(0)); } } }"; var verifier = VerifyInPreview(source, expectedOutput: "1"); verifier.VerifyIL("C.Main", @" { // Code size 72 (0x48) .maxstack 5 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: nop IL_0001: ldtoken ""int"" IL_0006: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000b: ldstr ""x"" IL_0010: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0015: stloc.0 IL_0016: ldloc.0 IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: ldtoken ""int"" IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0027: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_002c: call ""System.Linq.Expressions.BinaryExpression System.Linq.Expressions.Expression.Add(System.Linq.Expressions.Expression, System.Linq.Expressions.Expression)"" IL_0031: ldc.i4.1 IL_0032: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0037: dup IL_0038: ldc.i4.0 IL_0039: ldloc.0 IL_003a: stelem.ref IL_003b: call ""System.Linq.Expressions.Expression<System.Func<int, int>> System.Linq.Expressions.Expression.Lambda<System.Func<int, int>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0040: call ""void C.<Main>g__local|0_1(System.Linq.Expressions.Expression<System.Func<int, int>>)"" IL_0045: nop IL_0046: nop IL_0047: ret }"); } [Fact] public void StaticLambda_FunctionPointer_01() { var source = @" class C { unsafe void M() { delegate*<void> ptr = &static () => { }; ptr(); } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,32): error CS1525: Invalid expression term 'static' // delegate*<void> ptr = &static () => { }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "static").WithArguments("static").WithLocation(6, 32), // (6,32): error CS1002: ; expected // delegate*<void> ptr = &static () => { }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "static").WithLocation(6, 32), // (6,32): error CS0106: The modifier 'static' is not valid for this item // delegate*<void> ptr = &static () => { }; Diagnostic(ErrorCode.ERR_BadMemberFlag, "static").WithArguments("static").WithLocation(6, 32), // (6,40): error CS8124: Tuple must contain at least two elements. // delegate*<void> ptr = &static () => { }; Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(6, 40), // (6,42): error CS1001: Identifier expected // delegate*<void> ptr = &static () => { }; Diagnostic(ErrorCode.ERR_IdentifierExpected, "=>").WithLocation(6, 42), // (6,42): error CS1003: Syntax error, ',' expected // delegate*<void> ptr = &static () => { }; Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(6, 42), // (6,45): error CS1002: ; expected // delegate*<void> ptr = &static () => { }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(6, 45) ); } [Fact] public void StaticLambda_FunctionPointer_02() { var source = @" class C { unsafe void M() { delegate*<void> ptr = static () => { }; ptr(); } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,31): error CS1660: Cannot convert lambda expression to type 'delegate*<void>' because it is not a delegate type // delegate*<void> ptr = static () => { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "static () => { }").WithArguments("lambda expression", "delegate*<void>").WithLocation(6, 31) ); } [Fact] public void StaticAnonymousMethod_FunctionPointer_01() { var source = @" class C { unsafe void M() { delegate*<void> ptr = &static delegate() { }; ptr(); } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,32): error CS0211: Cannot take the address of the given expression // delegate*<void> ptr = &static delegate() { }; Diagnostic(ErrorCode.ERR_InvalidAddrOp, "static delegate() { }").WithLocation(6, 32) ); } [Fact] public void StaticAnonymousMethod_FunctionPointer_02() { var source = @" class C { unsafe void M() { delegate*<void> ptr = static delegate() { }; ptr(); } } "; var comp = CreateCompilation(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,31): error CS1660: Cannot convert anonymous method to type 'delegate*<void>' because it is not a delegate type // delegate*<void> ptr = static delegate() { }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "static delegate() { }").WithArguments("anonymous method", "delegate*<void>").WithLocation(6, 31) ); } [Fact] public void ConditionalExpr() { var source = @" using static System.Console; class C { static void M(bool b, System.Action a) { a = b ? () => Write(1) : a; a(); a = b ? static () => Write(2) : a; a(); a = b ? () => { Write(3); } : a; a(); a = b ? static () => { Write(4); } : a; a(); a = b ? a : () => { }; a = b ? a : static () => { }; a = b ? delegate() { Write(5); } : a; a(); a = b ? static delegate() { Write(6); } : a; a(); a = b ? a : delegate() { }; a = b ? a : static delegate() { }; } static void Main() { M(true, () => { }); } } "; CompileAndVerify(source, expectedOutput: "123456", parseOptions: TestOptions.Regular9); } [Fact] public void RefConditionalExpr() { var source = @" using static System.Console; class C { static void M(bool b, ref System.Action a) { a = ref b ? ref () => Write(1) : ref a; a(); a = ref b ? ref static () => Write(2) : ref a; a(); a = ref b ? ref () => { Write(3); } : ref a; a(); a = ref b ? ref static () => { Write(4); } : ref a; a(); a = ref b ? ref a : ref () => { }; a = ref b ? ref a : ref static () => { }; a = ref b ? ref delegate() { Write(5); } : ref a; a(); a = ref b ? ref static delegate() { Write(6); } : ref a; a(); a = ref b ? ref a : ref delegate() { }; a = b ? ref a : ref static delegate() { }; } } "; VerifyInPreview(source, // (8,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref () => Write(1) : ref a; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "() => Write(1)").WithLocation(8, 25), // (11,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref static () => Write(2) : ref a; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "static () => Write(2)").WithLocation(11, 25), // (14,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref () => { Write(3); } : ref a; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "() => { Write(3); }").WithLocation(14, 25), // (17,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref static () => { Write(4); } : ref a; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "static () => { Write(4); }").WithLocation(17, 25), // (20,33): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref a : ref () => { }; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "() => { }").WithLocation(20, 33), // (21,33): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref a : ref static () => { }; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "static () => { }").WithLocation(21, 33), // (23,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref delegate() { Write(5); } : ref a; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "delegate() { Write(5); }").WithLocation(23, 25), // (26,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref static delegate() { Write(6); } : ref a; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "static delegate() { Write(6); }").WithLocation(26, 25), // (29,33): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = ref b ? ref a : ref delegate() { }; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "delegate() { }").WithLocation(29, 33), // (30,29): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // a = b ? ref a : ref static delegate() { }; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "static delegate() { }").WithLocation(30, 29) ); } [Fact] public void SwitchExpr() { var source = @" using static System.Console; class C { static void M(bool b, System.Action a) { a = b switch { true => () => Write(1), false => a }; a(); a = b switch { true => static () => Write(2), false => a }; a(); a = b switch { true => () => { Write(3); }, false => a }; a(); a = b switch { true => static () => { Write(4); }, false => a }; a(); a = b switch { true => a , false => () => { Write(0); } }; a = b switch { true => a , false => static () => { Write(0); } }; a = b switch { true => delegate() { Write(5); }, false => a }; a(); a = b switch { true => static delegate() { Write(6); }, false => a }; a(); a = b switch { true => a , false => delegate() { Write(0); } }; a = b switch { true => a , false => static delegate() { Write(0); } }; } static void Main() { M(true, () => { }); } } "; CompileAndVerify(source, expectedOutput: "123456", parseOptions: TestOptions.Regular9); } [Fact] public void DiscardParams() { var source = @" using System; class C { static void Main() { Action<int, int, string> fn = static (_, _, z) => Console.Write(z); fn(1, 2, ""hello""); fn = static delegate(int _, int _, string z) { Console.Write(z); }; fn(3, 4, "" world""); } } "; CompileAndVerify(source, expectedOutput: "hello world", parseOptions: TestOptions.Regular9); } [Fact] public void PrivateMemberAccessibility() { var source = @" using System; class C { private static void M1(int i) { Console.Write(i); } class Inner { static void Main() { Action a = static () => M1(1); a(); a = static delegate() { M1(2); }; a(); } } } "; verify(source); verify(source.Replace("static (", "(")); void verify(string source) { CompileAndVerify(source, expectedOutput: "12", parseOptions: TestOptions.Regular9); } } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Features/Core/Portable/Completion/Log/CompletionProvidersLogger.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Internal.Log; namespace Microsoft.CodeAnalysis.Completion.Log { internal sealed class CompletionProvidersLogger { private const string Max = "Maximum"; private const string Min = "Minimum"; private const string Mean = nameof(Mean); private const string Range = nameof(Range); private const string Count = nameof(Count); private static readonly StatisticLogAggregator s_statisticLogAggregator = new(); private static readonly LogAggregator s_logAggregator = new(); private static readonly HistogramLogAggregator s_histogramLogAggregator = new(bucketSize: 50, maxBucketValue: 1000); internal enum ActionInfo { TypeImportCompletionTicks, TypeImportCompletionItemCount, TypeImportCompletionReferenceCount, TypeImportCompletionCacheMissCount, CommitsOfTypeImportCompletionItem, TargetTypeCompletionTicks, ExtensionMethodCompletionTicks, ExtensionMethodCompletionMethodsProvided, ExtensionMethodCompletionGetSymbolsTicks, ExtensionMethodCompletionCreateItemsTicks, CommitsOfExtensionMethodImportCompletionItem, ExtensionMethodCompletionPartialResultCount, ExtensionMethodCompletionTimeoutCount, CommitUsingSemicolonToAddParenthesis, CommitUsingDotToAddParenthesis } internal static void LogTypeImportCompletionTicksDataPoint(int count) { s_histogramLogAggregator.IncreaseCount((int)ActionInfo.TypeImportCompletionTicks, count); s_statisticLogAggregator.AddDataPoint((int)ActionInfo.TypeImportCompletionTicks, count); } internal static void LogTypeImportCompletionItemCountDataPoint(int count) => s_statisticLogAggregator.AddDataPoint((int)ActionInfo.TypeImportCompletionItemCount, count); internal static void LogTypeImportCompletionReferenceCountDataPoint(int count) => s_statisticLogAggregator.AddDataPoint((int)ActionInfo.TypeImportCompletionReferenceCount, count); internal static void LogTypeImportCompletionCacheMiss() => s_logAggregator.IncreaseCount((int)ActionInfo.TypeImportCompletionCacheMissCount); internal static void LogCommitOfTypeImportCompletionItem() => s_logAggregator.IncreaseCount((int)ActionInfo.CommitsOfTypeImportCompletionItem); internal static void LogTargetTypeCompletionTicksDataPoint(int count) => s_statisticLogAggregator.AddDataPoint((int)ActionInfo.TargetTypeCompletionTicks, count); internal static void LogExtensionMethodCompletionTicksDataPoint(int count) { s_histogramLogAggregator.IncreaseCount((int)ActionInfo.ExtensionMethodCompletionTicks, count); s_statisticLogAggregator.AddDataPoint((int)ActionInfo.ExtensionMethodCompletionTicks, count); } internal static void LogExtensionMethodCompletionMethodsProvidedDataPoint(int count) => s_statisticLogAggregator.AddDataPoint((int)ActionInfo.ExtensionMethodCompletionMethodsProvided, count); internal static void LogExtensionMethodCompletionGetSymbolsTicksDataPoint(int count) => s_statisticLogAggregator.AddDataPoint((int)ActionInfo.ExtensionMethodCompletionGetSymbolsTicks, count); internal static void LogExtensionMethodCompletionCreateItemsTicksDataPoint(int count) => s_statisticLogAggregator.AddDataPoint((int)ActionInfo.ExtensionMethodCompletionCreateItemsTicks, count); internal static void LogCommitOfExtensionMethodImportCompletionItem() => s_logAggregator.IncreaseCount((int)ActionInfo.CommitsOfExtensionMethodImportCompletionItem); internal static void LogExtensionMethodCompletionPartialResultCount() => s_logAggregator.IncreaseCount((int)ActionInfo.ExtensionMethodCompletionPartialResultCount); internal static void LogExtensionMethodCompletionTimeoutCount() => s_logAggregator.IncreaseCount((int)ActionInfo.ExtensionMethodCompletionTimeoutCount); internal static void LogCommitUsingSemicolonToAddParenthesis() => s_logAggregator.IncreaseCount((int)ActionInfo.CommitUsingSemicolonToAddParenthesis); internal static void LogCommitUsingDotToAddParenthesis() => s_logAggregator.IncreaseCount((int)ActionInfo.CommitUsingDotToAddParenthesis); internal static void LogCustomizedCommitToAddParenthesis(char? commitChar) { switch (commitChar) { case '.': LogCommitUsingDotToAddParenthesis(); break; case ';': LogCommitUsingSemicolonToAddParenthesis(); break; } } internal static void ReportTelemetry() { Logger.Log(FunctionId.Intellisense_CompletionProviders_Data, KeyValueLogMessage.Create(m => { foreach (var kv in s_statisticLogAggregator) { var info = ((ActionInfo)kv.Key).ToString("f"); var statistics = kv.Value.GetStatisticResult(); m[CreateProperty(info, Max)] = statistics.Maximum; m[CreateProperty(info, Min)] = statistics.Minimum; m[CreateProperty(info, Mean)] = statistics.Mean; m[CreateProperty(info, Range)] = statistics.Range; m[CreateProperty(info, Count)] = statistics.Count; } foreach (var kv in s_logAggregator) { var info = ((ActionInfo)kv.Key).ToString("f"); m[info] = kv.Value.GetCount(); } foreach (var kv in s_histogramLogAggregator) { var info = ((ActionInfo)kv.Key).ToString("f"); m[$"{info}.BucketSize"] = kv.Value.BucketSize; m[$"{info}.MaxBucketValue"] = kv.Value.MaxBucketValue; m[$"{info}.Buckets"] = kv.Value.GetBucketsAsString(); } })); } private static string CreateProperty(string parent, string child) => parent + "." + child; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Internal.Log; namespace Microsoft.CodeAnalysis.Completion.Log { internal sealed class CompletionProvidersLogger { private const string Max = "Maximum"; private const string Min = "Minimum"; private const string Mean = nameof(Mean); private const string Range = nameof(Range); private const string Count = nameof(Count); private static readonly StatisticLogAggregator s_statisticLogAggregator = new(); private static readonly LogAggregator s_logAggregator = new(); private static readonly HistogramLogAggregator s_histogramLogAggregator = new(bucketSize: 50, maxBucketValue: 1000); internal enum ActionInfo { TypeImportCompletionTicks, TypeImportCompletionItemCount, TypeImportCompletionReferenceCount, TypeImportCompletionCacheMissCount, CommitsOfTypeImportCompletionItem, TargetTypeCompletionTicks, ExtensionMethodCompletionTicks, ExtensionMethodCompletionMethodsProvided, ExtensionMethodCompletionGetSymbolsTicks, ExtensionMethodCompletionCreateItemsTicks, CommitsOfExtensionMethodImportCompletionItem, ExtensionMethodCompletionPartialResultCount, ExtensionMethodCompletionTimeoutCount, CommitUsingSemicolonToAddParenthesis, CommitUsingDotToAddParenthesis } internal static void LogTypeImportCompletionTicksDataPoint(int count) { s_histogramLogAggregator.IncreaseCount((int)ActionInfo.TypeImportCompletionTicks, count); s_statisticLogAggregator.AddDataPoint((int)ActionInfo.TypeImportCompletionTicks, count); } internal static void LogTypeImportCompletionItemCountDataPoint(int count) => s_statisticLogAggregator.AddDataPoint((int)ActionInfo.TypeImportCompletionItemCount, count); internal static void LogTypeImportCompletionReferenceCountDataPoint(int count) => s_statisticLogAggregator.AddDataPoint((int)ActionInfo.TypeImportCompletionReferenceCount, count); internal static void LogTypeImportCompletionCacheMiss() => s_logAggregator.IncreaseCount((int)ActionInfo.TypeImportCompletionCacheMissCount); internal static void LogCommitOfTypeImportCompletionItem() => s_logAggregator.IncreaseCount((int)ActionInfo.CommitsOfTypeImportCompletionItem); internal static void LogTargetTypeCompletionTicksDataPoint(int count) => s_statisticLogAggregator.AddDataPoint((int)ActionInfo.TargetTypeCompletionTicks, count); internal static void LogExtensionMethodCompletionTicksDataPoint(int count) { s_histogramLogAggregator.IncreaseCount((int)ActionInfo.ExtensionMethodCompletionTicks, count); s_statisticLogAggregator.AddDataPoint((int)ActionInfo.ExtensionMethodCompletionTicks, count); } internal static void LogExtensionMethodCompletionMethodsProvidedDataPoint(int count) => s_statisticLogAggregator.AddDataPoint((int)ActionInfo.ExtensionMethodCompletionMethodsProvided, count); internal static void LogExtensionMethodCompletionGetSymbolsTicksDataPoint(int count) => s_statisticLogAggregator.AddDataPoint((int)ActionInfo.ExtensionMethodCompletionGetSymbolsTicks, count); internal static void LogExtensionMethodCompletionCreateItemsTicksDataPoint(int count) => s_statisticLogAggregator.AddDataPoint((int)ActionInfo.ExtensionMethodCompletionCreateItemsTicks, count); internal static void LogCommitOfExtensionMethodImportCompletionItem() => s_logAggregator.IncreaseCount((int)ActionInfo.CommitsOfExtensionMethodImportCompletionItem); internal static void LogExtensionMethodCompletionPartialResultCount() => s_logAggregator.IncreaseCount((int)ActionInfo.ExtensionMethodCompletionPartialResultCount); internal static void LogExtensionMethodCompletionTimeoutCount() => s_logAggregator.IncreaseCount((int)ActionInfo.ExtensionMethodCompletionTimeoutCount); internal static void LogCommitUsingSemicolonToAddParenthesis() => s_logAggregator.IncreaseCount((int)ActionInfo.CommitUsingSemicolonToAddParenthesis); internal static void LogCommitUsingDotToAddParenthesis() => s_logAggregator.IncreaseCount((int)ActionInfo.CommitUsingDotToAddParenthesis); internal static void LogCustomizedCommitToAddParenthesis(char? commitChar) { switch (commitChar) { case '.': LogCommitUsingDotToAddParenthesis(); break; case ';': LogCommitUsingSemicolonToAddParenthesis(); break; } } internal static void ReportTelemetry() { Logger.Log(FunctionId.Intellisense_CompletionProviders_Data, KeyValueLogMessage.Create(m => { foreach (var kv in s_statisticLogAggregator) { var info = ((ActionInfo)kv.Key).ToString("f"); var statistics = kv.Value.GetStatisticResult(); m[CreateProperty(info, Max)] = statistics.Maximum; m[CreateProperty(info, Min)] = statistics.Minimum; m[CreateProperty(info, Mean)] = statistics.Mean; m[CreateProperty(info, Range)] = statistics.Range; m[CreateProperty(info, Count)] = statistics.Count; } foreach (var kv in s_logAggregator) { var info = ((ActionInfo)kv.Key).ToString("f"); m[info] = kv.Value.GetCount(); } foreach (var kv in s_histogramLogAggregator) { var info = ((ActionInfo)kv.Key).ToString("f"); m[$"{info}.BucketSize"] = kv.Value.BucketSize; m[$"{info}.MaxBucketValue"] = kv.Value.MaxBucketValue; m[$"{info}.Buckets"] = kv.Value.GetBucketsAsString(); } })); } private static string CreateProperty(string parent, string child) => parent + "." + child; } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/VisualStudio/Core/Impl/SolutionExplorer/DiagnosticItem/SourceGeneratorItem.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; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.VisualStudio.Imaging; using Microsoft.VisualStudio.Imaging.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { internal sealed partial class SourceGeneratorItem : BaseItem { public ProjectId ProjectId { get; } public string GeneratorAssemblyName { get; } // Since the type name is also used for the display text, we can just reuse that. We'll still have an explicit // property so the assembly name/type name pair that is used in other places is also used here. public string GeneratorTypeName => base.Text; public AnalyzerReference AnalyzerReference { get; } public SourceGeneratorItem(ProjectId projectId, ISourceGenerator generator, AnalyzerReference analyzerReference) : base(name: SourceGeneratedDocumentIdentity.GetGeneratorTypeName(generator)) { ProjectId = projectId; GeneratorAssemblyName = SourceGeneratedDocumentIdentity.GetGeneratorAssemblyName(generator); AnalyzerReference = analyzerReference; } // TODO: do we need an icon for our use? public override ImageMoniker IconMoniker => KnownMonikers.Process; public override object GetBrowseObject() { return new BrowseObject(this); } } }
// Licensed to the .NET Foundation under one or more 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; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.VisualStudio.Imaging; using Microsoft.VisualStudio.Imaging.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { internal sealed partial class SourceGeneratorItem : BaseItem { public ProjectId ProjectId { get; } public string GeneratorAssemblyName { get; } // Since the type name is also used for the display text, we can just reuse that. We'll still have an explicit // property so the assembly name/type name pair that is used in other places is also used here. public string GeneratorTypeName => base.Text; public AnalyzerReference AnalyzerReference { get; } public SourceGeneratorItem(ProjectId projectId, ISourceGenerator generator, AnalyzerReference analyzerReference) : base(name: SourceGeneratedDocumentIdentity.GetGeneratorTypeName(generator)) { ProjectId = projectId; GeneratorAssemblyName = SourceGeneratedDocumentIdentity.GetGeneratorAssemblyName(generator); AnalyzerReference = analyzerReference; } // TODO: do we need an icon for our use? public override ImageMoniker IconMoniker => KnownMonikers.Process; public override object GetBrowseObject() { return new BrowseObject(this); } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/CodeStyle/Core/CodeFixes/xlf/CodeStyleFixesResources.pl.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="pl" original="../CodeStyleFixesResources.resx"> <body> <trans-unit id="EmptyResource"> <source>Remove this value when another is added.</source> <target state="translated">Usuń tę wartość, gdy dodawana jest kolejna.</target> <note>https://github.com/Microsoft/msbuild/issues/1661</note> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="pl" original="../CodeStyleFixesResources.resx"> <body> <trans-unit id="EmptyResource"> <source>Remove this value when another is added.</source> <target state="translated">Usuń tę wartość, gdy dodawana jest kolejna.</target> <note>https://github.com/Microsoft/msbuild/issues/1661</note> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Features/Core/Portable/QuickInfo/QuickInfoService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.QuickInfo { /// <summary> /// A service that is used to determine the appropriate quick info for a position in a document. /// </summary> public abstract class QuickInfoService : ILanguageService { /// <summary> /// Gets the appropriate <see cref="QuickInfoService"/> for the specified document. /// </summary> public static QuickInfoService? GetService(Document? document) => document?.GetLanguageService<QuickInfoService>(); /// <summary> /// Gets the <see cref="QuickInfoItem"/> associated with position in the document. /// </summary> public virtual Task<QuickInfoItem?> GetQuickInfoAsync( Document document, int position, CancellationToken cancellationToken = default) { return SpecializedTasks.Null<QuickInfoItem>(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.QuickInfo { /// <summary> /// A service that is used to determine the appropriate quick info for a position in a document. /// </summary> public abstract class QuickInfoService : ILanguageService { /// <summary> /// Gets the appropriate <see cref="QuickInfoService"/> for the specified document. /// </summary> public static QuickInfoService? GetService(Document? document) => document?.GetLanguageService<QuickInfoService>(); /// <summary> /// Gets the <see cref="QuickInfoItem"/> associated with position in the document. /// </summary> public virtual Task<QuickInfoItem?> GetQuickInfoAsync( Document document, int position, CancellationToken cancellationToken = default) { return SpecializedTasks.Null<QuickInfoItem>(); } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/EditorFeatures/VisualBasicTest/ConflictMarkerResolution/ConflictMarkerResolutionTests.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.ConflictMarkerResolution Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeFixVerifier(Of Microsoft.CodeAnalysis.Testing.EmptyDiagnosticAnalyzer, Microsoft.CodeAnalysis.VisualBasic.ConflictMarkerResolution.VisualBasicResolveConflictMarkerCodeFixProvider) Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ConflictMarkerResolution Public Class ConflictMarkerResolutionTests <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)> Public Async Function TestTakeTop1() As Task Dim source = " imports System namespace N {|BC37284:<<<<<<< This is mine!|} class Program sub Main() dim p as Program Console.WriteLine(""My section"") end sub end class {|BC37284:=======|} class Program2 sub Main2() dim p as Program2 Console.WriteLine(""Their section"") end sub end class {|BC37284:>>>>>>> This is theirs!|} end namespace" Dim fixedSource = " imports System namespace N class Program sub Main() dim p as Program Console.WriteLine(""My section"") end sub end class end namespace" Await New VerifyVB.Test With { .TestCode = source, .FixedCode = fixedSource, .NumberOfIncrementalIterations = 1, .CodeActionIndex = 0, .CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey }.RunAsync() End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)> Public Async Function TestTakeBottom1() As Task Dim source = " imports System namespace N {|BC37284:<<<<<<< This is mine!|} class Program sub Main() dim p as Program Console.WriteLine(""My section"") end sub end class {|BC37284:=======|} class Program2 sub Main2() dim p as Program2 Console.WriteLine(""Their section"") end sub end class {|BC37284:>>>>>>> This is theirs!|} end namespace" Dim fixedSource = " imports System namespace N class Program2 sub Main2() dim p as Program2 Console.WriteLine(""Their section"") end sub end class end namespace" Await New VerifyVB.Test With { .TestCode = source, .FixedCode = fixedSource, .NumberOfIncrementalIterations = 1, .CodeActionIndex = 1, .CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey }.RunAsync() End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)> Public Async Function TestTakeBoth1() As Task Dim source = " imports System namespace N {|BC37284:<<<<<<< This is mine!|} class Program sub Main() dim p as Program Console.WriteLine(""My section"") end sub end class {|BC37284:=======|} class Program2 sub Main2() dim p as Program2 Console.WriteLine(""Their section"") end sub end class {|BC37284:>>>>>>> This is theirs!|} end namespace" Dim fixedSource = " imports System namespace N class Program sub Main() dim p as Program Console.WriteLine(""My section"") end sub end class class Program2 sub Main2() dim p as Program2 Console.WriteLine(""Their section"") end sub end class end namespace" Await New VerifyVB.Test With { .TestCode = source, .FixedCode = fixedSource, .NumberOfIncrementalIterations = 1, .CodeActionIndex = 2, .CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBothEquivalenceKey }.RunAsync() End Function <WorkItem(21107, "https://github.com/dotnet/roslyn/issues/21107")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)> Public Async Function TestFixAll1() As Task Dim source = " imports System namespace N {|BC37284:<<<<<<< This is mine!|} class Program end class {|BC37284:=======|} class Program2 end class {|BC37284:>>>>>>> This is theirs!|} {|BC37284:<<<<<<< This is mine!|} class Program3 end class {|BC37284:=======|} class Program4 end class {|BC37284:>>>>>>> This is theirs!|} end namespace" Dim fixedSource = " imports System namespace N class Program end class class Program3 end class end namespace" Await New VerifyVB.Test With { .TestCode = source, .FixedCode = fixedSource, .NumberOfIncrementalIterations = 2, .CodeActionIndex = 0, .CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey }.RunAsync() End Function <WorkItem(21107, "https://github.com/dotnet/roslyn/issues/21107")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)> Public Async Function TestFixAll2() As Task Dim source = " imports System namespace N {|BC37284:<<<<<<< This is mine!|} class Program end class {|BC37284:=======|} class Program2 end class {|BC37284:>>>>>>> This is theirs!|} {|BC37284:<<<<<<< This is mine!|} class Program3 end class {|BC37284:=======|} class Program4 end class {|BC37284:>>>>>>> This is theirs!|} end namespace" Dim fixedSource = " imports System namespace N class Program2 end class class Program4 end class end namespace" Await New VerifyVB.Test With { .TestCode = source, .FixedCode = fixedSource, .NumberOfIncrementalIterations = 2, .CodeActionIndex = 1, .CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey }.RunAsync() End Function <WorkItem(21107, "https://github.com/dotnet/roslyn/issues/21107")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)> Public Async Function TestFixAll3() As Task Dim source = " imports System namespace N {|BC37284:<<<<<<< This is mine!|} class Program end class {|BC37284:=======|} class Program2 end class {|BC37284:>>>>>>> This is theirs!|} {|BC37284:<<<<<<< This is mine!|} class Program3 end class {|BC37284:=======|} class Program4 end class {|BC37284:>>>>>>> This is theirs!|} end namespace" Dim fixedSource = " imports System namespace N class Program end class class Program2 end class class Program3 end class class Program4 end class end namespace" Await New VerifyVB.Test With { .TestCode = source, .FixedCode = fixedSource, .NumberOfIncrementalIterations = 2, .CodeActionIndex = 2, .CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBothEquivalenceKey }.RunAsync() 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.ConflictMarkerResolution Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeFixVerifier(Of Microsoft.CodeAnalysis.Testing.EmptyDiagnosticAnalyzer, Microsoft.CodeAnalysis.VisualBasic.ConflictMarkerResolution.VisualBasicResolveConflictMarkerCodeFixProvider) Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ConflictMarkerResolution Public Class ConflictMarkerResolutionTests <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)> Public Async Function TestTakeTop1() As Task Dim source = " imports System namespace N {|BC37284:<<<<<<< This is mine!|} class Program sub Main() dim p as Program Console.WriteLine(""My section"") end sub end class {|BC37284:=======|} class Program2 sub Main2() dim p as Program2 Console.WriteLine(""Their section"") end sub end class {|BC37284:>>>>>>> This is theirs!|} end namespace" Dim fixedSource = " imports System namespace N class Program sub Main() dim p as Program Console.WriteLine(""My section"") end sub end class end namespace" Await New VerifyVB.Test With { .TestCode = source, .FixedCode = fixedSource, .NumberOfIncrementalIterations = 1, .CodeActionIndex = 0, .CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey }.RunAsync() End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)> Public Async Function TestTakeBottom1() As Task Dim source = " imports System namespace N {|BC37284:<<<<<<< This is mine!|} class Program sub Main() dim p as Program Console.WriteLine(""My section"") end sub end class {|BC37284:=======|} class Program2 sub Main2() dim p as Program2 Console.WriteLine(""Their section"") end sub end class {|BC37284:>>>>>>> This is theirs!|} end namespace" Dim fixedSource = " imports System namespace N class Program2 sub Main2() dim p as Program2 Console.WriteLine(""Their section"") end sub end class end namespace" Await New VerifyVB.Test With { .TestCode = source, .FixedCode = fixedSource, .NumberOfIncrementalIterations = 1, .CodeActionIndex = 1, .CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey }.RunAsync() End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)> Public Async Function TestTakeBoth1() As Task Dim source = " imports System namespace N {|BC37284:<<<<<<< This is mine!|} class Program sub Main() dim p as Program Console.WriteLine(""My section"") end sub end class {|BC37284:=======|} class Program2 sub Main2() dim p as Program2 Console.WriteLine(""Their section"") end sub end class {|BC37284:>>>>>>> This is theirs!|} end namespace" Dim fixedSource = " imports System namespace N class Program sub Main() dim p as Program Console.WriteLine(""My section"") end sub end class class Program2 sub Main2() dim p as Program2 Console.WriteLine(""Their section"") end sub end class end namespace" Await New VerifyVB.Test With { .TestCode = source, .FixedCode = fixedSource, .NumberOfIncrementalIterations = 1, .CodeActionIndex = 2, .CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBothEquivalenceKey }.RunAsync() End Function <WorkItem(21107, "https://github.com/dotnet/roslyn/issues/21107")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)> Public Async Function TestFixAll1() As Task Dim source = " imports System namespace N {|BC37284:<<<<<<< This is mine!|} class Program end class {|BC37284:=======|} class Program2 end class {|BC37284:>>>>>>> This is theirs!|} {|BC37284:<<<<<<< This is mine!|} class Program3 end class {|BC37284:=======|} class Program4 end class {|BC37284:>>>>>>> This is theirs!|} end namespace" Dim fixedSource = " imports System namespace N class Program end class class Program3 end class end namespace" Await New VerifyVB.Test With { .TestCode = source, .FixedCode = fixedSource, .NumberOfIncrementalIterations = 2, .CodeActionIndex = 0, .CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeTopEquivalenceKey }.RunAsync() End Function <WorkItem(21107, "https://github.com/dotnet/roslyn/issues/21107")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)> Public Async Function TestFixAll2() As Task Dim source = " imports System namespace N {|BC37284:<<<<<<< This is mine!|} class Program end class {|BC37284:=======|} class Program2 end class {|BC37284:>>>>>>> This is theirs!|} {|BC37284:<<<<<<< This is mine!|} class Program3 end class {|BC37284:=======|} class Program4 end class {|BC37284:>>>>>>> This is theirs!|} end namespace" Dim fixedSource = " imports System namespace N class Program2 end class class Program4 end class end namespace" Await New VerifyVB.Test With { .TestCode = source, .FixedCode = fixedSource, .NumberOfIncrementalIterations = 2, .CodeActionIndex = 1, .CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBottomEquivalenceKey }.RunAsync() End Function <WorkItem(21107, "https://github.com/dotnet/roslyn/issues/21107")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsResolveConflictMarker)> Public Async Function TestFixAll3() As Task Dim source = " imports System namespace N {|BC37284:<<<<<<< This is mine!|} class Program end class {|BC37284:=======|} class Program2 end class {|BC37284:>>>>>>> This is theirs!|} {|BC37284:<<<<<<< This is mine!|} class Program3 end class {|BC37284:=======|} class Program4 end class {|BC37284:>>>>>>> This is theirs!|} end namespace" Dim fixedSource = " imports System namespace N class Program end class class Program2 end class class Program3 end class class Program4 end class end namespace" Await New VerifyVB.Test With { .TestCode = source, .FixedCode = fixedSource, .NumberOfIncrementalIterations = 2, .CodeActionIndex = 2, .CodeActionEquivalenceKey = AbstractResolveConflictMarkerCodeFixProvider.TakeBothEquivalenceKey }.RunAsync() End Function End Class End Namespace
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/Core/Portable/CommandLine/CommonCompiler.CompilerRelativePathResolver.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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal abstract partial class CommonCompiler { /// <summary> /// Looks for metadata references among the assembly file references given to the compilation when constructed. /// When scripts are included into a project we don't want #r's to reference other assemblies than those /// specified explicitly in the project references. /// </summary> internal sealed class CompilerRelativePathResolver : RelativePathResolver { internal ICommonCompilerFileSystem FileSystem { get; } internal CompilerRelativePathResolver(ICommonCompilerFileSystem fileSystem, ImmutableArray<string> searchPaths, string? baseDirectory) : base(searchPaths, baseDirectory) { FileSystem = fileSystem; } protected override bool FileExists(string fullPath) => FileSystem.FileExists(fullPath); } } }
// Licensed to the .NET Foundation under one or more 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal abstract partial class CommonCompiler { /// <summary> /// Looks for metadata references among the assembly file references given to the compilation when constructed. /// When scripts are included into a project we don't want #r's to reference other assemblies than those /// specified explicitly in the project references. /// </summary> internal sealed class CompilerRelativePathResolver : RelativePathResolver { internal ICommonCompilerFileSystem FileSystem { get; } internal CompilerRelativePathResolver(ICommonCompilerFileSystem fileSystem, ImmutableArray<string> searchPaths, string? baseDirectory) : base(searchPaths, baseDirectory) { FileSystem = fileSystem; } protected override bool FileExists(string fullPath) => FileSystem.FileExists(fullPath); } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.cs.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="cs" original="../CSharpFeaturesResources.resx"> <body> <trans-unit id="Add_await"> <source>Add 'await'</source> <target state="translated">Přidat await</target> <note>{Locked="await"} "await" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_await_and_ConfigureAwaitFalse"> <source>Add 'await' and 'ConfigureAwait(false)'</source> <target state="translated">Přidat await a ConfigureAwait(false)</target> <note>{Locked="await"} "await" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_missing_usings"> <source>Add missing usings</source> <target state="translated">Přidat chybějící direktivy using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_remove_braces_for_single_line_control_statements"> <source>Add/remove braces for single-line control statements</source> <target state="translated">Přidat/odebrat složené závorky pro řídicí příkazy na jeden řádek</target> <note /> </trans-unit> <trans-unit id="Allow_unsafe_code_in_this_project"> <source>Allow unsafe code in this project</source> <target state="translated">Povolit v tomto projektu nezabezpečený kód</target> <note /> </trans-unit> <trans-unit id="Apply_expression_block_body_preferences"> <source>Apply expression/block body preferences</source> <target state="translated">Použít předvolby pro text výrazu/bloku</target> <note /> </trans-unit> <trans-unit id="Apply_implicit_explicit_type_preferences"> <source>Apply implicit/explicit type preferences</source> <target state="translated">Použít předvolby imlicitního/explicitního typu</target> <note /> </trans-unit> <trans-unit id="Apply_inline_out_variable_preferences"> <source>Apply inline 'out' variables preferences</source> <target state="translated">Použít předvolby vložených proměnných out</target> <note /> </trans-unit> <trans-unit id="Apply_language_framework_type_preferences"> <source>Apply language/framework type preferences</source> <target state="translated">Použít předvolby typu jazyka/architektury</target> <note /> </trans-unit> <trans-unit id="Apply_this_qualification_preferences"> <source>Apply 'this.' qualification preferences</source> <target state="translated">Použít předvolby kvalifikace this.</target> <note /> </trans-unit> <trans-unit id="Apply_using_directive_placement_preferences"> <source>Apply preferred 'using' placement preferences</source> <target state="translated">Použít upřednostňované předvolby umístění using</target> <note>'using' is a C# keyword and should not be localized</note> </trans-unit> <trans-unit id="Assign_out_parameters"> <source>Assign 'out' parameters</source> <target state="translated">Přiřadit parametry out</target> <note>{Locked="out"} "out" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Assign_out_parameters_at_start"> <source>Assign 'out' parameters (at start)</source> <target state="translated">Přiřadit parametry out (při spuštění)</target> <note>{Locked="out"} "out" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Assign_to_0"> <source>Assign to '{0}'</source> <target state="translated">Přiřadit k {0}</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_potential_pattern_variable_declaration"> <source>Autoselect disabled due to potential pattern variable declaration.</source> <target state="translated">Automatický výběr je zakázaný kvůli možné deklaraci proměnné vzoru.</target> <note /> </trans-unit> <trans-unit id="Change_to_as_expression"> <source>Change to 'as' expression</source> <target state="translated">Změnit na výraz as</target> <note /> </trans-unit> <trans-unit id="Change_to_cast"> <source>Change to cast</source> <target state="translated">Změnit na přetypování</target> <note /> </trans-unit> <trans-unit id="Compare_to_0"> <source>Compare to '{0}'</source> <target state="translated">Porovnat s {0}</target> <note /> </trans-unit> <trans-unit id="Convert_to_method"> <source>Convert to method</source> <target state="translated">Převést na metodu</target> <note /> </trans-unit> <trans-unit id="Convert_to_regular_string"> <source>Convert to regular string</source> <target state="translated">Převést na běžný řetězec</target> <note /> </trans-unit> <trans-unit id="Convert_to_switch_expression"> <source>Convert to 'switch' expression</source> <target state="translated">Převést na výraz switch</target> <note /> </trans-unit> <trans-unit id="Convert_to_switch_statement"> <source>Convert to 'switch' statement</source> <target state="translated">Převést na příkaz switch</target> <note /> </trans-unit> <trans-unit id="Convert_to_verbatim_string"> <source>Convert to verbatim string</source> <target state="translated">Převést na doslovný řetězec</target> <note /> </trans-unit> <trans-unit id="Declare_as_nullable"> <source>Declare as nullable</source> <target state="translated">Deklarovat jako s možnou hodnotou null</target> <note /> </trans-unit> <trans-unit id="Fix_return_type"> <source>Fix return type</source> <target state="translated">Opravit návratový typ</target> <note /> </trans-unit> <trans-unit id="Inline_temporary_variable"> <source>Inline temporary variable</source> <target state="translated">Dočasná vložená proměnná</target> <note /> </trans-unit> <trans-unit id="Conflict_s_detected"> <source>Conflict(s) detected.</source> <target state="translated">Zjistily se konflikty.</target> <note /> </trans-unit> <trans-unit id="Make_private_field_readonly_when_possible"> <source>Make private fields readonly when possible</source> <target state="translated">Nastavit privátní pole jako jenom pro čtení, kde je to možné</target> <note /> </trans-unit> <trans-unit id="Make_ref_struct"> <source>Make 'ref struct'</source> <target state="translated">Nastavit jako ref struct</target> <note>{Locked="ref"}{Locked="struct"} "ref" and "struct" are C# keywords and should not be localized.</note> </trans-unit> <trans-unit id="Remove_in_keyword"> <source>Remove 'in' keyword</source> <target state="translated">Odebrat klíčové slovo in</target> <note>{Locked="in"} "in" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Remove_new_modifier"> <source>Remove 'new' modifier</source> <target state="translated">Odebrat modifikátor new</target> <note /> </trans-unit> <trans-unit id="Reverse_for_statement"> <source>Reverse 'for' statement</source> <target state="translated">Obrátit příkaz for</target> <note>{Locked="for"} "for" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Simplify_lambda_expression"> <source>Simplify lambda expression</source> <target state="translated">Zjednodušit výraz lambda</target> <note /> </trans-unit> <trans-unit id="Simplify_all_occurrences"> <source>Simplify all occurrences</source> <target state="translated">Zjednodušit všechny výskyty</target> <note /> </trans-unit> <trans-unit id="Sort_accessibility_modifiers"> <source>Sort accessibility modifiers</source> <target state="translated">Seřadit modifikátory dostupnosti</target> <note /> </trans-unit> <trans-unit id="Unseal_class_0"> <source>Unseal class '{0}'</source> <target state="translated">Rozpečetit třídu {0}</target> <note /> </trans-unit> <trans-unit id="Use_recursive_patterns"> <source>Use recursive patterns</source> <target state="new">Use recursive patterns</target> <note /> </trans-unit> <trans-unit id="Warning_Inlining_temporary_into_conditional_method_call"> <source>Warning: Inlining temporary into conditional method call.</source> <target state="translated">Upozornění: dočasné vkládání do volání podmíněné metody.</target> <note /> </trans-unit> <trans-unit id="Warning_Inlining_temporary_variable_may_change_code_meaning"> <source>Warning: Inlining temporary variable may change code meaning.</source> <target state="translated">Upozornění: Vložení dočasné proměnné může změnit význam kódu.</target> <note /> </trans-unit> <trans-unit id="asynchronous_foreach_statement"> <source>asynchronous foreach statement</source> <target state="translated">asynchronní příkaz foreach</target> <note>{Locked="foreach"} "foreach" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="asynchronous_using_declaration"> <source>asynchronous using declaration</source> <target state="translated">asynchronní deklarace using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="extern_alias"> <source>extern alias</source> <target state="translated">externí alias</target> <note /> </trans-unit> <trans-unit id="lambda_expression"> <source>&lt;lambda expression&gt;</source> <target state="translated">&lt;lambda výraz&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_potential_lambda_declaration"> <source>Autoselect disabled due to potential lambda declaration.</source> <target state="translated">Automatický výběr je zakázaný kvůli možné deklaraci lambda.</target> <note /> </trans-unit> <trans-unit id="local_variable_declaration"> <source>local variable declaration</source> <target state="translated">deklarace lokální proměnné</target> <note /> </trans-unit> <trans-unit id="member_name"> <source>&lt;member name&gt; = </source> <target state="translated">&lt;název členu&gt; =</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_possible_explicitly_named_anonymous_type_member_creation"> <source>Autoselect disabled due to possible explicitly named anonymous type member creation.</source> <target state="translated">Automatický výběr je zakázaný kvůli možnému vytvoření explicitně pojmenovaného člena anonymního typu.</target> <note /> </trans-unit> <trans-unit id="element_name"> <source>&lt;element name&gt; : </source> <target state="translated">&lt;název prvku&gt;:</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_possible_tuple_type_element_creation"> <source>Autoselect disabled due to possible tuple type element creation.</source> <target state="translated">Automatický výběr je zakázaný kvůli možnému vytvoření elementu typu řazená kolekce členů.</target> <note /> </trans-unit> <trans-unit id="pattern_variable"> <source>&lt;pattern variable&gt;</source> <target state="translated">&lt;proměnná vzoru&gt;</target> <note /> </trans-unit> <trans-unit id="range_variable"> <source>&lt;range variable&gt;</source> <target state="translated">&lt;proměnná rozsahu&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_potential_range_variable_declaration"> <source>Autoselect disabled due to potential range variable declaration.</source> <target state="translated">Automatický výběr je zakázaný kvůli možné deklaraci proměnné rozsahu.</target> <note /> </trans-unit> <trans-unit id="Simplify_name_0"> <source>Simplify name '{0}'</source> <target state="translated">Zjednodušit název {0}</target> <note /> </trans-unit> <trans-unit id="Simplify_member_access_0"> <source>Simplify member access '{0}'</source> <target state="translated">Zjednodušit přístup ke členu {0}</target> <note /> </trans-unit> <trans-unit id="Remove_this_qualification"> <source>Remove 'this' qualification</source> <target state="translated">Odebrat kvalifikaci this</target> <note /> </trans-unit> <trans-unit id="Name_can_be_simplified"> <source>Name can be simplified</source> <target state="translated">Název může být zjednodušený.</target> <note /> </trans-unit> <trans-unit id="Can_t_determine_valid_range_of_statements_to_extract"> <source>Can't determine valid range of statements to extract</source> <target state="translated">Nemůže určit platný rozsah příkazů k extrakci.</target> <note /> </trans-unit> <trans-unit id="Not_all_code_paths_return"> <source>Not all code paths return</source> <target state="translated">Ne všechny cesty kódu vracejí</target> <note /> </trans-unit> <trans-unit id="Selection_does_not_contain_a_valid_node"> <source>Selection does not contain a valid node</source> <target state="translated">Výběr neobsahuje platný uzel.</target> <note /> </trans-unit> <trans-unit id="Invalid_selection"> <source>Invalid selection.</source> <target state="translated">Neplatný výběr</target> <note /> </trans-unit> <trans-unit id="Contains_invalid_selection"> <source>Contains invalid selection.</source> <target state="translated">Obsahuje neplatný výběr.</target> <note /> </trans-unit> <trans-unit id="The_selection_contains_syntactic_errors"> <source>The selection contains syntactic errors</source> <target state="translated">Výběr obsahuje syntaktické chyby.</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_cross_over_preprocessor_directives"> <source>Selection can not cross over preprocessor directives.</source> <target state="translated">Výběr nemůže zasahovat do direktiv preprocesorů.</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_contain_a_yield_statement"> <source>Selection can not contain a yield statement.</source> <target state="translated">Výběr nemůže obsahovat žádný příkaz Yield.</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_contain_throw_statement"> <source>Selection can not contain throw statement.</source> <target state="translated">Výběr nemůže obsahovat žádný příkaz Throw.</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_be_part_of_constant_initializer_expression"> <source>Selection can not be part of constant initializer expression.</source> <target state="translated">Výběr nemůže být součástí konstantního výrazu inicializátoru.</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_contain_a_pattern_expression"> <source>Selection can not contain a pattern expression.</source> <target state="translated">Výběr nesmí obsahovat výraz vzoru.</target> <note /> </trans-unit> <trans-unit id="The_selected_code_is_inside_an_unsafe_context"> <source>The selected code is inside an unsafe context.</source> <target state="translated">Vybraný uzel je uvnitř nezabezpečeného kontextu.</target> <note /> </trans-unit> <trans-unit id="No_valid_statement_range_to_extract"> <source>No valid statement range to extract</source> <target state="translated">Žádný platný rozsah příkazů pro extrakci</target> <note /> </trans-unit> <trans-unit id="deprecated"> <source>deprecated</source> <target state="translated">zastaralé</target> <note /> </trans-unit> <trans-unit id="extension"> <source>extension</source> <target state="translated">rozšíření</target> <note /> </trans-unit> <trans-unit id="awaitable"> <source>awaitable</source> <target state="translated">očekávatelný</target> <note /> </trans-unit> <trans-unit id="awaitable_extension"> <source>awaitable, extension</source> <target state="translated">očekávatelný, rozšíření</target> <note /> </trans-unit> <trans-unit id="Organize_Usings"> <source>Organize Usings</source> <target state="translated">Uspořádat direktivy using</target> <note /> </trans-unit> <trans-unit id="Insert_await"> <source>Insert 'await'.</source> <target state="translated">Vložit operátor Await</target> <note /> </trans-unit> <trans-unit id="Make_0_return_Task_instead_of_void"> <source>Make {0} return Task instead of void.</source> <target state="translated">Nastavit, že {0} má místo hodnoty typu Void vracet hodnotu Task</target> <note /> </trans-unit> <trans-unit id="Change_return_type_from_0_to_1"> <source>Change return type from {0} to {1}</source> <target state="translated">Změnit typ návratové hodnoty z: {0} na: {1}</target> <note /> </trans-unit> <trans-unit id="Replace_return_with_yield_return"> <source>Replace return with yield return</source> <target state="translated">Nahradit příkaz return příkazem yield return</target> <note /> </trans-unit> <trans-unit id="Generate_explicit_conversion_operator_in_0"> <source>Generate explicit conversion operator in '{0}'</source> <target state="translated">Generovat explicitní operátor převodu v {0}</target> <note /> </trans-unit> <trans-unit id="Generate_implicit_conversion_operator_in_0"> <source>Generate implicit conversion operator in '{0}'</source> <target state="translated">Generovat implicitní operátor převodu v {0}</target> <note /> </trans-unit> <trans-unit id="record_"> <source>record</source> <target state="translated">záznam</target> <note /> </trans-unit> <trans-unit id="record_struct"> <source>record struct</source> <target state="new">record struct</target> <note /> </trans-unit> <trans-unit id="switch_statement"> <source>switch statement</source> <target state="translated">příkaz switch</target> <note>{Locked="switch"} "switch" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="switch_statement_case_clause"> <source>switch statement case clause</source> <target state="translated">klauzule case příkazu switch</target> <note>{Locked="switch"}{Locked="case"} "switch" and "case" are a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="try_block"> <source>try block</source> <target state="translated">blok try</target> <note>{Locked="try"} "try" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="catch_clause"> <source>catch clause</source> <target state="translated">klauzule catch</target> <note>{Locked="catch"} "catch" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="filter_clause"> <source>filter clause</source> <target state="translated">klauzule filter</target> <note /> </trans-unit> <trans-unit id="finally_clause"> <source>finally clause</source> <target state="translated">klauzule finally</target> <note>{Locked="finally"} "finally" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="fixed_statement"> <source>fixed statement</source> <target state="translated">příkaz fixed</target> <note>{Locked="fixed"} "fixed" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="using_declaration"> <source>using declaration</source> <target state="translated">deklarace using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="using_statement"> <source>using statement</source> <target state="translated">příkaz using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="lock_statement"> <source>lock statement</source> <target state="translated">příkaz lock</target> <note>{Locked="lock"} "lock" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="foreach_statement"> <source>foreach statement</source> <target state="translated">příkaz foreach</target> <note>{Locked="foreach"} "foreach" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="checked_statement"> <source>checked statement</source> <target state="translated">příkaz checked</target> <note>{Locked="checked"} "checked" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="unchecked_statement"> <source>unchecked statement</source> <target state="translated">příkaz unchecked</target> <note>{Locked="unchecked"} "unchecked" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="await_expression"> <source>await expression</source> <target state="translated">výraz await</target> <note>{Locked="await"} "await" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="lambda"> <source>lambda</source> <target state="translated">lambda</target> <note /> </trans-unit> <trans-unit id="anonymous_method"> <source>anonymous method</source> <target state="translated">anonymní metoda</target> <note /> </trans-unit> <trans-unit id="from_clause"> <source>from clause</source> <target state="translated">klauzule from</target> <note /> </trans-unit> <trans-unit id="join_clause"> <source>join clause</source> <target state="translated">klauzule join</target> <note>{Locked="join"} "join" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="let_clause"> <source>let clause</source> <target state="translated">klauzule let</target> <note>{Locked="let"} "let" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="where_clause"> <source>where clause</source> <target state="translated">klauzule where</target> <note>{Locked="where"} "where" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="orderby_clause"> <source>orderby clause</source> <target state="translated">klauzule orderby</target> <note>{Locked="orderby"} "orderby" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="select_clause"> <source>select clause</source> <target state="translated">klauzule select</target> <note>{Locked="select"} "select" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="groupby_clause"> <source>groupby clause</source> <target state="translated">klauzule groupby</target> <note>{Locked="groupby"} "groupby" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="query_body"> <source>query body</source> <target state="translated">tělo dotazu</target> <note /> </trans-unit> <trans-unit id="into_clause"> <source>into clause</source> <target state="translated">klauzule into</target> <note>{Locked="into"} "into" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="is_pattern"> <source>is pattern</source> <target state="translated">vzor is</target> <note>{Locked="is"} "is" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="deconstruction"> <source>deconstruction</source> <target state="translated">dekonstrukce</target> <note /> </trans-unit> <trans-unit id="tuple"> <source>tuple</source> <target state="translated">řazená kolekce členů</target> <note /> </trans-unit> <trans-unit id="local_function"> <source>local function</source> <target state="translated">lokální funkce</target> <note /> </trans-unit> <trans-unit id="out_var"> <source>out variable</source> <target state="translated">proměnná out</target> <note>{Locked="out"} "out" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="ref_local_or_expression"> <source>ref local or expression</source> <target state="translated">místní ref nebo výraz</target> <note>{Locked="ref"} "ref" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="global_statement"> <source>global statement</source> <target state="translated">příkaz global</target> <note>{Locked="global"} "global" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="using_directive"> <source>using directive</source> <target state="translated">direktiva using</target> <note /> </trans-unit> <trans-unit id="event_field"> <source>event field</source> <target state="translated">pole event</target> <note /> </trans-unit> <trans-unit id="conversion_operator"> <source>conversion operator</source> <target state="translated">operátor převodu</target> <note /> </trans-unit> <trans-unit id="destructor"> <source>destructor</source> <target state="translated">destruktor</target> <note /> </trans-unit> <trans-unit id="indexer"> <source>indexer</source> <target state="translated">indexer</target> <note /> </trans-unit> <trans-unit id="property_getter"> <source>property getter</source> <target state="translated">metoda getter vlastnosti</target> <note /> </trans-unit> <trans-unit id="indexer_getter"> <source>indexer getter</source> <target state="translated">metoda getter indexeru</target> <note /> </trans-unit> <trans-unit id="property_setter"> <source>property setter</source> <target state="translated">metoda Set vlastnosti</target> <note /> </trans-unit> <trans-unit id="indexer_setter"> <source>indexer setter</source> <target state="translated">metoda Set indexeru</target> <note /> </trans-unit> <trans-unit id="attribute_target"> <source>attribute target</source> <target state="translated">cíl atributu</target> <note /> </trans-unit> <trans-unit id="_0_does_not_contain_a_constructor_that_takes_that_many_arguments"> <source>'{0}' does not contain a constructor that takes that many arguments.</source> <target state="translated">{0} neobsahuje konstruktor, který přebírá tolik argumentů.</target> <note /> </trans-unit> <trans-unit id="The_name_0_does_not_exist_in_the_current_context"> <source>The name '{0}' does not exist in the current context.</source> <target state="translated">Název {0} v aktuálním kontextu neexistuje.</target> <note /> </trans-unit> <trans-unit id="Hide_base_member"> <source>Hide base member</source> <target state="translated">Skrýt základního člena</target> <note /> </trans-unit> <trans-unit id="Properties"> <source>Properties</source> <target state="translated">Vlastnosti</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_namespace_declaration"> <source>Autoselect disabled due to namespace declaration.</source> <target state="translated">Automatický výběr je zakázaný kvůli deklaraci oboru názvů.</target> <note /> </trans-unit> <trans-unit id="namespace_name"> <source>&lt;namespace name&gt;</source> <target state="translated">&lt;název oboru názvů&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_type_declaration"> <source>Autoselect disabled due to type declaration.</source> <target state="translated">Automatický výběr je zakázaný kvůli deklaraci typu.</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_possible_deconstruction_declaration"> <source>Autoselect disabled due to possible deconstruction declaration.</source> <target state="translated">Automatický výběr je zakázaný kvůli možné deklaraci dekonstrukce.</target> <note /> </trans-unit> <trans-unit id="Upgrade_this_project_to_csharp_language_version_0"> <source>Upgrade this project to C# language version '{0}'</source> <target state="translated">Upgradovat tento projekt na jazykovou verzi C# {0}</target> <note /> </trans-unit> <trans-unit id="Upgrade_all_csharp_projects_to_language_version_0"> <source>Upgrade all C# projects to language version '{0}'</source> <target state="translated">Upgradovat všechny projekty jazyka C# na jazykovou verzi {0}</target> <note /> </trans-unit> <trans-unit id="class_name"> <source>&lt;class name&gt;</source> <target state="translated">&lt;název třídy&gt;</target> <note /> </trans-unit> <trans-unit id="interface_name"> <source>&lt;interface name&gt;</source> <target state="translated">&lt;název rozhraní&gt;</target> <note /> </trans-unit> <trans-unit id="designation_name"> <source>&lt;designation name&gt;</source> <target state="translated">&lt;název označení&gt;</target> <note /> </trans-unit> <trans-unit id="struct_name"> <source>&lt;struct name&gt;</source> <target state="translated">&lt;název struktury&gt;</target> <note /> </trans-unit> <trans-unit id="Make_method_async"> <source>Make method async</source> <target state="translated">Převést metodu na asynchronní</target> <note /> </trans-unit> <trans-unit id="Make_method_async_remain_void"> <source>Make method async (stay void)</source> <target state="translated">Převést metodu na asynchronní (ponechat neplatné)</target> <note /> </trans-unit> <trans-unit id="Name"> <source>&lt;Name&gt;</source> <target state="translated">&lt;Název&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_member_declaration"> <source>Autoselect disabled due to member declaration</source> <target state="translated">Automatický výběr je zakázaný z důvodu deklarace člena.</target> <note /> </trans-unit> <trans-unit id="Suggested_name"> <source>(Suggested name)</source> <target state="translated">(Navržený název)</target> <note /> </trans-unit> <trans-unit id="Remove_unused_function"> <source>Remove unused function</source> <target state="translated">Odebrat nepoužitou funkci</target> <note /> </trans-unit> <trans-unit id="Add_parentheses_around_conditional_expression_in_interpolated_string"> <source>Add parentheses</source> <target state="translated">Přidat závorky</target> <note /> </trans-unit> <trans-unit id="Convert_to_foreach"> <source>Convert to 'foreach'</source> <target state="translated">Převést na foreach</target> <note /> </trans-unit> <trans-unit id="Convert_to_for"> <source>Convert to 'for'</source> <target state="translated">Převést na for</target> <note /> </trans-unit> <trans-unit id="Invert_if"> <source>Invert if</source> <target state="translated">Invertovat if</target> <note /> </trans-unit> <trans-unit id="Add_Obsolete"> <source>Add [Obsolete]</source> <target state="translated">Přidat [Obsolete]</target> <note /> </trans-unit> <trans-unit id="Use_0"> <source>Use '{0}'</source> <target state="translated">Použít {0}</target> <note /> </trans-unit> <trans-unit id="Introduce_using_statement"> <source>Introduce 'using' statement</source> <target state="translated">Zavést příkaz using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="yield_break_statement"> <source>yield break statement</source> <target state="translated">příkaz yield break</target> <note>{Locked="yield break"} "yield break" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="yield_return_statement"> <source>yield return statement</source> <target state="translated">příkaz yield return</target> <note>{Locked="yield return"} "yield return" is a C# keyword and should not be localized.</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="cs" original="../CSharpFeaturesResources.resx"> <body> <trans-unit id="Add_await"> <source>Add 'await'</source> <target state="translated">Přidat await</target> <note>{Locked="await"} "await" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_await_and_ConfigureAwaitFalse"> <source>Add 'await' and 'ConfigureAwait(false)'</source> <target state="translated">Přidat await a ConfigureAwait(false)</target> <note>{Locked="await"} "await" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_missing_usings"> <source>Add missing usings</source> <target state="translated">Přidat chybějící direktivy using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_remove_braces_for_single_line_control_statements"> <source>Add/remove braces for single-line control statements</source> <target state="translated">Přidat/odebrat složené závorky pro řídicí příkazy na jeden řádek</target> <note /> </trans-unit> <trans-unit id="Allow_unsafe_code_in_this_project"> <source>Allow unsafe code in this project</source> <target state="translated">Povolit v tomto projektu nezabezpečený kód</target> <note /> </trans-unit> <trans-unit id="Apply_expression_block_body_preferences"> <source>Apply expression/block body preferences</source> <target state="translated">Použít předvolby pro text výrazu/bloku</target> <note /> </trans-unit> <trans-unit id="Apply_implicit_explicit_type_preferences"> <source>Apply implicit/explicit type preferences</source> <target state="translated">Použít předvolby imlicitního/explicitního typu</target> <note /> </trans-unit> <trans-unit id="Apply_inline_out_variable_preferences"> <source>Apply inline 'out' variables preferences</source> <target state="translated">Použít předvolby vložených proměnných out</target> <note /> </trans-unit> <trans-unit id="Apply_language_framework_type_preferences"> <source>Apply language/framework type preferences</source> <target state="translated">Použít předvolby typu jazyka/architektury</target> <note /> </trans-unit> <trans-unit id="Apply_this_qualification_preferences"> <source>Apply 'this.' qualification preferences</source> <target state="translated">Použít předvolby kvalifikace this.</target> <note /> </trans-unit> <trans-unit id="Apply_using_directive_placement_preferences"> <source>Apply preferred 'using' placement preferences</source> <target state="translated">Použít upřednostňované předvolby umístění using</target> <note>'using' is a C# keyword and should not be localized</note> </trans-unit> <trans-unit id="Assign_out_parameters"> <source>Assign 'out' parameters</source> <target state="translated">Přiřadit parametry out</target> <note>{Locked="out"} "out" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Assign_out_parameters_at_start"> <source>Assign 'out' parameters (at start)</source> <target state="translated">Přiřadit parametry out (při spuštění)</target> <note>{Locked="out"} "out" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Assign_to_0"> <source>Assign to '{0}'</source> <target state="translated">Přiřadit k {0}</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_potential_pattern_variable_declaration"> <source>Autoselect disabled due to potential pattern variable declaration.</source> <target state="translated">Automatický výběr je zakázaný kvůli možné deklaraci proměnné vzoru.</target> <note /> </trans-unit> <trans-unit id="Change_to_as_expression"> <source>Change to 'as' expression</source> <target state="translated">Změnit na výraz as</target> <note /> </trans-unit> <trans-unit id="Change_to_cast"> <source>Change to cast</source> <target state="translated">Změnit na přetypování</target> <note /> </trans-unit> <trans-unit id="Compare_to_0"> <source>Compare to '{0}'</source> <target state="translated">Porovnat s {0}</target> <note /> </trans-unit> <trans-unit id="Convert_to_method"> <source>Convert to method</source> <target state="translated">Převést na metodu</target> <note /> </trans-unit> <trans-unit id="Convert_to_regular_string"> <source>Convert to regular string</source> <target state="translated">Převést na běžný řetězec</target> <note /> </trans-unit> <trans-unit id="Convert_to_switch_expression"> <source>Convert to 'switch' expression</source> <target state="translated">Převést na výraz switch</target> <note /> </trans-unit> <trans-unit id="Convert_to_switch_statement"> <source>Convert to 'switch' statement</source> <target state="translated">Převést na příkaz switch</target> <note /> </trans-unit> <trans-unit id="Convert_to_verbatim_string"> <source>Convert to verbatim string</source> <target state="translated">Převést na doslovný řetězec</target> <note /> </trans-unit> <trans-unit id="Declare_as_nullable"> <source>Declare as nullable</source> <target state="translated">Deklarovat jako s možnou hodnotou null</target> <note /> </trans-unit> <trans-unit id="Fix_return_type"> <source>Fix return type</source> <target state="translated">Opravit návratový typ</target> <note /> </trans-unit> <trans-unit id="Inline_temporary_variable"> <source>Inline temporary variable</source> <target state="translated">Dočasná vložená proměnná</target> <note /> </trans-unit> <trans-unit id="Conflict_s_detected"> <source>Conflict(s) detected.</source> <target state="translated">Zjistily se konflikty.</target> <note /> </trans-unit> <trans-unit id="Make_private_field_readonly_when_possible"> <source>Make private fields readonly when possible</source> <target state="translated">Nastavit privátní pole jako jenom pro čtení, kde je to možné</target> <note /> </trans-unit> <trans-unit id="Make_ref_struct"> <source>Make 'ref struct'</source> <target state="translated">Nastavit jako ref struct</target> <note>{Locked="ref"}{Locked="struct"} "ref" and "struct" are C# keywords and should not be localized.</note> </trans-unit> <trans-unit id="Remove_in_keyword"> <source>Remove 'in' keyword</source> <target state="translated">Odebrat klíčové slovo in</target> <note>{Locked="in"} "in" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Remove_new_modifier"> <source>Remove 'new' modifier</source> <target state="translated">Odebrat modifikátor new</target> <note /> </trans-unit> <trans-unit id="Reverse_for_statement"> <source>Reverse 'for' statement</source> <target state="translated">Obrátit příkaz for</target> <note>{Locked="for"} "for" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Simplify_lambda_expression"> <source>Simplify lambda expression</source> <target state="translated">Zjednodušit výraz lambda</target> <note /> </trans-unit> <trans-unit id="Simplify_all_occurrences"> <source>Simplify all occurrences</source> <target state="translated">Zjednodušit všechny výskyty</target> <note /> </trans-unit> <trans-unit id="Sort_accessibility_modifiers"> <source>Sort accessibility modifiers</source> <target state="translated">Seřadit modifikátory dostupnosti</target> <note /> </trans-unit> <trans-unit id="Unseal_class_0"> <source>Unseal class '{0}'</source> <target state="translated">Rozpečetit třídu {0}</target> <note /> </trans-unit> <trans-unit id="Use_recursive_patterns"> <source>Use recursive patterns</source> <target state="new">Use recursive patterns</target> <note /> </trans-unit> <trans-unit id="Warning_Inlining_temporary_into_conditional_method_call"> <source>Warning: Inlining temporary into conditional method call.</source> <target state="translated">Upozornění: dočasné vkládání do volání podmíněné metody.</target> <note /> </trans-unit> <trans-unit id="Warning_Inlining_temporary_variable_may_change_code_meaning"> <source>Warning: Inlining temporary variable may change code meaning.</source> <target state="translated">Upozornění: Vložení dočasné proměnné může změnit význam kódu.</target> <note /> </trans-unit> <trans-unit id="asynchronous_foreach_statement"> <source>asynchronous foreach statement</source> <target state="translated">asynchronní příkaz foreach</target> <note>{Locked="foreach"} "foreach" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="asynchronous_using_declaration"> <source>asynchronous using declaration</source> <target state="translated">asynchronní deklarace using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="extern_alias"> <source>extern alias</source> <target state="translated">externí alias</target> <note /> </trans-unit> <trans-unit id="lambda_expression"> <source>&lt;lambda expression&gt;</source> <target state="translated">&lt;lambda výraz&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_potential_lambda_declaration"> <source>Autoselect disabled due to potential lambda declaration.</source> <target state="translated">Automatický výběr je zakázaný kvůli možné deklaraci lambda.</target> <note /> </trans-unit> <trans-unit id="local_variable_declaration"> <source>local variable declaration</source> <target state="translated">deklarace lokální proměnné</target> <note /> </trans-unit> <trans-unit id="member_name"> <source>&lt;member name&gt; = </source> <target state="translated">&lt;název členu&gt; =</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_possible_explicitly_named_anonymous_type_member_creation"> <source>Autoselect disabled due to possible explicitly named anonymous type member creation.</source> <target state="translated">Automatický výběr je zakázaný kvůli možnému vytvoření explicitně pojmenovaného člena anonymního typu.</target> <note /> </trans-unit> <trans-unit id="element_name"> <source>&lt;element name&gt; : </source> <target state="translated">&lt;název prvku&gt;:</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_possible_tuple_type_element_creation"> <source>Autoselect disabled due to possible tuple type element creation.</source> <target state="translated">Automatický výběr je zakázaný kvůli možnému vytvoření elementu typu řazená kolekce členů.</target> <note /> </trans-unit> <trans-unit id="pattern_variable"> <source>&lt;pattern variable&gt;</source> <target state="translated">&lt;proměnná vzoru&gt;</target> <note /> </trans-unit> <trans-unit id="range_variable"> <source>&lt;range variable&gt;</source> <target state="translated">&lt;proměnná rozsahu&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_potential_range_variable_declaration"> <source>Autoselect disabled due to potential range variable declaration.</source> <target state="translated">Automatický výběr je zakázaný kvůli možné deklaraci proměnné rozsahu.</target> <note /> </trans-unit> <trans-unit id="Simplify_name_0"> <source>Simplify name '{0}'</source> <target state="translated">Zjednodušit název {0}</target> <note /> </trans-unit> <trans-unit id="Simplify_member_access_0"> <source>Simplify member access '{0}'</source> <target state="translated">Zjednodušit přístup ke členu {0}</target> <note /> </trans-unit> <trans-unit id="Remove_this_qualification"> <source>Remove 'this' qualification</source> <target state="translated">Odebrat kvalifikaci this</target> <note /> </trans-unit> <trans-unit id="Name_can_be_simplified"> <source>Name can be simplified</source> <target state="translated">Název může být zjednodušený.</target> <note /> </trans-unit> <trans-unit id="Can_t_determine_valid_range_of_statements_to_extract"> <source>Can't determine valid range of statements to extract</source> <target state="translated">Nemůže určit platný rozsah příkazů k extrakci.</target> <note /> </trans-unit> <trans-unit id="Not_all_code_paths_return"> <source>Not all code paths return</source> <target state="translated">Ne všechny cesty kódu vracejí</target> <note /> </trans-unit> <trans-unit id="Selection_does_not_contain_a_valid_node"> <source>Selection does not contain a valid node</source> <target state="translated">Výběr neobsahuje platný uzel.</target> <note /> </trans-unit> <trans-unit id="Invalid_selection"> <source>Invalid selection.</source> <target state="translated">Neplatný výběr</target> <note /> </trans-unit> <trans-unit id="Contains_invalid_selection"> <source>Contains invalid selection.</source> <target state="translated">Obsahuje neplatný výběr.</target> <note /> </trans-unit> <trans-unit id="The_selection_contains_syntactic_errors"> <source>The selection contains syntactic errors</source> <target state="translated">Výběr obsahuje syntaktické chyby.</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_cross_over_preprocessor_directives"> <source>Selection can not cross over preprocessor directives.</source> <target state="translated">Výběr nemůže zasahovat do direktiv preprocesorů.</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_contain_a_yield_statement"> <source>Selection can not contain a yield statement.</source> <target state="translated">Výběr nemůže obsahovat žádný příkaz Yield.</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_contain_throw_statement"> <source>Selection can not contain throw statement.</source> <target state="translated">Výběr nemůže obsahovat žádný příkaz Throw.</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_be_part_of_constant_initializer_expression"> <source>Selection can not be part of constant initializer expression.</source> <target state="translated">Výběr nemůže být součástí konstantního výrazu inicializátoru.</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_contain_a_pattern_expression"> <source>Selection can not contain a pattern expression.</source> <target state="translated">Výběr nesmí obsahovat výraz vzoru.</target> <note /> </trans-unit> <trans-unit id="The_selected_code_is_inside_an_unsafe_context"> <source>The selected code is inside an unsafe context.</source> <target state="translated">Vybraný uzel je uvnitř nezabezpečeného kontextu.</target> <note /> </trans-unit> <trans-unit id="No_valid_statement_range_to_extract"> <source>No valid statement range to extract</source> <target state="translated">Žádný platný rozsah příkazů pro extrakci</target> <note /> </trans-unit> <trans-unit id="deprecated"> <source>deprecated</source> <target state="translated">zastaralé</target> <note /> </trans-unit> <trans-unit id="extension"> <source>extension</source> <target state="translated">rozšíření</target> <note /> </trans-unit> <trans-unit id="awaitable"> <source>awaitable</source> <target state="translated">očekávatelný</target> <note /> </trans-unit> <trans-unit id="awaitable_extension"> <source>awaitable, extension</source> <target state="translated">očekávatelný, rozšíření</target> <note /> </trans-unit> <trans-unit id="Organize_Usings"> <source>Organize Usings</source> <target state="translated">Uspořádat direktivy using</target> <note /> </trans-unit> <trans-unit id="Insert_await"> <source>Insert 'await'.</source> <target state="translated">Vložit operátor Await</target> <note /> </trans-unit> <trans-unit id="Make_0_return_Task_instead_of_void"> <source>Make {0} return Task instead of void.</source> <target state="translated">Nastavit, že {0} má místo hodnoty typu Void vracet hodnotu Task</target> <note /> </trans-unit> <trans-unit id="Change_return_type_from_0_to_1"> <source>Change return type from {0} to {1}</source> <target state="translated">Změnit typ návratové hodnoty z: {0} na: {1}</target> <note /> </trans-unit> <trans-unit id="Replace_return_with_yield_return"> <source>Replace return with yield return</source> <target state="translated">Nahradit příkaz return příkazem yield return</target> <note /> </trans-unit> <trans-unit id="Generate_explicit_conversion_operator_in_0"> <source>Generate explicit conversion operator in '{0}'</source> <target state="translated">Generovat explicitní operátor převodu v {0}</target> <note /> </trans-unit> <trans-unit id="Generate_implicit_conversion_operator_in_0"> <source>Generate implicit conversion operator in '{0}'</source> <target state="translated">Generovat implicitní operátor převodu v {0}</target> <note /> </trans-unit> <trans-unit id="record_"> <source>record</source> <target state="translated">záznam</target> <note /> </trans-unit> <trans-unit id="record_struct"> <source>record struct</source> <target state="new">record struct</target> <note /> </trans-unit> <trans-unit id="switch_statement"> <source>switch statement</source> <target state="translated">příkaz switch</target> <note>{Locked="switch"} "switch" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="switch_statement_case_clause"> <source>switch statement case clause</source> <target state="translated">klauzule case příkazu switch</target> <note>{Locked="switch"}{Locked="case"} "switch" and "case" are a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="try_block"> <source>try block</source> <target state="translated">blok try</target> <note>{Locked="try"} "try" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="catch_clause"> <source>catch clause</source> <target state="translated">klauzule catch</target> <note>{Locked="catch"} "catch" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="filter_clause"> <source>filter clause</source> <target state="translated">klauzule filter</target> <note /> </trans-unit> <trans-unit id="finally_clause"> <source>finally clause</source> <target state="translated">klauzule finally</target> <note>{Locked="finally"} "finally" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="fixed_statement"> <source>fixed statement</source> <target state="translated">příkaz fixed</target> <note>{Locked="fixed"} "fixed" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="using_declaration"> <source>using declaration</source> <target state="translated">deklarace using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="using_statement"> <source>using statement</source> <target state="translated">příkaz using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="lock_statement"> <source>lock statement</source> <target state="translated">příkaz lock</target> <note>{Locked="lock"} "lock" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="foreach_statement"> <source>foreach statement</source> <target state="translated">příkaz foreach</target> <note>{Locked="foreach"} "foreach" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="checked_statement"> <source>checked statement</source> <target state="translated">příkaz checked</target> <note>{Locked="checked"} "checked" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="unchecked_statement"> <source>unchecked statement</source> <target state="translated">příkaz unchecked</target> <note>{Locked="unchecked"} "unchecked" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="await_expression"> <source>await expression</source> <target state="translated">výraz await</target> <note>{Locked="await"} "await" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="lambda"> <source>lambda</source> <target state="translated">lambda</target> <note /> </trans-unit> <trans-unit id="anonymous_method"> <source>anonymous method</source> <target state="translated">anonymní metoda</target> <note /> </trans-unit> <trans-unit id="from_clause"> <source>from clause</source> <target state="translated">klauzule from</target> <note /> </trans-unit> <trans-unit id="join_clause"> <source>join clause</source> <target state="translated">klauzule join</target> <note>{Locked="join"} "join" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="let_clause"> <source>let clause</source> <target state="translated">klauzule let</target> <note>{Locked="let"} "let" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="where_clause"> <source>where clause</source> <target state="translated">klauzule where</target> <note>{Locked="where"} "where" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="orderby_clause"> <source>orderby clause</source> <target state="translated">klauzule orderby</target> <note>{Locked="orderby"} "orderby" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="select_clause"> <source>select clause</source> <target state="translated">klauzule select</target> <note>{Locked="select"} "select" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="groupby_clause"> <source>groupby clause</source> <target state="translated">klauzule groupby</target> <note>{Locked="groupby"} "groupby" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="query_body"> <source>query body</source> <target state="translated">tělo dotazu</target> <note /> </trans-unit> <trans-unit id="into_clause"> <source>into clause</source> <target state="translated">klauzule into</target> <note>{Locked="into"} "into" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="is_pattern"> <source>is pattern</source> <target state="translated">vzor is</target> <note>{Locked="is"} "is" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="deconstruction"> <source>deconstruction</source> <target state="translated">dekonstrukce</target> <note /> </trans-unit> <trans-unit id="tuple"> <source>tuple</source> <target state="translated">řazená kolekce členů</target> <note /> </trans-unit> <trans-unit id="local_function"> <source>local function</source> <target state="translated">lokální funkce</target> <note /> </trans-unit> <trans-unit id="out_var"> <source>out variable</source> <target state="translated">proměnná out</target> <note>{Locked="out"} "out" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="ref_local_or_expression"> <source>ref local or expression</source> <target state="translated">místní ref nebo výraz</target> <note>{Locked="ref"} "ref" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="global_statement"> <source>global statement</source> <target state="translated">příkaz global</target> <note>{Locked="global"} "global" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="using_directive"> <source>using directive</source> <target state="translated">direktiva using</target> <note /> </trans-unit> <trans-unit id="event_field"> <source>event field</source> <target state="translated">pole event</target> <note /> </trans-unit> <trans-unit id="conversion_operator"> <source>conversion operator</source> <target state="translated">operátor převodu</target> <note /> </trans-unit> <trans-unit id="destructor"> <source>destructor</source> <target state="translated">destruktor</target> <note /> </trans-unit> <trans-unit id="indexer"> <source>indexer</source> <target state="translated">indexer</target> <note /> </trans-unit> <trans-unit id="property_getter"> <source>property getter</source> <target state="translated">metoda getter vlastnosti</target> <note /> </trans-unit> <trans-unit id="indexer_getter"> <source>indexer getter</source> <target state="translated">metoda getter indexeru</target> <note /> </trans-unit> <trans-unit id="property_setter"> <source>property setter</source> <target state="translated">metoda Set vlastnosti</target> <note /> </trans-unit> <trans-unit id="indexer_setter"> <source>indexer setter</source> <target state="translated">metoda Set indexeru</target> <note /> </trans-unit> <trans-unit id="attribute_target"> <source>attribute target</source> <target state="translated">cíl atributu</target> <note /> </trans-unit> <trans-unit id="_0_does_not_contain_a_constructor_that_takes_that_many_arguments"> <source>'{0}' does not contain a constructor that takes that many arguments.</source> <target state="translated">{0} neobsahuje konstruktor, který přebírá tolik argumentů.</target> <note /> </trans-unit> <trans-unit id="The_name_0_does_not_exist_in_the_current_context"> <source>The name '{0}' does not exist in the current context.</source> <target state="translated">Název {0} v aktuálním kontextu neexistuje.</target> <note /> </trans-unit> <trans-unit id="Hide_base_member"> <source>Hide base member</source> <target state="translated">Skrýt základního člena</target> <note /> </trans-unit> <trans-unit id="Properties"> <source>Properties</source> <target state="translated">Vlastnosti</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_namespace_declaration"> <source>Autoselect disabled due to namespace declaration.</source> <target state="translated">Automatický výběr je zakázaný kvůli deklaraci oboru názvů.</target> <note /> </trans-unit> <trans-unit id="namespace_name"> <source>&lt;namespace name&gt;</source> <target state="translated">&lt;název oboru názvů&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_type_declaration"> <source>Autoselect disabled due to type declaration.</source> <target state="translated">Automatický výběr je zakázaný kvůli deklaraci typu.</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_possible_deconstruction_declaration"> <source>Autoselect disabled due to possible deconstruction declaration.</source> <target state="translated">Automatický výběr je zakázaný kvůli možné deklaraci dekonstrukce.</target> <note /> </trans-unit> <trans-unit id="Upgrade_this_project_to_csharp_language_version_0"> <source>Upgrade this project to C# language version '{0}'</source> <target state="translated">Upgradovat tento projekt na jazykovou verzi C# {0}</target> <note /> </trans-unit> <trans-unit id="Upgrade_all_csharp_projects_to_language_version_0"> <source>Upgrade all C# projects to language version '{0}'</source> <target state="translated">Upgradovat všechny projekty jazyka C# na jazykovou verzi {0}</target> <note /> </trans-unit> <trans-unit id="class_name"> <source>&lt;class name&gt;</source> <target state="translated">&lt;název třídy&gt;</target> <note /> </trans-unit> <trans-unit id="interface_name"> <source>&lt;interface name&gt;</source> <target state="translated">&lt;název rozhraní&gt;</target> <note /> </trans-unit> <trans-unit id="designation_name"> <source>&lt;designation name&gt;</source> <target state="translated">&lt;název označení&gt;</target> <note /> </trans-unit> <trans-unit id="struct_name"> <source>&lt;struct name&gt;</source> <target state="translated">&lt;název struktury&gt;</target> <note /> </trans-unit> <trans-unit id="Make_method_async"> <source>Make method async</source> <target state="translated">Převést metodu na asynchronní</target> <note /> </trans-unit> <trans-unit id="Make_method_async_remain_void"> <source>Make method async (stay void)</source> <target state="translated">Převést metodu na asynchronní (ponechat neplatné)</target> <note /> </trans-unit> <trans-unit id="Name"> <source>&lt;Name&gt;</source> <target state="translated">&lt;Název&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_member_declaration"> <source>Autoselect disabled due to member declaration</source> <target state="translated">Automatický výběr je zakázaný z důvodu deklarace člena.</target> <note /> </trans-unit> <trans-unit id="Suggested_name"> <source>(Suggested name)</source> <target state="translated">(Navržený název)</target> <note /> </trans-unit> <trans-unit id="Remove_unused_function"> <source>Remove unused function</source> <target state="translated">Odebrat nepoužitou funkci</target> <note /> </trans-unit> <trans-unit id="Add_parentheses_around_conditional_expression_in_interpolated_string"> <source>Add parentheses</source> <target state="translated">Přidat závorky</target> <note /> </trans-unit> <trans-unit id="Convert_to_foreach"> <source>Convert to 'foreach'</source> <target state="translated">Převést na foreach</target> <note /> </trans-unit> <trans-unit id="Convert_to_for"> <source>Convert to 'for'</source> <target state="translated">Převést na for</target> <note /> </trans-unit> <trans-unit id="Invert_if"> <source>Invert if</source> <target state="translated">Invertovat if</target> <note /> </trans-unit> <trans-unit id="Add_Obsolete"> <source>Add [Obsolete]</source> <target state="translated">Přidat [Obsolete]</target> <note /> </trans-unit> <trans-unit id="Use_0"> <source>Use '{0}'</source> <target state="translated">Použít {0}</target> <note /> </trans-unit> <trans-unit id="Introduce_using_statement"> <source>Introduce 'using' statement</source> <target state="translated">Zavést příkaz using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="yield_break_statement"> <source>yield break statement</source> <target state="translated">příkaz yield break</target> <note>{Locked="yield break"} "yield break" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="yield_return_statement"> <source>yield return statement</source> <target state="translated">příkaz yield return</target> <note>{Locked="yield return"} "yield return" is a C# keyword and should not be localized.</note> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/Core/Portable/Symbols/IFieldSymbolInternal.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.Symbols { internal interface IFieldSymbolInternal : ISymbolInternal { /// <summary> /// Returns true if this field was declared as "volatile". /// </summary> bool IsVolatile { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.Symbols { internal interface IFieldSymbolInternal : ISymbolInternal { /// <summary> /// Returns true if this field was declared as "volatile". /// </summary> bool IsVolatile { get; } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerDriver.CompilationData.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace Microsoft.CodeAnalysis.Diagnostics { internal abstract partial class AnalyzerDriver : IDisposable { internal class CompilationData { private readonly Dictionary<SyntaxReference, DeclarationAnalysisData> _declarationAnalysisDataMap; public CompilationData(Compilation compilation) { Debug.Assert(compilation.SemanticModelProvider is CachingSemanticModelProvider); SemanticModelProvider = (CachingSemanticModelProvider)compilation.SemanticModelProvider; this.SuppressMessageAttributeState = new SuppressMessageAttributeState(compilation); _declarationAnalysisDataMap = new Dictionary<SyntaxReference, DeclarationAnalysisData>(); } public CachingSemanticModelProvider SemanticModelProvider { get; } public SuppressMessageAttributeState SuppressMessageAttributeState { get; } internal DeclarationAnalysisData GetOrComputeDeclarationAnalysisData( SyntaxReference declaration, Func<DeclarationAnalysisData> computeDeclarationAnalysisData, bool cacheAnalysisData) { if (!cacheAnalysisData) { return computeDeclarationAnalysisData(); } lock (_declarationAnalysisDataMap) { if (_declarationAnalysisDataMap.TryGetValue(declaration, out var cachedData)) { return cachedData; } } DeclarationAnalysisData data = computeDeclarationAnalysisData(); lock (_declarationAnalysisDataMap) { if (!_declarationAnalysisDataMap.TryGetValue(declaration, out var existingData)) { _declarationAnalysisDataMap.Add(declaration, data); } else { data = existingData; } } return data; } internal void ClearDeclarationAnalysisData(SyntaxReference declaration) { lock (_declarationAnalysisDataMap) { _declarationAnalysisDataMap.Remove(declaration); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace Microsoft.CodeAnalysis.Diagnostics { internal abstract partial class AnalyzerDriver : IDisposable { internal class CompilationData { private readonly Dictionary<SyntaxReference, DeclarationAnalysisData> _declarationAnalysisDataMap; public CompilationData(Compilation compilation) { Debug.Assert(compilation.SemanticModelProvider is CachingSemanticModelProvider); SemanticModelProvider = (CachingSemanticModelProvider)compilation.SemanticModelProvider; this.SuppressMessageAttributeState = new SuppressMessageAttributeState(compilation); _declarationAnalysisDataMap = new Dictionary<SyntaxReference, DeclarationAnalysisData>(); } public CachingSemanticModelProvider SemanticModelProvider { get; } public SuppressMessageAttributeState SuppressMessageAttributeState { get; } internal DeclarationAnalysisData GetOrComputeDeclarationAnalysisData( SyntaxReference declaration, Func<DeclarationAnalysisData> computeDeclarationAnalysisData, bool cacheAnalysisData) { if (!cacheAnalysisData) { return computeDeclarationAnalysisData(); } lock (_declarationAnalysisDataMap) { if (_declarationAnalysisDataMap.TryGetValue(declaration, out var cachedData)) { return cachedData; } } DeclarationAnalysisData data = computeDeclarationAnalysisData(); lock (_declarationAnalysisDataMap) { if (!_declarationAnalysisDataMap.TryGetValue(declaration, out var existingData)) { _declarationAnalysisDataMap.Add(declaration, data); } else { data = existingData; } } return data; } internal void ClearDeclarationAnalysisData(SyntaxReference declaration) { lock (_declarationAnalysisDataMap) { _declarationAnalysisDataMap.Remove(declaration); } } } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Workspaces/CSharp/Portable/Classification/SyntaxClassification/OperatorOverloadSyntaxClassifier.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 Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Classification.Classifiers; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Classification { internal class OperatorOverloadSyntaxClassifier : AbstractSyntaxClassifier { public override ImmutableArray<Type> SyntaxNodeTypes { get; } = ImmutableArray.Create( typeof(AssignmentExpressionSyntax), typeof(BinaryExpressionSyntax), typeof(PrefixUnaryExpressionSyntax), typeof(PostfixUnaryExpressionSyntax)); public override void AddClassifications( Workspace workspace, SyntaxNode syntax, SemanticModel semanticModel, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { var symbolInfo = semanticModel.GetSymbolInfo(syntax, cancellationToken); if (symbolInfo.Symbol is IMethodSymbol methodSymbol && methodSymbol.MethodKind == MethodKind.UserDefinedOperator) { var operatorSpan = GetOperatorTokenSpan(syntax); if (!operatorSpan.IsEmpty) { result.Add(new ClassifiedSpan(operatorSpan, ClassificationTypeNames.OperatorOverloaded)); } } } private static TextSpan GetOperatorTokenSpan(SyntaxNode syntax) => syntax switch { AssignmentExpressionSyntax assignmentExpression => assignmentExpression.OperatorToken.Span, BinaryExpressionSyntax binaryExpression => binaryExpression.OperatorToken.Span, PrefixUnaryExpressionSyntax prefixUnaryExpression => prefixUnaryExpression.OperatorToken.Span, PostfixUnaryExpressionSyntax postfixUnaryExpression => postfixUnaryExpression.OperatorToken.Span, _ => default, }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Classification.Classifiers; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Classification { internal class OperatorOverloadSyntaxClassifier : AbstractSyntaxClassifier { public override ImmutableArray<Type> SyntaxNodeTypes { get; } = ImmutableArray.Create( typeof(AssignmentExpressionSyntax), typeof(BinaryExpressionSyntax), typeof(PrefixUnaryExpressionSyntax), typeof(PostfixUnaryExpressionSyntax)); public override void AddClassifications( Workspace workspace, SyntaxNode syntax, SemanticModel semanticModel, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { var symbolInfo = semanticModel.GetSymbolInfo(syntax, cancellationToken); if (symbolInfo.Symbol is IMethodSymbol methodSymbol && methodSymbol.MethodKind == MethodKind.UserDefinedOperator) { var operatorSpan = GetOperatorTokenSpan(syntax); if (!operatorSpan.IsEmpty) { result.Add(new ClassifiedSpan(operatorSpan, ClassificationTypeNames.OperatorOverloaded)); } } } private static TextSpan GetOperatorTokenSpan(SyntaxNode syntax) => syntax switch { AssignmentExpressionSyntax assignmentExpression => assignmentExpression.OperatorToken.Span, BinaryExpressionSyntax binaryExpression => binaryExpression.OperatorToken.Span, PrefixUnaryExpressionSyntax prefixUnaryExpression => prefixUnaryExpression.OperatorToken.Span, PostfixUnaryExpressionSyntax postfixUnaryExpression => postfixUnaryExpression.OperatorToken.Span, _ => default, }; } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenShortCircuitOperatorTests.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 Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CodeGenShortCircuitOperatorTests : CSharpTestBase { [Fact] public void TestShortCircuitAnd() { var source = @" class C { public static bool Test(char ch, bool result) { System.Console.WriteLine(ch); return result; } public static void Main() { const bool c1 = true; const bool c2 = false; bool v1 = true; bool v2 = false; System.Console.WriteLine(true && true); System.Console.WriteLine(true && false); System.Console.WriteLine(false && true); System.Console.WriteLine(false && false); System.Console.WriteLine(c1 && c1); System.Console.WriteLine(c1 && c2); System.Console.WriteLine(c2 && c1); System.Console.WriteLine(c2 && c2); System.Console.WriteLine(v1 && v1); System.Console.WriteLine(v1 && v2); System.Console.WriteLine(v2 && v1); System.Console.WriteLine(v2 && v2); System.Console.WriteLine(Test('L', true) && Test('R', true)); System.Console.WriteLine(Test('L', true) && Test('R', false)); System.Console.WriteLine(Test('L', false) && Test('R', true)); System.Console.WriteLine(Test('L', false) && Test('R', false)); } } "; var compilation = CompileAndVerify(source, expectedOutput: @" True False False False True False False False True False False False L R True L R False L False L False "); compilation.VerifyIL("C.Main", @" { // Code size 189 (0xbd) .maxstack 2 .locals init (bool V_0, //v1 bool V_1) //v2 IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.0 IL_0003: stloc.1 IL_0004: ldc.i4.1 IL_0005: call ""void System.Console.WriteLine(bool)"" IL_000a: ldc.i4.0 IL_000b: call ""void System.Console.WriteLine(bool)"" IL_0010: ldc.i4.0 IL_0011: call ""void System.Console.WriteLine(bool)"" IL_0016: ldc.i4.0 IL_0017: call ""void System.Console.WriteLine(bool)"" IL_001c: ldc.i4.1 IL_001d: call ""void System.Console.WriteLine(bool)"" IL_0022: ldc.i4.0 IL_0023: call ""void System.Console.WriteLine(bool)"" IL_0028: ldc.i4.0 IL_0029: call ""void System.Console.WriteLine(bool)"" IL_002e: ldc.i4.0 IL_002f: call ""void System.Console.WriteLine(bool)"" IL_0034: ldloc.0 IL_0035: ldloc.0 IL_0036: and IL_0037: call ""void System.Console.WriteLine(bool)"" IL_003c: ldloc.0 IL_003d: ldloc.1 IL_003e: and IL_003f: call ""void System.Console.WriteLine(bool)"" IL_0044: ldloc.1 IL_0045: ldloc.0 IL_0046: and IL_0047: call ""void System.Console.WriteLine(bool)"" IL_004c: ldloc.1 IL_004d: ldloc.1 IL_004e: and IL_004f: call ""void System.Console.WriteLine(bool)"" IL_0054: ldc.i4.s 76 IL_0056: ldc.i4.1 IL_0057: call ""bool C.Test(char, bool)"" IL_005c: brfalse.s IL_0068 IL_005e: ldc.i4.s 82 IL_0060: ldc.i4.1 IL_0061: call ""bool C.Test(char, bool)"" IL_0066: br.s IL_0069 IL_0068: ldc.i4.0 IL_0069: call ""void System.Console.WriteLine(bool)"" IL_006e: ldc.i4.s 76 IL_0070: ldc.i4.1 IL_0071: call ""bool C.Test(char, bool)"" IL_0076: brfalse.s IL_0082 IL_0078: ldc.i4.s 82 IL_007a: ldc.i4.0 IL_007b: call ""bool C.Test(char, bool)"" IL_0080: br.s IL_0083 IL_0082: ldc.i4.0 IL_0083: call ""void System.Console.WriteLine(bool)"" IL_0088: ldc.i4.s 76 IL_008a: ldc.i4.0 IL_008b: call ""bool C.Test(char, bool)"" IL_0090: brfalse.s IL_009c IL_0092: ldc.i4.s 82 IL_0094: ldc.i4.1 IL_0095: call ""bool C.Test(char, bool)"" IL_009a: br.s IL_009d IL_009c: ldc.i4.0 IL_009d: call ""void System.Console.WriteLine(bool)"" IL_00a2: ldc.i4.s 76 IL_00a4: ldc.i4.0 IL_00a5: call ""bool C.Test(char, bool)"" IL_00aa: brfalse.s IL_00b6 IL_00ac: ldc.i4.s 82 IL_00ae: ldc.i4.0 IL_00af: call ""bool C.Test(char, bool)"" IL_00b4: br.s IL_00b7 IL_00b6: ldc.i4.0 IL_00b7: call ""void System.Console.WriteLine(bool)"" IL_00bc: ret }"); } [Fact] public void TestShortCircuitOr() { var source = @" class C { public static bool Test(char ch, bool result) { System.Console.WriteLine(ch); return result; } public static void Main() { const bool c1 = true; const bool c2 = false; bool v1 = true; bool v2 = false; System.Console.WriteLine(true || true); System.Console.WriteLine(true || false); System.Console.WriteLine(false || true); System.Console.WriteLine(false || false); System.Console.WriteLine(c1 || c1); System.Console.WriteLine(c1 || c2); System.Console.WriteLine(c2 || c1); System.Console.WriteLine(c2 || c2); System.Console.WriteLine(v1 || v1); System.Console.WriteLine(v1 || v2); System.Console.WriteLine(v2 || v1); System.Console.WriteLine(v2 || v2); System.Console.WriteLine(Test('L', true) || Test('R', true)); System.Console.WriteLine(Test('L', true) || Test('R', false)); System.Console.WriteLine(Test('L', false) || Test('R', true)); System.Console.WriteLine(Test('L', false) || Test('R', false)); } } "; var compilation = CompileAndVerify(source, expectedOutput: @" True True True False True True True False True True True False L True L True L R True L R False "); compilation.VerifyIL("C.Main", @" { // Code size 189 (0xbd) .maxstack 2 .locals init (bool V_0, //v1 bool V_1) //v2 IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.0 IL_0003: stloc.1 IL_0004: ldc.i4.1 IL_0005: call ""void System.Console.WriteLine(bool)"" IL_000a: ldc.i4.1 IL_000b: call ""void System.Console.WriteLine(bool)"" IL_0010: ldc.i4.1 IL_0011: call ""void System.Console.WriteLine(bool)"" IL_0016: ldc.i4.0 IL_0017: call ""void System.Console.WriteLine(bool)"" IL_001c: ldc.i4.1 IL_001d: call ""void System.Console.WriteLine(bool)"" IL_0022: ldc.i4.1 IL_0023: call ""void System.Console.WriteLine(bool)"" IL_0028: ldc.i4.1 IL_0029: call ""void System.Console.WriteLine(bool)"" IL_002e: ldc.i4.0 IL_002f: call ""void System.Console.WriteLine(bool)"" IL_0034: ldloc.0 IL_0035: ldloc.0 IL_0036: or IL_0037: call ""void System.Console.WriteLine(bool)"" IL_003c: ldloc.0 IL_003d: ldloc.1 IL_003e: or IL_003f: call ""void System.Console.WriteLine(bool)"" IL_0044: ldloc.1 IL_0045: ldloc.0 IL_0046: or IL_0047: call ""void System.Console.WriteLine(bool)"" IL_004c: ldloc.1 IL_004d: ldloc.1 IL_004e: or IL_004f: call ""void System.Console.WriteLine(bool)"" IL_0054: ldc.i4.s 76 IL_0056: ldc.i4.1 IL_0057: call ""bool C.Test(char, bool)"" IL_005c: brtrue.s IL_0068 IL_005e: ldc.i4.s 82 IL_0060: ldc.i4.1 IL_0061: call ""bool C.Test(char, bool)"" IL_0066: br.s IL_0069 IL_0068: ldc.i4.1 IL_0069: call ""void System.Console.WriteLine(bool)"" IL_006e: ldc.i4.s 76 IL_0070: ldc.i4.1 IL_0071: call ""bool C.Test(char, bool)"" IL_0076: brtrue.s IL_0082 IL_0078: ldc.i4.s 82 IL_007a: ldc.i4.0 IL_007b: call ""bool C.Test(char, bool)"" IL_0080: br.s IL_0083 IL_0082: ldc.i4.1 IL_0083: call ""void System.Console.WriteLine(bool)"" IL_0088: ldc.i4.s 76 IL_008a: ldc.i4.0 IL_008b: call ""bool C.Test(char, bool)"" IL_0090: brtrue.s IL_009c IL_0092: ldc.i4.s 82 IL_0094: ldc.i4.1 IL_0095: call ""bool C.Test(char, bool)"" IL_009a: br.s IL_009d IL_009c: ldc.i4.1 IL_009d: call ""void System.Console.WriteLine(bool)"" IL_00a2: ldc.i4.s 76 IL_00a4: ldc.i4.0 IL_00a5: call ""bool C.Test(char, bool)"" IL_00aa: brtrue.s IL_00b6 IL_00ac: ldc.i4.s 82 IL_00ae: ldc.i4.0 IL_00af: call ""bool C.Test(char, bool)"" IL_00b4: br.s IL_00b7 IL_00b6: ldc.i4.1 IL_00b7: call ""void System.Console.WriteLine(bool)"" IL_00bc: ret }"); } [Fact] public void TestChainedShortCircuitOperators() { var source = @" class C { public static bool Test(char ch, bool result) { System.Console.WriteLine(ch); return result; } public static void Main() { // AND AND System.Console.WriteLine(Test('A', true) && Test('B', true) && Test('C' , true)); System.Console.WriteLine(Test('A', true) && Test('B', true) && Test('C' , false)); System.Console.WriteLine(Test('A', true) && Test('B', false) && Test('C' , true)); System.Console.WriteLine(Test('A', true) && Test('B', false) && Test('C' , false)); System.Console.WriteLine(Test('A', false) && Test('B', true) && Test('C' , true)); System.Console.WriteLine(Test('A', false) && Test('B', true) && Test('C' , false)); System.Console.WriteLine(Test('A', false) && Test('B', false) && Test('C' , true)); System.Console.WriteLine(Test('A', false) && Test('B', false) && Test('C' , false)); // AND OR System.Console.WriteLine(Test('A', true) && Test('B', true) || Test('C' , true)); System.Console.WriteLine(Test('A', true) && Test('B', true) || Test('C' , false)); System.Console.WriteLine(Test('A', true) && Test('B', false) || Test('C' , true)); System.Console.WriteLine(Test('A', true) && Test('B', false) || Test('C' , false)); System.Console.WriteLine(Test('A', false) && Test('B', true) || Test('C' , true)); System.Console.WriteLine(Test('A', false) && Test('B', true) || Test('C' , false)); System.Console.WriteLine(Test('A', false) && Test('B', false) || Test('C' , true)); System.Console.WriteLine(Test('A', false) && Test('B', false) || Test('C' , false)); // OR AND System.Console.WriteLine(Test('A', true) || Test('B', true) && Test('C' , true)); System.Console.WriteLine(Test('A', true) || Test('B', true) && Test('C' , false)); System.Console.WriteLine(Test('A', true) || Test('B', false) && Test('C' , true)); System.Console.WriteLine(Test('A', true) || Test('B', false) && Test('C' , false)); System.Console.WriteLine(Test('A', false) || Test('B', true) && Test('C' , true)); System.Console.WriteLine(Test('A', false) || Test('B', true) && Test('C' , false)); System.Console.WriteLine(Test('A', false) || Test('B', false) && Test('C' , true)); System.Console.WriteLine(Test('A', false) || Test('B', false) && Test('C' , false)); // OR OR System.Console.WriteLine(Test('A', true) || Test('B', true) || Test('C' , true)); System.Console.WriteLine(Test('A', true) || Test('B', true) || Test('C' , false)); System.Console.WriteLine(Test('A', true) || Test('B', false) || Test('C' , true)); System.Console.WriteLine(Test('A', true) || Test('B', false) || Test('C' , false)); System.Console.WriteLine(Test('A', false) || Test('B', true) || Test('C' , true)); System.Console.WriteLine(Test('A', false) || Test('B', true) || Test('C' , false)); System.Console.WriteLine(Test('A', false) || Test('B', false) || Test('C' , true)); System.Console.WriteLine(Test('A', false) || Test('B', false) || Test('C' , false)); } } "; var compilation = CompileAndVerify(source, expectedOutput: @" A B C True A B C False A B False A B False A False A False A False A False A B True A B True A B C True A B C False A C True A C False A C True A C False A True A True A True A True A B C True A B C False A B False A B False A True A True A True A True A B True A B True A B C True A B C False "); compilation.VerifyIL("C.Main", @"{ // Code size 1177 (0x499) .maxstack 2 IL_0000: ldc.i4.s 65 IL_0002: ldc.i4.1 IL_0003: call ""bool C.Test(char, bool)"" IL_0008: brfalse.s IL_001e IL_000a: ldc.i4.s 66 IL_000c: ldc.i4.1 IL_000d: call ""bool C.Test(char, bool)"" IL_0012: brfalse.s IL_001e IL_0014: ldc.i4.s 67 IL_0016: ldc.i4.1 IL_0017: call ""bool C.Test(char, bool)"" IL_001c: br.s IL_001f IL_001e: ldc.i4.0 IL_001f: call ""void System.Console.WriteLine(bool)"" IL_0024: ldc.i4.s 65 IL_0026: ldc.i4.1 IL_0027: call ""bool C.Test(char, bool)"" IL_002c: brfalse.s IL_0042 IL_002e: ldc.i4.s 66 IL_0030: ldc.i4.1 IL_0031: call ""bool C.Test(char, bool)"" IL_0036: brfalse.s IL_0042 IL_0038: ldc.i4.s 67 IL_003a: ldc.i4.0 IL_003b: call ""bool C.Test(char, bool)"" IL_0040: br.s IL_0043 IL_0042: ldc.i4.0 IL_0043: call ""void System.Console.WriteLine(bool)"" IL_0048: ldc.i4.s 65 IL_004a: ldc.i4.1 IL_004b: call ""bool C.Test(char, bool)"" IL_0050: brfalse.s IL_0066 IL_0052: ldc.i4.s 66 IL_0054: ldc.i4.0 IL_0055: call ""bool C.Test(char, bool)"" IL_005a: brfalse.s IL_0066 IL_005c: ldc.i4.s 67 IL_005e: ldc.i4.1 IL_005f: call ""bool C.Test(char, bool)"" IL_0064: br.s IL_0067 IL_0066: ldc.i4.0 IL_0067: call ""void System.Console.WriteLine(bool)"" IL_006c: ldc.i4.s 65 IL_006e: ldc.i4.1 IL_006f: call ""bool C.Test(char, bool)"" IL_0074: brfalse.s IL_008a IL_0076: ldc.i4.s 66 IL_0078: ldc.i4.0 IL_0079: call ""bool C.Test(char, bool)"" IL_007e: brfalse.s IL_008a IL_0080: ldc.i4.s 67 IL_0082: ldc.i4.0 IL_0083: call ""bool C.Test(char, bool)"" IL_0088: br.s IL_008b IL_008a: ldc.i4.0 IL_008b: call ""void System.Console.WriteLine(bool)"" IL_0090: ldc.i4.s 65 IL_0092: ldc.i4.0 IL_0093: call ""bool C.Test(char, bool)"" IL_0098: brfalse.s IL_00ae IL_009a: ldc.i4.s 66 IL_009c: ldc.i4.1 IL_009d: call ""bool C.Test(char, bool)"" IL_00a2: brfalse.s IL_00ae IL_00a4: ldc.i4.s 67 IL_00a6: ldc.i4.1 IL_00a7: call ""bool C.Test(char, bool)"" IL_00ac: br.s IL_00af IL_00ae: ldc.i4.0 IL_00af: call ""void System.Console.WriteLine(bool)"" IL_00b4: ldc.i4.s 65 IL_00b6: ldc.i4.0 IL_00b7: call ""bool C.Test(char, bool)"" IL_00bc: brfalse.s IL_00d2 IL_00be: ldc.i4.s 66 IL_00c0: ldc.i4.1 IL_00c1: call ""bool C.Test(char, bool)"" IL_00c6: brfalse.s IL_00d2 IL_00c8: ldc.i4.s 67 IL_00ca: ldc.i4.0 IL_00cb: call ""bool C.Test(char, bool)"" IL_00d0: br.s IL_00d3 IL_00d2: ldc.i4.0 IL_00d3: call ""void System.Console.WriteLine(bool)"" IL_00d8: ldc.i4.s 65 IL_00da: ldc.i4.0 IL_00db: call ""bool C.Test(char, bool)"" IL_00e0: brfalse.s IL_00f6 IL_00e2: ldc.i4.s 66 IL_00e4: ldc.i4.0 IL_00e5: call ""bool C.Test(char, bool)"" IL_00ea: brfalse.s IL_00f6 IL_00ec: ldc.i4.s 67 IL_00ee: ldc.i4.1 IL_00ef: call ""bool C.Test(char, bool)"" IL_00f4: br.s IL_00f7 IL_00f6: ldc.i4.0 IL_00f7: call ""void System.Console.WriteLine(bool)"" IL_00fc: ldc.i4.s 65 IL_00fe: ldc.i4.0 IL_00ff: call ""bool C.Test(char, bool)"" IL_0104: brfalse.s IL_011a IL_0106: ldc.i4.s 66 IL_0108: ldc.i4.0 IL_0109: call ""bool C.Test(char, bool)"" IL_010e: brfalse.s IL_011a IL_0110: ldc.i4.s 67 IL_0112: ldc.i4.0 IL_0113: call ""bool C.Test(char, bool)"" IL_0118: br.s IL_011b IL_011a: ldc.i4.0 IL_011b: call ""void System.Console.WriteLine(bool)"" IL_0120: ldc.i4.s 65 IL_0122: ldc.i4.1 IL_0123: call ""bool C.Test(char, bool)"" IL_0128: brfalse.s IL_0134 IL_012a: ldc.i4.s 66 IL_012c: ldc.i4.1 IL_012d: call ""bool C.Test(char, bool)"" IL_0132: brtrue.s IL_013e IL_0134: ldc.i4.s 67 IL_0136: ldc.i4.1 IL_0137: call ""bool C.Test(char, bool)"" IL_013c: br.s IL_013f IL_013e: ldc.i4.1 IL_013f: call ""void System.Console.WriteLine(bool)"" IL_0144: ldc.i4.s 65 IL_0146: ldc.i4.1 IL_0147: call ""bool C.Test(char, bool)"" IL_014c: brfalse.s IL_0158 IL_014e: ldc.i4.s 66 IL_0150: ldc.i4.1 IL_0151: call ""bool C.Test(char, bool)"" IL_0156: brtrue.s IL_0162 IL_0158: ldc.i4.s 67 IL_015a: ldc.i4.0 IL_015b: call ""bool C.Test(char, bool)"" IL_0160: br.s IL_0163 IL_0162: ldc.i4.1 IL_0163: call ""void System.Console.WriteLine(bool)"" IL_0168: ldc.i4.s 65 IL_016a: ldc.i4.1 IL_016b: call ""bool C.Test(char, bool)"" IL_0170: brfalse.s IL_017c IL_0172: ldc.i4.s 66 IL_0174: ldc.i4.0 IL_0175: call ""bool C.Test(char, bool)"" IL_017a: brtrue.s IL_0186 IL_017c: ldc.i4.s 67 IL_017e: ldc.i4.1 IL_017f: call ""bool C.Test(char, bool)"" IL_0184: br.s IL_0187 IL_0186: ldc.i4.1 IL_0187: call ""void System.Console.WriteLine(bool)"" IL_018c: ldc.i4.s 65 IL_018e: ldc.i4.1 IL_018f: call ""bool C.Test(char, bool)"" IL_0194: brfalse.s IL_01a0 IL_0196: ldc.i4.s 66 IL_0198: ldc.i4.0 IL_0199: call ""bool C.Test(char, bool)"" IL_019e: brtrue.s IL_01aa IL_01a0: ldc.i4.s 67 IL_01a2: ldc.i4.0 IL_01a3: call ""bool C.Test(char, bool)"" IL_01a8: br.s IL_01ab IL_01aa: ldc.i4.1 IL_01ab: call ""void System.Console.WriteLine(bool)"" IL_01b0: ldc.i4.s 65 IL_01b2: ldc.i4.0 IL_01b3: call ""bool C.Test(char, bool)"" IL_01b8: brfalse.s IL_01c4 IL_01ba: ldc.i4.s 66 IL_01bc: ldc.i4.1 IL_01bd: call ""bool C.Test(char, bool)"" IL_01c2: brtrue.s IL_01ce IL_01c4: ldc.i4.s 67 IL_01c6: ldc.i4.1 IL_01c7: call ""bool C.Test(char, bool)"" IL_01cc: br.s IL_01cf IL_01ce: ldc.i4.1 IL_01cf: call ""void System.Console.WriteLine(bool)"" IL_01d4: ldc.i4.s 65 IL_01d6: ldc.i4.0 IL_01d7: call ""bool C.Test(char, bool)"" IL_01dc: brfalse.s IL_01e8 IL_01de: ldc.i4.s 66 IL_01e0: ldc.i4.1 IL_01e1: call ""bool C.Test(char, bool)"" IL_01e6: brtrue.s IL_01f2 IL_01e8: ldc.i4.s 67 IL_01ea: ldc.i4.0 IL_01eb: call ""bool C.Test(char, bool)"" IL_01f0: br.s IL_01f3 IL_01f2: ldc.i4.1 IL_01f3: call ""void System.Console.WriteLine(bool)"" IL_01f8: ldc.i4.s 65 IL_01fa: ldc.i4.0 IL_01fb: call ""bool C.Test(char, bool)"" IL_0200: brfalse.s IL_020c IL_0202: ldc.i4.s 66 IL_0204: ldc.i4.0 IL_0205: call ""bool C.Test(char, bool)"" IL_020a: brtrue.s IL_0216 IL_020c: ldc.i4.s 67 IL_020e: ldc.i4.1 IL_020f: call ""bool C.Test(char, bool)"" IL_0214: br.s IL_0217 IL_0216: ldc.i4.1 IL_0217: call ""void System.Console.WriteLine(bool)"" IL_021c: ldc.i4.s 65 IL_021e: ldc.i4.0 IL_021f: call ""bool C.Test(char, bool)"" IL_0224: brfalse.s IL_0230 IL_0226: ldc.i4.s 66 IL_0228: ldc.i4.0 IL_0229: call ""bool C.Test(char, bool)"" IL_022e: brtrue.s IL_023a IL_0230: ldc.i4.s 67 IL_0232: ldc.i4.0 IL_0233: call ""bool C.Test(char, bool)"" IL_0238: br.s IL_023b IL_023a: ldc.i4.1 IL_023b: call ""void System.Console.WriteLine(bool)"" IL_0240: ldc.i4.s 65 IL_0242: ldc.i4.1 IL_0243: call ""bool C.Test(char, bool)"" IL_0248: brtrue.s IL_0261 IL_024a: ldc.i4.s 66 IL_024c: ldc.i4.1 IL_024d: call ""bool C.Test(char, bool)"" IL_0252: brfalse.s IL_025e IL_0254: ldc.i4.s 67 IL_0256: ldc.i4.1 IL_0257: call ""bool C.Test(char, bool)"" IL_025c: br.s IL_0262 IL_025e: ldc.i4.0 IL_025f: br.s IL_0262 IL_0261: ldc.i4.1 IL_0262: call ""void System.Console.WriteLine(bool)"" IL_0267: ldc.i4.s 65 IL_0269: ldc.i4.1 IL_026a: call ""bool C.Test(char, bool)"" IL_026f: brtrue.s IL_0288 IL_0271: ldc.i4.s 66 IL_0273: ldc.i4.1 IL_0274: call ""bool C.Test(char, bool)"" IL_0279: brfalse.s IL_0285 IL_027b: ldc.i4.s 67 IL_027d: ldc.i4.0 IL_027e: call ""bool C.Test(char, bool)"" IL_0283: br.s IL_0289 IL_0285: ldc.i4.0 IL_0286: br.s IL_0289 IL_0288: ldc.i4.1 IL_0289: call ""void System.Console.WriteLine(bool)"" IL_028e: ldc.i4.s 65 IL_0290: ldc.i4.1 IL_0291: call ""bool C.Test(char, bool)"" IL_0296: brtrue.s IL_02af IL_0298: ldc.i4.s 66 IL_029a: ldc.i4.0 IL_029b: call ""bool C.Test(char, bool)"" IL_02a0: brfalse.s IL_02ac IL_02a2: ldc.i4.s 67 IL_02a4: ldc.i4.1 IL_02a5: call ""bool C.Test(char, bool)"" IL_02aa: br.s IL_02b0 IL_02ac: ldc.i4.0 IL_02ad: br.s IL_02b0 IL_02af: ldc.i4.1 IL_02b0: call ""void System.Console.WriteLine(bool)"" IL_02b5: ldc.i4.s 65 IL_02b7: ldc.i4.1 IL_02b8: call ""bool C.Test(char, bool)"" IL_02bd: brtrue.s IL_02d6 IL_02bf: ldc.i4.s 66 IL_02c1: ldc.i4.0 IL_02c2: call ""bool C.Test(char, bool)"" IL_02c7: brfalse.s IL_02d3 IL_02c9: ldc.i4.s 67 IL_02cb: ldc.i4.0 IL_02cc: call ""bool C.Test(char, bool)"" IL_02d1: br.s IL_02d7 IL_02d3: ldc.i4.0 IL_02d4: br.s IL_02d7 IL_02d6: ldc.i4.1 IL_02d7: call ""void System.Console.WriteLine(bool)"" IL_02dc: ldc.i4.s 65 IL_02de: ldc.i4.0 IL_02df: call ""bool C.Test(char, bool)"" IL_02e4: brtrue.s IL_02fd IL_02e6: ldc.i4.s 66 IL_02e8: ldc.i4.1 IL_02e9: call ""bool C.Test(char, bool)"" IL_02ee: brfalse.s IL_02fa IL_02f0: ldc.i4.s 67 IL_02f2: ldc.i4.1 IL_02f3: call ""bool C.Test(char, bool)"" IL_02f8: br.s IL_02fe IL_02fa: ldc.i4.0 IL_02fb: br.s IL_02fe IL_02fd: ldc.i4.1 IL_02fe: call ""void System.Console.WriteLine(bool)"" IL_0303: ldc.i4.s 65 IL_0305: ldc.i4.0 IL_0306: call ""bool C.Test(char, bool)"" IL_030b: brtrue.s IL_0324 IL_030d: ldc.i4.s 66 IL_030f: ldc.i4.1 IL_0310: call ""bool C.Test(char, bool)"" IL_0315: brfalse.s IL_0321 IL_0317: ldc.i4.s 67 IL_0319: ldc.i4.0 IL_031a: call ""bool C.Test(char, bool)"" IL_031f: br.s IL_0325 IL_0321: ldc.i4.0 IL_0322: br.s IL_0325 IL_0324: ldc.i4.1 IL_0325: call ""void System.Console.WriteLine(bool)"" IL_032a: ldc.i4.s 65 IL_032c: ldc.i4.0 IL_032d: call ""bool C.Test(char, bool)"" IL_0332: brtrue.s IL_034b IL_0334: ldc.i4.s 66 IL_0336: ldc.i4.0 IL_0337: call ""bool C.Test(char, bool)"" IL_033c: brfalse.s IL_0348 IL_033e: ldc.i4.s 67 IL_0340: ldc.i4.1 IL_0341: call ""bool C.Test(char, bool)"" IL_0346: br.s IL_034c IL_0348: ldc.i4.0 IL_0349: br.s IL_034c IL_034b: ldc.i4.1 IL_034c: call ""void System.Console.WriteLine(bool)"" IL_0351: ldc.i4.s 65 IL_0353: ldc.i4.0 IL_0354: call ""bool C.Test(char, bool)"" IL_0359: brtrue.s IL_0372 IL_035b: ldc.i4.s 66 IL_035d: ldc.i4.0 IL_035e: call ""bool C.Test(char, bool)"" IL_0363: brfalse.s IL_036f IL_0365: ldc.i4.s 67 IL_0367: ldc.i4.0 IL_0368: call ""bool C.Test(char, bool)"" IL_036d: br.s IL_0373 IL_036f: ldc.i4.0 IL_0370: br.s IL_0373 IL_0372: ldc.i4.1 IL_0373: call ""void System.Console.WriteLine(bool)"" IL_0378: ldc.i4.s 65 IL_037a: ldc.i4.1 IL_037b: call ""bool C.Test(char, bool)"" IL_0380: brtrue.s IL_0396 IL_0382: ldc.i4.s 66 IL_0384: ldc.i4.1 IL_0385: call ""bool C.Test(char, bool)"" IL_038a: brtrue.s IL_0396 IL_038c: ldc.i4.s 67 IL_038e: ldc.i4.1 IL_038f: call ""bool C.Test(char, bool)"" IL_0394: br.s IL_0397 IL_0396: ldc.i4.1 IL_0397: call ""void System.Console.WriteLine(bool)"" IL_039c: ldc.i4.s 65 IL_039e: ldc.i4.1 IL_039f: call ""bool C.Test(char, bool)"" IL_03a4: brtrue.s IL_03ba IL_03a6: ldc.i4.s 66 IL_03a8: ldc.i4.1 IL_03a9: call ""bool C.Test(char, bool)"" IL_03ae: brtrue.s IL_03ba IL_03b0: ldc.i4.s 67 IL_03b2: ldc.i4.0 IL_03b3: call ""bool C.Test(char, bool)"" IL_03b8: br.s IL_03bb IL_03ba: ldc.i4.1 IL_03bb: call ""void System.Console.WriteLine(bool)"" IL_03c0: ldc.i4.s 65 IL_03c2: ldc.i4.1 IL_03c3: call ""bool C.Test(char, bool)"" IL_03c8: brtrue.s IL_03de IL_03ca: ldc.i4.s 66 IL_03cc: ldc.i4.0 IL_03cd: call ""bool C.Test(char, bool)"" IL_03d2: brtrue.s IL_03de IL_03d4: ldc.i4.s 67 IL_03d6: ldc.i4.1 IL_03d7: call ""bool C.Test(char, bool)"" IL_03dc: br.s IL_03df IL_03de: ldc.i4.1 IL_03df: call ""void System.Console.WriteLine(bool)"" IL_03e4: ldc.i4.s 65 IL_03e6: ldc.i4.1 IL_03e7: call ""bool C.Test(char, bool)"" IL_03ec: brtrue.s IL_0402 IL_03ee: ldc.i4.s 66 IL_03f0: ldc.i4.0 IL_03f1: call ""bool C.Test(char, bool)"" IL_03f6: brtrue.s IL_0402 IL_03f8: ldc.i4.s 67 IL_03fa: ldc.i4.0 IL_03fb: call ""bool C.Test(char, bool)"" IL_0400: br.s IL_0403 IL_0402: ldc.i4.1 IL_0403: call ""void System.Console.WriteLine(bool)"" IL_0408: ldc.i4.s 65 IL_040a: ldc.i4.0 IL_040b: call ""bool C.Test(char, bool)"" IL_0410: brtrue.s IL_0426 IL_0412: ldc.i4.s 66 IL_0414: ldc.i4.1 IL_0415: call ""bool C.Test(char, bool)"" IL_041a: brtrue.s IL_0426 IL_041c: ldc.i4.s 67 IL_041e: ldc.i4.1 IL_041f: call ""bool C.Test(char, bool)"" IL_0424: br.s IL_0427 IL_0426: ldc.i4.1 IL_0427: call ""void System.Console.WriteLine(bool)"" IL_042c: ldc.i4.s 65 IL_042e: ldc.i4.0 IL_042f: call ""bool C.Test(char, bool)"" IL_0434: brtrue.s IL_044a IL_0436: ldc.i4.s 66 IL_0438: ldc.i4.1 IL_0439: call ""bool C.Test(char, bool)"" IL_043e: brtrue.s IL_044a IL_0440: ldc.i4.s 67 IL_0442: ldc.i4.0 IL_0443: call ""bool C.Test(char, bool)"" IL_0448: br.s IL_044b IL_044a: ldc.i4.1 IL_044b: call ""void System.Console.WriteLine(bool)"" IL_0450: ldc.i4.s 65 IL_0452: ldc.i4.0 IL_0453: call ""bool C.Test(char, bool)"" IL_0458: brtrue.s IL_046e IL_045a: ldc.i4.s 66 IL_045c: ldc.i4.0 IL_045d: call ""bool C.Test(char, bool)"" IL_0462: brtrue.s IL_046e IL_0464: ldc.i4.s 67 IL_0466: ldc.i4.1 IL_0467: call ""bool C.Test(char, bool)"" IL_046c: br.s IL_046f IL_046e: ldc.i4.1 IL_046f: call ""void System.Console.WriteLine(bool)"" IL_0474: ldc.i4.s 65 IL_0476: ldc.i4.0 IL_0477: call ""bool C.Test(char, bool)"" IL_047c: brtrue.s IL_0492 IL_047e: ldc.i4.s 66 IL_0480: ldc.i4.0 IL_0481: call ""bool C.Test(char, bool)"" IL_0486: brtrue.s IL_0492 IL_0488: ldc.i4.s 67 IL_048a: ldc.i4.0 IL_048b: call ""bool C.Test(char, bool)"" IL_0490: br.s IL_0493 IL_0492: ldc.i4.1 IL_0493: call ""void System.Console.WriteLine(bool)"" IL_0498: ret } "); } [Fact] public void TestConditionalMemberAccess001() { var source = @" public class C { static void Main() { Test(null); System.Console.Write('#'); int[] a = new int[] { }; Test(a); } static void Test(int[] x) { System.Console.Write(x?.ToString().ToString().ToString() ?? ""NULL""); } }"; var comp = CompileAndVerify(source, expectedOutput: "NULL#System.Int32[]"); comp.VerifyIL("C.Test", @" { // Code size 37 (0x25) .maxstack 2 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0006 IL_0003: ldnull IL_0004: br.s IL_0016 IL_0006: ldarg.0 IL_0007: callvirt ""string object.ToString()"" IL_000c: callvirt ""string object.ToString()"" IL_0011: callvirt ""string object.ToString()"" IL_0016: dup IL_0017: brtrue.s IL_001f IL_0019: pop IL_001a: ldstr ""NULL"" IL_001f: call ""void System.Console.Write(string)"" IL_0024: ret } "); } [Fact] public void TestConditionalMemberAccess001ext() { var source = @" public static class C { static void Main() { Test(null); System.Console.Write('#'); int[] a = new int[] { }; Test(a); } static void Test(int[] x) { System.Console.Write(x?.ToStr().ToStr().ToStr() ?? ""NULL""); } static string ToStr(this object arg) { return arg.ToString(); } }"; var comp = CompileAndVerify(source, expectedOutput: "NULL#System.Int32[]"); comp.VerifyIL("C.Test", @" { // Code size 37 (0x25) .maxstack 2 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0006 IL_0003: ldnull IL_0004: br.s IL_0016 IL_0006: ldarg.0 IL_0007: call ""string C.ToStr(object)"" IL_000c: call ""string C.ToStr(object)"" IL_0011: call ""string C.ToStr(object)"" IL_0016: dup IL_0017: brtrue.s IL_001f IL_0019: pop IL_001a: ldstr ""NULL"" IL_001f: call ""void System.Console.Write(string)"" IL_0024: ret } "); } [Fact] public void TestConditionalMemberAccess001dyn() { var source = @" public static class C { static void Main() { Test(null); System.Console.Write('#'); int[] a = new int[] { }; Test(a); } static void Test(dynamic x) { System.Console.Write(x?.ToString().ToString()?.ToString() ?? ""NULL""); } }"; var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: "NULL#System.Int32[]"); comp.VerifyIL("C.Test", @" { // Code size 355 (0x163) .maxstack 14 .locals init (object V_0, object V_1) IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> C.<>o__1.<>p__3"" IL_0005: brtrue.s IL_0046 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""Write"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.s 33 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: dup IL_002e: ldc.i4.1 IL_002f: ldc.i4.0 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003c: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0041: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> C.<>o__1.<>p__3"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> C.<>o__1.<>p__3"" IL_004b: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>>.Target"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> C.<>o__1.<>p__3"" IL_0055: ldtoken ""System.Console"" IL_005a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005f: ldarg.0 IL_0060: stloc.0 IL_0061: ldloc.0 IL_0062: brtrue.s IL_006a IL_0064: ldnull IL_0065: br IL_0154 IL_006a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_006f: brtrue.s IL_00a1 IL_0071: ldc.i4.0 IL_0072: ldstr ""ToString"" IL_0077: ldnull IL_0078: ldtoken ""C"" IL_007d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0082: ldc.i4.1 IL_0083: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0088: dup IL_0089: ldc.i4.0 IL_008a: ldc.i4.0 IL_008b: ldnull IL_008c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0091: stelem.ref IL_0092: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0097: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_009c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_00a1: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_00a6: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_00ab: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_00b0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_00b5: brtrue.s IL_00e7 IL_00b7: ldc.i4.0 IL_00b8: ldstr ""ToString"" IL_00bd: ldnull IL_00be: ldtoken ""C"" IL_00c3: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00c8: ldc.i4.1 IL_00c9: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00ce: dup IL_00cf: ldc.i4.0 IL_00d0: ldc.i4.0 IL_00d1: ldnull IL_00d2: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00d7: stelem.ref IL_00d8: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00dd: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00e2: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_00e7: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_00ec: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_00f1: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_00f6: ldloc.0 IL_00f7: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00fc: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_0101: stloc.1 IL_0102: ldloc.1 IL_0103: brtrue.s IL_0108 IL_0105: ldnull IL_0106: br.s IL_0154 IL_0108: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__2"" IL_010d: brtrue.s IL_013f IL_010f: ldc.i4.0 IL_0110: ldstr ""ToString"" IL_0115: ldnull IL_0116: ldtoken ""C"" IL_011b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0120: ldc.i4.1 IL_0121: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0126: dup IL_0127: ldc.i4.0 IL_0128: ldc.i4.0 IL_0129: ldnull IL_012a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_012f: stelem.ref IL_0130: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0135: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_013a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__2"" IL_013f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__2"" IL_0144: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_0149: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__2"" IL_014e: ldloc.1 IL_014f: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_0154: dup IL_0155: brtrue.s IL_015d IL_0157: pop IL_0158: ldstr ""NULL"" IL_015d: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_0162: ret } "); } [Fact] public void TestConditionalMemberAccess001dyn1() { var source = @" public static class C { static void Main() { Test(null); System.Console.Write('#'); int[] a = new int[] { }; Test(a); } static void Test(dynamic x) { System.Console.Write(x?.ToString()?[1].ToString() ?? ""NULL""); } }"; var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: "NULL#y"); } [Fact] public void TestConditionalMemberAccess001dyn2() { var source = @" public static class C { static void Main() { Test(null, ""aa""); System.Console.Write('#'); Test(""aa"", ""bb""); } static void Test(string s, dynamic ds) { System.Console.Write(s?.CompareTo(ds) ?? ""NULL""); } }"; var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: "NULL#-1"); } [Fact] public void TestConditionalMemberAccess001dyn3() { var source = @" public static class C { static void Main() { Test(null, 1); System.Console.Write('#'); int[] a = new int[] { }; Test(a, 1); } static void Test(int[] x, dynamic i) { System.Console.Write(x?.ToString()?[i].ToString() ?? ""NULL""); } }"; var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: "NULL#y"); } [Fact] public void TestConditionalMemberAccess001dyn4() { var source = @" public static class C { static void Main() { Test(null); System.Console.Write('#'); int[] a = new int[] {1,2,3}; Test(a); } static void Test(dynamic x) { System.Console.Write(x?.Length.ToString() ?? ""NULL""); } }"; var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: "NULL#3"); } [Fact] public void TestConditionalMemberAccess001dyn5() { var source = @" public static class C { static void Main() { Test(null); System.Console.Write('#'); int[] a = new int[] {1,2,3}; Test(a); } static void Test(dynamic x) { System.Console.Write(x?.Length?.ToString() ?? ""NULL""); } }"; var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: "NULL#3"); } [Fact] public void TestConditionalMemberAccessUnused() { var source = @" public class C { static void Main() { var dummy1 = ((string)null)?.ToString(); var dummy2 = ""qqq""?.ToString(); var dummy3 = 1.ToString()?.ToString(); } }"; var comp = CompileAndVerify(source, expectedOutput: ""); comp.VerifyIL("C.Main", @" { // Code size 32 (0x20) .maxstack 2 .locals init (int V_0) IL_0000: ldstr ""qqq"" IL_0005: callvirt ""string object.ToString()"" IL_000a: pop IL_000b: ldc.i4.1 IL_000c: stloc.0 IL_000d: ldloca.s V_0 IL_000f: call ""string int.ToString()"" IL_0014: dup IL_0015: brtrue.s IL_0019 IL_0017: pop IL_0018: ret IL_0019: callvirt ""string object.ToString()"" IL_001e: pop IL_001f: ret } "); } [Fact] public void TestConditionalMemberAccessUsed() { var source = @" public class C { static void Main() { var dummy1 = ((string)null)?.ToString(); var dummy2 = ""qqq""?.ToString(); var dummy3 = 1.ToString()?.ToString(); dummy1 += dummy2 += dummy3; } }"; var comp = CompileAndVerify(source, expectedOutput: ""); comp.VerifyIL("C.Main", @" { // Code size 50 (0x32) .maxstack 3 .locals init (string V_0, //dummy2 string V_1, //dummy3 int V_2) IL_0000: ldnull IL_0001: ldstr ""qqq"" IL_0006: callvirt ""string object.ToString()"" IL_000b: stloc.0 IL_000c: ldc.i4.1 IL_000d: stloc.2 IL_000e: ldloca.s V_2 IL_0010: call ""string int.ToString()"" IL_0015: dup IL_0016: brtrue.s IL_001c IL_0018: pop IL_0019: ldnull IL_001a: br.s IL_0021 IL_001c: callvirt ""string object.ToString()"" IL_0021: stloc.1 IL_0022: ldloc.0 IL_0023: ldloc.1 IL_0024: call ""string string.Concat(string, string)"" IL_0029: dup IL_002a: stloc.0 IL_002b: call ""string string.Concat(string, string)"" IL_0030: pop IL_0031: ret } "); } [Fact] public void TestConditionalMemberAccessUnused1() { var source = @" public class C { static void Main() { var dummy1 = ((string)null)?.ToString().Length; var dummy2 = ""qqq""?.ToString().Length; var dummy3 = 1.ToString()?.ToString().Length; } }"; var comp = CompileAndVerify(source, expectedOutput: ""); comp.VerifyIL("C.Main", @" { // Code size 42 (0x2a) .maxstack 2 .locals init (int V_0) IL_0000: ldstr ""qqq"" IL_0005: callvirt ""string object.ToString()"" IL_000a: callvirt ""int string.Length.get"" IL_000f: pop IL_0010: ldc.i4.1 IL_0011: stloc.0 IL_0012: ldloca.s V_0 IL_0014: call ""string int.ToString()"" IL_0019: dup IL_001a: brtrue.s IL_001e IL_001c: pop IL_001d: ret IL_001e: callvirt ""string object.ToString()"" IL_0023: callvirt ""int string.Length.get"" IL_0028: pop IL_0029: ret } "); } [Fact] public void TestConditionalMemberAccessUsed1() { var source = @" public class C { static void Main() { var dummy1 = ((string)null)?.ToString().Length; System.Console.WriteLine(dummy1); var dummy2 = ""qqq""?.ToString().Length; System.Console.WriteLine(dummy2); var dummy3 = 1.ToString()?.ToString().Length; System.Console.WriteLine(dummy3); } }"; var comp = CompileAndVerify(source, expectedOutput: @"3 1"); comp.VerifyIL("C.Main", @" { // Code size 99 (0x63) .maxstack 2 .locals init (int? V_0, int V_1) IL_0000: ldloca.s V_0 IL_0002: initobj ""int?"" IL_0008: ldloc.0 IL_0009: box ""int?"" IL_000e: call ""void System.Console.WriteLine(object)"" IL_0013: ldstr ""qqq"" IL_0018: callvirt ""string object.ToString()"" IL_001d: callvirt ""int string.Length.get"" IL_0022: newobj ""int?..ctor(int)"" IL_0027: box ""int?"" IL_002c: call ""void System.Console.WriteLine(object)"" IL_0031: ldc.i4.1 IL_0032: stloc.1 IL_0033: ldloca.s V_1 IL_0035: call ""string int.ToString()"" IL_003a: dup IL_003b: brtrue.s IL_0049 IL_003d: pop IL_003e: ldloca.s V_0 IL_0040: initobj ""int?"" IL_0046: ldloc.0 IL_0047: br.s IL_0058 IL_0049: callvirt ""string object.ToString()"" IL_004e: callvirt ""int string.Length.get"" IL_0053: newobj ""int?..ctor(int)"" IL_0058: box ""int?"" IL_005d: call ""void System.Console.WriteLine(object)"" IL_0062: ret } "); } [Fact] public void TestConditionalMemberAccessUnused2() { var source = @" public class C { static void Main() { var dummy1 = ((string)null)?.ToString().NullableLength()?.ToString(); var dummy2 = ""qqq""?.ToString().NullableLength().ToString(); var dummy3 = 1.ToString()?.ToString().NullableLength()?.ToString(); } } public static class C1 { public static int? NullableLength(this string self) { return self.Length; } } "; var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: ""); comp.VerifyIL("C.Main", @" { // Code size 82 (0x52) .maxstack 2 .locals init (int? V_0, int V_1) IL_0000: ldstr ""qqq"" IL_0005: callvirt ""string object.ToString()"" IL_000a: call ""int? C1.NullableLength(string)"" IL_000f: stloc.0 IL_0010: ldloca.s V_0 IL_0012: constrained. ""int?"" IL_0018: callvirt ""string object.ToString()"" IL_001d: pop IL_001e: ldc.i4.1 IL_001f: stloc.1 IL_0020: ldloca.s V_1 IL_0022: call ""string int.ToString()"" IL_0027: dup IL_0028: brtrue.s IL_002c IL_002a: pop IL_002b: ret IL_002c: callvirt ""string object.ToString()"" IL_0031: call ""int? C1.NullableLength(string)"" IL_0036: stloc.0 IL_0037: ldloca.s V_0 IL_0039: dup IL_003a: call ""bool int?.HasValue.get"" IL_003f: brtrue.s IL_0043 IL_0041: pop IL_0042: ret IL_0043: call ""int int?.GetValueOrDefault()"" IL_0048: stloc.1 IL_0049: ldloca.s V_1 IL_004b: call ""string int.ToString()"" IL_0050: pop IL_0051: ret } "); } [Fact] public void TestConditionalMemberAccessUnused2a() { var source = @" public class C { static void Main() { var dummy1 = ((string)null)?.ToString()?.Length.ToString(); var dummy2 = ""qqq""?.ToString().Length.ToString(); var dummy3 = 1.ToString()?.ToString().Length.ToString(); } }"; var comp = CompileAndVerify(source, expectedOutput: ""); comp.VerifyIL("C.Main", @" { // Code size 58 (0x3a) .maxstack 2 .locals init (int V_0) IL_0000: ldstr ""qqq"" IL_0005: callvirt ""string object.ToString()"" IL_000a: callvirt ""int string.Length.get"" IL_000f: stloc.0 IL_0010: ldloca.s V_0 IL_0012: call ""string int.ToString()"" IL_0017: pop IL_0018: ldc.i4.1 IL_0019: stloc.0 IL_001a: ldloca.s V_0 IL_001c: call ""string int.ToString()"" IL_0021: dup IL_0022: brtrue.s IL_0026 IL_0024: pop IL_0025: ret IL_0026: callvirt ""string object.ToString()"" IL_002b: callvirt ""int string.Length.get"" IL_0030: stloc.0 IL_0031: ldloca.s V_0 IL_0033: call ""string int.ToString()"" IL_0038: pop IL_0039: ret } "); } [Fact] public void TestConditionalMemberAccessUsed2() { var source = @" public class C { static void Main() { var dummy1 = ((string)null)?.ToString().NullableLength()?.ToString(); System.Console.WriteLine(dummy1); var dummy2 = ""qqq""?.ToString().NullableLength()?.ToString(); System.Console.WriteLine(dummy2); var dummy3 = 1.ToString()?.ToString().NullableLength()?.ToString(); System.Console.WriteLine(dummy3); } } public static class C1 { public static int? NullableLength(this string self) { return self.Length; } }"; var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: @"3 1"); comp.VerifyIL("C.Main", @" { // Code size 114 (0x72) .maxstack 2 .locals init (int? V_0, int V_1) IL_0000: ldnull IL_0001: call ""void System.Console.WriteLine(string)"" IL_0006: ldstr ""qqq"" IL_000b: callvirt ""string object.ToString()"" IL_0010: call ""int? C1.NullableLength(string)"" IL_0015: stloc.0 IL_0016: ldloca.s V_0 IL_0018: dup IL_0019: call ""bool int?.HasValue.get"" IL_001e: brtrue.s IL_0024 IL_0020: pop IL_0021: ldnull IL_0022: br.s IL_0031 IL_0024: call ""int int?.GetValueOrDefault()"" IL_0029: stloc.1 IL_002a: ldloca.s V_1 IL_002c: call ""string int.ToString()"" IL_0031: call ""void System.Console.WriteLine(string)"" IL_0036: ldc.i4.1 IL_0037: stloc.1 IL_0038: ldloca.s V_1 IL_003a: call ""string int.ToString()"" IL_003f: dup IL_0040: brtrue.s IL_0046 IL_0042: pop IL_0043: ldnull IL_0044: br.s IL_006c IL_0046: callvirt ""string object.ToString()"" IL_004b: call ""int? C1.NullableLength(string)"" IL_0050: stloc.0 IL_0051: ldloca.s V_0 IL_0053: dup IL_0054: call ""bool int?.HasValue.get"" IL_0059: brtrue.s IL_005f IL_005b: pop IL_005c: ldnull IL_005d: br.s IL_006c IL_005f: call ""int int?.GetValueOrDefault()"" IL_0064: stloc.1 IL_0065: ldloca.s V_1 IL_0067: call ""string int.ToString()"" IL_006c: call ""void System.Console.WriteLine(string)"" IL_0071: ret } "); } [Fact] public void TestConditionalMemberAccessUsed2a() { var source = @" public class C { static void Main() { var dummy1 = ((string)null)?.ToString()?.Length.ToString(); System.Console.WriteLine(dummy1); var dummy2 = ""qqq""?.ToString()?.Length.ToString(); System.Console.WriteLine(dummy2); var dummy3 = 1.ToString()?.ToString()?.Length.ToString(); System.Console.WriteLine(dummy3); } }"; var comp = CompileAndVerify(source, expectedOutput: @"3 1"); comp.VerifyIL("C.Main", @" { // Code size 88 (0x58) .maxstack 2 .locals init (int V_0) IL_0000: ldnull IL_0001: call ""void System.Console.WriteLine(string)"" IL_0006: ldstr ""qqq"" IL_000b: callvirt ""string object.ToString()"" IL_0010: dup IL_0011: brtrue.s IL_0017 IL_0013: pop IL_0014: ldnull IL_0015: br.s IL_0024 IL_0017: call ""int string.Length.get"" IL_001c: stloc.0 IL_001d: ldloca.s V_0 IL_001f: call ""string int.ToString()"" IL_0024: call ""void System.Console.WriteLine(string)"" IL_0029: ldc.i4.1 IL_002a: stloc.0 IL_002b: ldloca.s V_0 IL_002d: call ""string int.ToString()"" IL_0032: dup IL_0033: brtrue.s IL_0039 IL_0035: pop IL_0036: ldnull IL_0037: br.s IL_0052 IL_0039: callvirt ""string object.ToString()"" IL_003e: dup IL_003f: brtrue.s IL_0045 IL_0041: pop IL_0042: ldnull IL_0043: br.s IL_0052 IL_0045: call ""int string.Length.get"" IL_004a: stloc.0 IL_004b: ldloca.s V_0 IL_004d: call ""string int.ToString()"" IL_0052: call ""void System.Console.WriteLine(string)"" IL_0057: ret } "); } [Fact] [WorkItem(976765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/976765")] public void ConditionalMemberAccessConstrained() { var source = @" class Program { static void M<T>(T x) where T: System.Exception { object s = x?.ToString(); System.Console.WriteLine(s); s = x?.GetType(); System.Console.WriteLine(s); } static void Main() { M(new System.Exception(""a"")); } } "; var comp = CompileAndVerify(source, expectedOutput: @"System.Exception: a System.Exception"); comp.VerifyIL("Program.M<T>", @" { // Code size 47 (0x2f) .maxstack 2 IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: dup IL_0007: brtrue.s IL_000d IL_0009: pop IL_000a: ldnull IL_000b: br.s IL_0012 IL_000d: callvirt ""string object.ToString()"" IL_0012: call ""void System.Console.WriteLine(object)"" IL_0017: ldarg.0 IL_0018: box ""T"" IL_001d: dup IL_001e: brtrue.s IL_0024 IL_0020: pop IL_0021: ldnull IL_0022: br.s IL_0029 IL_0024: callvirt ""System.Type System.Exception.GetType()"" IL_0029: call ""void System.Console.WriteLine(object)"" IL_002e: ret } "); } [Fact] [WorkItem(991400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991400")] public void ConditionalMemberAccessStatement() { var source = @" class Program { class C1 { public void Print0() { System.Console.WriteLine(""print0""); } public int Print1() { System.Console.WriteLine(""print1""); return 1; } public object Print2() { System.Console.WriteLine(""print2""); return 1; } } static void M(C1 x) { x?.Print0(); x?.Print1(); x?.Print2(); } static void Main() { M(null); M(new C1()); } } "; var comp = CompileAndVerify(source, expectedOutput: @"print0 print1 print2"); comp.VerifyIL("Program.M(Program.C1)", @" { // Code size 30 (0x1e) .maxstack 1 IL_0000: ldarg.0 IL_0001: brfalse.s IL_0009 IL_0003: ldarg.0 IL_0004: call ""void Program.C1.Print0()"" IL_0009: ldarg.0 IL_000a: brfalse.s IL_0013 IL_000c: ldarg.0 IL_000d: call ""int Program.C1.Print1()"" IL_0012: pop IL_0013: ldarg.0 IL_0014: brfalse.s IL_001d IL_0016: ldarg.0 IL_0017: call ""object Program.C1.Print2()"" IL_001c: pop IL_001d: ret } "); } [Fact] [WorkItem(991400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991400")] public void ConditionalMemberAccessStatement01() { var source = @" class Program { struct S1 { public void Print0() { System.Console.WriteLine(""print0""); } public int Print1() { System.Console.WriteLine(""print1""); return 1; } public object Print2() { System.Console.WriteLine(""print2""); return 1; } } static void M(S1? x) { x?.Print0(); x?.Print1(); x?.Print2()?.ToString().ToString()?.ToString(); } static void Main() { M(null); M(new S1()); } } "; var comp = CompileAndVerify(source, expectedOutput: @"print0 print1 print2"); comp.VerifyIL("Program.M(Program.S1?)", @" { // Code size 100 (0x64) .maxstack 2 .locals init (Program.S1 V_0) IL_0000: ldarga.s V_0 IL_0002: call ""bool Program.S1?.HasValue.get"" IL_0007: brfalse.s IL_0018 IL_0009: ldarga.s V_0 IL_000b: call ""Program.S1 Program.S1?.GetValueOrDefault()"" IL_0010: stloc.0 IL_0011: ldloca.s V_0 IL_0013: call ""void Program.S1.Print0()"" IL_0018: ldarga.s V_0 IL_001a: call ""bool Program.S1?.HasValue.get"" IL_001f: brfalse.s IL_0031 IL_0021: ldarga.s V_0 IL_0023: call ""Program.S1 Program.S1?.GetValueOrDefault()"" IL_0028: stloc.0 IL_0029: ldloca.s V_0 IL_002b: call ""int Program.S1.Print1()"" IL_0030: pop IL_0031: ldarga.s V_0 IL_0033: call ""bool Program.S1?.HasValue.get"" IL_0038: brfalse.s IL_0063 IL_003a: ldarga.s V_0 IL_003c: call ""Program.S1 Program.S1?.GetValueOrDefault()"" IL_0041: stloc.0 IL_0042: ldloca.s V_0 IL_0044: call ""object Program.S1.Print2()"" IL_0049: dup IL_004a: brtrue.s IL_004e IL_004c: pop IL_004d: ret IL_004e: callvirt ""string object.ToString()"" IL_0053: callvirt ""string object.ToString()"" IL_0058: dup IL_0059: brtrue.s IL_005d IL_005b: pop IL_005c: ret IL_005d: callvirt ""string object.ToString()"" IL_0062: pop IL_0063: ret } "); } [ConditionalFact(typeof(DesktopOnly))] [WorkItem(991400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991400")] public void ConditionalMemberAccessStatement02() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class Program { class C1 { public void Print0(int i) { System.Console.WriteLine(""print0""); } public int Print1(int i) { System.Console.WriteLine(""print1""); return 1; } public object Print2(int i) { System.Console.WriteLine(""print2""); return 1; } } static async Task<int> Val() { await Task.Yield(); return 1; } static async Task<int> M(C1 x) { x?.Print0(await Val()); x?.Print1(await Val()); x?.Print2(await Val()); return 1; } static void Main() { M(null).Wait(); M(new C1()).Wait(); } } "; var comp = CompileAndVerify(source, targetFramework: TargetFramework.Empty, references: new[] { MscorlibRef_v4_0_30316_17626 }, expectedOutput: @"print0 print1 print2"); } [ConditionalFact(typeof(DesktopOnly))] [WorkItem(991400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991400")] public void ConditionalMemberAccessStatement03() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class Program { struct C1 { public void Print0(int i) { System.Console.WriteLine(""print0""); } public int Print1(int i) { System.Console.WriteLine(""print1""); return 1; } public object Print2(int i) { System.Console.WriteLine(""print2""); return 1; } } static async Task<int> Val() { await Task.Yield(); return 1; } static async Task<int> M(C1? x) { x?.Print0(await Val()); x?.Print1(await Val()); x?.Print2(await Val()); return 1; } static void Main() { M(null).Wait(); M(new C1()).Wait(); } } "; var comp = CompileAndVerify(source, targetFramework: TargetFramework.Empty, references: new[] { MscorlibRef_v4_0_30316_17626 }, expectedOutput: @"print0 print1 print2"); } [Fact] public void ConditionalMemberAccessUnConstrained() { var source = @" using System; using System.Collections.Generic; class Program { class C1 : IDisposable { private bool disposed; public void Dispose() { System.Console.WriteLine(disposed); disposed = true; } } struct S1 : IDisposable { private bool disposed; public void Dispose() { System.Console.WriteLine(disposed); disposed = true; } } static void Main(string[] args) { C1 c = new C1(); Test(ref c, ref c); S1 s = new S1(); Test(ref s, ref s); } static void Test<T>(ref T x, ref T y) where T : IDisposable { x?.Dispose(); y?.Dispose(); } } "; var comp = CompileAndVerify(source, expectedOutput: @"False True False True"); comp.VerifyIL("Program.Test<T>(ref T, ref T)", @" { // Code size 94 (0x5e) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: initobj ""T"" IL_0009: ldloc.0 IL_000a: box ""T"" IL_000f: brtrue.s IL_0024 IL_0011: ldobj ""T"" IL_0016: stloc.0 IL_0017: ldloca.s V_0 IL_0019: ldloc.0 IL_001a: box ""T"" IL_001f: brtrue.s IL_0024 IL_0021: pop IL_0022: br.s IL_002f IL_0024: constrained. ""T"" IL_002a: callvirt ""void System.IDisposable.Dispose()"" IL_002f: ldarg.1 IL_0030: ldloca.s V_0 IL_0032: initobj ""T"" IL_0038: ldloc.0 IL_0039: box ""T"" IL_003e: brtrue.s IL_0052 IL_0040: ldobj ""T"" IL_0045: stloc.0 IL_0046: ldloca.s V_0 IL_0048: ldloc.0 IL_0049: box ""T"" IL_004e: brtrue.s IL_0052 IL_0050: pop IL_0051: ret IL_0052: constrained. ""T"" IL_0058: callvirt ""void System.IDisposable.Dispose()"" IL_005d: ret }"); } [Fact] public void ConditionalMemberAccessUnConstrained1() { var source = @" using System; using System.Collections.Generic; class Program { class C1 : IDisposable { private bool disposed; public void Dispose() { System.Console.WriteLine(disposed); disposed = true; } } struct S1 : IDisposable { private bool disposed; public void Dispose() { System.Console.WriteLine(disposed); disposed = true; } } static void Main(string[] args) { var c = new C1[] {new C1()}; Test(c, c); var s = new S1[] {new S1()}; Test(s, s); } static void Test<T>(T[] x, T[] y) where T : IDisposable { x[0]?.Dispose(); y[0]?.Dispose(); } } "; var comp = CompileAndVerify(source, expectedOutput: @"False True False True"); comp.VerifyIL("Program.Test<T>(T[], T[])", @" { // Code size 110 (0x6e) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: readonly. IL_0004: ldelema ""T"" IL_0009: ldloca.s V_0 IL_000b: initobj ""T"" IL_0011: ldloc.0 IL_0012: box ""T"" IL_0017: brtrue.s IL_002c IL_0019: ldobj ""T"" IL_001e: stloc.0 IL_001f: ldloca.s V_0 IL_0021: ldloc.0 IL_0022: box ""T"" IL_0027: brtrue.s IL_002c IL_0029: pop IL_002a: br.s IL_0037 IL_002c: constrained. ""T"" IL_0032: callvirt ""void System.IDisposable.Dispose()"" IL_0037: ldarg.1 IL_0038: ldc.i4.0 IL_0039: readonly. IL_003b: ldelema ""T"" IL_0040: ldloca.s V_0 IL_0042: initobj ""T"" IL_0048: ldloc.0 IL_0049: box ""T"" IL_004e: brtrue.s IL_0062 IL_0050: ldobj ""T"" IL_0055: stloc.0 IL_0056: ldloca.s V_0 IL_0058: ldloc.0 IL_0059: box ""T"" IL_005e: brtrue.s IL_0062 IL_0060: pop IL_0061: ret IL_0062: constrained. ""T"" IL_0068: callvirt ""void System.IDisposable.Dispose()"" IL_006d: ret } "); } [Fact] public void ConditionalMemberAccessConstrained1() { var source = @" using System; using System.Collections.Generic; class Program { class C1 : IDisposable { private bool disposed; public void Dispose() { System.Console.WriteLine(disposed); disposed = true; } } struct S1 : IDisposable { private bool disposed; public void Dispose() { System.Console.WriteLine(disposed); disposed = true; } } static void Main(string[] args) { var c = new C1[] {new C1()}; Test(c, c); } static void Test<T>(T[] x, T[] y) where T : class, IDisposable { x[0]?.Dispose(); y[0]?.Dispose(); } } "; var comp = CompileAndVerify(source, expectedOutput: @"False True "); comp.VerifyIL("Program.Test<T>(T[], T[])", @" { // Code size 46 (0x2e) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldelem ""T"" IL_0007: box ""T"" IL_000c: dup IL_000d: brtrue.s IL_0012 IL_000f: pop IL_0010: br.s IL_0017 IL_0012: callvirt ""void System.IDisposable.Dispose()"" IL_0017: ldarg.1 IL_0018: ldc.i4.0 IL_0019: ldelem ""T"" IL_001e: box ""T"" IL_0023: dup IL_0024: brtrue.s IL_0028 IL_0026: pop IL_0027: ret IL_0028: callvirt ""void System.IDisposable.Dispose()"" IL_002d: ret } "); } [Fact] public void ConditionalMemberAccessUnConstrainedVal() { var source = @" using System; using System.Collections.Generic; class Program { class C1 : IDisposable { private bool disposed; public void Dispose() { System.Console.WriteLine(disposed); disposed = true; } } struct S1 : IDisposable { private bool disposed; public void Dispose() { System.Console.WriteLine(disposed); disposed = true; } } static void Main(string[] args) { C1 c = new C1(); Test(c); S1 s = new S1(); Test(s); } static void Test<T>(T x) where T : IDisposable { x?.Dispose(); x?.Dispose(); } } "; var comp = CompileAndVerify(source, expectedOutput: @"False True False True"); comp.VerifyIL("Program.Test<T>(T)", @" { // Code size 43 (0x2b) .maxstack 1 IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: brfalse.s IL_0015 IL_0008: ldarga.s V_0 IL_000a: constrained. ""T"" IL_0010: callvirt ""void System.IDisposable.Dispose()"" IL_0015: ldarg.0 IL_0016: box ""T"" IL_001b: brfalse.s IL_002a IL_001d: ldarga.s V_0 IL_001f: constrained. ""T"" IL_0025: callvirt ""void System.IDisposable.Dispose()"" IL_002a: ret } "); } [Fact] public void ConditionalMemberAccessUnConstrainedVal001() { var source = @" using System; using System.Collections.Generic; class Program { class C1 : IDisposable { private bool disposed; public void Dispose() { System.Console.WriteLine(disposed); disposed = true; } } struct S1 : IDisposable { private bool disposed; public void Dispose() { System.Console.WriteLine(disposed); disposed = true; } } static void Main(string[] args) { C1 c = new C1(); Test(() => c); S1 s = new S1(); Test(() => s); } static void Test<T>(Func<T> x) where T : IDisposable { x()?.Dispose(); x()?.Dispose(); } } "; var comp = CompileAndVerify(source, expectedOutput: @"False True False False"); comp.VerifyIL("Program.Test<T>(System.Func<T>)", @" { // Code size 72 (0x48) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: callvirt ""T System.Func<T>.Invoke()"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: dup IL_000a: ldobj ""T"" IL_000f: box ""T"" IL_0014: brtrue.s IL_0019 IL_0016: pop IL_0017: br.s IL_0024 IL_0019: constrained. ""T"" IL_001f: callvirt ""void System.IDisposable.Dispose()"" IL_0024: ldarg.0 IL_0025: callvirt ""T System.Func<T>.Invoke()"" IL_002a: stloc.0 IL_002b: ldloca.s V_0 IL_002d: dup IL_002e: ldobj ""T"" IL_0033: box ""T"" IL_0038: brtrue.s IL_003c IL_003a: pop IL_003b: ret IL_003c: constrained. ""T"" IL_0042: callvirt ""void System.IDisposable.Dispose()"" IL_0047: ret } "); } [Fact] public void ConditionalMemberAccessConstrainedVal001() { var source = @" using System; using System.Collections.Generic; class Program { class C1 : IDisposable { private bool disposed; public void Dispose() { System.Console.WriteLine(disposed); disposed = true; } } struct S1 : IDisposable { private bool disposed; public void Dispose() { System.Console.WriteLine(disposed); disposed = true; } } static void Main(string[] args) { C1 c = new C1(); Test(() => c); } static void Test<T>(Func<T> x) where T : class, IDisposable { x()?.Dispose(); x()?.Dispose(); } } "; var comp = CompileAndVerify(source, expectedOutput: @"False True"); comp.VerifyIL("Program.Test<T>(System.Func<T>)", @" { // Code size 44 (0x2c) .maxstack 2 IL_0000: ldarg.0 IL_0001: callvirt ""T System.Func<T>.Invoke()"" IL_0006: box ""T"" IL_000b: dup IL_000c: brtrue.s IL_0011 IL_000e: pop IL_000f: br.s IL_0016 IL_0011: callvirt ""void System.IDisposable.Dispose()"" IL_0016: ldarg.0 IL_0017: callvirt ""T System.Func<T>.Invoke()"" IL_001c: box ""T"" IL_0021: dup IL_0022: brtrue.s IL_0026 IL_0024: pop IL_0025: ret IL_0026: callvirt ""void System.IDisposable.Dispose()"" IL_002b: ret } "); } [Fact] public void ConditionalMemberAccessUnConstrainedDyn() { var source = @" using System; using System.Collections.Generic; class Program { interface IDisposable1 { void Dispose(int i); } class C1 : IDisposable1 { private bool disposed; public void Dispose(int i) { System.Console.WriteLine(disposed); disposed = true; } } struct S1 : IDisposable1 { private bool disposed; public void Dispose(int i) { System.Console.WriteLine(disposed); disposed = true; } } static void Main(string[] args) { C1 c = new C1(); Test(ref c, ref c); S1 s = new S1(); Test(ref s, ref s); } static void Test<T>(ref T x, ref T y) where T : IDisposable1 { dynamic d = 1; x?.Dispose(d); y?.Dispose(d); } } "; var comp = CompileAndVerify(source, references: new MetadataReference[] { CSharpRef }, expectedOutput: @"False True False False"); } [Fact] public void ConditionalMemberAccessUnConstrainedDynVal() { var source = @" using System; using System.Collections.Generic; class Program { interface IDisposable1 { void Dispose(int i); } class C1 : IDisposable1 { private bool disposed; public void Dispose(int i) { System.Console.WriteLine(disposed); disposed = true; } } struct S1 : IDisposable1 { private bool disposed; public void Dispose(int i) { System.Console.WriteLine(disposed); disposed = true; } } static void Main(string[] args) { C1 c = new C1(); Test(c, c); S1 s = new S1(); Test(s, s); } static void Test<T>(T x, T y) where T : IDisposable1 { dynamic d = 1; x?.Dispose(d); y?.Dispose(d); } } "; var comp = CompileAndVerify(source, references: new MetadataReference[] { CSharpRef }, expectedOutput: @"False True False False"); } [Fact] public void ConditionalMemberAccessUnConstrainedAsync() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class Program { interface IDisposable1 { void Dispose(int i); } class C1 : IDisposable1 { private bool disposed; public void Dispose(int i) { System.Console.WriteLine(disposed); disposed = true; } } struct S1 : IDisposable1 { private bool disposed; public void Dispose(int i) { System.Console.WriteLine(disposed); disposed = true; } } static void Main(string[] args) { C1[] c = new C1[] { new C1() }; Test(c, c).Wait(); S1[] s = new S1[] { new S1() }; Test(s, s).Wait(); } static async Task<int> Val() { await Task.Yield(); return 0; } static async Task<int> Test<T>(T[] x, T[] y) where T : IDisposable1 { x[0]?.Dispose(await Val()); y[0]?.Dispose(await Val()); return 1; } }"; var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe); var comp = CompileAndVerify(c, expectedOutput: @"False True False True"); } [Fact] public void ConditionalMemberAccessUnConstrainedAsyncVal() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class Program { interface IDisposable1 { int Dispose(int i); } class C1 : IDisposable1 { private bool disposed; public int Dispose(int i) { System.Console.WriteLine(disposed); disposed = true; return 1; } } struct S1 : IDisposable1 { private bool disposed; public int Dispose(int i) { System.Console.WriteLine(disposed); disposed = true; return 1; } } static void Main(string[] args) { C1 c = new C1(); Test(c, c).Wait(); S1 s = new S1(); Test(s, s).Wait(); } static async Task<int> Val() { await Task.Yield(); return 0; } static async Task<int> Test<T>(T x, T y) where T : IDisposable1 { x?.Dispose(await Val()); y?.Dispose(await Val()); return 1; } } "; var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe); var comp = CompileAndVerify(c, expectedOutput: @"False True False False"); } [Fact] public void ConditionalMemberAccessUnConstrainedAsyncValExt() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; using DE; namespace DE { public static class IDispExt { public static void DisposeExt(this Program.IDisposable1 d, int i) { d.Dispose(i); } } } public class Program { public interface IDisposable1 { int Dispose(int i); } class C1 : IDisposable1 { private bool disposed; public int Dispose(int i) { System.Console.WriteLine(disposed); disposed = true; return 1; } } struct S1 : IDisposable1 { private bool disposed; public int Dispose(int i) { System.Console.WriteLine(disposed); disposed = true; return 1; } } static void Main(string[] args) { C1 c = new C1(); Test(c, c).Wait(); S1 s = new S1(); Test(s, s).Wait(); } static async Task<int> Val() { await Task.Yield(); return 0; } static async Task<int> Test<T>(T x, T y) where T : IDisposable1 { x?.DisposeExt(await Val()); y?.DisposeExt(await Val()); return 1; } } "; var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe); var comp = CompileAndVerify(c, expectedOutput: @"False True False False"); } [Fact] public void ConditionalMemberAccessUnConstrainedAsyncNested() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class Program { interface IDisposable1 { IDisposable1 Dispose(int i); } class C1 : IDisposable1 { private bool disposed; public IDisposable1 Dispose(int i) { System.Console.WriteLine(disposed); disposed ^= true; return this; } } struct S1 : IDisposable1 { private bool disposed; public IDisposable1 Dispose(int i) { System.Console.WriteLine(disposed); disposed ^= true; return this; } } static void Main(string[] args) { C1[] c = new C1[] { new C1() }; Test(c, c).Wait(); System.Console.WriteLine(); S1[] s = new S1[] { new S1() }; Test(s, s).Wait(); } static async Task<int> Val() { await Task.Yield(); return 0; } static async Task<int> Test<T>(T[] x, T[] y) where T : IDisposable1 { x[0]?.Dispose(await Val())?.Dispose(await Val())?.Dispose(await Val())?.Dispose(await Val()); y[0]?.Dispose(await Val())?.Dispose(await Val())?.Dispose(await Val())?.Dispose(await Val()); return 1; } }"; var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe); var comp = CompileAndVerify(c, expectedOutput: @"False True False True False True False True False True False True True False True False"); } [Fact] public void ConditionalMemberAccessUnConstrainedAsyncNestedArr() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class Program { interface IDisposable1 { IDisposable1[] Dispose(int i); } class C1 : IDisposable1 { private bool disposed; public IDisposable1[] Dispose(int i) { System.Console.WriteLine(disposed); disposed ^= true; return new IDisposable1[] { this }; } } struct S1 : IDisposable1 { private bool disposed; public IDisposable1[] Dispose(int i) { System.Console.WriteLine(disposed); disposed ^= true; return new IDisposable1[]{this}; } } static void Main(string[] args) { C1[] c = new C1[] { new C1() }; Test(c, c).Wait(); System.Console.WriteLine(); S1[] s = new S1[] { new S1() }; Test(s, s).Wait(); } static async Task<int> Val() { await Task.Yield(); return 0; } static async Task<int> Test<T>(T[] x, T[] y) where T : IDisposable1 { x[0]?.Dispose(await Val())[0]?.Dispose(await Val())[0]?.Dispose(await Val())[0]?.Dispose(await Val()); y[0]?.Dispose(await Val())[0]?.Dispose(await Val())[0]?.Dispose(await Val())[0]?.Dispose(await Val()); return 1; } }"; var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe); var comp = CompileAndVerify(c, expectedOutput: @"False True False True False True False True False True False True True False True False"); } [Fact] public void ConditionalMemberAccessUnConstrainedAsyncSuperNested() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class Program { interface IDisposable1 { Task<int> Dispose(int i); } class C1 : IDisposable1 { private bool disposed; public Task<int> Dispose(int i) { System.Console.WriteLine(disposed); disposed ^= true; return Task.FromResult(i); } } struct S1 : IDisposable1 { private bool disposed; public Task<int> Dispose(int i) { System.Console.WriteLine(disposed); disposed ^= true; return Task.FromResult(i); } } static void Main(string[] args) { C1[] c = new C1[] { new C1() }; Test(c, c).Wait(); System.Console.WriteLine(); S1[] s = new S1[] { new S1() }; Test(s, s).Wait(); } static async Task<int> Val() { await Task.Yield(); return 0; } static async Task<int> Test<T>(T[] x, T[] y) where T : IDisposable1 { x[0]?.Dispose(await x[0]?.Dispose(await x[0]?.Dispose(await x[0]?.Dispose(await Val())))); y[0]?.Dispose(await y[0]?.Dispose(await y[0]?.Dispose(await y[0]?.Dispose(await Val())))); return 1; } }"; var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe); var comp = CompileAndVerify(c, expectedOutput: @"False True False True False True False True False True False True False True False True"); } [Fact] public void ConditionalExtensionAccessGeneric001() { var source = @" using System; using System.Collections.Generic; class Test { static void Main() { long? x = 1; Test0(x); return; } static void Test0<T>(T x) { x?.CheckT(); } } static class Ext { public static void CheckT<T>(this T x) { System.Console.WriteLine(typeof(T)); return; } } "; var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: @"System.Nullable`1[System.Int64]"); comp.VerifyIL("Test.Test0<T>(T)", @" { // Code size 21 (0x15) .maxstack 1 IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: brfalse.s IL_0014 IL_0008: ldarga.s V_0 IL_000a: ldobj ""T"" IL_000f: call ""void Ext.CheckT<T>(T)"" IL_0014: ret } "); } [Fact] public void ConditionalExtensionAccessGeneric002() { var source = @" using System; using System.Collections.Generic; class Test { static void Main() { long? x = 1; Test0(ref x); return; } static void Test0<T>(ref T x) { x?.CheckT(); } } static class Ext { public static void CheckT<T>(this T x) { System.Console.WriteLine(typeof(T)); return; } } "; var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: @"System.Nullable`1[System.Int64]"); comp.VerifyIL("Test.Test0<T>(ref T)", @" { // Code size 46 (0x2e) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: initobj ""T"" IL_0009: ldloc.0 IL_000a: box ""T"" IL_000f: brtrue.s IL_0023 IL_0011: ldobj ""T"" IL_0016: stloc.0 IL_0017: ldloca.s V_0 IL_0019: ldloc.0 IL_001a: box ""T"" IL_001f: brtrue.s IL_0023 IL_0021: pop IL_0022: ret IL_0023: ldobj ""T"" IL_0028: call ""void Ext.CheckT<T>(T)"" IL_002d: ret } "); } [Fact] public void ConditionalExtensionAccessGeneric003() { var source = @" using System; using System.Linq; using System.Collections.Generic; class Test { static void Main() { Test0(""qqq""); } static void Test0<T>(T x) where T:IEnumerable<char> { x?.Count(); } static void Test1<T>(ref T x) where T:IEnumerable<char> { x?.Count(); } } "; var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: @""); comp.VerifyIL("Test.Test0<T>(T)", @" { // Code size 27 (0x1b) .maxstack 1 IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: brfalse.s IL_001a IL_0008: ldarga.s V_0 IL_000a: ldobj ""T"" IL_000f: box ""T"" IL_0014: call ""int System.Linq.Enumerable.Count<char>(System.Collections.Generic.IEnumerable<char>)"" IL_0019: pop IL_001a: ret } ").VerifyIL("Test.Test1<T>(ref T)", @" { // Code size 52 (0x34) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: initobj ""T"" IL_0009: ldloc.0 IL_000a: box ""T"" IL_000f: brtrue.s IL_0023 IL_0011: ldobj ""T"" IL_0016: stloc.0 IL_0017: ldloca.s V_0 IL_0019: ldloc.0 IL_001a: box ""T"" IL_001f: brtrue.s IL_0023 IL_0021: pop IL_0022: ret IL_0023: ldobj ""T"" IL_0028: box ""T"" IL_002d: call ""int System.Linq.Enumerable.Count<char>(System.Collections.Generic.IEnumerable<char>)"" IL_0032: pop IL_0033: ret } "); } [Fact] public void ConditionalExtensionAccessGenericAsync001() { var source = @" using System.Threading.Tasks; class Test { static void Main() { } async Task<int?> TestAsync<T>(T[] x) where T : I1 { return x[0]?.CallAsync(await PassAsync()); } static async Task<int> PassAsync() { await Task.Yield(); return 1; } } interface I1 { int CallAsync(int x); } "; var comp = CreateCompilationWithMscorlib45(source, references: new[] { CSharpRef }); base.CompileAndVerify(comp); } [Fact] public void ConditionalExtensionAccessGenericAsyncNullable001() { var source = @" using System; using System.Threading.Tasks; class Test { static void Main() { var arr = new S1?[] { new S1(), new S1()}; TestAsync(arr).Wait(); System.Console.WriteLine(arr[1].Value.called); } static async Task<int?> TestAsync<T>(T?[] x) where T : struct, I1 { return x[await PassAsync()]?.CallAsync(await PassAsync()); } static async Task<int> PassAsync() { await Task.Yield(); return 1; } } struct S1 : I1 { public int called; public int CallAsync(int x) { called++; System.Console.Write(called + 41); return called; } } interface I1 { int CallAsync(int x); } "; var comp = CreateCompilationWithMscorlib45(source, references: new[] { CSharpRef }, options: TestOptions.ReleaseExe); base.CompileAndVerify(comp, expectedOutput: "420"); } [Fact] public void ConditionalMemberAccessCoalesce001() { var source = @" class Program { class C1 { public int x{get; set;} public int? y{get; set;} } static void Main() { var c = new C1(); System.Console.WriteLine(Test1(c)); System.Console.WriteLine(Test1(null)); System.Console.WriteLine(Test2(c)); System.Console.WriteLine(Test2(null)); } static int Test1(C1 c) { return c?.x ?? 42; } static int Test2(C1 c) { return c?.y ?? 42; } } "; var comp = CompileAndVerify(source, expectedOutput: @"0 42 42 42"); comp.VerifyIL("Program.Test1(Program.C1)", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0006 IL_0003: ldc.i4.s 42 IL_0005: ret IL_0006: ldarg.0 IL_0007: call ""int Program.C1.x.get"" IL_000c: ret } ").VerifyIL("Program.Test2(Program.C1)", @" { // Code size 41 (0x29) .maxstack 1 .locals init (int? V_0, int? V_1) IL_0000: ldarg.0 IL_0001: brtrue.s IL_000e IL_0003: ldloca.s V_1 IL_0005: initobj ""int?"" IL_000b: ldloc.1 IL_000c: br.s IL_0014 IL_000e: ldarg.0 IL_000f: call ""int? Program.C1.y.get"" IL_0014: stloc.0 IL_0015: ldloca.s V_0 IL_0017: call ""bool int?.HasValue.get"" IL_001c: brtrue.s IL_0021 IL_001e: ldc.i4.s 42 IL_0020: ret IL_0021: ldloca.s V_0 IL_0023: call ""int int?.GetValueOrDefault()"" IL_0028: ret } "); } [Fact] public void ConditionalMemberAccessCoalesce001n() { var source = @" class Program { class C1 { public int x{get; set;} public int? y{get; set;} } static void Main() { var c = new C1(); System.Console.WriteLine(Test1(c)); System.Console.WriteLine(Test1(null)); System.Console.WriteLine(Test2(c)); System.Console.WriteLine(Test2(null)); } static int? Test1(C1 c) { return c?.x ?? (int?)42; } static int? Test2(C1 c) { return c?.y ?? (int?)42; } } "; var comp = CompileAndVerify(source, expectedOutput: @"0 42 42 42"); comp.VerifyIL("Program.Test1(Program.C1)", @" { // Code size 23 (0x17) .maxstack 1 IL_0000: ldarg.0 IL_0001: brtrue.s IL_000b IL_0003: ldc.i4.s 42 IL_0005: newobj ""int?..ctor(int)"" IL_000a: ret IL_000b: ldarg.0 IL_000c: call ""int Program.C1.x.get"" IL_0011: newobj ""int?..ctor(int)"" IL_0016: ret } ").VerifyIL("Program.Test2(Program.C1)", @" { // Code size 40 (0x28) .maxstack 1 .locals init (int? V_0, int? V_1) IL_0000: ldarg.0 IL_0001: brtrue.s IL_000e IL_0003: ldloca.s V_1 IL_0005: initobj ""int?"" IL_000b: ldloc.1 IL_000c: br.s IL_0014 IL_000e: ldarg.0 IL_000f: call ""int? Program.C1.y.get"" IL_0014: stloc.0 IL_0015: ldloca.s V_0 IL_0017: call ""bool int?.HasValue.get"" IL_001c: brtrue.s IL_0026 IL_001e: ldc.i4.s 42 IL_0020: newobj ""int?..ctor(int)"" IL_0025: ret IL_0026: ldloc.0 IL_0027: ret }"); } [Fact] public void ConditionalMemberAccessCoalesce001r() { var source = @" class Program { class C1 { public int x {get; set;} public int? y {get; set;} } static void Main() { var c = new C1(); C1 n = null; System.Console.WriteLine(Test1(ref c)); System.Console.WriteLine(Test1(ref n)); System.Console.WriteLine(Test2(ref c)); System.Console.WriteLine(Test2(ref n)); } static int Test1(ref C1 c) { return c?.x ?? 42; } static int Test2(ref C1 c) { return c?.y ?? 42; } } "; var comp = CompileAndVerify(source, expectedOutput: @"0 42 42 42"); comp.VerifyIL("Program.Test1(ref Program.C1)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldind.ref IL_0002: dup IL_0003: brtrue.s IL_0009 IL_0005: pop IL_0006: ldc.i4.s 42 IL_0008: ret IL_0009: call ""int Program.C1.x.get"" IL_000e: ret } ").VerifyIL("Program.Test2(ref Program.C1)", @" { // Code size 43 (0x2b) .maxstack 2 .locals init (int? V_0, int? V_1) IL_0000: ldarg.0 IL_0001: ldind.ref IL_0002: dup IL_0003: brtrue.s IL_0011 IL_0005: pop IL_0006: ldloca.s V_1 IL_0008: initobj ""int?"" IL_000e: ldloc.1 IL_000f: br.s IL_0016 IL_0011: call ""int? Program.C1.y.get"" IL_0016: stloc.0 IL_0017: ldloca.s V_0 IL_0019: call ""bool int?.HasValue.get"" IL_001e: brtrue.s IL_0023 IL_0020: ldc.i4.s 42 IL_0022: ret IL_0023: ldloca.s V_0 IL_0025: call ""int int?.GetValueOrDefault()"" IL_002a: ret } "); } [Fact] public void ConditionalMemberAccessCoalesce002() { var source = @" class Program { struct C1 { public int x{get; set;} public int? y{get; set;} } static void Main() { var c = new C1(); System.Console.WriteLine(Test1(c)); System.Console.WriteLine(Test1(null)); System.Console.WriteLine(Test2(c)); System.Console.WriteLine(Test2(null)); } static int Test1(C1? c) { return c?.x ?? 42; } static int Test2(C1? c) { return c?.y ?? 42; } } "; var comp = CompileAndVerify(source, expectedOutput: @"0 42 42 42"); comp.VerifyIL("Program.Test1(Program.C1?)", @" { // Code size 28 (0x1c) .maxstack 1 .locals init (Program.C1 V_0) IL_0000: ldarga.s V_0 IL_0002: call ""bool Program.C1?.HasValue.get"" IL_0007: brtrue.s IL_000c IL_0009: ldc.i4.s 42 IL_000b: ret IL_000c: ldarga.s V_0 IL_000e: call ""Program.C1 Program.C1?.GetValueOrDefault()"" IL_0013: stloc.0 IL_0014: ldloca.s V_0 IL_0016: call ""readonly int Program.C1.x.get"" IL_001b: ret } ").VerifyIL("Program.Test2(Program.C1?)", @" { // Code size 56 (0x38) .maxstack 1 .locals init (int? V_0, int? V_1, Program.C1 V_2) IL_0000: ldarga.s V_0 IL_0002: call ""bool Program.C1?.HasValue.get"" IL_0007: brtrue.s IL_0014 IL_0009: ldloca.s V_1 IL_000b: initobj ""int?"" IL_0011: ldloc.1 IL_0012: br.s IL_0023 IL_0014: ldarga.s V_0 IL_0016: call ""Program.C1 Program.C1?.GetValueOrDefault()"" IL_001b: stloc.2 IL_001c: ldloca.s V_2 IL_001e: call ""readonly int? Program.C1.y.get"" IL_0023: stloc.0 IL_0024: ldloca.s V_0 IL_0026: call ""bool int?.HasValue.get"" IL_002b: brtrue.s IL_0030 IL_002d: ldc.i4.s 42 IL_002f: ret IL_0030: ldloca.s V_0 IL_0032: call ""int int?.GetValueOrDefault()"" IL_0037: ret } "); } [Fact] public void ConditionalMemberAccessCoalesce002r() { var source = @" class Program { struct C1 { public int x{get; set;} public int? y{get; set;} } static void Main() { C1? c = new C1(); C1? n = null; System.Console.WriteLine(Test1(ref c)); System.Console.WriteLine(Test1(ref n)); System.Console.WriteLine(Test2(ref c)); System.Console.WriteLine(Test2(ref n)); } static int Test1(ref C1? c) { return c?.x ?? 42; } static int Test2(ref C1? c) { return c?.y ?? 42; } } "; var comp = CompileAndVerify(source, expectedOutput: @"0 42 42 42"); comp.VerifyIL("Program.Test1(ref Program.C1?)", @" { // Code size 27 (0x1b) .maxstack 2 .locals init (Program.C1 V_0) IL_0000: ldarg.0 IL_0001: dup IL_0002: call ""bool Program.C1?.HasValue.get"" IL_0007: brtrue.s IL_000d IL_0009: pop IL_000a: ldc.i4.s 42 IL_000c: ret IL_000d: call ""Program.C1 Program.C1?.GetValueOrDefault()"" IL_0012: stloc.0 IL_0013: ldloca.s V_0 IL_0015: call ""readonly int Program.C1.x.get"" IL_001a: ret } ").VerifyIL("Program.Test2(ref Program.C1?)", @" { // Code size 55 (0x37) .maxstack 2 .locals init (int? V_0, int? V_1, Program.C1 V_2) IL_0000: ldarg.0 IL_0001: dup IL_0002: call ""bool Program.C1?.HasValue.get"" IL_0007: brtrue.s IL_0015 IL_0009: pop IL_000a: ldloca.s V_1 IL_000c: initobj ""int?"" IL_0012: ldloc.1 IL_0013: br.s IL_0022 IL_0015: call ""Program.C1 Program.C1?.GetValueOrDefault()"" IL_001a: stloc.2 IL_001b: ldloca.s V_2 IL_001d: call ""readonly int? Program.C1.y.get"" IL_0022: stloc.0 IL_0023: ldloca.s V_0 IL_0025: call ""bool int?.HasValue.get"" IL_002a: brtrue.s IL_002f IL_002c: ldc.i4.s 42 IL_002e: ret IL_002f: ldloca.s V_0 IL_0031: call ""int int?.GetValueOrDefault()"" IL_0036: ret } "); } [Fact] public void ConditionalMemberAccessCoalesceDefault() { var source = @" class Program { class C1 { public int x { get; set; } } static void Main() { var c = new C1() { x = 42 }; System.Console.WriteLine(Test(c)); System.Console.WriteLine(Test(null)); } static int Test(C1 c) { return c?.x ?? 0; } } "; var comp = CompileAndVerify(source, expectedOutput: @" 42 0"); comp.VerifyIL("Program.Test(Program.C1)", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldc.i4.0 IL_0004: ret IL_0005: ldarg.0 IL_0006: call ""int Program.C1.x.get"" IL_000b: ret } "); } [Fact] public void ConditionalMemberAccessNullCheck001() { var source = @" class Program { class C1 { public int x{get; set;} } static void Main() { var c = new C1(); System.Console.WriteLine(Test1(c)); System.Console.WriteLine(Test1(null)); System.Console.WriteLine(Test2(c)); System.Console.WriteLine(Test2(null)); System.Console.WriteLine(Test3(c)); System.Console.WriteLine(Test3(null)); } static bool Test1(C1 c) { return c?.x == null; } static bool Test2(C1 c) { return c?.x != null; } static bool Test3(C1 c) { return c?.x > null; } } "; var comp = CompileAndVerify(source, expectedOutput: @"False True True False False False"); comp.VerifyIL("Program.Test1(Program.C1)", @" { // Code size 14 (0xe) .maxstack 1 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldc.i4.1 IL_0004: ret IL_0005: ldarg.0 IL_0006: call ""int Program.C1.x.get"" IL_000b: pop IL_000c: ldc.i4.0 IL_000d: ret } ").VerifyIL("Program.Test2(Program.C1)", @" { // Code size 14 (0xe) .maxstack 1 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldc.i4.0 IL_0004: ret IL_0005: ldarg.0 IL_0006: call ""int Program.C1.x.get"" IL_000b: pop IL_000c: ldc.i4.1 IL_000d: ret } ").VerifyIL("Program.Test3(Program.C1)", @" { // Code size 14 (0xe) .maxstack 1 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldc.i4.0 IL_0004: ret IL_0005: ldarg.0 IL_0006: call ""int Program.C1.x.get"" IL_000b: pop IL_000c: ldc.i4.0 IL_000d: ret } "); } [Fact] public void ConditionalMemberAccessBinary001() { var source = @" public enum N { zero = 0, one = 1, mone = -1 } class Program { class C1 { public N x{get; set;} } static void Main() { var c = new C1(); System.Console.WriteLine(Test1(c)); System.Console.WriteLine(Test1(null)); System.Console.WriteLine(Test2(c)); System.Console.WriteLine(Test2(null)); System.Console.WriteLine(Test3(c)); System.Console.WriteLine(Test3(null)); } static bool Test1(C1 c) { return c?.x == N.zero; } static bool Test2(C1 c) { return c?.x != N.one; } static bool Test3(C1 c) { return c?.x > N.mone; } } "; var comp = CompileAndVerify(source, expectedOutput: @"True False True True True False"); comp.VerifyIL("Program.Test1(Program.C1)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldc.i4.0 IL_0004: ret IL_0005: ldarg.0 IL_0006: call ""N Program.C1.x.get"" IL_000b: ldc.i4.0 IL_000c: ceq IL_000e: ret } ").VerifyIL("Program.Test2(Program.C1)", @" { // Code size 18 (0x12) .maxstack 2 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldc.i4.1 IL_0004: ret IL_0005: ldarg.0 IL_0006: call ""N Program.C1.x.get"" IL_000b: ldc.i4.1 IL_000c: ceq IL_000e: ldc.i4.0 IL_000f: ceq IL_0011: ret } ").VerifyIL("Program.Test3(Program.C1)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldc.i4.0 IL_0004: ret IL_0005: ldarg.0 IL_0006: call ""N Program.C1.x.get"" IL_000b: ldc.i4.m1 IL_000c: cgt IL_000e: ret } "); } [Fact] public void ConditionalMemberAccessBinary002() { var source = @" static class ext { public static Program.C1.S1 y(this Program.C1 self) { return self.x; } } class Program { public class C1 { public struct S1 { public static bool operator <(S1 s1, int s2) { System.Console.WriteLine('<'); return true; } public static bool operator >(S1 s1, int s2) { System.Console.WriteLine('>'); return false; } } public S1 x { get; set; } } static void Main() { C1 c = new C1(); C1 n = null; System.Console.WriteLine(Test1(c)); System.Console.WriteLine(Test1(n)); System.Console.WriteLine(Test2(ref c)); System.Console.WriteLine(Test2(ref n)); System.Console.WriteLine(Test3(c)); System.Console.WriteLine(Test3(n)); System.Console.WriteLine(Test4(ref c)); System.Console.WriteLine(Test4(ref n)); } static bool Test1(C1 c) { return c?.x > -1; } static bool Test2(ref C1 c) { return c?.x < -1; } static bool Test3(C1 c) { return c?.y() > -1; } static bool Test4(ref C1 c) { return c?.y() < -1; } } "; var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: @" > False False < True False > False False < True False"); comp.VerifyIL("Program.Test1(Program.C1)", @" { // Code size 18 (0x12) .maxstack 2 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldc.i4.0 IL_0004: ret IL_0005: ldarg.0 IL_0006: call ""Program.C1.S1 Program.C1.x.get"" IL_000b: ldc.i4.m1 IL_000c: call ""bool Program.C1.S1.op_GreaterThan(Program.C1.S1, int)"" IL_0011: ret } ").VerifyIL("Program.Test2(ref Program.C1)", @" { // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldind.ref IL_0002: dup IL_0003: brtrue.s IL_0008 IL_0005: pop IL_0006: ldc.i4.0 IL_0007: ret IL_0008: call ""Program.C1.S1 Program.C1.x.get"" IL_000d: ldc.i4.m1 IL_000e: call ""bool Program.C1.S1.op_LessThan(Program.C1.S1, int)"" IL_0013: ret } ").VerifyIL("Program.Test3(Program.C1)", @" { // Code size 18 (0x12) .maxstack 2 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldc.i4.0 IL_0004: ret IL_0005: ldarg.0 IL_0006: call ""Program.C1.S1 ext.y(Program.C1)"" IL_000b: ldc.i4.m1 IL_000c: call ""bool Program.C1.S1.op_GreaterThan(Program.C1.S1, int)"" IL_0011: ret } ").VerifyIL("Program.Test4(ref Program.C1)", @" { // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldind.ref IL_0002: dup IL_0003: brtrue.s IL_0008 IL_0005: pop IL_0006: ldc.i4.0 IL_0007: ret IL_0008: call ""Program.C1.S1 ext.y(Program.C1)"" IL_000d: ldc.i4.m1 IL_000e: call ""bool Program.C1.S1.op_LessThan(Program.C1.S1, int)"" IL_0013: ret } "); } [Fact] public void ConditionalMemberAccessOptimizedLocal001() { var source = @" using System; class Program { class C1 : System.IDisposable { public bool disposed; public void Dispose() { disposed = true; } } static void Main() { Test1(); Test2<C1>(); } static void Test1() { var c = new C1(); c?.Dispose(); } static void Test2<T>() where T : IDisposable, new() { var c = new T(); c?.Dispose(); } } "; var comp = CompileAndVerify(source, expectedOutput: @""); comp.VerifyIL("Program.Test1()", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: newobj ""Program.C1..ctor()"" IL_0005: dup IL_0006: brtrue.s IL_000a IL_0008: pop IL_0009: ret IL_000a: call ""void Program.C1.Dispose()"" IL_000f: ret } ").VerifyIL("Program.Test2<T>()", @" { // Code size 28 (0x1c) .maxstack 1 .locals init (T V_0) //c IL_0000: call ""T System.Activator.CreateInstance<T>()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: box ""T"" IL_000c: brfalse.s IL_001b IL_000e: ldloca.s V_0 IL_0010: constrained. ""T"" IL_0016: callvirt ""void System.IDisposable.Dispose()"" IL_001b: ret } "); } [Fact] public void ConditionalMemberAccessOptimizedLocal002() { var source = @" using System; class Program { interface I1 { void Goo(I1 arg); } class C1 : I1 { public void Goo(I1 arg) { } } static void Main() { Test1(); Test2<C1>(); } static void Test1() { var c = new C1(); c?.Goo(c); } static void Test2<T>() where T : I1, new() { var c = new T(); c?.Goo(c); } } "; var comp = CompileAndVerify(source, expectedOutput: @""); comp.VerifyIL("Program.Test1()", @" { // Code size 17 (0x11) .maxstack 2 .locals init (Program.C1 V_0) //c IL_0000: newobj ""Program.C1..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: brfalse.s IL_0010 IL_0009: ldloc.0 IL_000a: ldloc.0 IL_000b: call ""void Program.C1.Goo(Program.I1)"" IL_0010: ret } ").VerifyIL("Program.Test2<T>()", @" { // Code size 34 (0x22) .maxstack 2 .locals init (T V_0) //c IL_0000: call ""T System.Activator.CreateInstance<T>()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: box ""T"" IL_000c: brfalse.s IL_0021 IL_000e: ldloca.s V_0 IL_0010: ldloc.0 IL_0011: box ""T"" IL_0016: constrained. ""T"" IL_001c: callvirt ""void Program.I1.Goo(Program.I1)"" IL_0021: ret } "); } [Fact] public void ConditionalMemberAccessRace001() { var source = @" using System.Threading; using System.Threading.Tasks; class Program { static void Main() { string s = ""hello""; System.Action a = () => { for (int i = 0; i < 1000000; i++) { try { s = s?.Length.ToString(); s = null; Thread.Yield(); } catch (System.Exception ex) { System.Console.WriteLine(ex); } finally { s = s ?? ""hello""; } } }; Task.Factory.StartNew(a); Task.Factory.StartNew(a); Task.Factory.StartNew(a); Task.Factory.StartNew(a); Task.Factory.StartNew(a); Task.Factory.StartNew(a); Task.Factory.StartNew(a); Task.Factory.StartNew(a); Task.Factory.StartNew(a); Task.Factory.StartNew(a); Task.Factory.StartNew(a); Task.Factory.StartNew(a); Task.Factory.StartNew(a); Task.Factory.StartNew(a); Task.Factory.StartNew(a); Task.Factory.StartNew(a); a(); System.Console.WriteLine(""Success""); } } "; var comp = CompileAndVerify(source, expectedOutput: @"Success"); } [Fact(), WorkItem(836, "GitHub")] public void ConditionalMemberAccessRace002() { var source = @" using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; class Program { static void Main() { string s = ""hello""; Test(s); } private static void Test<T>(T s) where T : IEnumerable<char> { Action a = () => { for (int i = 0; i < 1000000; i++) { var temp = s; try { s?.GetEnumerator(); s = default(T); Thread.Yield(); } catch (System.Exception ex) { System.Console.WriteLine(ex); } finally { s = temp; } } }; var tasks = new List<Task>(); tasks.Add(Task.Factory.StartNew(a)); tasks.Add(Task.Factory.StartNew(a)); tasks.Add(Task.Factory.StartNew(a)); tasks.Add(Task.Factory.StartNew(a)); tasks.Add(Task.Factory.StartNew(a)); tasks.Add(Task.Factory.StartNew(a)); tasks.Add(Task.Factory.StartNew(a)); tasks.Add(Task.Factory.StartNew(a)); tasks.Add(Task.Factory.StartNew(a)); tasks.Add(Task.Factory.StartNew(a)); tasks.Add(Task.Factory.StartNew(a)); tasks.Add(Task.Factory.StartNew(a)); tasks.Add(Task.Factory.StartNew(a)); tasks.Add(Task.Factory.StartNew(a)); tasks.Add(Task.Factory.StartNew(a)); tasks.Add(Task.Factory.StartNew(a)); a(); // wait for all tasks to exit or we may have // test issues when unloading ApDomain while threads still running in it Task.WaitAll(tasks.ToArray()); System.Console.WriteLine(""Success""); } } "; var comp = CompileAndVerify(source, expectedOutput: @"Success"); } [Fact] public void ConditionalMemberAccessConditional001() { var source = @" using System; class Program { static void Main() { Test1<string>(null); Test2<string>(null); } static string Test1<T>(T[] arr) { if (arr != null && arr.Length > 0) { return arr[0].ToString(); } return ""none""; } static string Test2<T>(T[] arr) { if (arr?.Length > 0) { return arr[0].ToString(); } return ""none""; } } "; var comp = CompileAndVerify(source, expectedOutput: @""); comp.VerifyIL("Program.Test1<T>(T[])", @" { // Code size 34 (0x22) .maxstack 2 IL_0000: ldarg.0 IL_0001: brfalse.s IL_001c IL_0003: ldarg.0 IL_0004: ldlen IL_0005: brfalse.s IL_001c IL_0007: ldarg.0 IL_0008: ldc.i4.0 IL_0009: readonly. IL_000b: ldelema ""T"" IL_0010: constrained. ""T"" IL_0016: callvirt ""string object.ToString()"" IL_001b: ret IL_001c: ldstr ""none"" IL_0021: ret } ").VerifyIL("Program.Test2<T>(T[])", @" { // Code size 34 (0x22) .maxstack 2 IL_0000: ldarg.0 IL_0001: brfalse.s IL_001c IL_0003: ldarg.0 IL_0004: ldlen IL_0005: brfalse.s IL_001c IL_0007: ldarg.0 IL_0008: ldc.i4.0 IL_0009: readonly. IL_000b: ldelema ""T"" IL_0010: constrained. ""T"" IL_0016: callvirt ""string object.ToString()"" IL_001b: ret IL_001c: ldstr ""none"" IL_0021: ret } "); } [Fact] public void ConditionalMemberAccessConditional002() { var source = @" using System; class Program { static void Main() { Test1<string>(null); Test2<string>(null); } static string Test1<T>(T[] arr) { if (!(arr != null && arr.Length > 0)) { return ""none""; } return arr[0].ToString(); } static string Test2<T>(T[] arr) { if (!(arr?.Length > 0)) { return ""none""; } return arr[0].ToString(); } } "; var comp = CompileAndVerify(source, expectedOutput: @""); comp.VerifyIL("Program.Test1<T>(T[])", @" { // Code size 34 (0x22) .maxstack 2 IL_0000: ldarg.0 IL_0001: brfalse.s IL_0007 IL_0003: ldarg.0 IL_0004: ldlen IL_0005: brtrue.s IL_000d IL_0007: ldstr ""none"" IL_000c: ret IL_000d: ldarg.0 IL_000e: ldc.i4.0 IL_000f: readonly. IL_0011: ldelema ""T"" IL_0016: constrained. ""T"" IL_001c: callvirt ""string object.ToString()"" IL_0021: ret } ").VerifyIL("Program.Test2<T>(T[])", @" { // Code size 34 (0x22) .maxstack 2 IL_0000: ldarg.0 IL_0001: brfalse.s IL_0007 IL_0003: ldarg.0 IL_0004: ldlen IL_0005: brtrue.s IL_000d IL_0007: ldstr ""none"" IL_000c: ret IL_000d: ldarg.0 IL_000e: ldc.i4.0 IL_000f: readonly. IL_0011: ldelema ""T"" IL_0016: constrained. ""T"" IL_001c: callvirt ""string object.ToString()"" IL_0021: ret } "); } [Fact] public void ConditionalMemberAccessConditional003() { var source = @" using System; class Program { static void Main() { System.Console.WriteLine(Test1<string>(null)); System.Console.WriteLine(Test2<string>(null)); System.Console.WriteLine(Test1<string>(new string[] {})); System.Console.WriteLine(Test2<string>(new string[] {})); System.Console.WriteLine(Test1<string>(new string[] { System.String.Empty })); System.Console.WriteLine(Test2<string>(new string[] { System.String.Empty })); } static string Test1<T>(T[] arr1) { var arr = arr1; if (arr != null && arr.Length == 0) { return ""empty""; } return ""not empty""; } static string Test2<T>(T[] arr1) { var arr = arr1; if (!(arr?.Length != 0)) { return ""empty""; } return ""not empty""; } } "; var comp = CompileAndVerify(source, expectedOutput: @"not empty not empty empty empty not empty not empty"); comp.VerifyIL("Program.Test1<T>(T[])", @" { // Code size 21 (0x15) .maxstack 1 .locals init (T[] V_0) //arr IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: brfalse.s IL_000f IL_0005: ldloc.0 IL_0006: ldlen IL_0007: brtrue.s IL_000f IL_0009: ldstr ""empty"" IL_000e: ret IL_000f: ldstr ""not empty"" IL_0014: ret } ").VerifyIL("Program.Test2<T>(T[])", @" { // Code size 26 (0x1a) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: brtrue.s IL_0008 IL_0004: pop IL_0005: ldc.i4.1 IL_0006: br.s IL_000c IL_0008: ldlen IL_0009: ldc.i4.0 IL_000a: cgt.un IL_000c: brtrue.s IL_0014 IL_000e: ldstr ""empty"" IL_0013: ret IL_0014: ldstr ""not empty"" IL_0019: ret } "); } [Fact] public void ConditionalMemberAccessConditional004() { var source = @" using System; class Program { static void Main() { var w = new WeakReference<string>(null); Test0(ref w); Test1(ref w); Test2(ref w); Test3(ref w); } static string Test0(ref WeakReference<string> slot) { string value = null; WeakReference<string> weak = slot; if (weak != null && weak.TryGetTarget(out value)) { return value; } return ""hello""; } static string Test1(ref WeakReference<string> slot) { string value = null; WeakReference<string> weak = slot; if (weak?.TryGetTarget(out value) == true) { return value; } return ""hello""; } static string Test2(ref WeakReference<string> slot) { string value = null; if (slot?.TryGetTarget(out value) == true) { return value; } return ""hello""; } static string Test3(ref WeakReference<string> slot) { string value = null; if (slot?.TryGetTarget(out value) ?? false) { return value; } return ""hello""; } } "; var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: ""). VerifyIL("Program.Test0(ref System.WeakReference<string>)", @" { // Code size 26 (0x1a) .maxstack 2 .locals init (string V_0, //value System.WeakReference<string> V_1) //weak IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: ldind.ref IL_0004: stloc.1 IL_0005: ldloc.1 IL_0006: brfalse.s IL_0014 IL_0008: ldloc.1 IL_0009: ldloca.s V_0 IL_000b: callvirt ""bool System.WeakReference<string>.TryGetTarget(out string)"" IL_0010: brfalse.s IL_0014 IL_0012: ldloc.0 IL_0013: ret IL_0014: ldstr ""hello"" IL_0019: ret } ").VerifyIL("Program.Test1(ref System.WeakReference<string>)", @" { // Code size 28 (0x1c) .maxstack 2 .locals init (string V_0) //value IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: ldind.ref IL_0004: dup IL_0005: brtrue.s IL_000b IL_0007: pop IL_0008: ldc.i4.0 IL_0009: br.s IL_0012 IL_000b: ldloca.s V_0 IL_000d: call ""bool System.WeakReference<string>.TryGetTarget(out string)"" IL_0012: brfalse.s IL_0016 IL_0014: ldloc.0 IL_0015: ret IL_0016: ldstr ""hello"" IL_001b: ret } ").VerifyIL("Program.Test2(ref System.WeakReference<string>)", @" { // Code size 28 (0x1c) .maxstack 2 .locals init (string V_0) //value IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: ldind.ref IL_0004: dup IL_0005: brtrue.s IL_000b IL_0007: pop IL_0008: ldc.i4.0 IL_0009: br.s IL_0012 IL_000b: ldloca.s V_0 IL_000d: call ""bool System.WeakReference<string>.TryGetTarget(out string)"" IL_0012: brfalse.s IL_0016 IL_0014: ldloc.0 IL_0015: ret IL_0016: ldstr ""hello"" IL_001b: ret } ").VerifyIL("Program.Test3(ref System.WeakReference<string>)", @" { // Code size 28 (0x1c) .maxstack 2 .locals init (string V_0) //value IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: ldind.ref IL_0004: dup IL_0005: brtrue.s IL_000b IL_0007: pop IL_0008: ldc.i4.0 IL_0009: br.s IL_0012 IL_000b: ldloca.s V_0 IL_000d: call ""bool System.WeakReference<string>.TryGetTarget(out string)"" IL_0012: brfalse.s IL_0016 IL_0014: ldloc.0 IL_0015: ret IL_0016: ldstr ""hello"" IL_001b: ret } "); } [WorkItem(1042288, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1042288")] [Fact] public void Bug1042288() { var source = @" using System; class Test { static void Main() { var c1 = new C1(); System.Console.WriteLine(c1?.M1() ?? (long)1000); return; } } class C1 { public int M1() { return 1; } } "; var comp = CompileAndVerify(source, expectedOutput: @"1"); comp.VerifyIL("Test.Main", @" { // Code size 62 (0x3e) .maxstack 2 .locals init (int? V_0, int? V_1) IL_0000: newobj ""C1..ctor()"" IL_0005: dup IL_0006: brtrue.s IL_0014 IL_0008: pop IL_0009: ldloca.s V_1 IL_000b: initobj ""int?"" IL_0011: ldloc.1 IL_0012: br.s IL_001e IL_0014: call ""int C1.M1()"" IL_0019: newobj ""int?..ctor(int)"" IL_001e: stloc.0 IL_001f: ldloca.s V_0 IL_0021: call ""bool int?.HasValue.get"" IL_0026: brtrue.s IL_0030 IL_0028: ldc.i4 0x3e8 IL_002d: conv.i8 IL_002e: br.s IL_0038 IL_0030: ldloca.s V_0 IL_0032: call ""int int?.GetValueOrDefault()"" IL_0037: conv.i8 IL_0038: call ""void System.Console.WriteLine(long)"" IL_003d: ret } "); } [WorkItem(470, "CodPlex")] [Fact] public void CodPlexBug470_01() { var source = @" class C { public static void Main() { System.Console.WriteLine(MyMethod(null)); System.Console.WriteLine(MyMethod(new MyType())); } public static decimal MyMethod(MyType myObject) { return myObject?.MyField ?? 0m; } } public class MyType { public decimal MyField = 123; } "; var verifier = CompileAndVerify(source, expectedOutput: @"0 123"); verifier.VerifyIL("C.MyMethod", @" { // Code size 16 (0x10) .maxstack 1 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0009 IL_0003: ldsfld ""decimal decimal.Zero"" IL_0008: ret IL_0009: ldarg.0 IL_000a: ldfld ""decimal MyType.MyField"" IL_000f: ret }"); } [WorkItem(470, "CodPlex")] [Fact] public void CodPlexBug470_02() { var source = @" class C { public static void Main() { System.Console.WriteLine(MyMethod(null)); System.Console.WriteLine(MyMethod(new MyType())); } public static decimal MyMethod(MyType myObject) { return myObject?.MyField ?? default(decimal); } } public class MyType { public decimal MyField = 123; } "; var verifier = CompileAndVerify(source, expectedOutput: @"0 123"); verifier.VerifyIL("C.MyMethod", @" { // Code size 16 (0x10) .maxstack 1 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0009 IL_0003: ldsfld ""decimal decimal.Zero"" IL_0008: ret IL_0009: ldarg.0 IL_000a: ldfld ""decimal MyType.MyField"" IL_000f: ret }"); } [WorkItem(470, "CodPlex")] [Fact] public void CodPlexBug470_03() { var source = @" using System; class C { public static void Main() { System.Console.WriteLine(String.Format(System.Globalization.CultureInfo.InvariantCulture, ""{0}"", MyMethod(null))); System.Console.WriteLine(String.Format(System.Globalization.CultureInfo.InvariantCulture, ""{0}"", MyMethod(new MyType()))); } public static DateTime MyMethod(MyType myObject) { return myObject?.MyField ?? default(DateTime); } } public class MyType { public DateTime MyField = new DateTime(100000000); } "; var verifier = CompileAndVerify(source, expectedOutput: @"01/01/0001 00:00:00 01/01/0001 00:00:10"); verifier.VerifyIL("C.MyMethod", @" { // Code size 20 (0x14) .maxstack 1 .locals init (System.DateTime V_0) IL_0000: ldarg.0 IL_0001: brtrue.s IL_000d IL_0003: ldloca.s V_0 IL_0005: initobj ""System.DateTime"" IL_000b: ldloc.0 IL_000c: ret IL_000d: ldarg.0 IL_000e: ldfld ""System.DateTime MyType.MyField"" IL_0013: ret }"); } [WorkItem(470, "CodPlex")] [Fact] public void CodPlexBug470_04() { var source = @" class C { public static void Main() { System.Console.WriteLine(MyMethod(null).F); System.Console.WriteLine(MyMethod(new MyType()).F); } public static MyStruct MyMethod(MyType myObject) { return myObject?.MyField ?? default(MyStruct); } } public class MyType { public MyStruct MyField = new MyStruct() {F = 123}; } public struct MyStruct { public int F; } "; var verifier = CompileAndVerify(source, expectedOutput: @"0 123"); verifier.VerifyIL("C.MyMethod", @" { // Code size 20 (0x14) .maxstack 1 .locals init (MyStruct V_0) IL_0000: ldarg.0 IL_0001: brtrue.s IL_000d IL_0003: ldloca.s V_0 IL_0005: initobj ""MyStruct"" IL_000b: ldloc.0 IL_000c: ret IL_000d: ldarg.0 IL_000e: ldfld ""MyStruct MyType.MyField"" IL_0013: ret }"); } [WorkItem(1103294, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1103294")] [Fact] public void Bug1103294_01() { var source = @" class C { static void Main() { System.Console.WriteLine(""---""); Goo<int>(new C<int>()); System.Console.WriteLine(""---""); Goo<int>(null); System.Console.WriteLine(""---""); } static void Goo<T>(C<T> x) { x?.M(); } } class C<T> { public T M() { System.Console.WriteLine(""M""); return default(T); } }"; var verifier = CompileAndVerify(source, expectedOutput: @"--- M --- ---"); verifier.VerifyIL("C.Goo<T>", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldarg.0 IL_0001: brfalse.s IL_000a IL_0003: ldarg.0 IL_0004: call ""T C<T>.M()"" IL_0009: pop IL_000a: ret }"); } [WorkItem(1103294, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1103294")] [Fact] public void Bug1103294_02() { var source = @" unsafe class C { static void Main() { System.Console.WriteLine(""---""); Goo(new C()); System.Console.WriteLine(""---""); Goo(null); System.Console.WriteLine(""---""); } static void Goo(C x) { x?.M(); } public int* M() { System.Console.WriteLine(""M""); return null; } } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), verify: Verification.Fails, expectedOutput: @"--- M --- ---"); verifier.VerifyIL("C.Goo", @" { // Code size 14 (0xe) .maxstack 1 IL_0000: nop IL_0001: ldarg.0 IL_0002: brtrue.s IL_0006 IL_0004: br.s IL_000d IL_0006: ldarg.0 IL_0007: call ""int* C.M()"" IL_000c: pop IL_000d: ret }"); } [WorkItem(23422, "https://github.com/dotnet/roslyn/issues/23422")] [Fact] public void ConditionalRefLike() { var source = @" class C { static void Main() { System.Console.WriteLine(""---""); Goo(new C()); System.Console.WriteLine(""---""); Goo(null); System.Console.WriteLine(""---""); } static void Goo(C x) { x?.M(); } public RefLike M() { System.Console.WriteLine(""M""); return default; } public ref struct RefLike{} } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), expectedOutput: @"--- M --- ---"); verifier.VerifyIL("C.Goo", @" { // Code size 14 (0xe) .maxstack 1 IL_0000: nop IL_0001: ldarg.0 IL_0002: brtrue.s IL_0006 IL_0004: br.s IL_000d IL_0006: ldarg.0 IL_0007: call ""C.RefLike C.M()"" IL_000c: pop IL_000d: ret }"); } [WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")] [Fact] public void Bug1109164_01() { var source = @" using System; class Test { static void Main() { System.Console.WriteLine(""---""); C.F1(null); System.Console.WriteLine(""---""); C.F1(new C()); System.Console.WriteLine(""---""); C.F2(null); System.Console.WriteLine(""---""); C.F2(new C()); System.Console.WriteLine(""---""); } } class C { static public void F1(C c) { System.Console.WriteLine(""F1""); Action a = () => c?.M(); a(); } static public void F2(C c) => c?.M(); void M() => System.Console.WriteLine(""M""); } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"--- F1 --- F1 M --- --- M ---"); verifier.VerifyIL("C.<>c__DisplayClass0_0.<F1>b__0", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""C C.<>c__DisplayClass0_0.c"" IL_0006: dup IL_0007: brtrue.s IL_000c IL_0009: pop IL_000a: br.s IL_0012 IL_000c: call ""void C.M()"" IL_0011: nop IL_0012: ret }"); verifier.VerifyIL("C.F2", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: br.s IL_000c IL_0005: ldarg.0 IL_0006: call ""void C.M()"" IL_000b: nop IL_000c: ret }"); } [WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")] [Fact] public void Bug1109164_02() { var source = @" using System; class Test { static void Main() { } } class C { static public void F1(C c) { System.Console.WriteLine(""F1""); Func<object> a = () => c?.M(); } static public object F2(C c) => c?.M(); static public object P1 => (new C())?.M(); void M() => System.Console.WriteLine(""M""); } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (16,32): error CS0029: Cannot implicitly convert type 'void' to 'object' // Func<object> a = () => c?.M(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "c?.M()").WithArguments("void", "object").WithLocation(16, 32), // (16,32): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // Func<object> a = () => c?.M(); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "c?.M()").WithArguments("lambda expression").WithLocation(16, 32), // (19,37): error CS0029: Cannot implicitly convert type 'void' to 'object' // static public object F2(C c) => c?.M(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "c?.M()").WithArguments("void", "object").WithLocation(19, 37), // (21,32): error CS0029: Cannot implicitly convert type 'void' to 'object' // static public object P1 => (new C())?.M(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(new C())?.M()").WithArguments("void", "object").WithLocation(21, 32) ); } [WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")] [Fact] public void Bug1109164_03() { var source = @" using System; class Test { static void Main() { System.Console.WriteLine(""---""); C<int>.F1(null); System.Console.WriteLine(""---""); C<int>.F1(new C<int>()); System.Console.WriteLine(""---""); C<int>.F2(null); System.Console.WriteLine(""---""); C<int>.F2(new C<int>()); System.Console.WriteLine(""---""); } } class C<T> { static public void F1(C<T> c) { System.Console.WriteLine(""F1""); Action a = () => c?.M(); a(); } static public void F2(C<T> c) => c?.M(); T M() { System.Console.WriteLine(""M""); return default(T); } } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"--- F1 --- F1 M --- --- M ---"); verifier.VerifyIL("C<T>.<>c__DisplayClass0_0.<F1>b__0()", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""C<T> C<T>.<>c__DisplayClass0_0.c"" IL_0006: dup IL_0007: brtrue.s IL_000c IL_0009: pop IL_000a: br.s IL_0012 IL_000c: call ""T C<T>.M()"" IL_0011: pop IL_0012: ret }"); verifier.VerifyIL("C<T>.F2", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: br.s IL_000c IL_0005: ldarg.0 IL_0006: call ""T C<T>.M()"" IL_000b: pop IL_000c: ret }"); } [WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")] [Fact] public void Bug1109164_04() { var source = @" using System; class Test { static void Main() { } } class C<T> { static public void F1(C<T> c) { Func<object> a = () => c?.M(); } static public object F2(C<T> c) => c?.M(); static public object P1 => (new C<T>())?.M(); T M() { return default(T); } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (15,33): error CS0023: Operator '?' cannot be applied to operand of type 'T' // Func<object> a = () => c?.M(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "T").WithLocation(15, 33), // (18,41): error CS0023: Operator '?' cannot be applied to operand of type 'T' // static public object F2(C<T> c) => c?.M(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "T").WithLocation(18, 41), // (20,44): error CS0023: Operator '?' cannot be applied to operand of type 'T' // static public object P1 => (new C<T>())?.M(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "T").WithLocation(20, 44) ); } [WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")] [Fact] public void Bug1109164_05() { var source = @" using System; class Test { static void Main() { System.Console.WriteLine(""---""); C.F1(null); System.Console.WriteLine(""---""); C.F1(new C()); System.Console.WriteLine(""---""); C.F2(null); System.Console.WriteLine(""---""); C.F2(new C()); System.Console.WriteLine(""---""); } } unsafe class C { static public void F1(C c) { System.Console.WriteLine(""F1""); Action<object> a = o => c?.M(); a(null); } static public void F2(C c) => c?.M(); void* M() { System.Console.WriteLine(""M""); return null; } } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), verify: Verification.Fails, expectedOutput: @"--- F1 --- F1 M --- --- M ---"); verifier.VerifyIL("C.<>c__DisplayClass0_0.<F1>b__0", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""C C.<>c__DisplayClass0_0.c"" IL_0006: dup IL_0007: brtrue.s IL_000c IL_0009: pop IL_000a: br.s IL_0012 IL_000c: call ""void* C.M()"" IL_0011: pop IL_0012: ret }"); verifier.VerifyIL("C.F2", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: br.s IL_000c IL_0005: ldarg.0 IL_0006: call ""void* C.M()"" IL_000b: pop IL_000c: ret }"); } [WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")] [Fact] public void Bug1109164_06() { var source = @" using System; class Test { static void Main() { } } unsafe class C { static public void F1(C c) { System.Console.WriteLine(""F1""); Func<object, object> a = o => c?.M(); } static public object F2(C c) => c?.M(); static public object P1 => (new C())?.M(); void* M() { System.Console.WriteLine(""M""); return null; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe.WithAllowUnsafe(true)); compilation.VerifyDiagnostics( // (16,40): error CS0023: Operator '?' cannot be applied to operand of type 'void*' // Func<object, object> a = o => c?.M(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "void*").WithLocation(16, 40), // (19,38): error CS0023: Operator '?' cannot be applied to operand of type 'void*' // static public object F2(C c) => c?.M(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "void*").WithLocation(19, 38), // (21,41): error CS0023: Operator '?' cannot be applied to operand of type 'void*' // static public object P1 => (new C())?.M(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "void*").WithLocation(21, 41) ); } [WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")] [Fact] public void Bug1109164_07() { var source = @" using System; class Test { static void Main() { C<int>.Test(); } } class C<T> { public static void Test() { var x = new [] {null, new C<T>()}; for (int i = 0; i < 2; x[i-1]?.M()) { System.Console.WriteLine(""---""); System.Console.WriteLine(""Loop""); i++; } System.Console.WriteLine(""---""); } public T M() { System.Console.WriteLine(""M""); return default(T); } } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @" --- Loop --- Loop M ---"); } [WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")] [Fact] public void Bug1109164_08() { var source = @" using System; class Test { static void Main() { C<int>.Test(); } } class C<T> { public static void Test() { var x = new [] {null, new C<T>()}; System.Console.WriteLine(""---""); for (x[0]?.M(); false;) { } System.Console.WriteLine(""---""); for (x[1]?.M(); false;) { } System.Console.WriteLine(""---""); } public T M() { System.Console.WriteLine(""M""); return default(T); } } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"--- --- M ---"); } [WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")] [Fact] public void Bug1109164_09() { var source = @" class Test { static void Main() { } } class C<T> { public static void Test() { C<T> x = null; for (; x?.M();) { } } public T M() { return default(T); } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (15,17): error CS0023: Operator '?' cannot be applied to operand of type 'T' // for (; x?.M();) Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "T").WithLocation(15, 17) ); } [WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")] [Fact] public void Bug1109164_10() { var source = @" using System; class Test { static void Main() { C<int>.Test(); } } class C<T> { public static void Test() { System.Console.WriteLine(""---""); M1(a => a?.M(), null); System.Console.WriteLine(""---""); M1((a) => a?.M(), new C<T>()); System.Console.WriteLine(""---""); } static void M1(Action<C<T>> x, C<T> y) { System.Console.WriteLine(""M1(Action<C<T>> x)""); x(y); } static void M1(Func<C<T>, object> x, C<T> y) { System.Console.WriteLine(""M1(Func<C<T>, object> x)""); x(y); } public T M() { System.Console.WriteLine(""M""); return default(T); } } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"--- M1(Action<C<T>> x) --- M1(Action<C<T>> x) M ---"); } [WorkItem(74, "https://github.com/dotnet/roslyn/issues/74")] [Fact] public void ConditionalInAsyncTask() { var source = @" #pragma warning disable CS1998 // suppress 'no await in async' warning using System; using System.Threading.Tasks; class Goo<T> { public T Method(int i) { Console.Write(i); return default(T); // returns value of unconstrained type parameter type } public void M1(Goo<T> x) => x?.Method(4); public async void M2(Goo<T> x) => x?.Method(5); public async Task M3(Goo<T> x) => x?.Method(6); public async Task M4() { Goo<T> a = new Goo<T>(); Goo<T> b = null; Action f1 = async () => a?.Method(1); f1(); f1 = async () => b?.Method(0); f1(); Func<Task> f2 = async () => a?.Method(2); await f2(); Func<Task> f3 = async () => b?.Method(3); await f3(); M1(a); M1(b); M2(a); M2(b); await M3(a); await M3(b); } } class Program { public static void Main() { // this will complete synchronously as there are no truly async ops. new Goo<int>().M4(); } }"; var compilation = CreateCompilationWithMscorlib45( source, references: new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: "12456"); } [WorkItem(825, "https://github.com/dotnet/roslyn/issues/825")] [Fact] public void ConditionalBoolExpr01() { var source = @" class C { public static void Main() { System.Console.WriteLine(HasLength(null, 0)); } static bool HasLength(string s, int len) { return s?.Length == len; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"False"); verifier.VerifyIL("C.HasLength", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldc.i4.0 IL_0004: ret IL_0005: ldarg.0 IL_0006: call ""int string.Length.get"" IL_000b: ldarg.1 IL_000c: ceq IL_000e: ret }"); } [WorkItem(825, "https://github.com/dotnet/roslyn/issues/825")] [Fact] public void ConditionalBoolExpr01a() { var source = @" class C { public static void Main() { System.Console.WriteLine(HasLength(null, 0)); } static bool HasLength(string s, byte len) { return s?.Length == len; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"False"); verifier.VerifyIL("C.HasLength", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldc.i4.0 IL_0004: ret IL_0005: ldarg.0 IL_0006: call ""int string.Length.get"" IL_000b: ldarg.1 IL_000c: ceq IL_000e: ret }"); } [WorkItem(825, "https://github.com/dotnet/roslyn/issues/825")] [WorkItem(5662, "https://github.com/dotnet/roslyn/issues/5662")] [Fact] public void ConditionalBoolExpr01b() { var source = @" class C { public static void Main() { System.Console.WriteLine(HasLength(null, long.MaxValue)); try { System.Console.WriteLine(HasLengthChecked(null, long.MaxValue)); } catch (System.Exception ex) { System.Console.WriteLine(ex.GetType().Name); } } static bool HasLength(string s, long len) { return s?.Length == (int)(byte)len; } static bool HasLengthChecked(string s, long len) { checked { return s?.Length == (int)(byte)len; } } } "; var verifier = CompileAndVerify(source, expectedOutput: @"False OverflowException"); verifier.VerifyIL("C.HasLength", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldc.i4.0 IL_0004: ret IL_0005: ldarg.0 IL_0006: call ""int string.Length.get"" IL_000b: ldarg.1 IL_000c: conv.u1 IL_000d: ceq IL_000f: ret }").VerifyIL("C.HasLengthChecked", @" { // Code size 48 (0x30) .maxstack 2 .locals init (int? V_0, int V_1, int? V_2) IL_0000: ldarg.0 IL_0001: brtrue.s IL_000e IL_0003: ldloca.s V_2 IL_0005: initobj ""int?"" IL_000b: ldloc.2 IL_000c: br.s IL_0019 IL_000e: ldarg.0 IL_000f: call ""int string.Length.get"" IL_0014: newobj ""int?..ctor(int)"" IL_0019: stloc.0 IL_001a: ldarg.1 IL_001b: conv.ovf.u1 IL_001c: stloc.1 IL_001d: ldloca.s V_0 IL_001f: call ""int int?.GetValueOrDefault()"" IL_0024: ldloc.1 IL_0025: ceq IL_0027: ldloca.s V_0 IL_0029: call ""bool int?.HasValue.get"" IL_002e: and IL_002f: ret }"); } [Fact] public void ConditionalBoolExpr02() { var source = @" class C { public static void Main() { System.Console.Write(HasLength(null, 0)); System.Console.Write(HasLength(null, 3)); System.Console.Write(HasLength(""q"", 2)); } static bool HasLength(string s, int len) { return (s?.Length ?? 2) + 1 == len; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"FalseTrueTrue"); verifier.VerifyIL("C.HasLength", @" { // Code size 18 (0x12) .maxstack 2 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0006 IL_0003: ldc.i4.2 IL_0004: br.s IL_000c IL_0006: ldarg.0 IL_0007: call ""int string.Length.get"" IL_000c: ldc.i4.1 IL_000d: add IL_000e: ldarg.1 IL_000f: ceq IL_0011: ret }"); } [Fact] public void ConditionalBoolExpr02a() { var source = @" class C { public static void Main() { System.Console.Write(NotHasLength(null, 0)); System.Console.Write(NotHasLength(null, 3)); System.Console.Write(NotHasLength(""q"", 2)); } static bool NotHasLength(string s, int len) { return s?.Length + 1 != len; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"TrueTrueFalse"); verifier.VerifyIL("C.NotHasLength", @" { // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldc.i4.1 IL_0004: ret IL_0005: ldarg.0 IL_0006: call ""int string.Length.get"" IL_000b: ldc.i4.1 IL_000c: add IL_000d: ldarg.1 IL_000e: ceq IL_0010: ldc.i4.0 IL_0011: ceq IL_0013: ret }"); } [Fact] public void ConditionalBoolExpr02b() { var source = @" class C { public static void Main() { System.Console.Write(NotHasLength(null, 0)); System.Console.Write(NotHasLength(null, 3)); System.Console.Write(NotHasLength(""q"", 2)); System.Console.Write(NotHasLength(null, null)); } static bool NotHasLength(string s, int? len) { return s?.Length + 1 != len; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"TrueTrueFalseFalse"); verifier.VerifyIL("C.NotHasLength", @" { // Code size 42 (0x2a) .maxstack 2 .locals init (int? V_0) IL_0000: ldarg.0 IL_0001: brtrue.s IL_000b IL_0003: ldarga.s V_1 IL_0005: call ""bool int?.HasValue.get"" IL_000a: ret IL_000b: ldarg.0 IL_000c: call ""int string.Length.get"" IL_0011: ldc.i4.1 IL_0012: add IL_0013: ldarg.1 IL_0014: stloc.0 IL_0015: ldloca.s V_0 IL_0017: call ""int int?.GetValueOrDefault()"" IL_001c: ceq IL_001e: ldloca.s V_0 IL_0020: call ""bool int?.HasValue.get"" IL_0025: and IL_0026: ldc.i4.0 IL_0027: ceq IL_0029: ret }"); } [Fact] public void ConditionalBoolExpr03() { var source = @" using System.Threading.Tasks; static class C { public static void Main() { System.Console.Write(HasLength(null, 0).Result); System.Console.Write(HasLength(null, 3).Result); System.Console.Write(HasLength(""q"", 2).Result); } static async Task<bool> HasLength(string s, int len) { return (s?.Goo(await Bar()) ?? await Bar() + await Bar()) + 1 == len; } static int Goo(this string s, int arg) { return s.Length; } static async Task<int> Bar() { await Task.Yield(); return 1; } } "; var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe); var comp = CompileAndVerify(c, expectedOutput: @"FalseTrueTrue"); } [Fact] public void ConditionalBoolExpr04() { var source = @" using System.Threading.Tasks; static class C { public static void Main() { System.Console.Write(HasLength((string)null, 0).Result); System.Console.Write(HasLength((string)null, 3).Result); System.Console.Write(HasLength(""q"", 2).Result); } static async Task<bool> HasLength<T>(T s, int len) { return (s?.Goo(await Bar()) ?? 2) + 1 == len; } static int Goo<T>(this T s, int arg) { return ((string)(object)s).Length; } static async Task<int> Bar() { await Task.Yield(); return 1; } } "; var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe); var comp = CompileAndVerify(c, expectedOutput: @"FalseTrueTrue"); } [Fact] public void ConditionalBoolExpr05() { var source = @" using System.Threading.Tasks; static class C { public static void Main() { System.Console.Write(HasLength((string)null, 0).Result); System.Console.Write(HasLength((string)null, 3).Result); System.Console.Write(HasLength(""q"", 2).Result); } static async Task<bool> HasLength<T>(T s, int len) { return (s?.Goo(await Bar(await Bar())) ?? 2) + 1 == len; } static int Goo<T>(this T s, int arg) { return ((string)(object)s).Length; } static async Task<int> Bar() { await Task.Yield(); return 1; } static async Task<int> Bar(int arg) { await Task.Yield(); return arg; } } "; var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe); var comp = CompileAndVerify(c, expectedOutput: @"FalseTrueTrue"); } [Fact] public void ConditionalBoolExpr06() { var source = @" using System.Threading.Tasks; static class C { public static void Main() { System.Console.Write(HasLength(null, 0).Result); System.Console.Write(HasLength(null, 7).Result); System.Console.Write(HasLength(""q"", 7).Result); } static async Task<bool> HasLength(string s, int len) { System.Console.WriteLine(s?.Goo(await Bar())?.Goo(await Bar()) + ""#""); return s?.Goo(await Bar())?.Goo(await Bar()).Length == len; } static string Goo(this string s, string arg) { return s + arg; } static async Task<string> Bar() { await Task.Yield(); return ""Bar""; } } "; var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe); var comp = CompileAndVerify(c, expectedOutput: @"# False# FalseqBarBar# True"); } [Fact] public void ConditionalBoolExpr07() { var source = @" using System.Threading.Tasks; static class C { public static void Main() { System.Console.WriteLine(Test(null).Result); System.Console.WriteLine(Test(""q"").Result); } static async Task<bool> Test(string s) { return (await Bar(s))?.Goo(await Bar())?.ToString()?.Length > 1; } static string Goo(this string s, string arg1) { return s + arg1; } static async Task<string> Bar() { await Task.Yield(); return ""Bar""; } static async Task<string> Bar(string arg) { await Task.Yield(); return arg; } } "; var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe); var comp = CompileAndVerify(c, expectedOutput: @"False True"); } [Fact] public void ConditionalBoolExpr08() { var source = @" using System.Threading.Tasks; static class C { public static void Main() { System.Console.WriteLine(Test(null).Result); System.Console.WriteLine(Test(""q"").Result); } static async Task<bool> Test(string s) { return (await Bar(s))?.Insert(0, await Bar())?.ToString()?.Length > 1; } static async Task<string> Bar() { await Task.Yield(); return ""Bar""; } static async Task<dynamic> Bar(string arg) { await Task.Yield(); return arg; } }"; var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe); var comp = CompileAndVerify(c, expectedOutput: @"False True"); } [Fact] public void ConditionalUserDef01() { var source = @" class C { struct S1 { public static bool operator ==(S1? x, S1?y) { System.Console.Write(""==""); return true; } public static bool operator !=(S1? x, S1? y) { System.Console.Write(""!=""); return false; } } class C1 { public S1 Goo() { return new S1(); } } public static void Main() { System.Console.WriteLine(TestEq(null, new S1())); System.Console.WriteLine(TestEq(new C1(), new S1())); System.Console.WriteLine(TestNeq(null, new S1())); System.Console.WriteLine(TestNeq(new C1(), new S1())); } static bool TestEq(C1 c, S1 arg) { return c?.Goo() == arg; } static bool TestNeq(C1 c, S1 arg) { return c?.Goo() != arg; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"==True ==True !=False !=False"); verifier.VerifyIL("C.TestNeq", @" { // Code size 37 (0x25) .maxstack 2 .locals init (C.S1? V_0) IL_0000: ldarg.0 IL_0001: brtrue.s IL_000e IL_0003: ldloca.s V_0 IL_0005: initobj ""C.S1?"" IL_000b: ldloc.0 IL_000c: br.s IL_0019 IL_000e: ldarg.0 IL_000f: call ""C.S1 C.C1.Goo()"" IL_0014: newobj ""C.S1?..ctor(C.S1)"" IL_0019: ldarg.1 IL_001a: newobj ""C.S1?..ctor(C.S1)"" IL_001f: call ""bool C.S1.op_Inequality(C.S1?, C.S1?)"" IL_0024: ret }"); } [Fact] public void ConditionalUserDef01n() { var source = @" class C { struct S1 { public static bool operator ==(S1? x, S1?y) { System.Console.Write(""==""); return true; } public static bool operator !=(S1? x, S1? y) { System.Console.Write(""!=""); return false; } } class C1 { public S1 Goo() { return new S1(); } } public static void Main() { System.Console.WriteLine(TestEq(null, new S1())); System.Console.WriteLine(TestEq(new C1(), new S1())); System.Console.WriteLine(TestEq(new C1(), null)); System.Console.WriteLine(TestNeq(null, new S1())); System.Console.WriteLine(TestNeq(new C1(), new S1())); System.Console.WriteLine(TestNeq(new C1(), null)); } static bool TestEq(C1 c, S1? arg) { return c?.Goo() == arg; } static bool TestNeq(C1 c, S1? arg) { return c?.Goo() != arg; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"==True ==True ==True !=False !=False !=False"); verifier.VerifyIL("C.TestNeq", @" { // Code size 32 (0x20) .maxstack 2 .locals init (C.S1? V_0) IL_0000: ldarg.0 IL_0001: brtrue.s IL_000e IL_0003: ldloca.s V_0 IL_0005: initobj ""C.S1?"" IL_000b: ldloc.0 IL_000c: br.s IL_0019 IL_000e: ldarg.0 IL_000f: call ""C.S1 C.C1.Goo()"" IL_0014: newobj ""C.S1?..ctor(C.S1)"" IL_0019: ldarg.1 IL_001a: call ""bool C.S1.op_Inequality(C.S1?, C.S1?)"" IL_001f: ret }"); } [Fact] public void ConditionalUserDef02() { var source = @" class C { struct S1 { public static bool operator ==(S1 x, S1 y) { System.Console.Write(""==""); return true; } public static bool operator !=(S1 x, S1 y) { System.Console.Write(""!=""); return false; } } class C1 { public S1 Goo() { return new S1(); } } public static void Main() { System.Console.WriteLine(TestEq(null, new S1())); System.Console.WriteLine(TestEq(new C1(), new S1())); System.Console.WriteLine(TestNeq(null, new S1())); System.Console.WriteLine(TestNeq(new C1(), new S1())); } static bool TestEq(C1 c, S1 arg) { return c?.Goo() == arg; } static bool TestNeq(C1 c, S1 arg) { return c?.Goo() != arg; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"False ==True True !=False"); verifier.VerifyIL("C.TestNeq", @" { // Code size 18 (0x12) .maxstack 2 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldc.i4.1 IL_0004: ret IL_0005: ldarg.0 IL_0006: call ""C.S1 C.C1.Goo()"" IL_000b: ldarg.1 IL_000c: call ""bool C.S1.op_Inequality(C.S1, C.S1)"" IL_0011: ret }"); } [Fact] public void ConditionalUserDef02n() { var source = @" class C { struct S1 { public static bool operator ==(S1 x, S1 y) { System.Console.Write(""==""); return true; } public static bool operator !=(S1 x, S1 y) { System.Console.Write(""!=""); return false; } } class C1 { public S1 Goo() { return new S1(); } } public static void Main() { System.Console.WriteLine(TestEq(null, new S1())); System.Console.WriteLine(TestEq(new C1(), new S1())); System.Console.WriteLine(TestEq(new C1(), null)); System.Console.WriteLine(TestNeq(null, new S1())); System.Console.WriteLine(TestNeq(new C1(), new S1())); System.Console.WriteLine(TestNeq(new C1(), null)); } static bool TestEq(C1 c, S1? arg) { return c?.Goo() == arg; } static bool TestNeq(C1 c, S1? arg) { return c?.Goo() != arg; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"False ==True False True !=False True"); verifier.VerifyIL("C.TestNeq", @" { // Code size 45 (0x2d) .maxstack 2 .locals init (C.S1 V_0, C.S1? V_1) IL_0000: ldarg.0 IL_0001: brtrue.s IL_000b IL_0003: ldarga.s V_1 IL_0005: call ""bool C.S1?.HasValue.get"" IL_000a: ret IL_000b: ldarg.0 IL_000c: call ""C.S1 C.C1.Goo()"" IL_0011: stloc.0 IL_0012: ldarg.1 IL_0013: stloc.1 IL_0014: ldloca.s V_1 IL_0016: call ""bool C.S1?.HasValue.get"" IL_001b: brtrue.s IL_001f IL_001d: ldc.i4.1 IL_001e: ret IL_001f: ldloc.0 IL_0020: ldloca.s V_1 IL_0022: call ""C.S1 C.S1?.GetValueOrDefault()"" IL_0027: call ""bool C.S1.op_Inequality(C.S1, C.S1)"" IL_002c: ret }"); } [Fact] public void Bug1() { var source = @" using System; class Test { static void Main() { var c1 = new C1(); M1(c1); M2(c1); } static void M1(C1 c1) { if (c1?.P == 1) Console.WriteLine(1); } static void M2(C1 c1) { if (c1 != null && c1.P == 1) Console.WriteLine(1); } } class C1 { public int P => 1; } "; var comp = CompileAndVerify(source, expectedOutput: @"1 1"); comp.VerifyIL("Test.M1", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: brfalse.s IL_0012 IL_0003: ldarg.0 IL_0004: call ""int C1.P.get"" IL_0009: ldc.i4.1 IL_000a: bne.un.s IL_0012 IL_000c: ldc.i4.1 IL_000d: call ""void System.Console.WriteLine(int)"" IL_0012: ret } "); comp.VerifyIL("Test.M2", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: brfalse.s IL_0012 IL_0003: ldarg.0 IL_0004: callvirt ""int C1.P.get"" IL_0009: ldc.i4.1 IL_000a: bne.un.s IL_0012 IL_000c: ldc.i4.1 IL_000d: call ""void System.Console.WriteLine(int)"" IL_0012: ret } "); } [Fact] public void ConditionalBoolExpr02ba() { var source = @" class C { public static void Main() { System.Console.Write(NotHasLength(null, 0)); System.Console.Write(NotHasLength(null, 3)); System.Console.Write(NotHasLength(1, 2)); } static bool NotHasLength(int? s, int len) { return s?.GetHashCode() + 1 != len; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"TrueTrueFalse"); verifier.VerifyIL("C.NotHasLength", @" { // Code size 35 (0x23) .maxstack 2 .locals init (int V_0) IL_0000: ldarga.s V_0 IL_0002: call ""bool int?.HasValue.get"" IL_0007: brtrue.s IL_000b IL_0009: ldc.i4.1 IL_000a: ret IL_000b: ldarga.s V_0 IL_000d: call ""int int?.GetValueOrDefault()"" IL_0012: stloc.0 IL_0013: ldloca.s V_0 IL_0015: call ""int int.GetHashCode()"" IL_001a: ldc.i4.1 IL_001b: add IL_001c: ldarg.1 IL_001d: ceq IL_001f: ldc.i4.0 IL_0020: ceq IL_0022: ret } "); } [Fact] public void ConditionalBoolExpr02bb() { var source = @" class C { public static void Main() { System.Console.Write(NotHasLength(null, 0)); System.Console.Write(NotHasLength(null, 3)); System.Console.Write(NotHasLength(1, 2)); System.Console.Write(NotHasLength(null, null)); } static bool NotHasLength(int? s, int? len) { return s?.GetHashCode() + 1 != len; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"TrueTrueFalseFalse"); verifier.VerifyIL("C.NotHasLength", @" { // Code size 57 (0x39) .maxstack 2 .locals init (int? V_0, int V_1) IL_0000: ldarga.s V_0 IL_0002: call ""bool int?.HasValue.get"" IL_0007: brtrue.s IL_0011 IL_0009: ldarga.s V_1 IL_000b: call ""bool int?.HasValue.get"" IL_0010: ret IL_0011: ldarga.s V_0 IL_0013: call ""int int?.GetValueOrDefault()"" IL_0018: stloc.1 IL_0019: ldloca.s V_1 IL_001b: call ""int int.GetHashCode()"" IL_0020: ldc.i4.1 IL_0021: add IL_0022: ldarg.1 IL_0023: stloc.0 IL_0024: ldloca.s V_0 IL_0026: call ""int int?.GetValueOrDefault()"" IL_002b: ceq IL_002d: ldloca.s V_0 IL_002f: call ""bool int?.HasValue.get"" IL_0034: and IL_0035: ldc.i4.0 IL_0036: ceq IL_0038: ret }"); } [Fact] public void ConditionalUnary() { var source = @" class C { public static void Main() { var x = - - -((string)null)?.Length ?? - - -string.Empty?.Length; System.Console.WriteLine(x); } } "; var verifier = CompileAndVerify(source, expectedOutput: @"0"); verifier.VerifyIL("C.Main", @" { // Code size 44 (0x2c) .maxstack 2 .locals init (int? V_0) IL_0000: ldsfld ""string string.Empty"" IL_0005: dup IL_0006: brtrue.s IL_0014 IL_0008: pop IL_0009: ldloca.s V_0 IL_000b: initobj ""int?"" IL_0011: ldloc.0 IL_0012: br.s IL_0021 IL_0014: call ""int string.Length.get"" IL_0019: neg IL_001a: neg IL_001b: neg IL_001c: newobj ""int?..ctor(int)"" IL_0021: box ""int?"" IL_0026: call ""void System.Console.WriteLine(object)"" IL_002b: ret } "); } [WorkItem(7388, "https://github.com/dotnet/roslyn/issues/7388")] [Fact] public void ConditionalClassConstrained001() { var source = @" using System; namespace ConsoleApplication9 { class Program { static void Main(string[] args) { var v = new A<object>(); System.Console.WriteLine(A<object>.Test(v)); } public class A<T> : object where T : class { public T Value { get { return (T)(object)42; }} public static T Test(A<T> val) { return val?.Value; } } } } "; var verifier = CompileAndVerify(source, expectedOutput: @"42"); verifier.VerifyIL("ConsoleApplication9.Program.A<T>.Test(ConsoleApplication9.Program.A<T>)", @" { // Code size 20 (0x14) .maxstack 1 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: brtrue.s IL_000d IL_0003: ldloca.s V_0 IL_0005: initobj ""T"" IL_000b: ldloc.0 IL_000c: ret IL_000d: ldarg.0 IL_000e: call ""T ConsoleApplication9.Program.A<T>.Value.get"" IL_0013: ret }"); } [Fact, WorkItem(15670, "https://github.com/dotnet/roslyn/issues/15670")] public void ConditionalAccessOffOfUnconstrainedDefault1() { var source = @" using System; public class Test<T> { public string Run() { return default(T)?.ToString(); } } class Program { static void Main() { Console.WriteLine(""--""); Console.WriteLine(new Test<string>().Run()); Console.WriteLine(""--""); Console.WriteLine(new Test<int>().Run()); Console.WriteLine(""--""); } } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"-- -- 0 --"); verifier.VerifyIL("Test<T>.Run", @" { // Code size 45 (0x2d) .maxstack 2 .locals init (T V_0, string V_1) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: initobj ""T"" IL_0009: ldloc.0 IL_000a: box ""T"" IL_000f: brtrue.s IL_0014 IL_0011: ldnull IL_0012: br.s IL_0028 IL_0014: ldloca.s V_0 IL_0016: dup IL_0017: initobj ""T"" IL_001d: constrained. ""T"" IL_0023: callvirt ""string object.ToString()"" IL_0028: stloc.1 IL_0029: br.s IL_002b IL_002b: ldloc.1 IL_002c: ret }"); } [Fact, WorkItem(15670, "https://github.com/dotnet/roslyn/issues/15670")] public void ConditionalAccessOffOfUnconstrainedDefault2() { var source = @" using System; public class Test<T> { public string Run() { var v = default(T); return v?.ToString(); } } class Program { static void Main() { Console.WriteLine(""--""); Console.WriteLine(new Test<string>().Run()); Console.WriteLine(""--""); Console.WriteLine(new Test<int>().Run()); Console.WriteLine(""--""); } } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"-- -- 0 --"); verifier.VerifyIL("Test<T>.Run", @" { // Code size 38 (0x26) .maxstack 1 .locals init (T V_0, //v string V_1) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: initobj ""T"" IL_0009: ldloc.0 IL_000a: box ""T"" IL_000f: brtrue.s IL_0014 IL_0011: ldnull IL_0012: br.s IL_0021 IL_0014: ldloca.s V_0 IL_0016: constrained. ""T"" IL_001c: callvirt ""string object.ToString()"" IL_0021: stloc.1 IL_0022: br.s IL_0024 IL_0024: ldloc.1 IL_0025: ret }"); } [Fact, WorkItem(15670, "https://github.com/dotnet/roslyn/issues/15670")] public void ConditionalAccessOffOfInterfaceConstrainedDefault1() { var source = @" using System; public class Test<T> where T : IComparable { public string Run() { return default(T)?.ToString(); } } class Program { static void Main() { Console.WriteLine(""--""); Console.WriteLine(new Test<string>().Run()); Console.WriteLine(""--""); Console.WriteLine(new Test<int>().Run()); Console.WriteLine(""--""); } } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"-- -- 0 --"); verifier.VerifyIL("Test<T>.Run", @" { // Code size 45 (0x2d) .maxstack 2 .locals init (T V_0, string V_1) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: initobj ""T"" IL_0009: ldloc.0 IL_000a: box ""T"" IL_000f: brtrue.s IL_0014 IL_0011: ldnull IL_0012: br.s IL_0028 IL_0014: ldloca.s V_0 IL_0016: dup IL_0017: initobj ""T"" IL_001d: constrained. ""T"" IL_0023: callvirt ""string object.ToString()"" IL_0028: stloc.1 IL_0029: br.s IL_002b IL_002b: ldloc.1 IL_002c: ret }"); } [Fact, WorkItem(15670, "https://github.com/dotnet/roslyn/issues/15670")] public void ConditionalAccessOffOfInterfaceConstrainedDefault2() { var source = @" using System; public class Test<T> where T : IComparable { public string Run() { var v = default(T); return v?.ToString(); } } class Program { static void Main() { Console.WriteLine(""--""); Console.WriteLine(new Test<string>().Run()); Console.WriteLine(""--""); Console.WriteLine(new Test<int>().Run()); Console.WriteLine(""--""); } } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"-- -- 0 --"); verifier.VerifyIL("Test<T>.Run", @" { // Code size 38 (0x26) .maxstack 1 .locals init (T V_0, //v string V_1) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: initobj ""T"" IL_0009: ldloc.0 IL_000a: box ""T"" IL_000f: brtrue.s IL_0014 IL_0011: ldnull IL_0012: br.s IL_0021 IL_0014: ldloca.s V_0 IL_0016: constrained. ""T"" IL_001c: callvirt ""string object.ToString()"" IL_0021: stloc.1 IL_0022: br.s IL_0024 IL_0024: ldloc.1 IL_0025: ret }"); } [Fact, WorkItem(15670, "https://github.com/dotnet/roslyn/issues/15670")] public void ConditionalAccessOffOfClassConstrainedDefault1() { var source = @" using System; public class Test<T> where T : class { public string Run() { return default(T)?.ToString(); } } class Program { static void Main() { Console.WriteLine(""--""); Console.WriteLine(new Test<string>().Run()); Console.WriteLine(""--""); } } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"-- --"); verifier.VerifyIL("Test<T>.Run", @" { // Code size 7 (0x7) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: br.s IL_0005 IL_0005: ldloc.0 IL_0006: ret }"); } [Fact, WorkItem(15670, "https://github.com/dotnet/roslyn/issues/15670")] public void ConditionalAccessOffOfClassConstrainedDefault2() { var source = @" using System; public class Test<T> where T : class { public string Run() { var v = default(T); return v?.ToString(); } } class Program { static void Main() { Console.WriteLine(""--""); Console.WriteLine(new Test<string>().Run()); Console.WriteLine(""--""); } } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"-- --"); verifier.VerifyIL("Test<T>.Run", @" { // Code size 32 (0x20) .maxstack 2 .locals init (T V_0, //v string V_1) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: initobj ""T"" IL_0009: ldloc.0 IL_000a: box ""T"" IL_000f: dup IL_0010: brtrue.s IL_0016 IL_0012: pop IL_0013: ldnull IL_0014: br.s IL_001b IL_0016: callvirt ""string object.ToString()"" IL_001b: stloc.1 IL_001c: br.s IL_001e IL_001e: ldloc.1 IL_001f: ret }"); } [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void ConditionalAccessOffReadOnlyNullable1() { var source = @" using System; class Program { private static readonly Guid? g = null; static void Main() { Console.WriteLine(g?.ToString()); } } "; var comp = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"", verify: Verification.Fails); comp.VerifyIL("Program.Main", @" { // Code size 44 (0x2c) .maxstack 2 .locals init (System.Guid V_0) IL_0000: nop IL_0001: ldsflda ""System.Guid? Program.g"" IL_0006: dup IL_0007: call ""bool System.Guid?.HasValue.get"" IL_000c: brtrue.s IL_0012 IL_000e: pop IL_000f: ldnull IL_0010: br.s IL_0025 IL_0012: call ""System.Guid System.Guid?.GetValueOrDefault()"" IL_0017: stloc.0 IL_0018: ldloca.s V_0 IL_001a: constrained. ""System.Guid"" IL_0020: callvirt ""string object.ToString()"" IL_0025: call ""void System.Console.WriteLine(string)"" IL_002a: nop IL_002b: ret }"); comp = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"", parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes); comp.VerifyIL("Program.Main", @" { // Code size 47 (0x2f) .maxstack 2 .locals init (System.Guid? V_0, System.Guid V_1) IL_0000: nop IL_0001: ldsfld ""System.Guid? Program.g"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: dup IL_000a: call ""bool System.Guid?.HasValue.get"" IL_000f: brtrue.s IL_0015 IL_0011: pop IL_0012: ldnull IL_0013: br.s IL_0028 IL_0015: call ""System.Guid System.Guid?.GetValueOrDefault()"" IL_001a: stloc.1 IL_001b: ldloca.s V_1 IL_001d: constrained. ""System.Guid"" IL_0023: callvirt ""string object.ToString()"" IL_0028: call ""void System.Console.WriteLine(string)"" IL_002d: nop IL_002e: ret }"); } [Fact] public void ConditionalAccessOffReadOnlyNullable2() { var source = @" using System; class Program { static void Main() { Console.WriteLine(default(Guid?)?.ToString()); } } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @""); verifier.VerifyIL("Program.Main", @" { // Code size 55 (0x37) .maxstack 2 .locals init (System.Guid? V_0, System.Guid V_1) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: dup IL_0004: initobj ""System.Guid?"" IL_000a: call ""bool System.Guid?.HasValue.get"" IL_000f: brtrue.s IL_0014 IL_0011: ldnull IL_0012: br.s IL_0030 IL_0014: ldloca.s V_0 IL_0016: dup IL_0017: initobj ""System.Guid?"" IL_001d: call ""System.Guid System.Guid?.GetValueOrDefault()"" IL_0022: stloc.1 IL_0023: ldloca.s V_1 IL_0025: constrained. ""System.Guid"" IL_002b: callvirt ""string object.ToString()"" IL_0030: call ""void System.Console.WriteLine(string)"" IL_0035: nop IL_0036: ret }"); } [Fact] [WorkItem(23351, "https://github.com/dotnet/roslyn/issues/23351")] public void ConditionalAccessOffConstrainedTypeParameter_Property() { var source = @" using System; class Program { static void Main(string[] args) { var obj1 = new MyObject1 { MyDate = new DateTime(636461511000000000L) }; var obj2 = new MyObject2<MyObject1>(obj1); System.Console.WriteLine(obj1.MyDate.Ticks); System.Console.WriteLine(obj2.CurrentDate.Value.Ticks); System.Console.WriteLine(new MyObject2<MyObject1>(null).CurrentDate.HasValue); } } abstract class MyBaseObject1 { public DateTime MyDate { get; set; } } class MyObject1 : MyBaseObject1 { } class MyObject2<MyObjectType> where MyObjectType : MyBaseObject1, new() { public MyObject2(MyObjectType obj) { m_CurrentObject1 = obj; } private MyObjectType m_CurrentObject1 = null; public MyObjectType CurrentObject1 => m_CurrentObject1; public DateTime? CurrentDate => CurrentObject1?.MyDate; } "; var expectedOutput = @" 636461511000000000 636461511000000000 False "; CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] [WorkItem(23351, "https://github.com/dotnet/roslyn/issues/23351")] public void ConditionalAccessOffConstrainedTypeParameter_Field() { var source = @" using System; class Program { static void Main(string[] args) { var obj1 = new MyObject1 { MyDate = new DateTime(636461511000000000L) }; var obj2 = new MyObject2<MyObject1>(obj1); System.Console.WriteLine(obj1.MyDate.Ticks); System.Console.WriteLine(obj2.CurrentDate.Value.Ticks); System.Console.WriteLine(new MyObject2<MyObject1>(null).CurrentDate.HasValue); } } abstract class MyBaseObject1 { public DateTime MyDate; } class MyObject1 : MyBaseObject1 { } class MyObject2<MyObjectType> where MyObjectType : MyBaseObject1, new() { public MyObject2(MyObjectType obj) { m_CurrentObject1 = obj; } private MyObjectType m_CurrentObject1 = null; public MyObjectType CurrentObject1 => m_CurrentObject1; public DateTime? CurrentDate => CurrentObject1?.MyDate; } "; var expectedOutput = @" 636461511000000000 636461511000000000 False "; CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CodeGenShortCircuitOperatorTests : CSharpTestBase { [Fact] public void TestShortCircuitAnd() { var source = @" class C { public static bool Test(char ch, bool result) { System.Console.WriteLine(ch); return result; } public static void Main() { const bool c1 = true; const bool c2 = false; bool v1 = true; bool v2 = false; System.Console.WriteLine(true && true); System.Console.WriteLine(true && false); System.Console.WriteLine(false && true); System.Console.WriteLine(false && false); System.Console.WriteLine(c1 && c1); System.Console.WriteLine(c1 && c2); System.Console.WriteLine(c2 && c1); System.Console.WriteLine(c2 && c2); System.Console.WriteLine(v1 && v1); System.Console.WriteLine(v1 && v2); System.Console.WriteLine(v2 && v1); System.Console.WriteLine(v2 && v2); System.Console.WriteLine(Test('L', true) && Test('R', true)); System.Console.WriteLine(Test('L', true) && Test('R', false)); System.Console.WriteLine(Test('L', false) && Test('R', true)); System.Console.WriteLine(Test('L', false) && Test('R', false)); } } "; var compilation = CompileAndVerify(source, expectedOutput: @" True False False False True False False False True False False False L R True L R False L False L False "); compilation.VerifyIL("C.Main", @" { // Code size 189 (0xbd) .maxstack 2 .locals init (bool V_0, //v1 bool V_1) //v2 IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.0 IL_0003: stloc.1 IL_0004: ldc.i4.1 IL_0005: call ""void System.Console.WriteLine(bool)"" IL_000a: ldc.i4.0 IL_000b: call ""void System.Console.WriteLine(bool)"" IL_0010: ldc.i4.0 IL_0011: call ""void System.Console.WriteLine(bool)"" IL_0016: ldc.i4.0 IL_0017: call ""void System.Console.WriteLine(bool)"" IL_001c: ldc.i4.1 IL_001d: call ""void System.Console.WriteLine(bool)"" IL_0022: ldc.i4.0 IL_0023: call ""void System.Console.WriteLine(bool)"" IL_0028: ldc.i4.0 IL_0029: call ""void System.Console.WriteLine(bool)"" IL_002e: ldc.i4.0 IL_002f: call ""void System.Console.WriteLine(bool)"" IL_0034: ldloc.0 IL_0035: ldloc.0 IL_0036: and IL_0037: call ""void System.Console.WriteLine(bool)"" IL_003c: ldloc.0 IL_003d: ldloc.1 IL_003e: and IL_003f: call ""void System.Console.WriteLine(bool)"" IL_0044: ldloc.1 IL_0045: ldloc.0 IL_0046: and IL_0047: call ""void System.Console.WriteLine(bool)"" IL_004c: ldloc.1 IL_004d: ldloc.1 IL_004e: and IL_004f: call ""void System.Console.WriteLine(bool)"" IL_0054: ldc.i4.s 76 IL_0056: ldc.i4.1 IL_0057: call ""bool C.Test(char, bool)"" IL_005c: brfalse.s IL_0068 IL_005e: ldc.i4.s 82 IL_0060: ldc.i4.1 IL_0061: call ""bool C.Test(char, bool)"" IL_0066: br.s IL_0069 IL_0068: ldc.i4.0 IL_0069: call ""void System.Console.WriteLine(bool)"" IL_006e: ldc.i4.s 76 IL_0070: ldc.i4.1 IL_0071: call ""bool C.Test(char, bool)"" IL_0076: brfalse.s IL_0082 IL_0078: ldc.i4.s 82 IL_007a: ldc.i4.0 IL_007b: call ""bool C.Test(char, bool)"" IL_0080: br.s IL_0083 IL_0082: ldc.i4.0 IL_0083: call ""void System.Console.WriteLine(bool)"" IL_0088: ldc.i4.s 76 IL_008a: ldc.i4.0 IL_008b: call ""bool C.Test(char, bool)"" IL_0090: brfalse.s IL_009c IL_0092: ldc.i4.s 82 IL_0094: ldc.i4.1 IL_0095: call ""bool C.Test(char, bool)"" IL_009a: br.s IL_009d IL_009c: ldc.i4.0 IL_009d: call ""void System.Console.WriteLine(bool)"" IL_00a2: ldc.i4.s 76 IL_00a4: ldc.i4.0 IL_00a5: call ""bool C.Test(char, bool)"" IL_00aa: brfalse.s IL_00b6 IL_00ac: ldc.i4.s 82 IL_00ae: ldc.i4.0 IL_00af: call ""bool C.Test(char, bool)"" IL_00b4: br.s IL_00b7 IL_00b6: ldc.i4.0 IL_00b7: call ""void System.Console.WriteLine(bool)"" IL_00bc: ret }"); } [Fact] public void TestShortCircuitOr() { var source = @" class C { public static bool Test(char ch, bool result) { System.Console.WriteLine(ch); return result; } public static void Main() { const bool c1 = true; const bool c2 = false; bool v1 = true; bool v2 = false; System.Console.WriteLine(true || true); System.Console.WriteLine(true || false); System.Console.WriteLine(false || true); System.Console.WriteLine(false || false); System.Console.WriteLine(c1 || c1); System.Console.WriteLine(c1 || c2); System.Console.WriteLine(c2 || c1); System.Console.WriteLine(c2 || c2); System.Console.WriteLine(v1 || v1); System.Console.WriteLine(v1 || v2); System.Console.WriteLine(v2 || v1); System.Console.WriteLine(v2 || v2); System.Console.WriteLine(Test('L', true) || Test('R', true)); System.Console.WriteLine(Test('L', true) || Test('R', false)); System.Console.WriteLine(Test('L', false) || Test('R', true)); System.Console.WriteLine(Test('L', false) || Test('R', false)); } } "; var compilation = CompileAndVerify(source, expectedOutput: @" True True True False True True True False True True True False L True L True L R True L R False "); compilation.VerifyIL("C.Main", @" { // Code size 189 (0xbd) .maxstack 2 .locals init (bool V_0, //v1 bool V_1) //v2 IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.0 IL_0003: stloc.1 IL_0004: ldc.i4.1 IL_0005: call ""void System.Console.WriteLine(bool)"" IL_000a: ldc.i4.1 IL_000b: call ""void System.Console.WriteLine(bool)"" IL_0010: ldc.i4.1 IL_0011: call ""void System.Console.WriteLine(bool)"" IL_0016: ldc.i4.0 IL_0017: call ""void System.Console.WriteLine(bool)"" IL_001c: ldc.i4.1 IL_001d: call ""void System.Console.WriteLine(bool)"" IL_0022: ldc.i4.1 IL_0023: call ""void System.Console.WriteLine(bool)"" IL_0028: ldc.i4.1 IL_0029: call ""void System.Console.WriteLine(bool)"" IL_002e: ldc.i4.0 IL_002f: call ""void System.Console.WriteLine(bool)"" IL_0034: ldloc.0 IL_0035: ldloc.0 IL_0036: or IL_0037: call ""void System.Console.WriteLine(bool)"" IL_003c: ldloc.0 IL_003d: ldloc.1 IL_003e: or IL_003f: call ""void System.Console.WriteLine(bool)"" IL_0044: ldloc.1 IL_0045: ldloc.0 IL_0046: or IL_0047: call ""void System.Console.WriteLine(bool)"" IL_004c: ldloc.1 IL_004d: ldloc.1 IL_004e: or IL_004f: call ""void System.Console.WriteLine(bool)"" IL_0054: ldc.i4.s 76 IL_0056: ldc.i4.1 IL_0057: call ""bool C.Test(char, bool)"" IL_005c: brtrue.s IL_0068 IL_005e: ldc.i4.s 82 IL_0060: ldc.i4.1 IL_0061: call ""bool C.Test(char, bool)"" IL_0066: br.s IL_0069 IL_0068: ldc.i4.1 IL_0069: call ""void System.Console.WriteLine(bool)"" IL_006e: ldc.i4.s 76 IL_0070: ldc.i4.1 IL_0071: call ""bool C.Test(char, bool)"" IL_0076: brtrue.s IL_0082 IL_0078: ldc.i4.s 82 IL_007a: ldc.i4.0 IL_007b: call ""bool C.Test(char, bool)"" IL_0080: br.s IL_0083 IL_0082: ldc.i4.1 IL_0083: call ""void System.Console.WriteLine(bool)"" IL_0088: ldc.i4.s 76 IL_008a: ldc.i4.0 IL_008b: call ""bool C.Test(char, bool)"" IL_0090: brtrue.s IL_009c IL_0092: ldc.i4.s 82 IL_0094: ldc.i4.1 IL_0095: call ""bool C.Test(char, bool)"" IL_009a: br.s IL_009d IL_009c: ldc.i4.1 IL_009d: call ""void System.Console.WriteLine(bool)"" IL_00a2: ldc.i4.s 76 IL_00a4: ldc.i4.0 IL_00a5: call ""bool C.Test(char, bool)"" IL_00aa: brtrue.s IL_00b6 IL_00ac: ldc.i4.s 82 IL_00ae: ldc.i4.0 IL_00af: call ""bool C.Test(char, bool)"" IL_00b4: br.s IL_00b7 IL_00b6: ldc.i4.1 IL_00b7: call ""void System.Console.WriteLine(bool)"" IL_00bc: ret }"); } [Fact] public void TestChainedShortCircuitOperators() { var source = @" class C { public static bool Test(char ch, bool result) { System.Console.WriteLine(ch); return result; } public static void Main() { // AND AND System.Console.WriteLine(Test('A', true) && Test('B', true) && Test('C' , true)); System.Console.WriteLine(Test('A', true) && Test('B', true) && Test('C' , false)); System.Console.WriteLine(Test('A', true) && Test('B', false) && Test('C' , true)); System.Console.WriteLine(Test('A', true) && Test('B', false) && Test('C' , false)); System.Console.WriteLine(Test('A', false) && Test('B', true) && Test('C' , true)); System.Console.WriteLine(Test('A', false) && Test('B', true) && Test('C' , false)); System.Console.WriteLine(Test('A', false) && Test('B', false) && Test('C' , true)); System.Console.WriteLine(Test('A', false) && Test('B', false) && Test('C' , false)); // AND OR System.Console.WriteLine(Test('A', true) && Test('B', true) || Test('C' , true)); System.Console.WriteLine(Test('A', true) && Test('B', true) || Test('C' , false)); System.Console.WriteLine(Test('A', true) && Test('B', false) || Test('C' , true)); System.Console.WriteLine(Test('A', true) && Test('B', false) || Test('C' , false)); System.Console.WriteLine(Test('A', false) && Test('B', true) || Test('C' , true)); System.Console.WriteLine(Test('A', false) && Test('B', true) || Test('C' , false)); System.Console.WriteLine(Test('A', false) && Test('B', false) || Test('C' , true)); System.Console.WriteLine(Test('A', false) && Test('B', false) || Test('C' , false)); // OR AND System.Console.WriteLine(Test('A', true) || Test('B', true) && Test('C' , true)); System.Console.WriteLine(Test('A', true) || Test('B', true) && Test('C' , false)); System.Console.WriteLine(Test('A', true) || Test('B', false) && Test('C' , true)); System.Console.WriteLine(Test('A', true) || Test('B', false) && Test('C' , false)); System.Console.WriteLine(Test('A', false) || Test('B', true) && Test('C' , true)); System.Console.WriteLine(Test('A', false) || Test('B', true) && Test('C' , false)); System.Console.WriteLine(Test('A', false) || Test('B', false) && Test('C' , true)); System.Console.WriteLine(Test('A', false) || Test('B', false) && Test('C' , false)); // OR OR System.Console.WriteLine(Test('A', true) || Test('B', true) || Test('C' , true)); System.Console.WriteLine(Test('A', true) || Test('B', true) || Test('C' , false)); System.Console.WriteLine(Test('A', true) || Test('B', false) || Test('C' , true)); System.Console.WriteLine(Test('A', true) || Test('B', false) || Test('C' , false)); System.Console.WriteLine(Test('A', false) || Test('B', true) || Test('C' , true)); System.Console.WriteLine(Test('A', false) || Test('B', true) || Test('C' , false)); System.Console.WriteLine(Test('A', false) || Test('B', false) || Test('C' , true)); System.Console.WriteLine(Test('A', false) || Test('B', false) || Test('C' , false)); } } "; var compilation = CompileAndVerify(source, expectedOutput: @" A B C True A B C False A B False A B False A False A False A False A False A B True A B True A B C True A B C False A C True A C False A C True A C False A True A True A True A True A B C True A B C False A B False A B False A True A True A True A True A B True A B True A B C True A B C False "); compilation.VerifyIL("C.Main", @"{ // Code size 1177 (0x499) .maxstack 2 IL_0000: ldc.i4.s 65 IL_0002: ldc.i4.1 IL_0003: call ""bool C.Test(char, bool)"" IL_0008: brfalse.s IL_001e IL_000a: ldc.i4.s 66 IL_000c: ldc.i4.1 IL_000d: call ""bool C.Test(char, bool)"" IL_0012: brfalse.s IL_001e IL_0014: ldc.i4.s 67 IL_0016: ldc.i4.1 IL_0017: call ""bool C.Test(char, bool)"" IL_001c: br.s IL_001f IL_001e: ldc.i4.0 IL_001f: call ""void System.Console.WriteLine(bool)"" IL_0024: ldc.i4.s 65 IL_0026: ldc.i4.1 IL_0027: call ""bool C.Test(char, bool)"" IL_002c: brfalse.s IL_0042 IL_002e: ldc.i4.s 66 IL_0030: ldc.i4.1 IL_0031: call ""bool C.Test(char, bool)"" IL_0036: brfalse.s IL_0042 IL_0038: ldc.i4.s 67 IL_003a: ldc.i4.0 IL_003b: call ""bool C.Test(char, bool)"" IL_0040: br.s IL_0043 IL_0042: ldc.i4.0 IL_0043: call ""void System.Console.WriteLine(bool)"" IL_0048: ldc.i4.s 65 IL_004a: ldc.i4.1 IL_004b: call ""bool C.Test(char, bool)"" IL_0050: brfalse.s IL_0066 IL_0052: ldc.i4.s 66 IL_0054: ldc.i4.0 IL_0055: call ""bool C.Test(char, bool)"" IL_005a: brfalse.s IL_0066 IL_005c: ldc.i4.s 67 IL_005e: ldc.i4.1 IL_005f: call ""bool C.Test(char, bool)"" IL_0064: br.s IL_0067 IL_0066: ldc.i4.0 IL_0067: call ""void System.Console.WriteLine(bool)"" IL_006c: ldc.i4.s 65 IL_006e: ldc.i4.1 IL_006f: call ""bool C.Test(char, bool)"" IL_0074: brfalse.s IL_008a IL_0076: ldc.i4.s 66 IL_0078: ldc.i4.0 IL_0079: call ""bool C.Test(char, bool)"" IL_007e: brfalse.s IL_008a IL_0080: ldc.i4.s 67 IL_0082: ldc.i4.0 IL_0083: call ""bool C.Test(char, bool)"" IL_0088: br.s IL_008b IL_008a: ldc.i4.0 IL_008b: call ""void System.Console.WriteLine(bool)"" IL_0090: ldc.i4.s 65 IL_0092: ldc.i4.0 IL_0093: call ""bool C.Test(char, bool)"" IL_0098: brfalse.s IL_00ae IL_009a: ldc.i4.s 66 IL_009c: ldc.i4.1 IL_009d: call ""bool C.Test(char, bool)"" IL_00a2: brfalse.s IL_00ae IL_00a4: ldc.i4.s 67 IL_00a6: ldc.i4.1 IL_00a7: call ""bool C.Test(char, bool)"" IL_00ac: br.s IL_00af IL_00ae: ldc.i4.0 IL_00af: call ""void System.Console.WriteLine(bool)"" IL_00b4: ldc.i4.s 65 IL_00b6: ldc.i4.0 IL_00b7: call ""bool C.Test(char, bool)"" IL_00bc: brfalse.s IL_00d2 IL_00be: ldc.i4.s 66 IL_00c0: ldc.i4.1 IL_00c1: call ""bool C.Test(char, bool)"" IL_00c6: brfalse.s IL_00d2 IL_00c8: ldc.i4.s 67 IL_00ca: ldc.i4.0 IL_00cb: call ""bool C.Test(char, bool)"" IL_00d0: br.s IL_00d3 IL_00d2: ldc.i4.0 IL_00d3: call ""void System.Console.WriteLine(bool)"" IL_00d8: ldc.i4.s 65 IL_00da: ldc.i4.0 IL_00db: call ""bool C.Test(char, bool)"" IL_00e0: brfalse.s IL_00f6 IL_00e2: ldc.i4.s 66 IL_00e4: ldc.i4.0 IL_00e5: call ""bool C.Test(char, bool)"" IL_00ea: brfalse.s IL_00f6 IL_00ec: ldc.i4.s 67 IL_00ee: ldc.i4.1 IL_00ef: call ""bool C.Test(char, bool)"" IL_00f4: br.s IL_00f7 IL_00f6: ldc.i4.0 IL_00f7: call ""void System.Console.WriteLine(bool)"" IL_00fc: ldc.i4.s 65 IL_00fe: ldc.i4.0 IL_00ff: call ""bool C.Test(char, bool)"" IL_0104: brfalse.s IL_011a IL_0106: ldc.i4.s 66 IL_0108: ldc.i4.0 IL_0109: call ""bool C.Test(char, bool)"" IL_010e: brfalse.s IL_011a IL_0110: ldc.i4.s 67 IL_0112: ldc.i4.0 IL_0113: call ""bool C.Test(char, bool)"" IL_0118: br.s IL_011b IL_011a: ldc.i4.0 IL_011b: call ""void System.Console.WriteLine(bool)"" IL_0120: ldc.i4.s 65 IL_0122: ldc.i4.1 IL_0123: call ""bool C.Test(char, bool)"" IL_0128: brfalse.s IL_0134 IL_012a: ldc.i4.s 66 IL_012c: ldc.i4.1 IL_012d: call ""bool C.Test(char, bool)"" IL_0132: brtrue.s IL_013e IL_0134: ldc.i4.s 67 IL_0136: ldc.i4.1 IL_0137: call ""bool C.Test(char, bool)"" IL_013c: br.s IL_013f IL_013e: ldc.i4.1 IL_013f: call ""void System.Console.WriteLine(bool)"" IL_0144: ldc.i4.s 65 IL_0146: ldc.i4.1 IL_0147: call ""bool C.Test(char, bool)"" IL_014c: brfalse.s IL_0158 IL_014e: ldc.i4.s 66 IL_0150: ldc.i4.1 IL_0151: call ""bool C.Test(char, bool)"" IL_0156: brtrue.s IL_0162 IL_0158: ldc.i4.s 67 IL_015a: ldc.i4.0 IL_015b: call ""bool C.Test(char, bool)"" IL_0160: br.s IL_0163 IL_0162: ldc.i4.1 IL_0163: call ""void System.Console.WriteLine(bool)"" IL_0168: ldc.i4.s 65 IL_016a: ldc.i4.1 IL_016b: call ""bool C.Test(char, bool)"" IL_0170: brfalse.s IL_017c IL_0172: ldc.i4.s 66 IL_0174: ldc.i4.0 IL_0175: call ""bool C.Test(char, bool)"" IL_017a: brtrue.s IL_0186 IL_017c: ldc.i4.s 67 IL_017e: ldc.i4.1 IL_017f: call ""bool C.Test(char, bool)"" IL_0184: br.s IL_0187 IL_0186: ldc.i4.1 IL_0187: call ""void System.Console.WriteLine(bool)"" IL_018c: ldc.i4.s 65 IL_018e: ldc.i4.1 IL_018f: call ""bool C.Test(char, bool)"" IL_0194: brfalse.s IL_01a0 IL_0196: ldc.i4.s 66 IL_0198: ldc.i4.0 IL_0199: call ""bool C.Test(char, bool)"" IL_019e: brtrue.s IL_01aa IL_01a0: ldc.i4.s 67 IL_01a2: ldc.i4.0 IL_01a3: call ""bool C.Test(char, bool)"" IL_01a8: br.s IL_01ab IL_01aa: ldc.i4.1 IL_01ab: call ""void System.Console.WriteLine(bool)"" IL_01b0: ldc.i4.s 65 IL_01b2: ldc.i4.0 IL_01b3: call ""bool C.Test(char, bool)"" IL_01b8: brfalse.s IL_01c4 IL_01ba: ldc.i4.s 66 IL_01bc: ldc.i4.1 IL_01bd: call ""bool C.Test(char, bool)"" IL_01c2: brtrue.s IL_01ce IL_01c4: ldc.i4.s 67 IL_01c6: ldc.i4.1 IL_01c7: call ""bool C.Test(char, bool)"" IL_01cc: br.s IL_01cf IL_01ce: ldc.i4.1 IL_01cf: call ""void System.Console.WriteLine(bool)"" IL_01d4: ldc.i4.s 65 IL_01d6: ldc.i4.0 IL_01d7: call ""bool C.Test(char, bool)"" IL_01dc: brfalse.s IL_01e8 IL_01de: ldc.i4.s 66 IL_01e0: ldc.i4.1 IL_01e1: call ""bool C.Test(char, bool)"" IL_01e6: brtrue.s IL_01f2 IL_01e8: ldc.i4.s 67 IL_01ea: ldc.i4.0 IL_01eb: call ""bool C.Test(char, bool)"" IL_01f0: br.s IL_01f3 IL_01f2: ldc.i4.1 IL_01f3: call ""void System.Console.WriteLine(bool)"" IL_01f8: ldc.i4.s 65 IL_01fa: ldc.i4.0 IL_01fb: call ""bool C.Test(char, bool)"" IL_0200: brfalse.s IL_020c IL_0202: ldc.i4.s 66 IL_0204: ldc.i4.0 IL_0205: call ""bool C.Test(char, bool)"" IL_020a: brtrue.s IL_0216 IL_020c: ldc.i4.s 67 IL_020e: ldc.i4.1 IL_020f: call ""bool C.Test(char, bool)"" IL_0214: br.s IL_0217 IL_0216: ldc.i4.1 IL_0217: call ""void System.Console.WriteLine(bool)"" IL_021c: ldc.i4.s 65 IL_021e: ldc.i4.0 IL_021f: call ""bool C.Test(char, bool)"" IL_0224: brfalse.s IL_0230 IL_0226: ldc.i4.s 66 IL_0228: ldc.i4.0 IL_0229: call ""bool C.Test(char, bool)"" IL_022e: brtrue.s IL_023a IL_0230: ldc.i4.s 67 IL_0232: ldc.i4.0 IL_0233: call ""bool C.Test(char, bool)"" IL_0238: br.s IL_023b IL_023a: ldc.i4.1 IL_023b: call ""void System.Console.WriteLine(bool)"" IL_0240: ldc.i4.s 65 IL_0242: ldc.i4.1 IL_0243: call ""bool C.Test(char, bool)"" IL_0248: brtrue.s IL_0261 IL_024a: ldc.i4.s 66 IL_024c: ldc.i4.1 IL_024d: call ""bool C.Test(char, bool)"" IL_0252: brfalse.s IL_025e IL_0254: ldc.i4.s 67 IL_0256: ldc.i4.1 IL_0257: call ""bool C.Test(char, bool)"" IL_025c: br.s IL_0262 IL_025e: ldc.i4.0 IL_025f: br.s IL_0262 IL_0261: ldc.i4.1 IL_0262: call ""void System.Console.WriteLine(bool)"" IL_0267: ldc.i4.s 65 IL_0269: ldc.i4.1 IL_026a: call ""bool C.Test(char, bool)"" IL_026f: brtrue.s IL_0288 IL_0271: ldc.i4.s 66 IL_0273: ldc.i4.1 IL_0274: call ""bool C.Test(char, bool)"" IL_0279: brfalse.s IL_0285 IL_027b: ldc.i4.s 67 IL_027d: ldc.i4.0 IL_027e: call ""bool C.Test(char, bool)"" IL_0283: br.s IL_0289 IL_0285: ldc.i4.0 IL_0286: br.s IL_0289 IL_0288: ldc.i4.1 IL_0289: call ""void System.Console.WriteLine(bool)"" IL_028e: ldc.i4.s 65 IL_0290: ldc.i4.1 IL_0291: call ""bool C.Test(char, bool)"" IL_0296: brtrue.s IL_02af IL_0298: ldc.i4.s 66 IL_029a: ldc.i4.0 IL_029b: call ""bool C.Test(char, bool)"" IL_02a0: brfalse.s IL_02ac IL_02a2: ldc.i4.s 67 IL_02a4: ldc.i4.1 IL_02a5: call ""bool C.Test(char, bool)"" IL_02aa: br.s IL_02b0 IL_02ac: ldc.i4.0 IL_02ad: br.s IL_02b0 IL_02af: ldc.i4.1 IL_02b0: call ""void System.Console.WriteLine(bool)"" IL_02b5: ldc.i4.s 65 IL_02b7: ldc.i4.1 IL_02b8: call ""bool C.Test(char, bool)"" IL_02bd: brtrue.s IL_02d6 IL_02bf: ldc.i4.s 66 IL_02c1: ldc.i4.0 IL_02c2: call ""bool C.Test(char, bool)"" IL_02c7: brfalse.s IL_02d3 IL_02c9: ldc.i4.s 67 IL_02cb: ldc.i4.0 IL_02cc: call ""bool C.Test(char, bool)"" IL_02d1: br.s IL_02d7 IL_02d3: ldc.i4.0 IL_02d4: br.s IL_02d7 IL_02d6: ldc.i4.1 IL_02d7: call ""void System.Console.WriteLine(bool)"" IL_02dc: ldc.i4.s 65 IL_02de: ldc.i4.0 IL_02df: call ""bool C.Test(char, bool)"" IL_02e4: brtrue.s IL_02fd IL_02e6: ldc.i4.s 66 IL_02e8: ldc.i4.1 IL_02e9: call ""bool C.Test(char, bool)"" IL_02ee: brfalse.s IL_02fa IL_02f0: ldc.i4.s 67 IL_02f2: ldc.i4.1 IL_02f3: call ""bool C.Test(char, bool)"" IL_02f8: br.s IL_02fe IL_02fa: ldc.i4.0 IL_02fb: br.s IL_02fe IL_02fd: ldc.i4.1 IL_02fe: call ""void System.Console.WriteLine(bool)"" IL_0303: ldc.i4.s 65 IL_0305: ldc.i4.0 IL_0306: call ""bool C.Test(char, bool)"" IL_030b: brtrue.s IL_0324 IL_030d: ldc.i4.s 66 IL_030f: ldc.i4.1 IL_0310: call ""bool C.Test(char, bool)"" IL_0315: brfalse.s IL_0321 IL_0317: ldc.i4.s 67 IL_0319: ldc.i4.0 IL_031a: call ""bool C.Test(char, bool)"" IL_031f: br.s IL_0325 IL_0321: ldc.i4.0 IL_0322: br.s IL_0325 IL_0324: ldc.i4.1 IL_0325: call ""void System.Console.WriteLine(bool)"" IL_032a: ldc.i4.s 65 IL_032c: ldc.i4.0 IL_032d: call ""bool C.Test(char, bool)"" IL_0332: brtrue.s IL_034b IL_0334: ldc.i4.s 66 IL_0336: ldc.i4.0 IL_0337: call ""bool C.Test(char, bool)"" IL_033c: brfalse.s IL_0348 IL_033e: ldc.i4.s 67 IL_0340: ldc.i4.1 IL_0341: call ""bool C.Test(char, bool)"" IL_0346: br.s IL_034c IL_0348: ldc.i4.0 IL_0349: br.s IL_034c IL_034b: ldc.i4.1 IL_034c: call ""void System.Console.WriteLine(bool)"" IL_0351: ldc.i4.s 65 IL_0353: ldc.i4.0 IL_0354: call ""bool C.Test(char, bool)"" IL_0359: brtrue.s IL_0372 IL_035b: ldc.i4.s 66 IL_035d: ldc.i4.0 IL_035e: call ""bool C.Test(char, bool)"" IL_0363: brfalse.s IL_036f IL_0365: ldc.i4.s 67 IL_0367: ldc.i4.0 IL_0368: call ""bool C.Test(char, bool)"" IL_036d: br.s IL_0373 IL_036f: ldc.i4.0 IL_0370: br.s IL_0373 IL_0372: ldc.i4.1 IL_0373: call ""void System.Console.WriteLine(bool)"" IL_0378: ldc.i4.s 65 IL_037a: ldc.i4.1 IL_037b: call ""bool C.Test(char, bool)"" IL_0380: brtrue.s IL_0396 IL_0382: ldc.i4.s 66 IL_0384: ldc.i4.1 IL_0385: call ""bool C.Test(char, bool)"" IL_038a: brtrue.s IL_0396 IL_038c: ldc.i4.s 67 IL_038e: ldc.i4.1 IL_038f: call ""bool C.Test(char, bool)"" IL_0394: br.s IL_0397 IL_0396: ldc.i4.1 IL_0397: call ""void System.Console.WriteLine(bool)"" IL_039c: ldc.i4.s 65 IL_039e: ldc.i4.1 IL_039f: call ""bool C.Test(char, bool)"" IL_03a4: brtrue.s IL_03ba IL_03a6: ldc.i4.s 66 IL_03a8: ldc.i4.1 IL_03a9: call ""bool C.Test(char, bool)"" IL_03ae: brtrue.s IL_03ba IL_03b0: ldc.i4.s 67 IL_03b2: ldc.i4.0 IL_03b3: call ""bool C.Test(char, bool)"" IL_03b8: br.s IL_03bb IL_03ba: ldc.i4.1 IL_03bb: call ""void System.Console.WriteLine(bool)"" IL_03c0: ldc.i4.s 65 IL_03c2: ldc.i4.1 IL_03c3: call ""bool C.Test(char, bool)"" IL_03c8: brtrue.s IL_03de IL_03ca: ldc.i4.s 66 IL_03cc: ldc.i4.0 IL_03cd: call ""bool C.Test(char, bool)"" IL_03d2: brtrue.s IL_03de IL_03d4: ldc.i4.s 67 IL_03d6: ldc.i4.1 IL_03d7: call ""bool C.Test(char, bool)"" IL_03dc: br.s IL_03df IL_03de: ldc.i4.1 IL_03df: call ""void System.Console.WriteLine(bool)"" IL_03e4: ldc.i4.s 65 IL_03e6: ldc.i4.1 IL_03e7: call ""bool C.Test(char, bool)"" IL_03ec: brtrue.s IL_0402 IL_03ee: ldc.i4.s 66 IL_03f0: ldc.i4.0 IL_03f1: call ""bool C.Test(char, bool)"" IL_03f6: brtrue.s IL_0402 IL_03f8: ldc.i4.s 67 IL_03fa: ldc.i4.0 IL_03fb: call ""bool C.Test(char, bool)"" IL_0400: br.s IL_0403 IL_0402: ldc.i4.1 IL_0403: call ""void System.Console.WriteLine(bool)"" IL_0408: ldc.i4.s 65 IL_040a: ldc.i4.0 IL_040b: call ""bool C.Test(char, bool)"" IL_0410: brtrue.s IL_0426 IL_0412: ldc.i4.s 66 IL_0414: ldc.i4.1 IL_0415: call ""bool C.Test(char, bool)"" IL_041a: brtrue.s IL_0426 IL_041c: ldc.i4.s 67 IL_041e: ldc.i4.1 IL_041f: call ""bool C.Test(char, bool)"" IL_0424: br.s IL_0427 IL_0426: ldc.i4.1 IL_0427: call ""void System.Console.WriteLine(bool)"" IL_042c: ldc.i4.s 65 IL_042e: ldc.i4.0 IL_042f: call ""bool C.Test(char, bool)"" IL_0434: brtrue.s IL_044a IL_0436: ldc.i4.s 66 IL_0438: ldc.i4.1 IL_0439: call ""bool C.Test(char, bool)"" IL_043e: brtrue.s IL_044a IL_0440: ldc.i4.s 67 IL_0442: ldc.i4.0 IL_0443: call ""bool C.Test(char, bool)"" IL_0448: br.s IL_044b IL_044a: ldc.i4.1 IL_044b: call ""void System.Console.WriteLine(bool)"" IL_0450: ldc.i4.s 65 IL_0452: ldc.i4.0 IL_0453: call ""bool C.Test(char, bool)"" IL_0458: brtrue.s IL_046e IL_045a: ldc.i4.s 66 IL_045c: ldc.i4.0 IL_045d: call ""bool C.Test(char, bool)"" IL_0462: brtrue.s IL_046e IL_0464: ldc.i4.s 67 IL_0466: ldc.i4.1 IL_0467: call ""bool C.Test(char, bool)"" IL_046c: br.s IL_046f IL_046e: ldc.i4.1 IL_046f: call ""void System.Console.WriteLine(bool)"" IL_0474: ldc.i4.s 65 IL_0476: ldc.i4.0 IL_0477: call ""bool C.Test(char, bool)"" IL_047c: brtrue.s IL_0492 IL_047e: ldc.i4.s 66 IL_0480: ldc.i4.0 IL_0481: call ""bool C.Test(char, bool)"" IL_0486: brtrue.s IL_0492 IL_0488: ldc.i4.s 67 IL_048a: ldc.i4.0 IL_048b: call ""bool C.Test(char, bool)"" IL_0490: br.s IL_0493 IL_0492: ldc.i4.1 IL_0493: call ""void System.Console.WriteLine(bool)"" IL_0498: ret } "); } [Fact] public void TestConditionalMemberAccess001() { var source = @" public class C { static void Main() { Test(null); System.Console.Write('#'); int[] a = new int[] { }; Test(a); } static void Test(int[] x) { System.Console.Write(x?.ToString().ToString().ToString() ?? ""NULL""); } }"; var comp = CompileAndVerify(source, expectedOutput: "NULL#System.Int32[]"); comp.VerifyIL("C.Test", @" { // Code size 37 (0x25) .maxstack 2 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0006 IL_0003: ldnull IL_0004: br.s IL_0016 IL_0006: ldarg.0 IL_0007: callvirt ""string object.ToString()"" IL_000c: callvirt ""string object.ToString()"" IL_0011: callvirt ""string object.ToString()"" IL_0016: dup IL_0017: brtrue.s IL_001f IL_0019: pop IL_001a: ldstr ""NULL"" IL_001f: call ""void System.Console.Write(string)"" IL_0024: ret } "); } [Fact] public void TestConditionalMemberAccess001ext() { var source = @" public static class C { static void Main() { Test(null); System.Console.Write('#'); int[] a = new int[] { }; Test(a); } static void Test(int[] x) { System.Console.Write(x?.ToStr().ToStr().ToStr() ?? ""NULL""); } static string ToStr(this object arg) { return arg.ToString(); } }"; var comp = CompileAndVerify(source, expectedOutput: "NULL#System.Int32[]"); comp.VerifyIL("C.Test", @" { // Code size 37 (0x25) .maxstack 2 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0006 IL_0003: ldnull IL_0004: br.s IL_0016 IL_0006: ldarg.0 IL_0007: call ""string C.ToStr(object)"" IL_000c: call ""string C.ToStr(object)"" IL_0011: call ""string C.ToStr(object)"" IL_0016: dup IL_0017: brtrue.s IL_001f IL_0019: pop IL_001a: ldstr ""NULL"" IL_001f: call ""void System.Console.Write(string)"" IL_0024: ret } "); } [Fact] public void TestConditionalMemberAccess001dyn() { var source = @" public static class C { static void Main() { Test(null); System.Console.Write('#'); int[] a = new int[] { }; Test(a); } static void Test(dynamic x) { System.Console.Write(x?.ToString().ToString()?.ToString() ?? ""NULL""); } }"; var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: "NULL#System.Int32[]"); comp.VerifyIL("C.Test", @" { // Code size 355 (0x163) .maxstack 14 .locals init (object V_0, object V_1) IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> C.<>o__1.<>p__3"" IL_0005: brtrue.s IL_0046 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""Write"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.s 33 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: dup IL_002e: ldc.i4.1 IL_002f: ldc.i4.0 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003c: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0041: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> C.<>o__1.<>p__3"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> C.<>o__1.<>p__3"" IL_004b: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>>.Target"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> C.<>o__1.<>p__3"" IL_0055: ldtoken ""System.Console"" IL_005a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005f: ldarg.0 IL_0060: stloc.0 IL_0061: ldloc.0 IL_0062: brtrue.s IL_006a IL_0064: ldnull IL_0065: br IL_0154 IL_006a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_006f: brtrue.s IL_00a1 IL_0071: ldc.i4.0 IL_0072: ldstr ""ToString"" IL_0077: ldnull IL_0078: ldtoken ""C"" IL_007d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0082: ldc.i4.1 IL_0083: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0088: dup IL_0089: ldc.i4.0 IL_008a: ldc.i4.0 IL_008b: ldnull IL_008c: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0091: stelem.ref IL_0092: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0097: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_009c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_00a1: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_00a6: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_00ab: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_00b0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_00b5: brtrue.s IL_00e7 IL_00b7: ldc.i4.0 IL_00b8: ldstr ""ToString"" IL_00bd: ldnull IL_00be: ldtoken ""C"" IL_00c3: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00c8: ldc.i4.1 IL_00c9: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_00ce: dup IL_00cf: ldc.i4.0 IL_00d0: ldc.i4.0 IL_00d1: ldnull IL_00d2: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_00d7: stelem.ref IL_00d8: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_00dd: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00e2: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_00e7: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_00ec: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_00f1: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_00f6: ldloc.0 IL_00f7: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00fc: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_0101: stloc.1 IL_0102: ldloc.1 IL_0103: brtrue.s IL_0108 IL_0105: ldnull IL_0106: br.s IL_0154 IL_0108: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__2"" IL_010d: brtrue.s IL_013f IL_010f: ldc.i4.0 IL_0110: ldstr ""ToString"" IL_0115: ldnull IL_0116: ldtoken ""C"" IL_011b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0120: ldc.i4.1 IL_0121: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0126: dup IL_0127: ldc.i4.0 IL_0128: ldc.i4.0 IL_0129: ldnull IL_012a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_012f: stelem.ref IL_0130: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0135: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_013a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__2"" IL_013f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__2"" IL_0144: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_0149: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__2"" IL_014e: ldloc.1 IL_014f: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_0154: dup IL_0155: brtrue.s IL_015d IL_0157: pop IL_0158: ldstr ""NULL"" IL_015d: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_0162: ret } "); } [Fact] public void TestConditionalMemberAccess001dyn1() { var source = @" public static class C { static void Main() { Test(null); System.Console.Write('#'); int[] a = new int[] { }; Test(a); } static void Test(dynamic x) { System.Console.Write(x?.ToString()?[1].ToString() ?? ""NULL""); } }"; var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: "NULL#y"); } [Fact] public void TestConditionalMemberAccess001dyn2() { var source = @" public static class C { static void Main() { Test(null, ""aa""); System.Console.Write('#'); Test(""aa"", ""bb""); } static void Test(string s, dynamic ds) { System.Console.Write(s?.CompareTo(ds) ?? ""NULL""); } }"; var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: "NULL#-1"); } [Fact] public void TestConditionalMemberAccess001dyn3() { var source = @" public static class C { static void Main() { Test(null, 1); System.Console.Write('#'); int[] a = new int[] { }; Test(a, 1); } static void Test(int[] x, dynamic i) { System.Console.Write(x?.ToString()?[i].ToString() ?? ""NULL""); } }"; var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: "NULL#y"); } [Fact] public void TestConditionalMemberAccess001dyn4() { var source = @" public static class C { static void Main() { Test(null); System.Console.Write('#'); int[] a = new int[] {1,2,3}; Test(a); } static void Test(dynamic x) { System.Console.Write(x?.Length.ToString() ?? ""NULL""); } }"; var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: "NULL#3"); } [Fact] public void TestConditionalMemberAccess001dyn5() { var source = @" public static class C { static void Main() { Test(null); System.Console.Write('#'); int[] a = new int[] {1,2,3}; Test(a); } static void Test(dynamic x) { System.Console.Write(x?.Length?.ToString() ?? ""NULL""); } }"; var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: "NULL#3"); } [Fact] public void TestConditionalMemberAccessUnused() { var source = @" public class C { static void Main() { var dummy1 = ((string)null)?.ToString(); var dummy2 = ""qqq""?.ToString(); var dummy3 = 1.ToString()?.ToString(); } }"; var comp = CompileAndVerify(source, expectedOutput: ""); comp.VerifyIL("C.Main", @" { // Code size 32 (0x20) .maxstack 2 .locals init (int V_0) IL_0000: ldstr ""qqq"" IL_0005: callvirt ""string object.ToString()"" IL_000a: pop IL_000b: ldc.i4.1 IL_000c: stloc.0 IL_000d: ldloca.s V_0 IL_000f: call ""string int.ToString()"" IL_0014: dup IL_0015: brtrue.s IL_0019 IL_0017: pop IL_0018: ret IL_0019: callvirt ""string object.ToString()"" IL_001e: pop IL_001f: ret } "); } [Fact] public void TestConditionalMemberAccessUsed() { var source = @" public class C { static void Main() { var dummy1 = ((string)null)?.ToString(); var dummy2 = ""qqq""?.ToString(); var dummy3 = 1.ToString()?.ToString(); dummy1 += dummy2 += dummy3; } }"; var comp = CompileAndVerify(source, expectedOutput: ""); comp.VerifyIL("C.Main", @" { // Code size 50 (0x32) .maxstack 3 .locals init (string V_0, //dummy2 string V_1, //dummy3 int V_2) IL_0000: ldnull IL_0001: ldstr ""qqq"" IL_0006: callvirt ""string object.ToString()"" IL_000b: stloc.0 IL_000c: ldc.i4.1 IL_000d: stloc.2 IL_000e: ldloca.s V_2 IL_0010: call ""string int.ToString()"" IL_0015: dup IL_0016: brtrue.s IL_001c IL_0018: pop IL_0019: ldnull IL_001a: br.s IL_0021 IL_001c: callvirt ""string object.ToString()"" IL_0021: stloc.1 IL_0022: ldloc.0 IL_0023: ldloc.1 IL_0024: call ""string string.Concat(string, string)"" IL_0029: dup IL_002a: stloc.0 IL_002b: call ""string string.Concat(string, string)"" IL_0030: pop IL_0031: ret } "); } [Fact] public void TestConditionalMemberAccessUnused1() { var source = @" public class C { static void Main() { var dummy1 = ((string)null)?.ToString().Length; var dummy2 = ""qqq""?.ToString().Length; var dummy3 = 1.ToString()?.ToString().Length; } }"; var comp = CompileAndVerify(source, expectedOutput: ""); comp.VerifyIL("C.Main", @" { // Code size 42 (0x2a) .maxstack 2 .locals init (int V_0) IL_0000: ldstr ""qqq"" IL_0005: callvirt ""string object.ToString()"" IL_000a: callvirt ""int string.Length.get"" IL_000f: pop IL_0010: ldc.i4.1 IL_0011: stloc.0 IL_0012: ldloca.s V_0 IL_0014: call ""string int.ToString()"" IL_0019: dup IL_001a: brtrue.s IL_001e IL_001c: pop IL_001d: ret IL_001e: callvirt ""string object.ToString()"" IL_0023: callvirt ""int string.Length.get"" IL_0028: pop IL_0029: ret } "); } [Fact] public void TestConditionalMemberAccessUsed1() { var source = @" public class C { static void Main() { var dummy1 = ((string)null)?.ToString().Length; System.Console.WriteLine(dummy1); var dummy2 = ""qqq""?.ToString().Length; System.Console.WriteLine(dummy2); var dummy3 = 1.ToString()?.ToString().Length; System.Console.WriteLine(dummy3); } }"; var comp = CompileAndVerify(source, expectedOutput: @"3 1"); comp.VerifyIL("C.Main", @" { // Code size 99 (0x63) .maxstack 2 .locals init (int? V_0, int V_1) IL_0000: ldloca.s V_0 IL_0002: initobj ""int?"" IL_0008: ldloc.0 IL_0009: box ""int?"" IL_000e: call ""void System.Console.WriteLine(object)"" IL_0013: ldstr ""qqq"" IL_0018: callvirt ""string object.ToString()"" IL_001d: callvirt ""int string.Length.get"" IL_0022: newobj ""int?..ctor(int)"" IL_0027: box ""int?"" IL_002c: call ""void System.Console.WriteLine(object)"" IL_0031: ldc.i4.1 IL_0032: stloc.1 IL_0033: ldloca.s V_1 IL_0035: call ""string int.ToString()"" IL_003a: dup IL_003b: brtrue.s IL_0049 IL_003d: pop IL_003e: ldloca.s V_0 IL_0040: initobj ""int?"" IL_0046: ldloc.0 IL_0047: br.s IL_0058 IL_0049: callvirt ""string object.ToString()"" IL_004e: callvirt ""int string.Length.get"" IL_0053: newobj ""int?..ctor(int)"" IL_0058: box ""int?"" IL_005d: call ""void System.Console.WriteLine(object)"" IL_0062: ret } "); } [Fact] public void TestConditionalMemberAccessUnused2() { var source = @" public class C { static void Main() { var dummy1 = ((string)null)?.ToString().NullableLength()?.ToString(); var dummy2 = ""qqq""?.ToString().NullableLength().ToString(); var dummy3 = 1.ToString()?.ToString().NullableLength()?.ToString(); } } public static class C1 { public static int? NullableLength(this string self) { return self.Length; } } "; var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: ""); comp.VerifyIL("C.Main", @" { // Code size 82 (0x52) .maxstack 2 .locals init (int? V_0, int V_1) IL_0000: ldstr ""qqq"" IL_0005: callvirt ""string object.ToString()"" IL_000a: call ""int? C1.NullableLength(string)"" IL_000f: stloc.0 IL_0010: ldloca.s V_0 IL_0012: constrained. ""int?"" IL_0018: callvirt ""string object.ToString()"" IL_001d: pop IL_001e: ldc.i4.1 IL_001f: stloc.1 IL_0020: ldloca.s V_1 IL_0022: call ""string int.ToString()"" IL_0027: dup IL_0028: brtrue.s IL_002c IL_002a: pop IL_002b: ret IL_002c: callvirt ""string object.ToString()"" IL_0031: call ""int? C1.NullableLength(string)"" IL_0036: stloc.0 IL_0037: ldloca.s V_0 IL_0039: dup IL_003a: call ""bool int?.HasValue.get"" IL_003f: brtrue.s IL_0043 IL_0041: pop IL_0042: ret IL_0043: call ""int int?.GetValueOrDefault()"" IL_0048: stloc.1 IL_0049: ldloca.s V_1 IL_004b: call ""string int.ToString()"" IL_0050: pop IL_0051: ret } "); } [Fact] public void TestConditionalMemberAccessUnused2a() { var source = @" public class C { static void Main() { var dummy1 = ((string)null)?.ToString()?.Length.ToString(); var dummy2 = ""qqq""?.ToString().Length.ToString(); var dummy3 = 1.ToString()?.ToString().Length.ToString(); } }"; var comp = CompileAndVerify(source, expectedOutput: ""); comp.VerifyIL("C.Main", @" { // Code size 58 (0x3a) .maxstack 2 .locals init (int V_0) IL_0000: ldstr ""qqq"" IL_0005: callvirt ""string object.ToString()"" IL_000a: callvirt ""int string.Length.get"" IL_000f: stloc.0 IL_0010: ldloca.s V_0 IL_0012: call ""string int.ToString()"" IL_0017: pop IL_0018: ldc.i4.1 IL_0019: stloc.0 IL_001a: ldloca.s V_0 IL_001c: call ""string int.ToString()"" IL_0021: dup IL_0022: brtrue.s IL_0026 IL_0024: pop IL_0025: ret IL_0026: callvirt ""string object.ToString()"" IL_002b: callvirt ""int string.Length.get"" IL_0030: stloc.0 IL_0031: ldloca.s V_0 IL_0033: call ""string int.ToString()"" IL_0038: pop IL_0039: ret } "); } [Fact] public void TestConditionalMemberAccessUsed2() { var source = @" public class C { static void Main() { var dummy1 = ((string)null)?.ToString().NullableLength()?.ToString(); System.Console.WriteLine(dummy1); var dummy2 = ""qqq""?.ToString().NullableLength()?.ToString(); System.Console.WriteLine(dummy2); var dummy3 = 1.ToString()?.ToString().NullableLength()?.ToString(); System.Console.WriteLine(dummy3); } } public static class C1 { public static int? NullableLength(this string self) { return self.Length; } }"; var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: @"3 1"); comp.VerifyIL("C.Main", @" { // Code size 114 (0x72) .maxstack 2 .locals init (int? V_0, int V_1) IL_0000: ldnull IL_0001: call ""void System.Console.WriteLine(string)"" IL_0006: ldstr ""qqq"" IL_000b: callvirt ""string object.ToString()"" IL_0010: call ""int? C1.NullableLength(string)"" IL_0015: stloc.0 IL_0016: ldloca.s V_0 IL_0018: dup IL_0019: call ""bool int?.HasValue.get"" IL_001e: brtrue.s IL_0024 IL_0020: pop IL_0021: ldnull IL_0022: br.s IL_0031 IL_0024: call ""int int?.GetValueOrDefault()"" IL_0029: stloc.1 IL_002a: ldloca.s V_1 IL_002c: call ""string int.ToString()"" IL_0031: call ""void System.Console.WriteLine(string)"" IL_0036: ldc.i4.1 IL_0037: stloc.1 IL_0038: ldloca.s V_1 IL_003a: call ""string int.ToString()"" IL_003f: dup IL_0040: brtrue.s IL_0046 IL_0042: pop IL_0043: ldnull IL_0044: br.s IL_006c IL_0046: callvirt ""string object.ToString()"" IL_004b: call ""int? C1.NullableLength(string)"" IL_0050: stloc.0 IL_0051: ldloca.s V_0 IL_0053: dup IL_0054: call ""bool int?.HasValue.get"" IL_0059: brtrue.s IL_005f IL_005b: pop IL_005c: ldnull IL_005d: br.s IL_006c IL_005f: call ""int int?.GetValueOrDefault()"" IL_0064: stloc.1 IL_0065: ldloca.s V_1 IL_0067: call ""string int.ToString()"" IL_006c: call ""void System.Console.WriteLine(string)"" IL_0071: ret } "); } [Fact] public void TestConditionalMemberAccessUsed2a() { var source = @" public class C { static void Main() { var dummy1 = ((string)null)?.ToString()?.Length.ToString(); System.Console.WriteLine(dummy1); var dummy2 = ""qqq""?.ToString()?.Length.ToString(); System.Console.WriteLine(dummy2); var dummy3 = 1.ToString()?.ToString()?.Length.ToString(); System.Console.WriteLine(dummy3); } }"; var comp = CompileAndVerify(source, expectedOutput: @"3 1"); comp.VerifyIL("C.Main", @" { // Code size 88 (0x58) .maxstack 2 .locals init (int V_0) IL_0000: ldnull IL_0001: call ""void System.Console.WriteLine(string)"" IL_0006: ldstr ""qqq"" IL_000b: callvirt ""string object.ToString()"" IL_0010: dup IL_0011: brtrue.s IL_0017 IL_0013: pop IL_0014: ldnull IL_0015: br.s IL_0024 IL_0017: call ""int string.Length.get"" IL_001c: stloc.0 IL_001d: ldloca.s V_0 IL_001f: call ""string int.ToString()"" IL_0024: call ""void System.Console.WriteLine(string)"" IL_0029: ldc.i4.1 IL_002a: stloc.0 IL_002b: ldloca.s V_0 IL_002d: call ""string int.ToString()"" IL_0032: dup IL_0033: brtrue.s IL_0039 IL_0035: pop IL_0036: ldnull IL_0037: br.s IL_0052 IL_0039: callvirt ""string object.ToString()"" IL_003e: dup IL_003f: brtrue.s IL_0045 IL_0041: pop IL_0042: ldnull IL_0043: br.s IL_0052 IL_0045: call ""int string.Length.get"" IL_004a: stloc.0 IL_004b: ldloca.s V_0 IL_004d: call ""string int.ToString()"" IL_0052: call ""void System.Console.WriteLine(string)"" IL_0057: ret } "); } [Fact] [WorkItem(976765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/976765")] public void ConditionalMemberAccessConstrained() { var source = @" class Program { static void M<T>(T x) where T: System.Exception { object s = x?.ToString(); System.Console.WriteLine(s); s = x?.GetType(); System.Console.WriteLine(s); } static void Main() { M(new System.Exception(""a"")); } } "; var comp = CompileAndVerify(source, expectedOutput: @"System.Exception: a System.Exception"); comp.VerifyIL("Program.M<T>", @" { // Code size 47 (0x2f) .maxstack 2 IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: dup IL_0007: brtrue.s IL_000d IL_0009: pop IL_000a: ldnull IL_000b: br.s IL_0012 IL_000d: callvirt ""string object.ToString()"" IL_0012: call ""void System.Console.WriteLine(object)"" IL_0017: ldarg.0 IL_0018: box ""T"" IL_001d: dup IL_001e: brtrue.s IL_0024 IL_0020: pop IL_0021: ldnull IL_0022: br.s IL_0029 IL_0024: callvirt ""System.Type System.Exception.GetType()"" IL_0029: call ""void System.Console.WriteLine(object)"" IL_002e: ret } "); } [Fact] [WorkItem(991400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991400")] public void ConditionalMemberAccessStatement() { var source = @" class Program { class C1 { public void Print0() { System.Console.WriteLine(""print0""); } public int Print1() { System.Console.WriteLine(""print1""); return 1; } public object Print2() { System.Console.WriteLine(""print2""); return 1; } } static void M(C1 x) { x?.Print0(); x?.Print1(); x?.Print2(); } static void Main() { M(null); M(new C1()); } } "; var comp = CompileAndVerify(source, expectedOutput: @"print0 print1 print2"); comp.VerifyIL("Program.M(Program.C1)", @" { // Code size 30 (0x1e) .maxstack 1 IL_0000: ldarg.0 IL_0001: brfalse.s IL_0009 IL_0003: ldarg.0 IL_0004: call ""void Program.C1.Print0()"" IL_0009: ldarg.0 IL_000a: brfalse.s IL_0013 IL_000c: ldarg.0 IL_000d: call ""int Program.C1.Print1()"" IL_0012: pop IL_0013: ldarg.0 IL_0014: brfalse.s IL_001d IL_0016: ldarg.0 IL_0017: call ""object Program.C1.Print2()"" IL_001c: pop IL_001d: ret } "); } [Fact] [WorkItem(991400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991400")] public void ConditionalMemberAccessStatement01() { var source = @" class Program { struct S1 { public void Print0() { System.Console.WriteLine(""print0""); } public int Print1() { System.Console.WriteLine(""print1""); return 1; } public object Print2() { System.Console.WriteLine(""print2""); return 1; } } static void M(S1? x) { x?.Print0(); x?.Print1(); x?.Print2()?.ToString().ToString()?.ToString(); } static void Main() { M(null); M(new S1()); } } "; var comp = CompileAndVerify(source, expectedOutput: @"print0 print1 print2"); comp.VerifyIL("Program.M(Program.S1?)", @" { // Code size 100 (0x64) .maxstack 2 .locals init (Program.S1 V_0) IL_0000: ldarga.s V_0 IL_0002: call ""bool Program.S1?.HasValue.get"" IL_0007: brfalse.s IL_0018 IL_0009: ldarga.s V_0 IL_000b: call ""Program.S1 Program.S1?.GetValueOrDefault()"" IL_0010: stloc.0 IL_0011: ldloca.s V_0 IL_0013: call ""void Program.S1.Print0()"" IL_0018: ldarga.s V_0 IL_001a: call ""bool Program.S1?.HasValue.get"" IL_001f: brfalse.s IL_0031 IL_0021: ldarga.s V_0 IL_0023: call ""Program.S1 Program.S1?.GetValueOrDefault()"" IL_0028: stloc.0 IL_0029: ldloca.s V_0 IL_002b: call ""int Program.S1.Print1()"" IL_0030: pop IL_0031: ldarga.s V_0 IL_0033: call ""bool Program.S1?.HasValue.get"" IL_0038: brfalse.s IL_0063 IL_003a: ldarga.s V_0 IL_003c: call ""Program.S1 Program.S1?.GetValueOrDefault()"" IL_0041: stloc.0 IL_0042: ldloca.s V_0 IL_0044: call ""object Program.S1.Print2()"" IL_0049: dup IL_004a: brtrue.s IL_004e IL_004c: pop IL_004d: ret IL_004e: callvirt ""string object.ToString()"" IL_0053: callvirt ""string object.ToString()"" IL_0058: dup IL_0059: brtrue.s IL_005d IL_005b: pop IL_005c: ret IL_005d: callvirt ""string object.ToString()"" IL_0062: pop IL_0063: ret } "); } [ConditionalFact(typeof(DesktopOnly))] [WorkItem(991400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991400")] public void ConditionalMemberAccessStatement02() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class Program { class C1 { public void Print0(int i) { System.Console.WriteLine(""print0""); } public int Print1(int i) { System.Console.WriteLine(""print1""); return 1; } public object Print2(int i) { System.Console.WriteLine(""print2""); return 1; } } static async Task<int> Val() { await Task.Yield(); return 1; } static async Task<int> M(C1 x) { x?.Print0(await Val()); x?.Print1(await Val()); x?.Print2(await Val()); return 1; } static void Main() { M(null).Wait(); M(new C1()).Wait(); } } "; var comp = CompileAndVerify(source, targetFramework: TargetFramework.Empty, references: new[] { MscorlibRef_v4_0_30316_17626 }, expectedOutput: @"print0 print1 print2"); } [ConditionalFact(typeof(DesktopOnly))] [WorkItem(991400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991400")] public void ConditionalMemberAccessStatement03() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class Program { struct C1 { public void Print0(int i) { System.Console.WriteLine(""print0""); } public int Print1(int i) { System.Console.WriteLine(""print1""); return 1; } public object Print2(int i) { System.Console.WriteLine(""print2""); return 1; } } static async Task<int> Val() { await Task.Yield(); return 1; } static async Task<int> M(C1? x) { x?.Print0(await Val()); x?.Print1(await Val()); x?.Print2(await Val()); return 1; } static void Main() { M(null).Wait(); M(new C1()).Wait(); } } "; var comp = CompileAndVerify(source, targetFramework: TargetFramework.Empty, references: new[] { MscorlibRef_v4_0_30316_17626 }, expectedOutput: @"print0 print1 print2"); } [Fact] public void ConditionalMemberAccessUnConstrained() { var source = @" using System; using System.Collections.Generic; class Program { class C1 : IDisposable { private bool disposed; public void Dispose() { System.Console.WriteLine(disposed); disposed = true; } } struct S1 : IDisposable { private bool disposed; public void Dispose() { System.Console.WriteLine(disposed); disposed = true; } } static void Main(string[] args) { C1 c = new C1(); Test(ref c, ref c); S1 s = new S1(); Test(ref s, ref s); } static void Test<T>(ref T x, ref T y) where T : IDisposable { x?.Dispose(); y?.Dispose(); } } "; var comp = CompileAndVerify(source, expectedOutput: @"False True False True"); comp.VerifyIL("Program.Test<T>(ref T, ref T)", @" { // Code size 94 (0x5e) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: initobj ""T"" IL_0009: ldloc.0 IL_000a: box ""T"" IL_000f: brtrue.s IL_0024 IL_0011: ldobj ""T"" IL_0016: stloc.0 IL_0017: ldloca.s V_0 IL_0019: ldloc.0 IL_001a: box ""T"" IL_001f: brtrue.s IL_0024 IL_0021: pop IL_0022: br.s IL_002f IL_0024: constrained. ""T"" IL_002a: callvirt ""void System.IDisposable.Dispose()"" IL_002f: ldarg.1 IL_0030: ldloca.s V_0 IL_0032: initobj ""T"" IL_0038: ldloc.0 IL_0039: box ""T"" IL_003e: brtrue.s IL_0052 IL_0040: ldobj ""T"" IL_0045: stloc.0 IL_0046: ldloca.s V_0 IL_0048: ldloc.0 IL_0049: box ""T"" IL_004e: brtrue.s IL_0052 IL_0050: pop IL_0051: ret IL_0052: constrained. ""T"" IL_0058: callvirt ""void System.IDisposable.Dispose()"" IL_005d: ret }"); } [Fact] public void ConditionalMemberAccessUnConstrained1() { var source = @" using System; using System.Collections.Generic; class Program { class C1 : IDisposable { private bool disposed; public void Dispose() { System.Console.WriteLine(disposed); disposed = true; } } struct S1 : IDisposable { private bool disposed; public void Dispose() { System.Console.WriteLine(disposed); disposed = true; } } static void Main(string[] args) { var c = new C1[] {new C1()}; Test(c, c); var s = new S1[] {new S1()}; Test(s, s); } static void Test<T>(T[] x, T[] y) where T : IDisposable { x[0]?.Dispose(); y[0]?.Dispose(); } } "; var comp = CompileAndVerify(source, expectedOutput: @"False True False True"); comp.VerifyIL("Program.Test<T>(T[], T[])", @" { // Code size 110 (0x6e) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: readonly. IL_0004: ldelema ""T"" IL_0009: ldloca.s V_0 IL_000b: initobj ""T"" IL_0011: ldloc.0 IL_0012: box ""T"" IL_0017: brtrue.s IL_002c IL_0019: ldobj ""T"" IL_001e: stloc.0 IL_001f: ldloca.s V_0 IL_0021: ldloc.0 IL_0022: box ""T"" IL_0027: brtrue.s IL_002c IL_0029: pop IL_002a: br.s IL_0037 IL_002c: constrained. ""T"" IL_0032: callvirt ""void System.IDisposable.Dispose()"" IL_0037: ldarg.1 IL_0038: ldc.i4.0 IL_0039: readonly. IL_003b: ldelema ""T"" IL_0040: ldloca.s V_0 IL_0042: initobj ""T"" IL_0048: ldloc.0 IL_0049: box ""T"" IL_004e: brtrue.s IL_0062 IL_0050: ldobj ""T"" IL_0055: stloc.0 IL_0056: ldloca.s V_0 IL_0058: ldloc.0 IL_0059: box ""T"" IL_005e: brtrue.s IL_0062 IL_0060: pop IL_0061: ret IL_0062: constrained. ""T"" IL_0068: callvirt ""void System.IDisposable.Dispose()"" IL_006d: ret } "); } [Fact] public void ConditionalMemberAccessConstrained1() { var source = @" using System; using System.Collections.Generic; class Program { class C1 : IDisposable { private bool disposed; public void Dispose() { System.Console.WriteLine(disposed); disposed = true; } } struct S1 : IDisposable { private bool disposed; public void Dispose() { System.Console.WriteLine(disposed); disposed = true; } } static void Main(string[] args) { var c = new C1[] {new C1()}; Test(c, c); } static void Test<T>(T[] x, T[] y) where T : class, IDisposable { x[0]?.Dispose(); y[0]?.Dispose(); } } "; var comp = CompileAndVerify(source, expectedOutput: @"False True "); comp.VerifyIL("Program.Test<T>(T[], T[])", @" { // Code size 46 (0x2e) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldelem ""T"" IL_0007: box ""T"" IL_000c: dup IL_000d: brtrue.s IL_0012 IL_000f: pop IL_0010: br.s IL_0017 IL_0012: callvirt ""void System.IDisposable.Dispose()"" IL_0017: ldarg.1 IL_0018: ldc.i4.0 IL_0019: ldelem ""T"" IL_001e: box ""T"" IL_0023: dup IL_0024: brtrue.s IL_0028 IL_0026: pop IL_0027: ret IL_0028: callvirt ""void System.IDisposable.Dispose()"" IL_002d: ret } "); } [Fact] public void ConditionalMemberAccessUnConstrainedVal() { var source = @" using System; using System.Collections.Generic; class Program { class C1 : IDisposable { private bool disposed; public void Dispose() { System.Console.WriteLine(disposed); disposed = true; } } struct S1 : IDisposable { private bool disposed; public void Dispose() { System.Console.WriteLine(disposed); disposed = true; } } static void Main(string[] args) { C1 c = new C1(); Test(c); S1 s = new S1(); Test(s); } static void Test<T>(T x) where T : IDisposable { x?.Dispose(); x?.Dispose(); } } "; var comp = CompileAndVerify(source, expectedOutput: @"False True False True"); comp.VerifyIL("Program.Test<T>(T)", @" { // Code size 43 (0x2b) .maxstack 1 IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: brfalse.s IL_0015 IL_0008: ldarga.s V_0 IL_000a: constrained. ""T"" IL_0010: callvirt ""void System.IDisposable.Dispose()"" IL_0015: ldarg.0 IL_0016: box ""T"" IL_001b: brfalse.s IL_002a IL_001d: ldarga.s V_0 IL_001f: constrained. ""T"" IL_0025: callvirt ""void System.IDisposable.Dispose()"" IL_002a: ret } "); } [Fact] public void ConditionalMemberAccessUnConstrainedVal001() { var source = @" using System; using System.Collections.Generic; class Program { class C1 : IDisposable { private bool disposed; public void Dispose() { System.Console.WriteLine(disposed); disposed = true; } } struct S1 : IDisposable { private bool disposed; public void Dispose() { System.Console.WriteLine(disposed); disposed = true; } } static void Main(string[] args) { C1 c = new C1(); Test(() => c); S1 s = new S1(); Test(() => s); } static void Test<T>(Func<T> x) where T : IDisposable { x()?.Dispose(); x()?.Dispose(); } } "; var comp = CompileAndVerify(source, expectedOutput: @"False True False False"); comp.VerifyIL("Program.Test<T>(System.Func<T>)", @" { // Code size 72 (0x48) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: callvirt ""T System.Func<T>.Invoke()"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: dup IL_000a: ldobj ""T"" IL_000f: box ""T"" IL_0014: brtrue.s IL_0019 IL_0016: pop IL_0017: br.s IL_0024 IL_0019: constrained. ""T"" IL_001f: callvirt ""void System.IDisposable.Dispose()"" IL_0024: ldarg.0 IL_0025: callvirt ""T System.Func<T>.Invoke()"" IL_002a: stloc.0 IL_002b: ldloca.s V_0 IL_002d: dup IL_002e: ldobj ""T"" IL_0033: box ""T"" IL_0038: brtrue.s IL_003c IL_003a: pop IL_003b: ret IL_003c: constrained. ""T"" IL_0042: callvirt ""void System.IDisposable.Dispose()"" IL_0047: ret } "); } [Fact] public void ConditionalMemberAccessConstrainedVal001() { var source = @" using System; using System.Collections.Generic; class Program { class C1 : IDisposable { private bool disposed; public void Dispose() { System.Console.WriteLine(disposed); disposed = true; } } struct S1 : IDisposable { private bool disposed; public void Dispose() { System.Console.WriteLine(disposed); disposed = true; } } static void Main(string[] args) { C1 c = new C1(); Test(() => c); } static void Test<T>(Func<T> x) where T : class, IDisposable { x()?.Dispose(); x()?.Dispose(); } } "; var comp = CompileAndVerify(source, expectedOutput: @"False True"); comp.VerifyIL("Program.Test<T>(System.Func<T>)", @" { // Code size 44 (0x2c) .maxstack 2 IL_0000: ldarg.0 IL_0001: callvirt ""T System.Func<T>.Invoke()"" IL_0006: box ""T"" IL_000b: dup IL_000c: brtrue.s IL_0011 IL_000e: pop IL_000f: br.s IL_0016 IL_0011: callvirt ""void System.IDisposable.Dispose()"" IL_0016: ldarg.0 IL_0017: callvirt ""T System.Func<T>.Invoke()"" IL_001c: box ""T"" IL_0021: dup IL_0022: brtrue.s IL_0026 IL_0024: pop IL_0025: ret IL_0026: callvirt ""void System.IDisposable.Dispose()"" IL_002b: ret } "); } [Fact] public void ConditionalMemberAccessUnConstrainedDyn() { var source = @" using System; using System.Collections.Generic; class Program { interface IDisposable1 { void Dispose(int i); } class C1 : IDisposable1 { private bool disposed; public void Dispose(int i) { System.Console.WriteLine(disposed); disposed = true; } } struct S1 : IDisposable1 { private bool disposed; public void Dispose(int i) { System.Console.WriteLine(disposed); disposed = true; } } static void Main(string[] args) { C1 c = new C1(); Test(ref c, ref c); S1 s = new S1(); Test(ref s, ref s); } static void Test<T>(ref T x, ref T y) where T : IDisposable1 { dynamic d = 1; x?.Dispose(d); y?.Dispose(d); } } "; var comp = CompileAndVerify(source, references: new MetadataReference[] { CSharpRef }, expectedOutput: @"False True False False"); } [Fact] public void ConditionalMemberAccessUnConstrainedDynVal() { var source = @" using System; using System.Collections.Generic; class Program { interface IDisposable1 { void Dispose(int i); } class C1 : IDisposable1 { private bool disposed; public void Dispose(int i) { System.Console.WriteLine(disposed); disposed = true; } } struct S1 : IDisposable1 { private bool disposed; public void Dispose(int i) { System.Console.WriteLine(disposed); disposed = true; } } static void Main(string[] args) { C1 c = new C1(); Test(c, c); S1 s = new S1(); Test(s, s); } static void Test<T>(T x, T y) where T : IDisposable1 { dynamic d = 1; x?.Dispose(d); y?.Dispose(d); } } "; var comp = CompileAndVerify(source, references: new MetadataReference[] { CSharpRef }, expectedOutput: @"False True False False"); } [Fact] public void ConditionalMemberAccessUnConstrainedAsync() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class Program { interface IDisposable1 { void Dispose(int i); } class C1 : IDisposable1 { private bool disposed; public void Dispose(int i) { System.Console.WriteLine(disposed); disposed = true; } } struct S1 : IDisposable1 { private bool disposed; public void Dispose(int i) { System.Console.WriteLine(disposed); disposed = true; } } static void Main(string[] args) { C1[] c = new C1[] { new C1() }; Test(c, c).Wait(); S1[] s = new S1[] { new S1() }; Test(s, s).Wait(); } static async Task<int> Val() { await Task.Yield(); return 0; } static async Task<int> Test<T>(T[] x, T[] y) where T : IDisposable1 { x[0]?.Dispose(await Val()); y[0]?.Dispose(await Val()); return 1; } }"; var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe); var comp = CompileAndVerify(c, expectedOutput: @"False True False True"); } [Fact] public void ConditionalMemberAccessUnConstrainedAsyncVal() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class Program { interface IDisposable1 { int Dispose(int i); } class C1 : IDisposable1 { private bool disposed; public int Dispose(int i) { System.Console.WriteLine(disposed); disposed = true; return 1; } } struct S1 : IDisposable1 { private bool disposed; public int Dispose(int i) { System.Console.WriteLine(disposed); disposed = true; return 1; } } static void Main(string[] args) { C1 c = new C1(); Test(c, c).Wait(); S1 s = new S1(); Test(s, s).Wait(); } static async Task<int> Val() { await Task.Yield(); return 0; } static async Task<int> Test<T>(T x, T y) where T : IDisposable1 { x?.Dispose(await Val()); y?.Dispose(await Val()); return 1; } } "; var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe); var comp = CompileAndVerify(c, expectedOutput: @"False True False False"); } [Fact] public void ConditionalMemberAccessUnConstrainedAsyncValExt() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; using DE; namespace DE { public static class IDispExt { public static void DisposeExt(this Program.IDisposable1 d, int i) { d.Dispose(i); } } } public class Program { public interface IDisposable1 { int Dispose(int i); } class C1 : IDisposable1 { private bool disposed; public int Dispose(int i) { System.Console.WriteLine(disposed); disposed = true; return 1; } } struct S1 : IDisposable1 { private bool disposed; public int Dispose(int i) { System.Console.WriteLine(disposed); disposed = true; return 1; } } static void Main(string[] args) { C1 c = new C1(); Test(c, c).Wait(); S1 s = new S1(); Test(s, s).Wait(); } static async Task<int> Val() { await Task.Yield(); return 0; } static async Task<int> Test<T>(T x, T y) where T : IDisposable1 { x?.DisposeExt(await Val()); y?.DisposeExt(await Val()); return 1; } } "; var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe); var comp = CompileAndVerify(c, expectedOutput: @"False True False False"); } [Fact] public void ConditionalMemberAccessUnConstrainedAsyncNested() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class Program { interface IDisposable1 { IDisposable1 Dispose(int i); } class C1 : IDisposable1 { private bool disposed; public IDisposable1 Dispose(int i) { System.Console.WriteLine(disposed); disposed ^= true; return this; } } struct S1 : IDisposable1 { private bool disposed; public IDisposable1 Dispose(int i) { System.Console.WriteLine(disposed); disposed ^= true; return this; } } static void Main(string[] args) { C1[] c = new C1[] { new C1() }; Test(c, c).Wait(); System.Console.WriteLine(); S1[] s = new S1[] { new S1() }; Test(s, s).Wait(); } static async Task<int> Val() { await Task.Yield(); return 0; } static async Task<int> Test<T>(T[] x, T[] y) where T : IDisposable1 { x[0]?.Dispose(await Val())?.Dispose(await Val())?.Dispose(await Val())?.Dispose(await Val()); y[0]?.Dispose(await Val())?.Dispose(await Val())?.Dispose(await Val())?.Dispose(await Val()); return 1; } }"; var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe); var comp = CompileAndVerify(c, expectedOutput: @"False True False True False True False True False True False True True False True False"); } [Fact] public void ConditionalMemberAccessUnConstrainedAsyncNestedArr() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class Program { interface IDisposable1 { IDisposable1[] Dispose(int i); } class C1 : IDisposable1 { private bool disposed; public IDisposable1[] Dispose(int i) { System.Console.WriteLine(disposed); disposed ^= true; return new IDisposable1[] { this }; } } struct S1 : IDisposable1 { private bool disposed; public IDisposable1[] Dispose(int i) { System.Console.WriteLine(disposed); disposed ^= true; return new IDisposable1[]{this}; } } static void Main(string[] args) { C1[] c = new C1[] { new C1() }; Test(c, c).Wait(); System.Console.WriteLine(); S1[] s = new S1[] { new S1() }; Test(s, s).Wait(); } static async Task<int> Val() { await Task.Yield(); return 0; } static async Task<int> Test<T>(T[] x, T[] y) where T : IDisposable1 { x[0]?.Dispose(await Val())[0]?.Dispose(await Val())[0]?.Dispose(await Val())[0]?.Dispose(await Val()); y[0]?.Dispose(await Val())[0]?.Dispose(await Val())[0]?.Dispose(await Val())[0]?.Dispose(await Val()); return 1; } }"; var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe); var comp = CompileAndVerify(c, expectedOutput: @"False True False True False True False True False True False True True False True False"); } [Fact] public void ConditionalMemberAccessUnConstrainedAsyncSuperNested() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class Program { interface IDisposable1 { Task<int> Dispose(int i); } class C1 : IDisposable1 { private bool disposed; public Task<int> Dispose(int i) { System.Console.WriteLine(disposed); disposed ^= true; return Task.FromResult(i); } } struct S1 : IDisposable1 { private bool disposed; public Task<int> Dispose(int i) { System.Console.WriteLine(disposed); disposed ^= true; return Task.FromResult(i); } } static void Main(string[] args) { C1[] c = new C1[] { new C1() }; Test(c, c).Wait(); System.Console.WriteLine(); S1[] s = new S1[] { new S1() }; Test(s, s).Wait(); } static async Task<int> Val() { await Task.Yield(); return 0; } static async Task<int> Test<T>(T[] x, T[] y) where T : IDisposable1 { x[0]?.Dispose(await x[0]?.Dispose(await x[0]?.Dispose(await x[0]?.Dispose(await Val())))); y[0]?.Dispose(await y[0]?.Dispose(await y[0]?.Dispose(await y[0]?.Dispose(await Val())))); return 1; } }"; var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe); var comp = CompileAndVerify(c, expectedOutput: @"False True False True False True False True False True False True False True False True"); } [Fact] public void ConditionalExtensionAccessGeneric001() { var source = @" using System; using System.Collections.Generic; class Test { static void Main() { long? x = 1; Test0(x); return; } static void Test0<T>(T x) { x?.CheckT(); } } static class Ext { public static void CheckT<T>(this T x) { System.Console.WriteLine(typeof(T)); return; } } "; var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: @"System.Nullable`1[System.Int64]"); comp.VerifyIL("Test.Test0<T>(T)", @" { // Code size 21 (0x15) .maxstack 1 IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: brfalse.s IL_0014 IL_0008: ldarga.s V_0 IL_000a: ldobj ""T"" IL_000f: call ""void Ext.CheckT<T>(T)"" IL_0014: ret } "); } [Fact] public void ConditionalExtensionAccessGeneric002() { var source = @" using System; using System.Collections.Generic; class Test { static void Main() { long? x = 1; Test0(ref x); return; } static void Test0<T>(ref T x) { x?.CheckT(); } } static class Ext { public static void CheckT<T>(this T x) { System.Console.WriteLine(typeof(T)); return; } } "; var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: @"System.Nullable`1[System.Int64]"); comp.VerifyIL("Test.Test0<T>(ref T)", @" { // Code size 46 (0x2e) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: initobj ""T"" IL_0009: ldloc.0 IL_000a: box ""T"" IL_000f: brtrue.s IL_0023 IL_0011: ldobj ""T"" IL_0016: stloc.0 IL_0017: ldloca.s V_0 IL_0019: ldloc.0 IL_001a: box ""T"" IL_001f: brtrue.s IL_0023 IL_0021: pop IL_0022: ret IL_0023: ldobj ""T"" IL_0028: call ""void Ext.CheckT<T>(T)"" IL_002d: ret } "); } [Fact] public void ConditionalExtensionAccessGeneric003() { var source = @" using System; using System.Linq; using System.Collections.Generic; class Test { static void Main() { Test0(""qqq""); } static void Test0<T>(T x) where T:IEnumerable<char> { x?.Count(); } static void Test1<T>(ref T x) where T:IEnumerable<char> { x?.Count(); } } "; var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: @""); comp.VerifyIL("Test.Test0<T>(T)", @" { // Code size 27 (0x1b) .maxstack 1 IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: brfalse.s IL_001a IL_0008: ldarga.s V_0 IL_000a: ldobj ""T"" IL_000f: box ""T"" IL_0014: call ""int System.Linq.Enumerable.Count<char>(System.Collections.Generic.IEnumerable<char>)"" IL_0019: pop IL_001a: ret } ").VerifyIL("Test.Test1<T>(ref T)", @" { // Code size 52 (0x34) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: initobj ""T"" IL_0009: ldloc.0 IL_000a: box ""T"" IL_000f: brtrue.s IL_0023 IL_0011: ldobj ""T"" IL_0016: stloc.0 IL_0017: ldloca.s V_0 IL_0019: ldloc.0 IL_001a: box ""T"" IL_001f: brtrue.s IL_0023 IL_0021: pop IL_0022: ret IL_0023: ldobj ""T"" IL_0028: box ""T"" IL_002d: call ""int System.Linq.Enumerable.Count<char>(System.Collections.Generic.IEnumerable<char>)"" IL_0032: pop IL_0033: ret } "); } [Fact] public void ConditionalExtensionAccessGenericAsync001() { var source = @" using System.Threading.Tasks; class Test { static void Main() { } async Task<int?> TestAsync<T>(T[] x) where T : I1 { return x[0]?.CallAsync(await PassAsync()); } static async Task<int> PassAsync() { await Task.Yield(); return 1; } } interface I1 { int CallAsync(int x); } "; var comp = CreateCompilationWithMscorlib45(source, references: new[] { CSharpRef }); base.CompileAndVerify(comp); } [Fact] public void ConditionalExtensionAccessGenericAsyncNullable001() { var source = @" using System; using System.Threading.Tasks; class Test { static void Main() { var arr = new S1?[] { new S1(), new S1()}; TestAsync(arr).Wait(); System.Console.WriteLine(arr[1].Value.called); } static async Task<int?> TestAsync<T>(T?[] x) where T : struct, I1 { return x[await PassAsync()]?.CallAsync(await PassAsync()); } static async Task<int> PassAsync() { await Task.Yield(); return 1; } } struct S1 : I1 { public int called; public int CallAsync(int x) { called++; System.Console.Write(called + 41); return called; } } interface I1 { int CallAsync(int x); } "; var comp = CreateCompilationWithMscorlib45(source, references: new[] { CSharpRef }, options: TestOptions.ReleaseExe); base.CompileAndVerify(comp, expectedOutput: "420"); } [Fact] public void ConditionalMemberAccessCoalesce001() { var source = @" class Program { class C1 { public int x{get; set;} public int? y{get; set;} } static void Main() { var c = new C1(); System.Console.WriteLine(Test1(c)); System.Console.WriteLine(Test1(null)); System.Console.WriteLine(Test2(c)); System.Console.WriteLine(Test2(null)); } static int Test1(C1 c) { return c?.x ?? 42; } static int Test2(C1 c) { return c?.y ?? 42; } } "; var comp = CompileAndVerify(source, expectedOutput: @"0 42 42 42"); comp.VerifyIL("Program.Test1(Program.C1)", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0006 IL_0003: ldc.i4.s 42 IL_0005: ret IL_0006: ldarg.0 IL_0007: call ""int Program.C1.x.get"" IL_000c: ret } ").VerifyIL("Program.Test2(Program.C1)", @" { // Code size 41 (0x29) .maxstack 1 .locals init (int? V_0, int? V_1) IL_0000: ldarg.0 IL_0001: brtrue.s IL_000e IL_0003: ldloca.s V_1 IL_0005: initobj ""int?"" IL_000b: ldloc.1 IL_000c: br.s IL_0014 IL_000e: ldarg.0 IL_000f: call ""int? Program.C1.y.get"" IL_0014: stloc.0 IL_0015: ldloca.s V_0 IL_0017: call ""bool int?.HasValue.get"" IL_001c: brtrue.s IL_0021 IL_001e: ldc.i4.s 42 IL_0020: ret IL_0021: ldloca.s V_0 IL_0023: call ""int int?.GetValueOrDefault()"" IL_0028: ret } "); } [Fact] public void ConditionalMemberAccessCoalesce001n() { var source = @" class Program { class C1 { public int x{get; set;} public int? y{get; set;} } static void Main() { var c = new C1(); System.Console.WriteLine(Test1(c)); System.Console.WriteLine(Test1(null)); System.Console.WriteLine(Test2(c)); System.Console.WriteLine(Test2(null)); } static int? Test1(C1 c) { return c?.x ?? (int?)42; } static int? Test2(C1 c) { return c?.y ?? (int?)42; } } "; var comp = CompileAndVerify(source, expectedOutput: @"0 42 42 42"); comp.VerifyIL("Program.Test1(Program.C1)", @" { // Code size 23 (0x17) .maxstack 1 IL_0000: ldarg.0 IL_0001: brtrue.s IL_000b IL_0003: ldc.i4.s 42 IL_0005: newobj ""int?..ctor(int)"" IL_000a: ret IL_000b: ldarg.0 IL_000c: call ""int Program.C1.x.get"" IL_0011: newobj ""int?..ctor(int)"" IL_0016: ret } ").VerifyIL("Program.Test2(Program.C1)", @" { // Code size 40 (0x28) .maxstack 1 .locals init (int? V_0, int? V_1) IL_0000: ldarg.0 IL_0001: brtrue.s IL_000e IL_0003: ldloca.s V_1 IL_0005: initobj ""int?"" IL_000b: ldloc.1 IL_000c: br.s IL_0014 IL_000e: ldarg.0 IL_000f: call ""int? Program.C1.y.get"" IL_0014: stloc.0 IL_0015: ldloca.s V_0 IL_0017: call ""bool int?.HasValue.get"" IL_001c: brtrue.s IL_0026 IL_001e: ldc.i4.s 42 IL_0020: newobj ""int?..ctor(int)"" IL_0025: ret IL_0026: ldloc.0 IL_0027: ret }"); } [Fact] public void ConditionalMemberAccessCoalesce001r() { var source = @" class Program { class C1 { public int x {get; set;} public int? y {get; set;} } static void Main() { var c = new C1(); C1 n = null; System.Console.WriteLine(Test1(ref c)); System.Console.WriteLine(Test1(ref n)); System.Console.WriteLine(Test2(ref c)); System.Console.WriteLine(Test2(ref n)); } static int Test1(ref C1 c) { return c?.x ?? 42; } static int Test2(ref C1 c) { return c?.y ?? 42; } } "; var comp = CompileAndVerify(source, expectedOutput: @"0 42 42 42"); comp.VerifyIL("Program.Test1(ref Program.C1)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldind.ref IL_0002: dup IL_0003: brtrue.s IL_0009 IL_0005: pop IL_0006: ldc.i4.s 42 IL_0008: ret IL_0009: call ""int Program.C1.x.get"" IL_000e: ret } ").VerifyIL("Program.Test2(ref Program.C1)", @" { // Code size 43 (0x2b) .maxstack 2 .locals init (int? V_0, int? V_1) IL_0000: ldarg.0 IL_0001: ldind.ref IL_0002: dup IL_0003: brtrue.s IL_0011 IL_0005: pop IL_0006: ldloca.s V_1 IL_0008: initobj ""int?"" IL_000e: ldloc.1 IL_000f: br.s IL_0016 IL_0011: call ""int? Program.C1.y.get"" IL_0016: stloc.0 IL_0017: ldloca.s V_0 IL_0019: call ""bool int?.HasValue.get"" IL_001e: brtrue.s IL_0023 IL_0020: ldc.i4.s 42 IL_0022: ret IL_0023: ldloca.s V_0 IL_0025: call ""int int?.GetValueOrDefault()"" IL_002a: ret } "); } [Fact] public void ConditionalMemberAccessCoalesce002() { var source = @" class Program { struct C1 { public int x{get; set;} public int? y{get; set;} } static void Main() { var c = new C1(); System.Console.WriteLine(Test1(c)); System.Console.WriteLine(Test1(null)); System.Console.WriteLine(Test2(c)); System.Console.WriteLine(Test2(null)); } static int Test1(C1? c) { return c?.x ?? 42; } static int Test2(C1? c) { return c?.y ?? 42; } } "; var comp = CompileAndVerify(source, expectedOutput: @"0 42 42 42"); comp.VerifyIL("Program.Test1(Program.C1?)", @" { // Code size 28 (0x1c) .maxstack 1 .locals init (Program.C1 V_0) IL_0000: ldarga.s V_0 IL_0002: call ""bool Program.C1?.HasValue.get"" IL_0007: brtrue.s IL_000c IL_0009: ldc.i4.s 42 IL_000b: ret IL_000c: ldarga.s V_0 IL_000e: call ""Program.C1 Program.C1?.GetValueOrDefault()"" IL_0013: stloc.0 IL_0014: ldloca.s V_0 IL_0016: call ""readonly int Program.C1.x.get"" IL_001b: ret } ").VerifyIL("Program.Test2(Program.C1?)", @" { // Code size 56 (0x38) .maxstack 1 .locals init (int? V_0, int? V_1, Program.C1 V_2) IL_0000: ldarga.s V_0 IL_0002: call ""bool Program.C1?.HasValue.get"" IL_0007: brtrue.s IL_0014 IL_0009: ldloca.s V_1 IL_000b: initobj ""int?"" IL_0011: ldloc.1 IL_0012: br.s IL_0023 IL_0014: ldarga.s V_0 IL_0016: call ""Program.C1 Program.C1?.GetValueOrDefault()"" IL_001b: stloc.2 IL_001c: ldloca.s V_2 IL_001e: call ""readonly int? Program.C1.y.get"" IL_0023: stloc.0 IL_0024: ldloca.s V_0 IL_0026: call ""bool int?.HasValue.get"" IL_002b: brtrue.s IL_0030 IL_002d: ldc.i4.s 42 IL_002f: ret IL_0030: ldloca.s V_0 IL_0032: call ""int int?.GetValueOrDefault()"" IL_0037: ret } "); } [Fact] public void ConditionalMemberAccessCoalesce002r() { var source = @" class Program { struct C1 { public int x{get; set;} public int? y{get; set;} } static void Main() { C1? c = new C1(); C1? n = null; System.Console.WriteLine(Test1(ref c)); System.Console.WriteLine(Test1(ref n)); System.Console.WriteLine(Test2(ref c)); System.Console.WriteLine(Test2(ref n)); } static int Test1(ref C1? c) { return c?.x ?? 42; } static int Test2(ref C1? c) { return c?.y ?? 42; } } "; var comp = CompileAndVerify(source, expectedOutput: @"0 42 42 42"); comp.VerifyIL("Program.Test1(ref Program.C1?)", @" { // Code size 27 (0x1b) .maxstack 2 .locals init (Program.C1 V_0) IL_0000: ldarg.0 IL_0001: dup IL_0002: call ""bool Program.C1?.HasValue.get"" IL_0007: brtrue.s IL_000d IL_0009: pop IL_000a: ldc.i4.s 42 IL_000c: ret IL_000d: call ""Program.C1 Program.C1?.GetValueOrDefault()"" IL_0012: stloc.0 IL_0013: ldloca.s V_0 IL_0015: call ""readonly int Program.C1.x.get"" IL_001a: ret } ").VerifyIL("Program.Test2(ref Program.C1?)", @" { // Code size 55 (0x37) .maxstack 2 .locals init (int? V_0, int? V_1, Program.C1 V_2) IL_0000: ldarg.0 IL_0001: dup IL_0002: call ""bool Program.C1?.HasValue.get"" IL_0007: brtrue.s IL_0015 IL_0009: pop IL_000a: ldloca.s V_1 IL_000c: initobj ""int?"" IL_0012: ldloc.1 IL_0013: br.s IL_0022 IL_0015: call ""Program.C1 Program.C1?.GetValueOrDefault()"" IL_001a: stloc.2 IL_001b: ldloca.s V_2 IL_001d: call ""readonly int? Program.C1.y.get"" IL_0022: stloc.0 IL_0023: ldloca.s V_0 IL_0025: call ""bool int?.HasValue.get"" IL_002a: brtrue.s IL_002f IL_002c: ldc.i4.s 42 IL_002e: ret IL_002f: ldloca.s V_0 IL_0031: call ""int int?.GetValueOrDefault()"" IL_0036: ret } "); } [Fact] public void ConditionalMemberAccessCoalesceDefault() { var source = @" class Program { class C1 { public int x { get; set; } } static void Main() { var c = new C1() { x = 42 }; System.Console.WriteLine(Test(c)); System.Console.WriteLine(Test(null)); } static int Test(C1 c) { return c?.x ?? 0; } } "; var comp = CompileAndVerify(source, expectedOutput: @" 42 0"); comp.VerifyIL("Program.Test(Program.C1)", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldc.i4.0 IL_0004: ret IL_0005: ldarg.0 IL_0006: call ""int Program.C1.x.get"" IL_000b: ret } "); } [Fact] public void ConditionalMemberAccessNullCheck001() { var source = @" class Program { class C1 { public int x{get; set;} } static void Main() { var c = new C1(); System.Console.WriteLine(Test1(c)); System.Console.WriteLine(Test1(null)); System.Console.WriteLine(Test2(c)); System.Console.WriteLine(Test2(null)); System.Console.WriteLine(Test3(c)); System.Console.WriteLine(Test3(null)); } static bool Test1(C1 c) { return c?.x == null; } static bool Test2(C1 c) { return c?.x != null; } static bool Test3(C1 c) { return c?.x > null; } } "; var comp = CompileAndVerify(source, expectedOutput: @"False True True False False False"); comp.VerifyIL("Program.Test1(Program.C1)", @" { // Code size 14 (0xe) .maxstack 1 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldc.i4.1 IL_0004: ret IL_0005: ldarg.0 IL_0006: call ""int Program.C1.x.get"" IL_000b: pop IL_000c: ldc.i4.0 IL_000d: ret } ").VerifyIL("Program.Test2(Program.C1)", @" { // Code size 14 (0xe) .maxstack 1 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldc.i4.0 IL_0004: ret IL_0005: ldarg.0 IL_0006: call ""int Program.C1.x.get"" IL_000b: pop IL_000c: ldc.i4.1 IL_000d: ret } ").VerifyIL("Program.Test3(Program.C1)", @" { // Code size 14 (0xe) .maxstack 1 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldc.i4.0 IL_0004: ret IL_0005: ldarg.0 IL_0006: call ""int Program.C1.x.get"" IL_000b: pop IL_000c: ldc.i4.0 IL_000d: ret } "); } [Fact] public void ConditionalMemberAccessBinary001() { var source = @" public enum N { zero = 0, one = 1, mone = -1 } class Program { class C1 { public N x{get; set;} } static void Main() { var c = new C1(); System.Console.WriteLine(Test1(c)); System.Console.WriteLine(Test1(null)); System.Console.WriteLine(Test2(c)); System.Console.WriteLine(Test2(null)); System.Console.WriteLine(Test3(c)); System.Console.WriteLine(Test3(null)); } static bool Test1(C1 c) { return c?.x == N.zero; } static bool Test2(C1 c) { return c?.x != N.one; } static bool Test3(C1 c) { return c?.x > N.mone; } } "; var comp = CompileAndVerify(source, expectedOutput: @"True False True True True False"); comp.VerifyIL("Program.Test1(Program.C1)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldc.i4.0 IL_0004: ret IL_0005: ldarg.0 IL_0006: call ""N Program.C1.x.get"" IL_000b: ldc.i4.0 IL_000c: ceq IL_000e: ret } ").VerifyIL("Program.Test2(Program.C1)", @" { // Code size 18 (0x12) .maxstack 2 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldc.i4.1 IL_0004: ret IL_0005: ldarg.0 IL_0006: call ""N Program.C1.x.get"" IL_000b: ldc.i4.1 IL_000c: ceq IL_000e: ldc.i4.0 IL_000f: ceq IL_0011: ret } ").VerifyIL("Program.Test3(Program.C1)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldc.i4.0 IL_0004: ret IL_0005: ldarg.0 IL_0006: call ""N Program.C1.x.get"" IL_000b: ldc.i4.m1 IL_000c: cgt IL_000e: ret } "); } [Fact] public void ConditionalMemberAccessBinary002() { var source = @" static class ext { public static Program.C1.S1 y(this Program.C1 self) { return self.x; } } class Program { public class C1 { public struct S1 { public static bool operator <(S1 s1, int s2) { System.Console.WriteLine('<'); return true; } public static bool operator >(S1 s1, int s2) { System.Console.WriteLine('>'); return false; } } public S1 x { get; set; } } static void Main() { C1 c = new C1(); C1 n = null; System.Console.WriteLine(Test1(c)); System.Console.WriteLine(Test1(n)); System.Console.WriteLine(Test2(ref c)); System.Console.WriteLine(Test2(ref n)); System.Console.WriteLine(Test3(c)); System.Console.WriteLine(Test3(n)); System.Console.WriteLine(Test4(ref c)); System.Console.WriteLine(Test4(ref n)); } static bool Test1(C1 c) { return c?.x > -1; } static bool Test2(ref C1 c) { return c?.x < -1; } static bool Test3(C1 c) { return c?.y() > -1; } static bool Test4(ref C1 c) { return c?.y() < -1; } } "; var comp = CompileAndVerify(source, references: new[] { CSharpRef }, expectedOutput: @" > False False < True False > False False < True False"); comp.VerifyIL("Program.Test1(Program.C1)", @" { // Code size 18 (0x12) .maxstack 2 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldc.i4.0 IL_0004: ret IL_0005: ldarg.0 IL_0006: call ""Program.C1.S1 Program.C1.x.get"" IL_000b: ldc.i4.m1 IL_000c: call ""bool Program.C1.S1.op_GreaterThan(Program.C1.S1, int)"" IL_0011: ret } ").VerifyIL("Program.Test2(ref Program.C1)", @" { // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldind.ref IL_0002: dup IL_0003: brtrue.s IL_0008 IL_0005: pop IL_0006: ldc.i4.0 IL_0007: ret IL_0008: call ""Program.C1.S1 Program.C1.x.get"" IL_000d: ldc.i4.m1 IL_000e: call ""bool Program.C1.S1.op_LessThan(Program.C1.S1, int)"" IL_0013: ret } ").VerifyIL("Program.Test3(Program.C1)", @" { // Code size 18 (0x12) .maxstack 2 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldc.i4.0 IL_0004: ret IL_0005: ldarg.0 IL_0006: call ""Program.C1.S1 ext.y(Program.C1)"" IL_000b: ldc.i4.m1 IL_000c: call ""bool Program.C1.S1.op_GreaterThan(Program.C1.S1, int)"" IL_0011: ret } ").VerifyIL("Program.Test4(ref Program.C1)", @" { // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldind.ref IL_0002: dup IL_0003: brtrue.s IL_0008 IL_0005: pop IL_0006: ldc.i4.0 IL_0007: ret IL_0008: call ""Program.C1.S1 ext.y(Program.C1)"" IL_000d: ldc.i4.m1 IL_000e: call ""bool Program.C1.S1.op_LessThan(Program.C1.S1, int)"" IL_0013: ret } "); } [Fact] public void ConditionalMemberAccessOptimizedLocal001() { var source = @" using System; class Program { class C1 : System.IDisposable { public bool disposed; public void Dispose() { disposed = true; } } static void Main() { Test1(); Test2<C1>(); } static void Test1() { var c = new C1(); c?.Dispose(); } static void Test2<T>() where T : IDisposable, new() { var c = new T(); c?.Dispose(); } } "; var comp = CompileAndVerify(source, expectedOutput: @""); comp.VerifyIL("Program.Test1()", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: newobj ""Program.C1..ctor()"" IL_0005: dup IL_0006: brtrue.s IL_000a IL_0008: pop IL_0009: ret IL_000a: call ""void Program.C1.Dispose()"" IL_000f: ret } ").VerifyIL("Program.Test2<T>()", @" { // Code size 28 (0x1c) .maxstack 1 .locals init (T V_0) //c IL_0000: call ""T System.Activator.CreateInstance<T>()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: box ""T"" IL_000c: brfalse.s IL_001b IL_000e: ldloca.s V_0 IL_0010: constrained. ""T"" IL_0016: callvirt ""void System.IDisposable.Dispose()"" IL_001b: ret } "); } [Fact] public void ConditionalMemberAccessOptimizedLocal002() { var source = @" using System; class Program { interface I1 { void Goo(I1 arg); } class C1 : I1 { public void Goo(I1 arg) { } } static void Main() { Test1(); Test2<C1>(); } static void Test1() { var c = new C1(); c?.Goo(c); } static void Test2<T>() where T : I1, new() { var c = new T(); c?.Goo(c); } } "; var comp = CompileAndVerify(source, expectedOutput: @""); comp.VerifyIL("Program.Test1()", @" { // Code size 17 (0x11) .maxstack 2 .locals init (Program.C1 V_0) //c IL_0000: newobj ""Program.C1..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: brfalse.s IL_0010 IL_0009: ldloc.0 IL_000a: ldloc.0 IL_000b: call ""void Program.C1.Goo(Program.I1)"" IL_0010: ret } ").VerifyIL("Program.Test2<T>()", @" { // Code size 34 (0x22) .maxstack 2 .locals init (T V_0) //c IL_0000: call ""T System.Activator.CreateInstance<T>()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: box ""T"" IL_000c: brfalse.s IL_0021 IL_000e: ldloca.s V_0 IL_0010: ldloc.0 IL_0011: box ""T"" IL_0016: constrained. ""T"" IL_001c: callvirt ""void Program.I1.Goo(Program.I1)"" IL_0021: ret } "); } [Fact] public void ConditionalMemberAccessRace001() { var source = @" using System.Threading; using System.Threading.Tasks; class Program { static void Main() { string s = ""hello""; System.Action a = () => { for (int i = 0; i < 1000000; i++) { try { s = s?.Length.ToString(); s = null; Thread.Yield(); } catch (System.Exception ex) { System.Console.WriteLine(ex); } finally { s = s ?? ""hello""; } } }; Task.Factory.StartNew(a); Task.Factory.StartNew(a); Task.Factory.StartNew(a); Task.Factory.StartNew(a); Task.Factory.StartNew(a); Task.Factory.StartNew(a); Task.Factory.StartNew(a); Task.Factory.StartNew(a); Task.Factory.StartNew(a); Task.Factory.StartNew(a); Task.Factory.StartNew(a); Task.Factory.StartNew(a); Task.Factory.StartNew(a); Task.Factory.StartNew(a); Task.Factory.StartNew(a); Task.Factory.StartNew(a); a(); System.Console.WriteLine(""Success""); } } "; var comp = CompileAndVerify(source, expectedOutput: @"Success"); } [Fact(), WorkItem(836, "GitHub")] public void ConditionalMemberAccessRace002() { var source = @" using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; class Program { static void Main() { string s = ""hello""; Test(s); } private static void Test<T>(T s) where T : IEnumerable<char> { Action a = () => { for (int i = 0; i < 1000000; i++) { var temp = s; try { s?.GetEnumerator(); s = default(T); Thread.Yield(); } catch (System.Exception ex) { System.Console.WriteLine(ex); } finally { s = temp; } } }; var tasks = new List<Task>(); tasks.Add(Task.Factory.StartNew(a)); tasks.Add(Task.Factory.StartNew(a)); tasks.Add(Task.Factory.StartNew(a)); tasks.Add(Task.Factory.StartNew(a)); tasks.Add(Task.Factory.StartNew(a)); tasks.Add(Task.Factory.StartNew(a)); tasks.Add(Task.Factory.StartNew(a)); tasks.Add(Task.Factory.StartNew(a)); tasks.Add(Task.Factory.StartNew(a)); tasks.Add(Task.Factory.StartNew(a)); tasks.Add(Task.Factory.StartNew(a)); tasks.Add(Task.Factory.StartNew(a)); tasks.Add(Task.Factory.StartNew(a)); tasks.Add(Task.Factory.StartNew(a)); tasks.Add(Task.Factory.StartNew(a)); tasks.Add(Task.Factory.StartNew(a)); a(); // wait for all tasks to exit or we may have // test issues when unloading ApDomain while threads still running in it Task.WaitAll(tasks.ToArray()); System.Console.WriteLine(""Success""); } } "; var comp = CompileAndVerify(source, expectedOutput: @"Success"); } [Fact] public void ConditionalMemberAccessConditional001() { var source = @" using System; class Program { static void Main() { Test1<string>(null); Test2<string>(null); } static string Test1<T>(T[] arr) { if (arr != null && arr.Length > 0) { return arr[0].ToString(); } return ""none""; } static string Test2<T>(T[] arr) { if (arr?.Length > 0) { return arr[0].ToString(); } return ""none""; } } "; var comp = CompileAndVerify(source, expectedOutput: @""); comp.VerifyIL("Program.Test1<T>(T[])", @" { // Code size 34 (0x22) .maxstack 2 IL_0000: ldarg.0 IL_0001: brfalse.s IL_001c IL_0003: ldarg.0 IL_0004: ldlen IL_0005: brfalse.s IL_001c IL_0007: ldarg.0 IL_0008: ldc.i4.0 IL_0009: readonly. IL_000b: ldelema ""T"" IL_0010: constrained. ""T"" IL_0016: callvirt ""string object.ToString()"" IL_001b: ret IL_001c: ldstr ""none"" IL_0021: ret } ").VerifyIL("Program.Test2<T>(T[])", @" { // Code size 34 (0x22) .maxstack 2 IL_0000: ldarg.0 IL_0001: brfalse.s IL_001c IL_0003: ldarg.0 IL_0004: ldlen IL_0005: brfalse.s IL_001c IL_0007: ldarg.0 IL_0008: ldc.i4.0 IL_0009: readonly. IL_000b: ldelema ""T"" IL_0010: constrained. ""T"" IL_0016: callvirt ""string object.ToString()"" IL_001b: ret IL_001c: ldstr ""none"" IL_0021: ret } "); } [Fact] public void ConditionalMemberAccessConditional002() { var source = @" using System; class Program { static void Main() { Test1<string>(null); Test2<string>(null); } static string Test1<T>(T[] arr) { if (!(arr != null && arr.Length > 0)) { return ""none""; } return arr[0].ToString(); } static string Test2<T>(T[] arr) { if (!(arr?.Length > 0)) { return ""none""; } return arr[0].ToString(); } } "; var comp = CompileAndVerify(source, expectedOutput: @""); comp.VerifyIL("Program.Test1<T>(T[])", @" { // Code size 34 (0x22) .maxstack 2 IL_0000: ldarg.0 IL_0001: brfalse.s IL_0007 IL_0003: ldarg.0 IL_0004: ldlen IL_0005: brtrue.s IL_000d IL_0007: ldstr ""none"" IL_000c: ret IL_000d: ldarg.0 IL_000e: ldc.i4.0 IL_000f: readonly. IL_0011: ldelema ""T"" IL_0016: constrained. ""T"" IL_001c: callvirt ""string object.ToString()"" IL_0021: ret } ").VerifyIL("Program.Test2<T>(T[])", @" { // Code size 34 (0x22) .maxstack 2 IL_0000: ldarg.0 IL_0001: brfalse.s IL_0007 IL_0003: ldarg.0 IL_0004: ldlen IL_0005: brtrue.s IL_000d IL_0007: ldstr ""none"" IL_000c: ret IL_000d: ldarg.0 IL_000e: ldc.i4.0 IL_000f: readonly. IL_0011: ldelema ""T"" IL_0016: constrained. ""T"" IL_001c: callvirt ""string object.ToString()"" IL_0021: ret } "); } [Fact] public void ConditionalMemberAccessConditional003() { var source = @" using System; class Program { static void Main() { System.Console.WriteLine(Test1<string>(null)); System.Console.WriteLine(Test2<string>(null)); System.Console.WriteLine(Test1<string>(new string[] {})); System.Console.WriteLine(Test2<string>(new string[] {})); System.Console.WriteLine(Test1<string>(new string[] { System.String.Empty })); System.Console.WriteLine(Test2<string>(new string[] { System.String.Empty })); } static string Test1<T>(T[] arr1) { var arr = arr1; if (arr != null && arr.Length == 0) { return ""empty""; } return ""not empty""; } static string Test2<T>(T[] arr1) { var arr = arr1; if (!(arr?.Length != 0)) { return ""empty""; } return ""not empty""; } } "; var comp = CompileAndVerify(source, expectedOutput: @"not empty not empty empty empty not empty not empty"); comp.VerifyIL("Program.Test1<T>(T[])", @" { // Code size 21 (0x15) .maxstack 1 .locals init (T[] V_0) //arr IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: brfalse.s IL_000f IL_0005: ldloc.0 IL_0006: ldlen IL_0007: brtrue.s IL_000f IL_0009: ldstr ""empty"" IL_000e: ret IL_000f: ldstr ""not empty"" IL_0014: ret } ").VerifyIL("Program.Test2<T>(T[])", @" { // Code size 26 (0x1a) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: brtrue.s IL_0008 IL_0004: pop IL_0005: ldc.i4.1 IL_0006: br.s IL_000c IL_0008: ldlen IL_0009: ldc.i4.0 IL_000a: cgt.un IL_000c: brtrue.s IL_0014 IL_000e: ldstr ""empty"" IL_0013: ret IL_0014: ldstr ""not empty"" IL_0019: ret } "); } [Fact] public void ConditionalMemberAccessConditional004() { var source = @" using System; class Program { static void Main() { var w = new WeakReference<string>(null); Test0(ref w); Test1(ref w); Test2(ref w); Test3(ref w); } static string Test0(ref WeakReference<string> slot) { string value = null; WeakReference<string> weak = slot; if (weak != null && weak.TryGetTarget(out value)) { return value; } return ""hello""; } static string Test1(ref WeakReference<string> slot) { string value = null; WeakReference<string> weak = slot; if (weak?.TryGetTarget(out value) == true) { return value; } return ""hello""; } static string Test2(ref WeakReference<string> slot) { string value = null; if (slot?.TryGetTarget(out value) == true) { return value; } return ""hello""; } static string Test3(ref WeakReference<string> slot) { string value = null; if (slot?.TryGetTarget(out value) ?? false) { return value; } return ""hello""; } } "; var comp = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: ""). VerifyIL("Program.Test0(ref System.WeakReference<string>)", @" { // Code size 26 (0x1a) .maxstack 2 .locals init (string V_0, //value System.WeakReference<string> V_1) //weak IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: ldind.ref IL_0004: stloc.1 IL_0005: ldloc.1 IL_0006: brfalse.s IL_0014 IL_0008: ldloc.1 IL_0009: ldloca.s V_0 IL_000b: callvirt ""bool System.WeakReference<string>.TryGetTarget(out string)"" IL_0010: brfalse.s IL_0014 IL_0012: ldloc.0 IL_0013: ret IL_0014: ldstr ""hello"" IL_0019: ret } ").VerifyIL("Program.Test1(ref System.WeakReference<string>)", @" { // Code size 28 (0x1c) .maxstack 2 .locals init (string V_0) //value IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: ldind.ref IL_0004: dup IL_0005: brtrue.s IL_000b IL_0007: pop IL_0008: ldc.i4.0 IL_0009: br.s IL_0012 IL_000b: ldloca.s V_0 IL_000d: call ""bool System.WeakReference<string>.TryGetTarget(out string)"" IL_0012: brfalse.s IL_0016 IL_0014: ldloc.0 IL_0015: ret IL_0016: ldstr ""hello"" IL_001b: ret } ").VerifyIL("Program.Test2(ref System.WeakReference<string>)", @" { // Code size 28 (0x1c) .maxstack 2 .locals init (string V_0) //value IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: ldind.ref IL_0004: dup IL_0005: brtrue.s IL_000b IL_0007: pop IL_0008: ldc.i4.0 IL_0009: br.s IL_0012 IL_000b: ldloca.s V_0 IL_000d: call ""bool System.WeakReference<string>.TryGetTarget(out string)"" IL_0012: brfalse.s IL_0016 IL_0014: ldloc.0 IL_0015: ret IL_0016: ldstr ""hello"" IL_001b: ret } ").VerifyIL("Program.Test3(ref System.WeakReference<string>)", @" { // Code size 28 (0x1c) .maxstack 2 .locals init (string V_0) //value IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldarg.0 IL_0003: ldind.ref IL_0004: dup IL_0005: brtrue.s IL_000b IL_0007: pop IL_0008: ldc.i4.0 IL_0009: br.s IL_0012 IL_000b: ldloca.s V_0 IL_000d: call ""bool System.WeakReference<string>.TryGetTarget(out string)"" IL_0012: brfalse.s IL_0016 IL_0014: ldloc.0 IL_0015: ret IL_0016: ldstr ""hello"" IL_001b: ret } "); } [WorkItem(1042288, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1042288")] [Fact] public void Bug1042288() { var source = @" using System; class Test { static void Main() { var c1 = new C1(); System.Console.WriteLine(c1?.M1() ?? (long)1000); return; } } class C1 { public int M1() { return 1; } } "; var comp = CompileAndVerify(source, expectedOutput: @"1"); comp.VerifyIL("Test.Main", @" { // Code size 62 (0x3e) .maxstack 2 .locals init (int? V_0, int? V_1) IL_0000: newobj ""C1..ctor()"" IL_0005: dup IL_0006: brtrue.s IL_0014 IL_0008: pop IL_0009: ldloca.s V_1 IL_000b: initobj ""int?"" IL_0011: ldloc.1 IL_0012: br.s IL_001e IL_0014: call ""int C1.M1()"" IL_0019: newobj ""int?..ctor(int)"" IL_001e: stloc.0 IL_001f: ldloca.s V_0 IL_0021: call ""bool int?.HasValue.get"" IL_0026: brtrue.s IL_0030 IL_0028: ldc.i4 0x3e8 IL_002d: conv.i8 IL_002e: br.s IL_0038 IL_0030: ldloca.s V_0 IL_0032: call ""int int?.GetValueOrDefault()"" IL_0037: conv.i8 IL_0038: call ""void System.Console.WriteLine(long)"" IL_003d: ret } "); } [WorkItem(470, "CodPlex")] [Fact] public void CodPlexBug470_01() { var source = @" class C { public static void Main() { System.Console.WriteLine(MyMethod(null)); System.Console.WriteLine(MyMethod(new MyType())); } public static decimal MyMethod(MyType myObject) { return myObject?.MyField ?? 0m; } } public class MyType { public decimal MyField = 123; } "; var verifier = CompileAndVerify(source, expectedOutput: @"0 123"); verifier.VerifyIL("C.MyMethod", @" { // Code size 16 (0x10) .maxstack 1 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0009 IL_0003: ldsfld ""decimal decimal.Zero"" IL_0008: ret IL_0009: ldarg.0 IL_000a: ldfld ""decimal MyType.MyField"" IL_000f: ret }"); } [WorkItem(470, "CodPlex")] [Fact] public void CodPlexBug470_02() { var source = @" class C { public static void Main() { System.Console.WriteLine(MyMethod(null)); System.Console.WriteLine(MyMethod(new MyType())); } public static decimal MyMethod(MyType myObject) { return myObject?.MyField ?? default(decimal); } } public class MyType { public decimal MyField = 123; } "; var verifier = CompileAndVerify(source, expectedOutput: @"0 123"); verifier.VerifyIL("C.MyMethod", @" { // Code size 16 (0x10) .maxstack 1 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0009 IL_0003: ldsfld ""decimal decimal.Zero"" IL_0008: ret IL_0009: ldarg.0 IL_000a: ldfld ""decimal MyType.MyField"" IL_000f: ret }"); } [WorkItem(470, "CodPlex")] [Fact] public void CodPlexBug470_03() { var source = @" using System; class C { public static void Main() { System.Console.WriteLine(String.Format(System.Globalization.CultureInfo.InvariantCulture, ""{0}"", MyMethod(null))); System.Console.WriteLine(String.Format(System.Globalization.CultureInfo.InvariantCulture, ""{0}"", MyMethod(new MyType()))); } public static DateTime MyMethod(MyType myObject) { return myObject?.MyField ?? default(DateTime); } } public class MyType { public DateTime MyField = new DateTime(100000000); } "; var verifier = CompileAndVerify(source, expectedOutput: @"01/01/0001 00:00:00 01/01/0001 00:00:10"); verifier.VerifyIL("C.MyMethod", @" { // Code size 20 (0x14) .maxstack 1 .locals init (System.DateTime V_0) IL_0000: ldarg.0 IL_0001: brtrue.s IL_000d IL_0003: ldloca.s V_0 IL_0005: initobj ""System.DateTime"" IL_000b: ldloc.0 IL_000c: ret IL_000d: ldarg.0 IL_000e: ldfld ""System.DateTime MyType.MyField"" IL_0013: ret }"); } [WorkItem(470, "CodPlex")] [Fact] public void CodPlexBug470_04() { var source = @" class C { public static void Main() { System.Console.WriteLine(MyMethod(null).F); System.Console.WriteLine(MyMethod(new MyType()).F); } public static MyStruct MyMethod(MyType myObject) { return myObject?.MyField ?? default(MyStruct); } } public class MyType { public MyStruct MyField = new MyStruct() {F = 123}; } public struct MyStruct { public int F; } "; var verifier = CompileAndVerify(source, expectedOutput: @"0 123"); verifier.VerifyIL("C.MyMethod", @" { // Code size 20 (0x14) .maxstack 1 .locals init (MyStruct V_0) IL_0000: ldarg.0 IL_0001: brtrue.s IL_000d IL_0003: ldloca.s V_0 IL_0005: initobj ""MyStruct"" IL_000b: ldloc.0 IL_000c: ret IL_000d: ldarg.0 IL_000e: ldfld ""MyStruct MyType.MyField"" IL_0013: ret }"); } [WorkItem(1103294, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1103294")] [Fact] public void Bug1103294_01() { var source = @" class C { static void Main() { System.Console.WriteLine(""---""); Goo<int>(new C<int>()); System.Console.WriteLine(""---""); Goo<int>(null); System.Console.WriteLine(""---""); } static void Goo<T>(C<T> x) { x?.M(); } } class C<T> { public T M() { System.Console.WriteLine(""M""); return default(T); } }"; var verifier = CompileAndVerify(source, expectedOutput: @"--- M --- ---"); verifier.VerifyIL("C.Goo<T>", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldarg.0 IL_0001: brfalse.s IL_000a IL_0003: ldarg.0 IL_0004: call ""T C<T>.M()"" IL_0009: pop IL_000a: ret }"); } [WorkItem(1103294, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1103294")] [Fact] public void Bug1103294_02() { var source = @" unsafe class C { static void Main() { System.Console.WriteLine(""---""); Goo(new C()); System.Console.WriteLine(""---""); Goo(null); System.Console.WriteLine(""---""); } static void Goo(C x) { x?.M(); } public int* M() { System.Console.WriteLine(""M""); return null; } } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), verify: Verification.Fails, expectedOutput: @"--- M --- ---"); verifier.VerifyIL("C.Goo", @" { // Code size 14 (0xe) .maxstack 1 IL_0000: nop IL_0001: ldarg.0 IL_0002: brtrue.s IL_0006 IL_0004: br.s IL_000d IL_0006: ldarg.0 IL_0007: call ""int* C.M()"" IL_000c: pop IL_000d: ret }"); } [WorkItem(23422, "https://github.com/dotnet/roslyn/issues/23422")] [Fact] public void ConditionalRefLike() { var source = @" class C { static void Main() { System.Console.WriteLine(""---""); Goo(new C()); System.Console.WriteLine(""---""); Goo(null); System.Console.WriteLine(""---""); } static void Goo(C x) { x?.M(); } public RefLike M() { System.Console.WriteLine(""M""); return default; } public ref struct RefLike{} } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), expectedOutput: @"--- M --- ---"); verifier.VerifyIL("C.Goo", @" { // Code size 14 (0xe) .maxstack 1 IL_0000: nop IL_0001: ldarg.0 IL_0002: brtrue.s IL_0006 IL_0004: br.s IL_000d IL_0006: ldarg.0 IL_0007: call ""C.RefLike C.M()"" IL_000c: pop IL_000d: ret }"); } [WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")] [Fact] public void Bug1109164_01() { var source = @" using System; class Test { static void Main() { System.Console.WriteLine(""---""); C.F1(null); System.Console.WriteLine(""---""); C.F1(new C()); System.Console.WriteLine(""---""); C.F2(null); System.Console.WriteLine(""---""); C.F2(new C()); System.Console.WriteLine(""---""); } } class C { static public void F1(C c) { System.Console.WriteLine(""F1""); Action a = () => c?.M(); a(); } static public void F2(C c) => c?.M(); void M() => System.Console.WriteLine(""M""); } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"--- F1 --- F1 M --- --- M ---"); verifier.VerifyIL("C.<>c__DisplayClass0_0.<F1>b__0", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""C C.<>c__DisplayClass0_0.c"" IL_0006: dup IL_0007: brtrue.s IL_000c IL_0009: pop IL_000a: br.s IL_0012 IL_000c: call ""void C.M()"" IL_0011: nop IL_0012: ret }"); verifier.VerifyIL("C.F2", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: br.s IL_000c IL_0005: ldarg.0 IL_0006: call ""void C.M()"" IL_000b: nop IL_000c: ret }"); } [WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")] [Fact] public void Bug1109164_02() { var source = @" using System; class Test { static void Main() { } } class C { static public void F1(C c) { System.Console.WriteLine(""F1""); Func<object> a = () => c?.M(); } static public object F2(C c) => c?.M(); static public object P1 => (new C())?.M(); void M() => System.Console.WriteLine(""M""); } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (16,32): error CS0029: Cannot implicitly convert type 'void' to 'object' // Func<object> a = () => c?.M(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "c?.M()").WithArguments("void", "object").WithLocation(16, 32), // (16,32): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // Func<object> a = () => c?.M(); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "c?.M()").WithArguments("lambda expression").WithLocation(16, 32), // (19,37): error CS0029: Cannot implicitly convert type 'void' to 'object' // static public object F2(C c) => c?.M(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "c?.M()").WithArguments("void", "object").WithLocation(19, 37), // (21,32): error CS0029: Cannot implicitly convert type 'void' to 'object' // static public object P1 => (new C())?.M(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "(new C())?.M()").WithArguments("void", "object").WithLocation(21, 32) ); } [WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")] [Fact] public void Bug1109164_03() { var source = @" using System; class Test { static void Main() { System.Console.WriteLine(""---""); C<int>.F1(null); System.Console.WriteLine(""---""); C<int>.F1(new C<int>()); System.Console.WriteLine(""---""); C<int>.F2(null); System.Console.WriteLine(""---""); C<int>.F2(new C<int>()); System.Console.WriteLine(""---""); } } class C<T> { static public void F1(C<T> c) { System.Console.WriteLine(""F1""); Action a = () => c?.M(); a(); } static public void F2(C<T> c) => c?.M(); T M() { System.Console.WriteLine(""M""); return default(T); } } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"--- F1 --- F1 M --- --- M ---"); verifier.VerifyIL("C<T>.<>c__DisplayClass0_0.<F1>b__0()", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""C<T> C<T>.<>c__DisplayClass0_0.c"" IL_0006: dup IL_0007: brtrue.s IL_000c IL_0009: pop IL_000a: br.s IL_0012 IL_000c: call ""T C<T>.M()"" IL_0011: pop IL_0012: ret }"); verifier.VerifyIL("C<T>.F2", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: br.s IL_000c IL_0005: ldarg.0 IL_0006: call ""T C<T>.M()"" IL_000b: pop IL_000c: ret }"); } [WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")] [Fact] public void Bug1109164_04() { var source = @" using System; class Test { static void Main() { } } class C<T> { static public void F1(C<T> c) { Func<object> a = () => c?.M(); } static public object F2(C<T> c) => c?.M(); static public object P1 => (new C<T>())?.M(); T M() { return default(T); } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (15,33): error CS0023: Operator '?' cannot be applied to operand of type 'T' // Func<object> a = () => c?.M(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "T").WithLocation(15, 33), // (18,41): error CS0023: Operator '?' cannot be applied to operand of type 'T' // static public object F2(C<T> c) => c?.M(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "T").WithLocation(18, 41), // (20,44): error CS0023: Operator '?' cannot be applied to operand of type 'T' // static public object P1 => (new C<T>())?.M(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "T").WithLocation(20, 44) ); } [WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")] [Fact] public void Bug1109164_05() { var source = @" using System; class Test { static void Main() { System.Console.WriteLine(""---""); C.F1(null); System.Console.WriteLine(""---""); C.F1(new C()); System.Console.WriteLine(""---""); C.F2(null); System.Console.WriteLine(""---""); C.F2(new C()); System.Console.WriteLine(""---""); } } unsafe class C { static public void F1(C c) { System.Console.WriteLine(""F1""); Action<object> a = o => c?.M(); a(null); } static public void F2(C c) => c?.M(); void* M() { System.Console.WriteLine(""M""); return null; } } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugExe.WithAllowUnsafe(true), verify: Verification.Fails, expectedOutput: @"--- F1 --- F1 M --- --- M ---"); verifier.VerifyIL("C.<>c__DisplayClass0_0.<F1>b__0", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""C C.<>c__DisplayClass0_0.c"" IL_0006: dup IL_0007: brtrue.s IL_000c IL_0009: pop IL_000a: br.s IL_0012 IL_000c: call ""void* C.M()"" IL_0011: pop IL_0012: ret }"); verifier.VerifyIL("C.F2", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: br.s IL_000c IL_0005: ldarg.0 IL_0006: call ""void* C.M()"" IL_000b: pop IL_000c: ret }"); } [WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")] [Fact] public void Bug1109164_06() { var source = @" using System; class Test { static void Main() { } } unsafe class C { static public void F1(C c) { System.Console.WriteLine(""F1""); Func<object, object> a = o => c?.M(); } static public object F2(C c) => c?.M(); static public object P1 => (new C())?.M(); void* M() { System.Console.WriteLine(""M""); return null; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe.WithAllowUnsafe(true)); compilation.VerifyDiagnostics( // (16,40): error CS0023: Operator '?' cannot be applied to operand of type 'void*' // Func<object, object> a = o => c?.M(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "void*").WithLocation(16, 40), // (19,38): error CS0023: Operator '?' cannot be applied to operand of type 'void*' // static public object F2(C c) => c?.M(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "void*").WithLocation(19, 38), // (21,41): error CS0023: Operator '?' cannot be applied to operand of type 'void*' // static public object P1 => (new C())?.M(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "void*").WithLocation(21, 41) ); } [WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")] [Fact] public void Bug1109164_07() { var source = @" using System; class Test { static void Main() { C<int>.Test(); } } class C<T> { public static void Test() { var x = new [] {null, new C<T>()}; for (int i = 0; i < 2; x[i-1]?.M()) { System.Console.WriteLine(""---""); System.Console.WriteLine(""Loop""); i++; } System.Console.WriteLine(""---""); } public T M() { System.Console.WriteLine(""M""); return default(T); } } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @" --- Loop --- Loop M ---"); } [WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")] [Fact] public void Bug1109164_08() { var source = @" using System; class Test { static void Main() { C<int>.Test(); } } class C<T> { public static void Test() { var x = new [] {null, new C<T>()}; System.Console.WriteLine(""---""); for (x[0]?.M(); false;) { } System.Console.WriteLine(""---""); for (x[1]?.M(); false;) { } System.Console.WriteLine(""---""); } public T M() { System.Console.WriteLine(""M""); return default(T); } } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"--- --- M ---"); } [WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")] [Fact] public void Bug1109164_09() { var source = @" class Test { static void Main() { } } class C<T> { public static void Test() { C<T> x = null; for (; x?.M();) { } } public T M() { return default(T); } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (15,17): error CS0023: Operator '?' cannot be applied to operand of type 'T' // for (; x?.M();) Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "T").WithLocation(15, 17) ); } [WorkItem(1109164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109164")] [Fact] public void Bug1109164_10() { var source = @" using System; class Test { static void Main() { C<int>.Test(); } } class C<T> { public static void Test() { System.Console.WriteLine(""---""); M1(a => a?.M(), null); System.Console.WriteLine(""---""); M1((a) => a?.M(), new C<T>()); System.Console.WriteLine(""---""); } static void M1(Action<C<T>> x, C<T> y) { System.Console.WriteLine(""M1(Action<C<T>> x)""); x(y); } static void M1(Func<C<T>, object> x, C<T> y) { System.Console.WriteLine(""M1(Func<C<T>, object> x)""); x(y); } public T M() { System.Console.WriteLine(""M""); return default(T); } } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"--- M1(Action<C<T>> x) --- M1(Action<C<T>> x) M ---"); } [WorkItem(74, "https://github.com/dotnet/roslyn/issues/74")] [Fact] public void ConditionalInAsyncTask() { var source = @" #pragma warning disable CS1998 // suppress 'no await in async' warning using System; using System.Threading.Tasks; class Goo<T> { public T Method(int i) { Console.Write(i); return default(T); // returns value of unconstrained type parameter type } public void M1(Goo<T> x) => x?.Method(4); public async void M2(Goo<T> x) => x?.Method(5); public async Task M3(Goo<T> x) => x?.Method(6); public async Task M4() { Goo<T> a = new Goo<T>(); Goo<T> b = null; Action f1 = async () => a?.Method(1); f1(); f1 = async () => b?.Method(0); f1(); Func<Task> f2 = async () => a?.Method(2); await f2(); Func<Task> f3 = async () => b?.Method(3); await f3(); M1(a); M1(b); M2(a); M2(b); await M3(a); await M3(b); } } class Program { public static void Main() { // this will complete synchronously as there are no truly async ops. new Goo<int>().M4(); } }"; var compilation = CreateCompilationWithMscorlib45( source, references: new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: "12456"); } [WorkItem(825, "https://github.com/dotnet/roslyn/issues/825")] [Fact] public void ConditionalBoolExpr01() { var source = @" class C { public static void Main() { System.Console.WriteLine(HasLength(null, 0)); } static bool HasLength(string s, int len) { return s?.Length == len; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"False"); verifier.VerifyIL("C.HasLength", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldc.i4.0 IL_0004: ret IL_0005: ldarg.0 IL_0006: call ""int string.Length.get"" IL_000b: ldarg.1 IL_000c: ceq IL_000e: ret }"); } [WorkItem(825, "https://github.com/dotnet/roslyn/issues/825")] [Fact] public void ConditionalBoolExpr01a() { var source = @" class C { public static void Main() { System.Console.WriteLine(HasLength(null, 0)); } static bool HasLength(string s, byte len) { return s?.Length == len; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"False"); verifier.VerifyIL("C.HasLength", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldc.i4.0 IL_0004: ret IL_0005: ldarg.0 IL_0006: call ""int string.Length.get"" IL_000b: ldarg.1 IL_000c: ceq IL_000e: ret }"); } [WorkItem(825, "https://github.com/dotnet/roslyn/issues/825")] [WorkItem(5662, "https://github.com/dotnet/roslyn/issues/5662")] [Fact] public void ConditionalBoolExpr01b() { var source = @" class C { public static void Main() { System.Console.WriteLine(HasLength(null, long.MaxValue)); try { System.Console.WriteLine(HasLengthChecked(null, long.MaxValue)); } catch (System.Exception ex) { System.Console.WriteLine(ex.GetType().Name); } } static bool HasLength(string s, long len) { return s?.Length == (int)(byte)len; } static bool HasLengthChecked(string s, long len) { checked { return s?.Length == (int)(byte)len; } } } "; var verifier = CompileAndVerify(source, expectedOutput: @"False OverflowException"); verifier.VerifyIL("C.HasLength", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldc.i4.0 IL_0004: ret IL_0005: ldarg.0 IL_0006: call ""int string.Length.get"" IL_000b: ldarg.1 IL_000c: conv.u1 IL_000d: ceq IL_000f: ret }").VerifyIL("C.HasLengthChecked", @" { // Code size 48 (0x30) .maxstack 2 .locals init (int? V_0, int V_1, int? V_2) IL_0000: ldarg.0 IL_0001: brtrue.s IL_000e IL_0003: ldloca.s V_2 IL_0005: initobj ""int?"" IL_000b: ldloc.2 IL_000c: br.s IL_0019 IL_000e: ldarg.0 IL_000f: call ""int string.Length.get"" IL_0014: newobj ""int?..ctor(int)"" IL_0019: stloc.0 IL_001a: ldarg.1 IL_001b: conv.ovf.u1 IL_001c: stloc.1 IL_001d: ldloca.s V_0 IL_001f: call ""int int?.GetValueOrDefault()"" IL_0024: ldloc.1 IL_0025: ceq IL_0027: ldloca.s V_0 IL_0029: call ""bool int?.HasValue.get"" IL_002e: and IL_002f: ret }"); } [Fact] public void ConditionalBoolExpr02() { var source = @" class C { public static void Main() { System.Console.Write(HasLength(null, 0)); System.Console.Write(HasLength(null, 3)); System.Console.Write(HasLength(""q"", 2)); } static bool HasLength(string s, int len) { return (s?.Length ?? 2) + 1 == len; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"FalseTrueTrue"); verifier.VerifyIL("C.HasLength", @" { // Code size 18 (0x12) .maxstack 2 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0006 IL_0003: ldc.i4.2 IL_0004: br.s IL_000c IL_0006: ldarg.0 IL_0007: call ""int string.Length.get"" IL_000c: ldc.i4.1 IL_000d: add IL_000e: ldarg.1 IL_000f: ceq IL_0011: ret }"); } [Fact] public void ConditionalBoolExpr02a() { var source = @" class C { public static void Main() { System.Console.Write(NotHasLength(null, 0)); System.Console.Write(NotHasLength(null, 3)); System.Console.Write(NotHasLength(""q"", 2)); } static bool NotHasLength(string s, int len) { return s?.Length + 1 != len; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"TrueTrueFalse"); verifier.VerifyIL("C.NotHasLength", @" { // Code size 20 (0x14) .maxstack 2 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldc.i4.1 IL_0004: ret IL_0005: ldarg.0 IL_0006: call ""int string.Length.get"" IL_000b: ldc.i4.1 IL_000c: add IL_000d: ldarg.1 IL_000e: ceq IL_0010: ldc.i4.0 IL_0011: ceq IL_0013: ret }"); } [Fact] public void ConditionalBoolExpr02b() { var source = @" class C { public static void Main() { System.Console.Write(NotHasLength(null, 0)); System.Console.Write(NotHasLength(null, 3)); System.Console.Write(NotHasLength(""q"", 2)); System.Console.Write(NotHasLength(null, null)); } static bool NotHasLength(string s, int? len) { return s?.Length + 1 != len; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"TrueTrueFalseFalse"); verifier.VerifyIL("C.NotHasLength", @" { // Code size 42 (0x2a) .maxstack 2 .locals init (int? V_0) IL_0000: ldarg.0 IL_0001: brtrue.s IL_000b IL_0003: ldarga.s V_1 IL_0005: call ""bool int?.HasValue.get"" IL_000a: ret IL_000b: ldarg.0 IL_000c: call ""int string.Length.get"" IL_0011: ldc.i4.1 IL_0012: add IL_0013: ldarg.1 IL_0014: stloc.0 IL_0015: ldloca.s V_0 IL_0017: call ""int int?.GetValueOrDefault()"" IL_001c: ceq IL_001e: ldloca.s V_0 IL_0020: call ""bool int?.HasValue.get"" IL_0025: and IL_0026: ldc.i4.0 IL_0027: ceq IL_0029: ret }"); } [Fact] public void ConditionalBoolExpr03() { var source = @" using System.Threading.Tasks; static class C { public static void Main() { System.Console.Write(HasLength(null, 0).Result); System.Console.Write(HasLength(null, 3).Result); System.Console.Write(HasLength(""q"", 2).Result); } static async Task<bool> HasLength(string s, int len) { return (s?.Goo(await Bar()) ?? await Bar() + await Bar()) + 1 == len; } static int Goo(this string s, int arg) { return s.Length; } static async Task<int> Bar() { await Task.Yield(); return 1; } } "; var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe); var comp = CompileAndVerify(c, expectedOutput: @"FalseTrueTrue"); } [Fact] public void ConditionalBoolExpr04() { var source = @" using System.Threading.Tasks; static class C { public static void Main() { System.Console.Write(HasLength((string)null, 0).Result); System.Console.Write(HasLength((string)null, 3).Result); System.Console.Write(HasLength(""q"", 2).Result); } static async Task<bool> HasLength<T>(T s, int len) { return (s?.Goo(await Bar()) ?? 2) + 1 == len; } static int Goo<T>(this T s, int arg) { return ((string)(object)s).Length; } static async Task<int> Bar() { await Task.Yield(); return 1; } } "; var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe); var comp = CompileAndVerify(c, expectedOutput: @"FalseTrueTrue"); } [Fact] public void ConditionalBoolExpr05() { var source = @" using System.Threading.Tasks; static class C { public static void Main() { System.Console.Write(HasLength((string)null, 0).Result); System.Console.Write(HasLength((string)null, 3).Result); System.Console.Write(HasLength(""q"", 2).Result); } static async Task<bool> HasLength<T>(T s, int len) { return (s?.Goo(await Bar(await Bar())) ?? 2) + 1 == len; } static int Goo<T>(this T s, int arg) { return ((string)(object)s).Length; } static async Task<int> Bar() { await Task.Yield(); return 1; } static async Task<int> Bar(int arg) { await Task.Yield(); return arg; } } "; var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe); var comp = CompileAndVerify(c, expectedOutput: @"FalseTrueTrue"); } [Fact] public void ConditionalBoolExpr06() { var source = @" using System.Threading.Tasks; static class C { public static void Main() { System.Console.Write(HasLength(null, 0).Result); System.Console.Write(HasLength(null, 7).Result); System.Console.Write(HasLength(""q"", 7).Result); } static async Task<bool> HasLength(string s, int len) { System.Console.WriteLine(s?.Goo(await Bar())?.Goo(await Bar()) + ""#""); return s?.Goo(await Bar())?.Goo(await Bar()).Length == len; } static string Goo(this string s, string arg) { return s + arg; } static async Task<string> Bar() { await Task.Yield(); return ""Bar""; } } "; var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe); var comp = CompileAndVerify(c, expectedOutput: @"# False# FalseqBarBar# True"); } [Fact] public void ConditionalBoolExpr07() { var source = @" using System.Threading.Tasks; static class C { public static void Main() { System.Console.WriteLine(Test(null).Result); System.Console.WriteLine(Test(""q"").Result); } static async Task<bool> Test(string s) { return (await Bar(s))?.Goo(await Bar())?.ToString()?.Length > 1; } static string Goo(this string s, string arg1) { return s + arg1; } static async Task<string> Bar() { await Task.Yield(); return ""Bar""; } static async Task<string> Bar(string arg) { await Task.Yield(); return arg; } } "; var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe); var comp = CompileAndVerify(c, expectedOutput: @"False True"); } [Fact] public void ConditionalBoolExpr08() { var source = @" using System.Threading.Tasks; static class C { public static void Main() { System.Console.WriteLine(Test(null).Result); System.Console.WriteLine(Test(""q"").Result); } static async Task<bool> Test(string s) { return (await Bar(s))?.Insert(0, await Bar())?.ToString()?.Length > 1; } static async Task<string> Bar() { await Task.Yield(); return ""Bar""; } static async Task<dynamic> Bar(string arg) { await Task.Yield(); return arg; } }"; var c = CreateCompilationWithMscorlib45(source, new[] { SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef }, TestOptions.ReleaseExe); var comp = CompileAndVerify(c, expectedOutput: @"False True"); } [Fact] public void ConditionalUserDef01() { var source = @" class C { struct S1 { public static bool operator ==(S1? x, S1?y) { System.Console.Write(""==""); return true; } public static bool operator !=(S1? x, S1? y) { System.Console.Write(""!=""); return false; } } class C1 { public S1 Goo() { return new S1(); } } public static void Main() { System.Console.WriteLine(TestEq(null, new S1())); System.Console.WriteLine(TestEq(new C1(), new S1())); System.Console.WriteLine(TestNeq(null, new S1())); System.Console.WriteLine(TestNeq(new C1(), new S1())); } static bool TestEq(C1 c, S1 arg) { return c?.Goo() == arg; } static bool TestNeq(C1 c, S1 arg) { return c?.Goo() != arg; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"==True ==True !=False !=False"); verifier.VerifyIL("C.TestNeq", @" { // Code size 37 (0x25) .maxstack 2 .locals init (C.S1? V_0) IL_0000: ldarg.0 IL_0001: brtrue.s IL_000e IL_0003: ldloca.s V_0 IL_0005: initobj ""C.S1?"" IL_000b: ldloc.0 IL_000c: br.s IL_0019 IL_000e: ldarg.0 IL_000f: call ""C.S1 C.C1.Goo()"" IL_0014: newobj ""C.S1?..ctor(C.S1)"" IL_0019: ldarg.1 IL_001a: newobj ""C.S1?..ctor(C.S1)"" IL_001f: call ""bool C.S1.op_Inequality(C.S1?, C.S1?)"" IL_0024: ret }"); } [Fact] public void ConditionalUserDef01n() { var source = @" class C { struct S1 { public static bool operator ==(S1? x, S1?y) { System.Console.Write(""==""); return true; } public static bool operator !=(S1? x, S1? y) { System.Console.Write(""!=""); return false; } } class C1 { public S1 Goo() { return new S1(); } } public static void Main() { System.Console.WriteLine(TestEq(null, new S1())); System.Console.WriteLine(TestEq(new C1(), new S1())); System.Console.WriteLine(TestEq(new C1(), null)); System.Console.WriteLine(TestNeq(null, new S1())); System.Console.WriteLine(TestNeq(new C1(), new S1())); System.Console.WriteLine(TestNeq(new C1(), null)); } static bool TestEq(C1 c, S1? arg) { return c?.Goo() == arg; } static bool TestNeq(C1 c, S1? arg) { return c?.Goo() != arg; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"==True ==True ==True !=False !=False !=False"); verifier.VerifyIL("C.TestNeq", @" { // Code size 32 (0x20) .maxstack 2 .locals init (C.S1? V_0) IL_0000: ldarg.0 IL_0001: brtrue.s IL_000e IL_0003: ldloca.s V_0 IL_0005: initobj ""C.S1?"" IL_000b: ldloc.0 IL_000c: br.s IL_0019 IL_000e: ldarg.0 IL_000f: call ""C.S1 C.C1.Goo()"" IL_0014: newobj ""C.S1?..ctor(C.S1)"" IL_0019: ldarg.1 IL_001a: call ""bool C.S1.op_Inequality(C.S1?, C.S1?)"" IL_001f: ret }"); } [Fact] public void ConditionalUserDef02() { var source = @" class C { struct S1 { public static bool operator ==(S1 x, S1 y) { System.Console.Write(""==""); return true; } public static bool operator !=(S1 x, S1 y) { System.Console.Write(""!=""); return false; } } class C1 { public S1 Goo() { return new S1(); } } public static void Main() { System.Console.WriteLine(TestEq(null, new S1())); System.Console.WriteLine(TestEq(new C1(), new S1())); System.Console.WriteLine(TestNeq(null, new S1())); System.Console.WriteLine(TestNeq(new C1(), new S1())); } static bool TestEq(C1 c, S1 arg) { return c?.Goo() == arg; } static bool TestNeq(C1 c, S1 arg) { return c?.Goo() != arg; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"False ==True True !=False"); verifier.VerifyIL("C.TestNeq", @" { // Code size 18 (0x12) .maxstack 2 IL_0000: ldarg.0 IL_0001: brtrue.s IL_0005 IL_0003: ldc.i4.1 IL_0004: ret IL_0005: ldarg.0 IL_0006: call ""C.S1 C.C1.Goo()"" IL_000b: ldarg.1 IL_000c: call ""bool C.S1.op_Inequality(C.S1, C.S1)"" IL_0011: ret }"); } [Fact] public void ConditionalUserDef02n() { var source = @" class C { struct S1 { public static bool operator ==(S1 x, S1 y) { System.Console.Write(""==""); return true; } public static bool operator !=(S1 x, S1 y) { System.Console.Write(""!=""); return false; } } class C1 { public S1 Goo() { return new S1(); } } public static void Main() { System.Console.WriteLine(TestEq(null, new S1())); System.Console.WriteLine(TestEq(new C1(), new S1())); System.Console.WriteLine(TestEq(new C1(), null)); System.Console.WriteLine(TestNeq(null, new S1())); System.Console.WriteLine(TestNeq(new C1(), new S1())); System.Console.WriteLine(TestNeq(new C1(), null)); } static bool TestEq(C1 c, S1? arg) { return c?.Goo() == arg; } static bool TestNeq(C1 c, S1? arg) { return c?.Goo() != arg; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"False ==True False True !=False True"); verifier.VerifyIL("C.TestNeq", @" { // Code size 45 (0x2d) .maxstack 2 .locals init (C.S1 V_0, C.S1? V_1) IL_0000: ldarg.0 IL_0001: brtrue.s IL_000b IL_0003: ldarga.s V_1 IL_0005: call ""bool C.S1?.HasValue.get"" IL_000a: ret IL_000b: ldarg.0 IL_000c: call ""C.S1 C.C1.Goo()"" IL_0011: stloc.0 IL_0012: ldarg.1 IL_0013: stloc.1 IL_0014: ldloca.s V_1 IL_0016: call ""bool C.S1?.HasValue.get"" IL_001b: brtrue.s IL_001f IL_001d: ldc.i4.1 IL_001e: ret IL_001f: ldloc.0 IL_0020: ldloca.s V_1 IL_0022: call ""C.S1 C.S1?.GetValueOrDefault()"" IL_0027: call ""bool C.S1.op_Inequality(C.S1, C.S1)"" IL_002c: ret }"); } [Fact] public void Bug1() { var source = @" using System; class Test { static void Main() { var c1 = new C1(); M1(c1); M2(c1); } static void M1(C1 c1) { if (c1?.P == 1) Console.WriteLine(1); } static void M2(C1 c1) { if (c1 != null && c1.P == 1) Console.WriteLine(1); } } class C1 { public int P => 1; } "; var comp = CompileAndVerify(source, expectedOutput: @"1 1"); comp.VerifyIL("Test.M1", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: brfalse.s IL_0012 IL_0003: ldarg.0 IL_0004: call ""int C1.P.get"" IL_0009: ldc.i4.1 IL_000a: bne.un.s IL_0012 IL_000c: ldc.i4.1 IL_000d: call ""void System.Console.WriteLine(int)"" IL_0012: ret } "); comp.VerifyIL("Test.M2", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: brfalse.s IL_0012 IL_0003: ldarg.0 IL_0004: callvirt ""int C1.P.get"" IL_0009: ldc.i4.1 IL_000a: bne.un.s IL_0012 IL_000c: ldc.i4.1 IL_000d: call ""void System.Console.WriteLine(int)"" IL_0012: ret } "); } [Fact] public void ConditionalBoolExpr02ba() { var source = @" class C { public static void Main() { System.Console.Write(NotHasLength(null, 0)); System.Console.Write(NotHasLength(null, 3)); System.Console.Write(NotHasLength(1, 2)); } static bool NotHasLength(int? s, int len) { return s?.GetHashCode() + 1 != len; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"TrueTrueFalse"); verifier.VerifyIL("C.NotHasLength", @" { // Code size 35 (0x23) .maxstack 2 .locals init (int V_0) IL_0000: ldarga.s V_0 IL_0002: call ""bool int?.HasValue.get"" IL_0007: brtrue.s IL_000b IL_0009: ldc.i4.1 IL_000a: ret IL_000b: ldarga.s V_0 IL_000d: call ""int int?.GetValueOrDefault()"" IL_0012: stloc.0 IL_0013: ldloca.s V_0 IL_0015: call ""int int.GetHashCode()"" IL_001a: ldc.i4.1 IL_001b: add IL_001c: ldarg.1 IL_001d: ceq IL_001f: ldc.i4.0 IL_0020: ceq IL_0022: ret } "); } [Fact] public void ConditionalBoolExpr02bb() { var source = @" class C { public static void Main() { System.Console.Write(NotHasLength(null, 0)); System.Console.Write(NotHasLength(null, 3)); System.Console.Write(NotHasLength(1, 2)); System.Console.Write(NotHasLength(null, null)); } static bool NotHasLength(int? s, int? len) { return s?.GetHashCode() + 1 != len; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"TrueTrueFalseFalse"); verifier.VerifyIL("C.NotHasLength", @" { // Code size 57 (0x39) .maxstack 2 .locals init (int? V_0, int V_1) IL_0000: ldarga.s V_0 IL_0002: call ""bool int?.HasValue.get"" IL_0007: brtrue.s IL_0011 IL_0009: ldarga.s V_1 IL_000b: call ""bool int?.HasValue.get"" IL_0010: ret IL_0011: ldarga.s V_0 IL_0013: call ""int int?.GetValueOrDefault()"" IL_0018: stloc.1 IL_0019: ldloca.s V_1 IL_001b: call ""int int.GetHashCode()"" IL_0020: ldc.i4.1 IL_0021: add IL_0022: ldarg.1 IL_0023: stloc.0 IL_0024: ldloca.s V_0 IL_0026: call ""int int?.GetValueOrDefault()"" IL_002b: ceq IL_002d: ldloca.s V_0 IL_002f: call ""bool int?.HasValue.get"" IL_0034: and IL_0035: ldc.i4.0 IL_0036: ceq IL_0038: ret }"); } [Fact] public void ConditionalUnary() { var source = @" class C { public static void Main() { var x = - - -((string)null)?.Length ?? - - -string.Empty?.Length; System.Console.WriteLine(x); } } "; var verifier = CompileAndVerify(source, expectedOutput: @"0"); verifier.VerifyIL("C.Main", @" { // Code size 44 (0x2c) .maxstack 2 .locals init (int? V_0) IL_0000: ldsfld ""string string.Empty"" IL_0005: dup IL_0006: brtrue.s IL_0014 IL_0008: pop IL_0009: ldloca.s V_0 IL_000b: initobj ""int?"" IL_0011: ldloc.0 IL_0012: br.s IL_0021 IL_0014: call ""int string.Length.get"" IL_0019: neg IL_001a: neg IL_001b: neg IL_001c: newobj ""int?..ctor(int)"" IL_0021: box ""int?"" IL_0026: call ""void System.Console.WriteLine(object)"" IL_002b: ret } "); } [WorkItem(7388, "https://github.com/dotnet/roslyn/issues/7388")] [Fact] public void ConditionalClassConstrained001() { var source = @" using System; namespace ConsoleApplication9 { class Program { static void Main(string[] args) { var v = new A<object>(); System.Console.WriteLine(A<object>.Test(v)); } public class A<T> : object where T : class { public T Value { get { return (T)(object)42; }} public static T Test(A<T> val) { return val?.Value; } } } } "; var verifier = CompileAndVerify(source, expectedOutput: @"42"); verifier.VerifyIL("ConsoleApplication9.Program.A<T>.Test(ConsoleApplication9.Program.A<T>)", @" { // Code size 20 (0x14) .maxstack 1 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: brtrue.s IL_000d IL_0003: ldloca.s V_0 IL_0005: initobj ""T"" IL_000b: ldloc.0 IL_000c: ret IL_000d: ldarg.0 IL_000e: call ""T ConsoleApplication9.Program.A<T>.Value.get"" IL_0013: ret }"); } [Fact, WorkItem(15670, "https://github.com/dotnet/roslyn/issues/15670")] public void ConditionalAccessOffOfUnconstrainedDefault1() { var source = @" using System; public class Test<T> { public string Run() { return default(T)?.ToString(); } } class Program { static void Main() { Console.WriteLine(""--""); Console.WriteLine(new Test<string>().Run()); Console.WriteLine(""--""); Console.WriteLine(new Test<int>().Run()); Console.WriteLine(""--""); } } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"-- -- 0 --"); verifier.VerifyIL("Test<T>.Run", @" { // Code size 45 (0x2d) .maxstack 2 .locals init (T V_0, string V_1) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: initobj ""T"" IL_0009: ldloc.0 IL_000a: box ""T"" IL_000f: brtrue.s IL_0014 IL_0011: ldnull IL_0012: br.s IL_0028 IL_0014: ldloca.s V_0 IL_0016: dup IL_0017: initobj ""T"" IL_001d: constrained. ""T"" IL_0023: callvirt ""string object.ToString()"" IL_0028: stloc.1 IL_0029: br.s IL_002b IL_002b: ldloc.1 IL_002c: ret }"); } [Fact, WorkItem(15670, "https://github.com/dotnet/roslyn/issues/15670")] public void ConditionalAccessOffOfUnconstrainedDefault2() { var source = @" using System; public class Test<T> { public string Run() { var v = default(T); return v?.ToString(); } } class Program { static void Main() { Console.WriteLine(""--""); Console.WriteLine(new Test<string>().Run()); Console.WriteLine(""--""); Console.WriteLine(new Test<int>().Run()); Console.WriteLine(""--""); } } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"-- -- 0 --"); verifier.VerifyIL("Test<T>.Run", @" { // Code size 38 (0x26) .maxstack 1 .locals init (T V_0, //v string V_1) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: initobj ""T"" IL_0009: ldloc.0 IL_000a: box ""T"" IL_000f: brtrue.s IL_0014 IL_0011: ldnull IL_0012: br.s IL_0021 IL_0014: ldloca.s V_0 IL_0016: constrained. ""T"" IL_001c: callvirt ""string object.ToString()"" IL_0021: stloc.1 IL_0022: br.s IL_0024 IL_0024: ldloc.1 IL_0025: ret }"); } [Fact, WorkItem(15670, "https://github.com/dotnet/roslyn/issues/15670")] public void ConditionalAccessOffOfInterfaceConstrainedDefault1() { var source = @" using System; public class Test<T> where T : IComparable { public string Run() { return default(T)?.ToString(); } } class Program { static void Main() { Console.WriteLine(""--""); Console.WriteLine(new Test<string>().Run()); Console.WriteLine(""--""); Console.WriteLine(new Test<int>().Run()); Console.WriteLine(""--""); } } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"-- -- 0 --"); verifier.VerifyIL("Test<T>.Run", @" { // Code size 45 (0x2d) .maxstack 2 .locals init (T V_0, string V_1) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: initobj ""T"" IL_0009: ldloc.0 IL_000a: box ""T"" IL_000f: brtrue.s IL_0014 IL_0011: ldnull IL_0012: br.s IL_0028 IL_0014: ldloca.s V_0 IL_0016: dup IL_0017: initobj ""T"" IL_001d: constrained. ""T"" IL_0023: callvirt ""string object.ToString()"" IL_0028: stloc.1 IL_0029: br.s IL_002b IL_002b: ldloc.1 IL_002c: ret }"); } [Fact, WorkItem(15670, "https://github.com/dotnet/roslyn/issues/15670")] public void ConditionalAccessOffOfInterfaceConstrainedDefault2() { var source = @" using System; public class Test<T> where T : IComparable { public string Run() { var v = default(T); return v?.ToString(); } } class Program { static void Main() { Console.WriteLine(""--""); Console.WriteLine(new Test<string>().Run()); Console.WriteLine(""--""); Console.WriteLine(new Test<int>().Run()); Console.WriteLine(""--""); } } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"-- -- 0 --"); verifier.VerifyIL("Test<T>.Run", @" { // Code size 38 (0x26) .maxstack 1 .locals init (T V_0, //v string V_1) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: initobj ""T"" IL_0009: ldloc.0 IL_000a: box ""T"" IL_000f: brtrue.s IL_0014 IL_0011: ldnull IL_0012: br.s IL_0021 IL_0014: ldloca.s V_0 IL_0016: constrained. ""T"" IL_001c: callvirt ""string object.ToString()"" IL_0021: stloc.1 IL_0022: br.s IL_0024 IL_0024: ldloc.1 IL_0025: ret }"); } [Fact, WorkItem(15670, "https://github.com/dotnet/roslyn/issues/15670")] public void ConditionalAccessOffOfClassConstrainedDefault1() { var source = @" using System; public class Test<T> where T : class { public string Run() { return default(T)?.ToString(); } } class Program { static void Main() { Console.WriteLine(""--""); Console.WriteLine(new Test<string>().Run()); Console.WriteLine(""--""); } } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"-- --"); verifier.VerifyIL("Test<T>.Run", @" { // Code size 7 (0x7) .maxstack 1 .locals init (string V_0) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: br.s IL_0005 IL_0005: ldloc.0 IL_0006: ret }"); } [Fact, WorkItem(15670, "https://github.com/dotnet/roslyn/issues/15670")] public void ConditionalAccessOffOfClassConstrainedDefault2() { var source = @" using System; public class Test<T> where T : class { public string Run() { var v = default(T); return v?.ToString(); } } class Program { static void Main() { Console.WriteLine(""--""); Console.WriteLine(new Test<string>().Run()); Console.WriteLine(""--""); } } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"-- --"); verifier.VerifyIL("Test<T>.Run", @" { // Code size 32 (0x20) .maxstack 2 .locals init (T V_0, //v string V_1) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: initobj ""T"" IL_0009: ldloc.0 IL_000a: box ""T"" IL_000f: dup IL_0010: brtrue.s IL_0016 IL_0012: pop IL_0013: ldnull IL_0014: br.s IL_001b IL_0016: callvirt ""string object.ToString()"" IL_001b: stloc.1 IL_001c: br.s IL_001e IL_001e: ldloc.1 IL_001f: ret }"); } [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void ConditionalAccessOffReadOnlyNullable1() { var source = @" using System; class Program { private static readonly Guid? g = null; static void Main() { Console.WriteLine(g?.ToString()); } } "; var comp = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"", verify: Verification.Fails); comp.VerifyIL("Program.Main", @" { // Code size 44 (0x2c) .maxstack 2 .locals init (System.Guid V_0) IL_0000: nop IL_0001: ldsflda ""System.Guid? Program.g"" IL_0006: dup IL_0007: call ""bool System.Guid?.HasValue.get"" IL_000c: brtrue.s IL_0012 IL_000e: pop IL_000f: ldnull IL_0010: br.s IL_0025 IL_0012: call ""System.Guid System.Guid?.GetValueOrDefault()"" IL_0017: stloc.0 IL_0018: ldloca.s V_0 IL_001a: constrained. ""System.Guid"" IL_0020: callvirt ""string object.ToString()"" IL_0025: call ""void System.Console.WriteLine(string)"" IL_002a: nop IL_002b: ret }"); comp = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @"", parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes); comp.VerifyIL("Program.Main", @" { // Code size 47 (0x2f) .maxstack 2 .locals init (System.Guid? V_0, System.Guid V_1) IL_0000: nop IL_0001: ldsfld ""System.Guid? Program.g"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: dup IL_000a: call ""bool System.Guid?.HasValue.get"" IL_000f: brtrue.s IL_0015 IL_0011: pop IL_0012: ldnull IL_0013: br.s IL_0028 IL_0015: call ""System.Guid System.Guid?.GetValueOrDefault()"" IL_001a: stloc.1 IL_001b: ldloca.s V_1 IL_001d: constrained. ""System.Guid"" IL_0023: callvirt ""string object.ToString()"" IL_0028: call ""void System.Console.WriteLine(string)"" IL_002d: nop IL_002e: ret }"); } [Fact] public void ConditionalAccessOffReadOnlyNullable2() { var source = @" using System; class Program { static void Main() { Console.WriteLine(default(Guid?)?.ToString()); } } "; var verifier = CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: @""); verifier.VerifyIL("Program.Main", @" { // Code size 55 (0x37) .maxstack 2 .locals init (System.Guid? V_0, System.Guid V_1) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: dup IL_0004: initobj ""System.Guid?"" IL_000a: call ""bool System.Guid?.HasValue.get"" IL_000f: brtrue.s IL_0014 IL_0011: ldnull IL_0012: br.s IL_0030 IL_0014: ldloca.s V_0 IL_0016: dup IL_0017: initobj ""System.Guid?"" IL_001d: call ""System.Guid System.Guid?.GetValueOrDefault()"" IL_0022: stloc.1 IL_0023: ldloca.s V_1 IL_0025: constrained. ""System.Guid"" IL_002b: callvirt ""string object.ToString()"" IL_0030: call ""void System.Console.WriteLine(string)"" IL_0035: nop IL_0036: ret }"); } [Fact] [WorkItem(23351, "https://github.com/dotnet/roslyn/issues/23351")] public void ConditionalAccessOffConstrainedTypeParameter_Property() { var source = @" using System; class Program { static void Main(string[] args) { var obj1 = new MyObject1 { MyDate = new DateTime(636461511000000000L) }; var obj2 = new MyObject2<MyObject1>(obj1); System.Console.WriteLine(obj1.MyDate.Ticks); System.Console.WriteLine(obj2.CurrentDate.Value.Ticks); System.Console.WriteLine(new MyObject2<MyObject1>(null).CurrentDate.HasValue); } } abstract class MyBaseObject1 { public DateTime MyDate { get; set; } } class MyObject1 : MyBaseObject1 { } class MyObject2<MyObjectType> where MyObjectType : MyBaseObject1, new() { public MyObject2(MyObjectType obj) { m_CurrentObject1 = obj; } private MyObjectType m_CurrentObject1 = null; public MyObjectType CurrentObject1 => m_CurrentObject1; public DateTime? CurrentDate => CurrentObject1?.MyDate; } "; var expectedOutput = @" 636461511000000000 636461511000000000 False "; CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } [Fact] [WorkItem(23351, "https://github.com/dotnet/roslyn/issues/23351")] public void ConditionalAccessOffConstrainedTypeParameter_Field() { var source = @" using System; class Program { static void Main(string[] args) { var obj1 = new MyObject1 { MyDate = new DateTime(636461511000000000L) }; var obj2 = new MyObject2<MyObject1>(obj1); System.Console.WriteLine(obj1.MyDate.Ticks); System.Console.WriteLine(obj2.CurrentDate.Value.Ticks); System.Console.WriteLine(new MyObject2<MyObject1>(null).CurrentDate.HasValue); } } abstract class MyBaseObject1 { public DateTime MyDate; } class MyObject1 : MyBaseObject1 { } class MyObject2<MyObjectType> where MyObjectType : MyBaseObject1, new() { public MyObject2(MyObjectType obj) { m_CurrentObject1 = obj; } private MyObjectType m_CurrentObject1 = null; public MyObjectType CurrentObject1 => m_CurrentObject1; public DateTime? CurrentDate => CurrentObject1?.MyDate; } "; var expectedOutput = @" 636461511000000000 636461511000000000 False "; CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: expectedOutput); CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expectedOutput); } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/EditorFeatures/VisualBasic/Highlighting/KeywordHighlighters/PropertyBlockHighlighter.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.ComponentModel.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.Implementation.Highlighting Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting <ExportHighlighter(LanguageNames.VisualBasic)> Friend Class PropertyBlockHighlighter Inherits AbstractKeywordHighlighter(Of SyntaxNode) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overloads Overrides Sub AddHighlights(node As SyntaxNode, highlights As List(Of TextSpan), cancellationToken As CancellationToken) Dim propertyBlock = node.GetAncestor(Of PropertyBlockSyntax)() If propertyBlock Is Nothing Then Return End If With propertyBlock With .PropertyStatement Dim firstKeyword = If(.Modifiers.Count > 0, .Modifiers.First(), .DeclarationKeyword) highlights.Add(TextSpan.FromBounds(firstKeyword.SpanStart, .DeclarationKeyword.Span.End)) If .ImplementsClause IsNot Nothing Then highlights.Add(.ImplementsClause.ImplementsKeyword.Span) End If End With highlights.Add(.EndPropertyStatement.Span) End With 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.ComponentModel.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.Implementation.Highlighting Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting <ExportHighlighter(LanguageNames.VisualBasic)> Friend Class PropertyBlockHighlighter Inherits AbstractKeywordHighlighter(Of SyntaxNode) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overloads Overrides Sub AddHighlights(node As SyntaxNode, highlights As List(Of TextSpan), cancellationToken As CancellationToken) Dim propertyBlock = node.GetAncestor(Of PropertyBlockSyntax)() If propertyBlock Is Nothing Then Return End If With propertyBlock With .PropertyStatement Dim firstKeyword = If(.Modifiers.Count > 0, .Modifiers.First(), .DeclarationKeyword) highlights.Add(TextSpan.FromBounds(firstKeyword.SpanStart, .DeclarationKeyword.Span.End)) If .ImplementsClause IsNot Nothing Then highlights.Add(.ImplementsClause.ImplementsKeyword.Span) End If End With highlights.Add(.EndPropertyStatement.Span) End With End Sub End Class End Namespace
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./eng/test-build-correctness.ps1
<# This script drives the Jenkins verification that our build is correct. In particular: - Our build has no double writes - Our project.json files are consistent - Our build files are well structured - Our solution states are consistent - Our generated files are consistent #> [CmdletBinding(PositionalBinding=$false)] param( [string]$configuration = "Debug", [switch]$enableDumps = $false, [switch]$help) Set-StrictMode -version 2.0 $ErrorActionPreference="Stop" function Print-Usage() { Write-Host "Usage: test-build-correctness.ps1" Write-Host " -configuration Build configuration ('Debug' or 'Release')" } try { if ($help) { Print-Usage exit 0 } $ci = $true . (Join-Path $PSScriptRoot "build-utils.ps1") Push-Location $RepoRoot if ($enableDumps) { $key = "HKLM:\\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps" New-Item -Path $key -ErrorAction SilentlyContinue New-ItemProperty -Path $key -Name 'DumpType' -PropertyType 'DWord' -Value 2 -Force New-ItemProperty -Path $key -Name 'DumpCount' -PropertyType 'DWord' -Value 2 -Force New-ItemProperty -Path $key -Name 'DumpFolder' -PropertyType 'String' -Value $LogDir -Force } # Verify no PROTOTYPE marker left in main if ($env:SYSTEM_PULLREQUEST_TARGETBRANCH -eq "main") { Write-Host "Checking no PROTOTYPE markers in source" $prototypes = Get-ChildItem -Path src, eng, scripts -Exclude *.dll,*.exe,*.pdb,*.xlf,test-build-correctness.ps1 -Recurse | Select-String -Pattern 'PROTOTYPE' -CaseSensitive -SimpleMatch if ($prototypes) { Write-Host "Found PROTOTYPE markers in source:" Write-Host $prototypes throw "PROTOTYPE markers disallowed in compiler source" } } Write-Host "Building Roslyn" Exec-Block { & (Join-Path $PSScriptRoot "build.ps1") -restore -build -bootstrap -bootstrapConfiguration:Debug -ci:$ci -runAnalyzers:$true -configuration:$configuration -pack -binaryLog -useGlobalNuGetCache:$false -warnAsError:$true -properties "/p:RoslynEnforceCodeStyle=true"} # Verify the state of our various build artifacts Write-Host "Running BuildBoss" $buildBossPath = GetProjectOutputBinary "BuildBoss.exe" Exec-Console $buildBossPath "-r `"$RepoRoot/`" -c $configuration" -p Roslyn.sln Write-Host "" # Verify the state of our generated syntax files Write-Host "Checking generated compiler files" Exec-Block { & (Join-Path $PSScriptRoot "generate-compiler-code.ps1") -test -configuration:$configuration } Exec-Console dotnet "tool run dotnet-format . --include-generated --include src/Compilers/CSharp/Portable/Generated/ src/Compilers/VisualBasic/Portable/Generated/ src/ExpressionEvaluator/VisualBasic/Source/ResultProvider/Generated/ --check -f" Write-Host "" exit 0 } catch [exception] { Write-Host $_ Write-Host $_.Exception exit 1 } finally { if ($enableDumps) { $key = "HKLM:\\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps" Remove-ItemProperty -Path $key -Name 'DumpType' Remove-ItemProperty -Path $key -Name 'DumpCount' Remove-ItemProperty -Path $key -Name 'DumpFolder' } Pop-Location }
<# This script drives the Jenkins verification that our build is correct. In particular: - Our build has no double writes - Our project.json files are consistent - Our build files are well structured - Our solution states are consistent - Our generated files are consistent #> [CmdletBinding(PositionalBinding=$false)] param( [string]$configuration = "Debug", [switch]$enableDumps = $false, [switch]$help) Set-StrictMode -version 2.0 $ErrorActionPreference="Stop" function Print-Usage() { Write-Host "Usage: test-build-correctness.ps1" Write-Host " -configuration Build configuration ('Debug' or 'Release')" } try { if ($help) { Print-Usage exit 0 } $ci = $true . (Join-Path $PSScriptRoot "build-utils.ps1") Push-Location $RepoRoot if ($enableDumps) { $key = "HKLM:\\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps" New-Item -Path $key -ErrorAction SilentlyContinue New-ItemProperty -Path $key -Name 'DumpType' -PropertyType 'DWord' -Value 2 -Force New-ItemProperty -Path $key -Name 'DumpCount' -PropertyType 'DWord' -Value 2 -Force New-ItemProperty -Path $key -Name 'DumpFolder' -PropertyType 'String' -Value $LogDir -Force } # Verify no PROTOTYPE marker left in main if ($env:SYSTEM_PULLREQUEST_TARGETBRANCH -eq "main") { Write-Host "Checking no PROTOTYPE markers in source" $prototypes = Get-ChildItem -Path src, eng, scripts -Exclude *.dll,*.exe,*.pdb,*.xlf,test-build-correctness.ps1 -Recurse | Select-String -Pattern 'PROTOTYPE' -CaseSensitive -SimpleMatch if ($prototypes) { Write-Host "Found PROTOTYPE markers in source:" Write-Host $prototypes throw "PROTOTYPE markers disallowed in compiler source" } } Write-Host "Building Roslyn" Exec-Block { & (Join-Path $PSScriptRoot "build.ps1") -restore -build -bootstrap -bootstrapConfiguration:Debug -ci:$ci -runAnalyzers:$true -configuration:$configuration -pack -binaryLog -useGlobalNuGetCache:$false -warnAsError:$true -properties "/p:RoslynEnforceCodeStyle=true"} # Verify the state of our various build artifacts Write-Host "Running BuildBoss" $buildBossPath = GetProjectOutputBinary "BuildBoss.exe" Exec-Console $buildBossPath "-r `"$RepoRoot/`" -c $configuration" -p Roslyn.sln Write-Host "" # Verify the state of our generated syntax files Write-Host "Checking generated compiler files" Exec-Block { & (Join-Path $PSScriptRoot "generate-compiler-code.ps1") -test -configuration:$configuration } Exec-Console dotnet "tool run dotnet-format . --include-generated --include src/Compilers/CSharp/Portable/Generated/ src/Compilers/VisualBasic/Portable/Generated/ src/ExpressionEvaluator/VisualBasic/Source/ResultProvider/Generated/ --check -f" Write-Host "" exit 0 } catch [exception] { Write-Host $_ Write-Host $_.Exception exit 1 } finally { if ($enableDumps) { $key = "HKLM:\\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps" Remove-ItemProperty -Path $key -Name 'DumpType' Remove-ItemProperty -Path $key -Name 'DumpCount' Remove-ItemProperty -Path $key -Name 'DumpFolder' } Pop-Location }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/TriviaDataFactory.FormattedComplexTrivia.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.Threading; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Formatting { internal partial class TriviaDataFactory { private class FormattedComplexTrivia : TriviaDataWithList { private readonly CSharpTriviaFormatter _formatter; private readonly IList<TextChange> _textChanges; public FormattedComplexTrivia( FormattingContext context, ChainedFormattingRules formattingRules, SyntaxToken token1, SyntaxToken token2, int lineBreaks, int spaces, string originalString, CancellationToken cancellationToken) : base(context.Options, LanguageNames.CSharp) { Contract.ThrowIfNull(context); Contract.ThrowIfNull(formattingRules); Contract.ThrowIfNull(originalString); this.LineBreaks = Math.Max(0, lineBreaks); this.Spaces = Math.Max(0, spaces); _formatter = new CSharpTriviaFormatter(context, formattingRules, token1, token2, originalString, this.LineBreaks, this.Spaces); _textChanges = _formatter.FormatToTextChanges(cancellationToken); } public override bool TreatAsElastic { get { return false; } } public override bool IsWhitespaceOnlyTrivia { get { return false; } } public override bool ContainsChanges { get { return _textChanges.Count > 0; } } public override IEnumerable<TextChange> GetTextChanges(TextSpan span) => _textChanges; public override SyntaxTriviaList GetTriviaList(CancellationToken cancellationToken) => _formatter.FormatToSyntaxTrivia(cancellationToken); public override TriviaData WithSpace(int space, FormattingContext context, ChainedFormattingRules formattingRules) => throw new NotImplementedException(); public override TriviaData WithLine(int line, int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken) => throw new NotImplementedException(); public override TriviaData WithIndentation(int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken) => throw new NotImplementedException(); public override void Format(FormattingContext context, ChainedFormattingRules formattingRules, Action<int, TokenStream, TriviaData> formattingResultApplier, CancellationToken cancellationToken, int tokenPairIndex = TokenPairIndexNotNeeded) => throw new NotImplementedException(); } } }
// Licensed to the .NET Foundation under one or more 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.Threading; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Formatting { internal partial class TriviaDataFactory { private class FormattedComplexTrivia : TriviaDataWithList { private readonly CSharpTriviaFormatter _formatter; private readonly IList<TextChange> _textChanges; public FormattedComplexTrivia( FormattingContext context, ChainedFormattingRules formattingRules, SyntaxToken token1, SyntaxToken token2, int lineBreaks, int spaces, string originalString, CancellationToken cancellationToken) : base(context.Options, LanguageNames.CSharp) { Contract.ThrowIfNull(context); Contract.ThrowIfNull(formattingRules); Contract.ThrowIfNull(originalString); this.LineBreaks = Math.Max(0, lineBreaks); this.Spaces = Math.Max(0, spaces); _formatter = new CSharpTriviaFormatter(context, formattingRules, token1, token2, originalString, this.LineBreaks, this.Spaces); _textChanges = _formatter.FormatToTextChanges(cancellationToken); } public override bool TreatAsElastic { get { return false; } } public override bool IsWhitespaceOnlyTrivia { get { return false; } } public override bool ContainsChanges { get { return _textChanges.Count > 0; } } public override IEnumerable<TextChange> GetTextChanges(TextSpan span) => _textChanges; public override SyntaxTriviaList GetTriviaList(CancellationToken cancellationToken) => _formatter.FormatToSyntaxTrivia(cancellationToken); public override TriviaData WithSpace(int space, FormattingContext context, ChainedFormattingRules formattingRules) => throw new NotImplementedException(); public override TriviaData WithLine(int line, int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken) => throw new NotImplementedException(); public override TriviaData WithIndentation(int indentation, FormattingContext context, ChainedFormattingRules formattingRules, CancellationToken cancellationToken) => throw new NotImplementedException(); public override void Format(FormattingContext context, ChainedFormattingRules formattingRules, Action<int, TokenStream, TriviaData> formattingResultApplier, CancellationToken cancellationToken, int tokenPairIndex = TokenPairIndexNotNeeded) => throw new NotImplementedException(); } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Compilers/CSharp/Test/Semantic/Semantics/StructsTests.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 Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { public class StructsTests : CompilingTestBase { [WorkItem(540982, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540982")] [Fact()] public void TestInitFieldStruct() { var text = @" public struct A { A a = new A(); // CS8036 public static int Main() { return 1; } } "; CreateCompilation(text, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (4,7): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // A a = new A(); // CS8036 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "a").WithArguments("struct field initializers", "10.0").WithLocation(4, 7), // (4,7): error CS0523: Struct member 'A.a' of type 'A' causes a cycle in the struct layout // A a = new A(); // CS8036 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "a").WithArguments("A.a", "A").WithLocation(4, 7), // (4,7): warning CS0414: The field 'A.a' is assigned but its value is never used // A a = new A(); // CS8036 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "a").WithArguments("A.a").WithLocation(4, 7)); } [WorkItem(1075325, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1075325"), WorkItem(343, "CodePlex")] [Fact()] public void TestInitEventStruct() { var text = @" struct S { event System.Action E = null; void M() { E(); } } "; CreateCompilation(text, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (3,25): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // event System.Action E = null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "E").WithArguments("struct field initializers", "10.0").WithLocation(3, 25)); CreateCompilation(text).VerifyDiagnostics(); } [WorkItem(1075325, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1075325"), WorkItem(343, "CodePlex")] [Fact()] public void TestStaticInitInStruct() { var text = @" struct S { static event System.Action E = M; static int F = 10; static int P {get; set;} = 20; static void M() { } static void Main() { System.Console.WriteLine(""{0} {1} {2}"", S.F, S.P, S.E == null); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "10 20 False").VerifyDiagnostics(); } // Test constructor forwarding works for structs [WorkItem(540896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540896")] [Fact] public void TestConstructorStruct() { var text = @" struct Goo { public Goo(int x) : this(5, 6) { } public Goo(int x, int y) { m_x = x; m_y = y; } public int m_x; public int m_y; public static void Main() { } } "; CompileAndVerify(text).VerifyDiagnostics(); } // Calling struct default constructor in another constructor [WorkItem(540896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540896")] [Fact] public void TestConstructorStruct02() { var text = @" public struct Struct { public int x; public Struct(int x) : this() { this.x = x; } public static void Main() { } } "; CompileAndVerify(text).VerifyDiagnostics(); } // Test constructor forwarding works for structs [WorkItem(540896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540896")] [Fact] public void TestConstructorStruct03() { var text = @" struct S { public int i; public int j; public S(int x) { j = i = x; Init(x); } void Init(int x) { } public void Set(S s) { s.Copy(out this); } public void CopySelf() { this.Copy(out this); } public void Copy(out S s) { s = this; } } class Program { static void Main(string[] args) { S s; s.i = 0; s.j = 1; S s2 = s; s2.i = 2; s.Set(s2); System.Console.Write(s.i); s.CopySelf(); System.Console.Write(s.i); } } "; CompileAndVerify(text, expectedOutput: "22").VerifyDiagnostics(); } // Overriding base System.Object methods on struct [WorkItem(20496, "https://github.com/dotnet/roslyn/issues/20496")] [WorkItem(540990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540990")] [ClrOnlyFact(ClrOnlyReason.MemberOrder)] public void TestOverridingBaseConstructorStruct() { var text = @" using System; public struct Gen<T> { public override bool Equals(object obj) { Console.WriteLine(""Gen{0}::Equals"", typeof(T)); return base.Equals(obj); } public override int GetHashCode() { Console.WriteLine(""Gen{0}::GetHashCode"", typeof(T)); return base.GetHashCode(); } public override string ToString() { Console.WriteLine(""Gen{0}::ToString"", typeof(T)); return base.ToString(); } } public struct S { public override bool Equals(object obj) { Console.WriteLine(""S::Equals""); return base.Equals(obj); } public override int GetHashCode() { Console.WriteLine(""S::GetHashCode""); return base.GetHashCode(); } public override string ToString() { Console.WriteLine(""S::ToString""); return base.ToString(); } } public class Test { public static int counter = 0; public static bool result = true; public static void Eval(bool exp) { counter++; if (!exp) { result = exp; Console.WriteLine(""Test Failed at location: "" + counter); } } public static void Main() { Gen<int> gInt = new Gen<int>(); Test.Eval(gInt.Equals(null) == false); Test.Eval(gInt.GetHashCode() == gInt.GetHashCode()); Test.Eval(gInt.ToString() == ""Gen`1[System.Int32]""); Gen<object> gObject = new Gen<object>(); Test.Eval(gObject.Equals(null) == false); Test.Eval(gObject.GetHashCode() == gObject.GetHashCode()); Test.Eval(gObject.ToString() == ""Gen`1[System.Object]""); S s = new S(); Test.Eval(s.Equals(null) == false); Test.Eval(s.GetHashCode() == s.GetHashCode()); Test.Eval(s.ToString() == ""S""); } } "; var expectedOutput = @"GenSystem.Int32::Equals GenSystem.Int32::GetHashCode GenSystem.Int32::GetHashCode GenSystem.Int32::ToString GenSystem.Object::Equals GenSystem.Object::GetHashCode GenSystem.Object::GetHashCode GenSystem.Object::ToString S::Equals S::GetHashCode S::GetHashCode S::ToString"; CompileAndVerify(text, expectedOutput: expectedOutput); } // Test constructor for generic struct [WorkItem(540993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540993")] [Fact] public void TestConstructorForGenericStruct() { var text = @" using System; struct C<T> { public int num; public int Goo1() { return this.num; } } class Test { static void Main(string[] args) { C<object> c; c.num = 1; bool verify = c.Goo1() == 1; Console.WriteLine(verify); } } "; var expectedOutput = @"True"; CompileAndVerify(text, expectedOutput: expectedOutput); } // Assign to decimal in struct constructor [WorkItem(540994, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540994")] [Fact] public void TestAssigntoDecimalInStructConstructor() { var text = @" using System; public struct Struct { public decimal Price; public Struct(decimal price) { Price = price; } } class Test { public static void Main() { } } "; var expectedIL = @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""decimal Struct.Price"" IL_0007: ret }"; CompileAndVerify(text).VerifyIL("Struct..ctor(decimal)", expectedIL); } [Fact] public void RetargetedSynthesizedStructConstructor() { var oldMsCorLib = TestMetadata.Net40.mscorlib; var c1 = CSharpCompilation.Create("C1", new[] { Parse(@"public struct S { }") }, new[] { oldMsCorLib }, TestOptions.ReleaseDll); var c2 = CSharpCompilation.Create("C2", new[] { Parse(@"public class C { void M() { S s = new S(); System.Console.WriteLine(s);} }") }, new[] { MscorlibRef, new CSharpCompilationReference(c1) }, TestOptions.ReleaseDll); var c1AsmRef = c2.GetReferencedAssemblySymbol(new CSharpCompilationReference(c1)); Assert.NotSame(c1.Assembly, c1AsmRef); var mscorlibAssembly = c2.GetReferencedAssemblySymbol(MscorlibRef); Assert.NotSame(mscorlibAssembly, c1.GetReferencedAssemblySymbol(oldMsCorLib)); var @struct = c2.GlobalNamespace.GetMember<RetargetingNamedTypeSymbol>("S"); var method = (RetargetingMethodSymbol)@struct.GetMembers().Single(); Assert.True(method.IsDefaultValueTypeConstructor(requireZeroInit: false)); //TODO (tomat) CompileAndVerify(c2).VerifyIL("C.M", @" { // Code size 20 (0x14) .maxstack 1 .locals init (S V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloc.0 IL_0009: box ""S"" IL_000e: call ""void System.Console.WriteLine(object)"" IL_0013: ret }"); } [Fact] public void SubstitutedSynthesizedStructConstructor() { string text = @" public struct S<T> { } public class C { void M() { S<int> s = new S<int>(); System.Console.WriteLine(s); } } "; CompileAndVerify(text).VerifyIL("C.M", @" { // Code size 20 (0x14) .maxstack 1 .locals init (S<int> V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""S<int>"" IL_0008: ldloc.0 IL_0009: box ""S<int>"" IL_000e: call ""void System.Console.WriteLine(object)"" IL_0013: ret }"); } [Fact] public void PublicParameterlessConstructorInMetadata() { string ilSource = @" .class public sequential ansi sealed beforefieldinit S extends [mscorlib]System.ValueType { .pack 0 .size 1 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } "; string csharpSource = @" public class C { void M() { S s = new S(); System.Console.WriteLine(s); s = default(S); System.Console.WriteLine(s); } } "; // Calls constructor (vs initobj), then initobj var compilation = CreateCompilationWithILAndMscorlib40(csharpSource, ilSource); // TODO (tomat) CompileAndVerify(compilation).VerifyIL("C.M", @" { // Code size 35 (0x23) .maxstack 1 .locals init (S V_0) IL_0000: newobj ""S..ctor()"" IL_0005: box ""S"" IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: ldloca.s V_0 IL_0011: initobj ""S"" IL_0017: ldloc.0 IL_0018: box ""S"" IL_001d: call ""void System.Console.WriteLine(object)"" IL_0022: ret }"); } [WorkItem(541309, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541309")] [Fact] public void PrivateParameterlessConstructorInMetadata() { string ilSource = @" .class public sequential ansi sealed beforefieldinit S extends [mscorlib]System.ValueType { .pack 0 .size 1 .method private hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } "; string csharpSource = @" public class C { void M() { S s = new S(); System.Console.WriteLine(s); s = default(S); System.Console.WriteLine(s); } } "; // Uses initobj for both // CONSIDER: This is the dev10 behavior, but it seems like a bug. // Shouldn't there be an error for trying to call an inaccessible ctor? var comp = CreateCompilationWithILAndMscorlib40(csharpSource, ilSource); CompileAndVerify(comp).VerifyIL("C.M", @" { // Code size 39 (0x27) .maxstack 1 .locals init (S V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloc.0 IL_0009: box ""S"" IL_000e: call ""void System.Console.WriteLine(object)"" IL_0013: ldloca.s V_0 IL_0015: initobj ""S"" IL_001b: ldloc.0 IL_001c: box ""S"" IL_0021: call ""void System.Console.WriteLine(object)"" IL_0026: ret }"); } [WorkItem(543934, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543934")] [Fact] public void ObjectCreationExprStructTypeInstanceFieldAssign() { var csSource = @" public struct TestStruct { public int IntI; } public class TestClass { public static void Main() { new TestStruct().IntI = 3; } } "; CreateCompilation(csSource).VerifyDiagnostics( // (13,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "new TestStruct().IntI") ); } [WorkItem(543896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543896")] [Fact] public void ObjectCreationExprStructTypePropertyAssign() { var csSource = @" public struct S { int n; public int P { set { n = value; System.Console.WriteLine(n); } } } public class mem033 { public static void Main() { new S().P = 1; // CS0131 } }"; CreateCompilation(csSource).VerifyDiagnostics( // (14,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // new S().P = 1; // CS0131 Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "new S().P") ); } [WorkItem(545498, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545498")] [Fact] public void StructMemberNullableTypeCausesCycle() { string source = @" public struct X { public X? recursiveFld; } "; CreateCompilation(source, targetFramework: TargetFramework.Mscorlib45).VerifyDiagnostics( // (4,15): error CS0523: Struct member 'X.recursiveFld' of type 'X?' causes a cycle in the struct layout // public X? recursiveFld; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "recursiveFld").WithArguments("X.recursiveFld", "X?") ); } [Fact] public void StructParameterlessCtorNotPublic() { string source = @" public struct X { private X() { } } public struct X1 { X1() { } } "; CreateCompilation(source, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (4,13): error CS8773: Feature 'parameterless struct constructors' is not available in C# 9.0. Please use language version 10.0 or greater. // private X() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "X").WithArguments("parameterless struct constructors", "10.0").WithLocation(4, 13), // (4,13): error CS8938: The parameterless struct constructor must be 'public'. // private X() Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "X").WithLocation(4, 13), // (11,5): error CS8773: Feature 'parameterless struct constructors' is not available in C# 9.0. Please use language version 10.0 or greater. // X1() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "X1").WithArguments("parameterless struct constructors", "10.0").WithLocation(11, 5), // (11,5): error CS8938: The parameterless struct constructor must be 'public'. // X1() Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "X1").WithLocation(11, 5)); CreateCompilation(source).VerifyDiagnostics( // (4,13): error CS8918: The parameterless struct constructor must be 'public'. // private X() Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "X").WithLocation(4, 13), // (11,5): error CS8918: The parameterless struct constructor must be 'public'. // X1() Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "X1").WithLocation(11, 5)); } [Fact] public void StructNonAutoPropertyInitializer() { var text = @"struct S { public int I { get { throw null; } set {} } = 9; }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (3,16): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public int I { get { throw null; } set {} } = 9; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "I").WithArguments("struct field initializers", "10.0").WithLocation(3, 16), // (3,16): error CS8050: Only auto-implemented properties can have initializers. // public int I { get { throw null; } set {} } = 9; Diagnostic(ErrorCode.ERR_InitializerOnNonAutoProperty, "I").WithArguments("S.I").WithLocation(3, 16)); comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,16): error CS8050: Only auto-implemented properties can have initializers. // public int I { get { throw null; } set {} } = 9; Diagnostic(ErrorCode.ERR_InitializerOnNonAutoProperty, "I").WithArguments("S.I").WithLocation(3, 16)); } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { public class StructsTests : CompilingTestBase { [WorkItem(540982, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540982")] [Fact()] public void TestInitFieldStruct() { var text = @" public struct A { A a = new A(); // CS8036 public static int Main() { return 1; } } "; CreateCompilation(text, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (4,7): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // A a = new A(); // CS8036 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "a").WithArguments("struct field initializers", "10.0").WithLocation(4, 7), // (4,7): error CS0523: Struct member 'A.a' of type 'A' causes a cycle in the struct layout // A a = new A(); // CS8036 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "a").WithArguments("A.a", "A").WithLocation(4, 7), // (4,7): warning CS0414: The field 'A.a' is assigned but its value is never used // A a = new A(); // CS8036 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "a").WithArguments("A.a").WithLocation(4, 7)); } [WorkItem(1075325, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1075325"), WorkItem(343, "CodePlex")] [Fact()] public void TestInitEventStruct() { var text = @" struct S { event System.Action E = null; void M() { E(); } } "; CreateCompilation(text, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (3,25): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // event System.Action E = null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "E").WithArguments("struct field initializers", "10.0").WithLocation(3, 25)); CreateCompilation(text).VerifyDiagnostics(); } [WorkItem(1075325, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1075325"), WorkItem(343, "CodePlex")] [Fact()] public void TestStaticInitInStruct() { var text = @" struct S { static event System.Action E = M; static int F = 10; static int P {get; set;} = 20; static void M() { } static void Main() { System.Console.WriteLine(""{0} {1} {2}"", S.F, S.P, S.E == null); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "10 20 False").VerifyDiagnostics(); } // Test constructor forwarding works for structs [WorkItem(540896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540896")] [Fact] public void TestConstructorStruct() { var text = @" struct Goo { public Goo(int x) : this(5, 6) { } public Goo(int x, int y) { m_x = x; m_y = y; } public int m_x; public int m_y; public static void Main() { } } "; CompileAndVerify(text).VerifyDiagnostics(); } // Calling struct default constructor in another constructor [WorkItem(540896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540896")] [Fact] public void TestConstructorStruct02() { var text = @" public struct Struct { public int x; public Struct(int x) : this() { this.x = x; } public static void Main() { } } "; CompileAndVerify(text).VerifyDiagnostics(); } // Test constructor forwarding works for structs [WorkItem(540896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540896")] [Fact] public void TestConstructorStruct03() { var text = @" struct S { public int i; public int j; public S(int x) { j = i = x; Init(x); } void Init(int x) { } public void Set(S s) { s.Copy(out this); } public void CopySelf() { this.Copy(out this); } public void Copy(out S s) { s = this; } } class Program { static void Main(string[] args) { S s; s.i = 0; s.j = 1; S s2 = s; s2.i = 2; s.Set(s2); System.Console.Write(s.i); s.CopySelf(); System.Console.Write(s.i); } } "; CompileAndVerify(text, expectedOutput: "22").VerifyDiagnostics(); } // Overriding base System.Object methods on struct [WorkItem(20496, "https://github.com/dotnet/roslyn/issues/20496")] [WorkItem(540990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540990")] [ClrOnlyFact(ClrOnlyReason.MemberOrder)] public void TestOverridingBaseConstructorStruct() { var text = @" using System; public struct Gen<T> { public override bool Equals(object obj) { Console.WriteLine(""Gen{0}::Equals"", typeof(T)); return base.Equals(obj); } public override int GetHashCode() { Console.WriteLine(""Gen{0}::GetHashCode"", typeof(T)); return base.GetHashCode(); } public override string ToString() { Console.WriteLine(""Gen{0}::ToString"", typeof(T)); return base.ToString(); } } public struct S { public override bool Equals(object obj) { Console.WriteLine(""S::Equals""); return base.Equals(obj); } public override int GetHashCode() { Console.WriteLine(""S::GetHashCode""); return base.GetHashCode(); } public override string ToString() { Console.WriteLine(""S::ToString""); return base.ToString(); } } public class Test { public static int counter = 0; public static bool result = true; public static void Eval(bool exp) { counter++; if (!exp) { result = exp; Console.WriteLine(""Test Failed at location: "" + counter); } } public static void Main() { Gen<int> gInt = new Gen<int>(); Test.Eval(gInt.Equals(null) == false); Test.Eval(gInt.GetHashCode() == gInt.GetHashCode()); Test.Eval(gInt.ToString() == ""Gen`1[System.Int32]""); Gen<object> gObject = new Gen<object>(); Test.Eval(gObject.Equals(null) == false); Test.Eval(gObject.GetHashCode() == gObject.GetHashCode()); Test.Eval(gObject.ToString() == ""Gen`1[System.Object]""); S s = new S(); Test.Eval(s.Equals(null) == false); Test.Eval(s.GetHashCode() == s.GetHashCode()); Test.Eval(s.ToString() == ""S""); } } "; var expectedOutput = @"GenSystem.Int32::Equals GenSystem.Int32::GetHashCode GenSystem.Int32::GetHashCode GenSystem.Int32::ToString GenSystem.Object::Equals GenSystem.Object::GetHashCode GenSystem.Object::GetHashCode GenSystem.Object::ToString S::Equals S::GetHashCode S::GetHashCode S::ToString"; CompileAndVerify(text, expectedOutput: expectedOutput); } // Test constructor for generic struct [WorkItem(540993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540993")] [Fact] public void TestConstructorForGenericStruct() { var text = @" using System; struct C<T> { public int num; public int Goo1() { return this.num; } } class Test { static void Main(string[] args) { C<object> c; c.num = 1; bool verify = c.Goo1() == 1; Console.WriteLine(verify); } } "; var expectedOutput = @"True"; CompileAndVerify(text, expectedOutput: expectedOutput); } // Assign to decimal in struct constructor [WorkItem(540994, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540994")] [Fact] public void TestAssigntoDecimalInStructConstructor() { var text = @" using System; public struct Struct { public decimal Price; public Struct(decimal price) { Price = price; } } class Test { public static void Main() { } } "; var expectedIL = @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""decimal Struct.Price"" IL_0007: ret }"; CompileAndVerify(text).VerifyIL("Struct..ctor(decimal)", expectedIL); } [Fact] public void RetargetedSynthesizedStructConstructor() { var oldMsCorLib = TestMetadata.Net40.mscorlib; var c1 = CSharpCompilation.Create("C1", new[] { Parse(@"public struct S { }") }, new[] { oldMsCorLib }, TestOptions.ReleaseDll); var c2 = CSharpCompilation.Create("C2", new[] { Parse(@"public class C { void M() { S s = new S(); System.Console.WriteLine(s);} }") }, new[] { MscorlibRef, new CSharpCompilationReference(c1) }, TestOptions.ReleaseDll); var c1AsmRef = c2.GetReferencedAssemblySymbol(new CSharpCompilationReference(c1)); Assert.NotSame(c1.Assembly, c1AsmRef); var mscorlibAssembly = c2.GetReferencedAssemblySymbol(MscorlibRef); Assert.NotSame(mscorlibAssembly, c1.GetReferencedAssemblySymbol(oldMsCorLib)); var @struct = c2.GlobalNamespace.GetMember<RetargetingNamedTypeSymbol>("S"); var method = (RetargetingMethodSymbol)@struct.GetMembers().Single(); Assert.True(method.IsDefaultValueTypeConstructor(requireZeroInit: false)); //TODO (tomat) CompileAndVerify(c2).VerifyIL("C.M", @" { // Code size 20 (0x14) .maxstack 1 .locals init (S V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloc.0 IL_0009: box ""S"" IL_000e: call ""void System.Console.WriteLine(object)"" IL_0013: ret }"); } [Fact] public void SubstitutedSynthesizedStructConstructor() { string text = @" public struct S<T> { } public class C { void M() { S<int> s = new S<int>(); System.Console.WriteLine(s); } } "; CompileAndVerify(text).VerifyIL("C.M", @" { // Code size 20 (0x14) .maxstack 1 .locals init (S<int> V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""S<int>"" IL_0008: ldloc.0 IL_0009: box ""S<int>"" IL_000e: call ""void System.Console.WriteLine(object)"" IL_0013: ret }"); } [Fact] public void PublicParameterlessConstructorInMetadata() { string ilSource = @" .class public sequential ansi sealed beforefieldinit S extends [mscorlib]System.ValueType { .pack 0 .size 1 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } "; string csharpSource = @" public class C { void M() { S s = new S(); System.Console.WriteLine(s); s = default(S); System.Console.WriteLine(s); } } "; // Calls constructor (vs initobj), then initobj var compilation = CreateCompilationWithILAndMscorlib40(csharpSource, ilSource); // TODO (tomat) CompileAndVerify(compilation).VerifyIL("C.M", @" { // Code size 35 (0x23) .maxstack 1 .locals init (S V_0) IL_0000: newobj ""S..ctor()"" IL_0005: box ""S"" IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: ldloca.s V_0 IL_0011: initobj ""S"" IL_0017: ldloc.0 IL_0018: box ""S"" IL_001d: call ""void System.Console.WriteLine(object)"" IL_0022: ret }"); } [WorkItem(541309, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541309")] [Fact] public void PrivateParameterlessConstructorInMetadata() { string ilSource = @" .class public sequential ansi sealed beforefieldinit S extends [mscorlib]System.ValueType { .pack 0 .size 1 .method private hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } "; string csharpSource = @" public class C { void M() { S s = new S(); System.Console.WriteLine(s); s = default(S); System.Console.WriteLine(s); } } "; // Uses initobj for both // CONSIDER: This is the dev10 behavior, but it seems like a bug. // Shouldn't there be an error for trying to call an inaccessible ctor? var comp = CreateCompilationWithILAndMscorlib40(csharpSource, ilSource); CompileAndVerify(comp).VerifyIL("C.M", @" { // Code size 39 (0x27) .maxstack 1 .locals init (S V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloc.0 IL_0009: box ""S"" IL_000e: call ""void System.Console.WriteLine(object)"" IL_0013: ldloca.s V_0 IL_0015: initobj ""S"" IL_001b: ldloc.0 IL_001c: box ""S"" IL_0021: call ""void System.Console.WriteLine(object)"" IL_0026: ret }"); } [WorkItem(543934, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543934")] [Fact] public void ObjectCreationExprStructTypeInstanceFieldAssign() { var csSource = @" public struct TestStruct { public int IntI; } public class TestClass { public static void Main() { new TestStruct().IntI = 3; } } "; CreateCompilation(csSource).VerifyDiagnostics( // (13,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "new TestStruct().IntI") ); } [WorkItem(543896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543896")] [Fact] public void ObjectCreationExprStructTypePropertyAssign() { var csSource = @" public struct S { int n; public int P { set { n = value; System.Console.WriteLine(n); } } } public class mem033 { public static void Main() { new S().P = 1; // CS0131 } }"; CreateCompilation(csSource).VerifyDiagnostics( // (14,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // new S().P = 1; // CS0131 Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "new S().P") ); } [WorkItem(545498, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545498")] [Fact] public void StructMemberNullableTypeCausesCycle() { string source = @" public struct X { public X? recursiveFld; } "; CreateCompilation(source, targetFramework: TargetFramework.Mscorlib45).VerifyDiagnostics( // (4,15): error CS0523: Struct member 'X.recursiveFld' of type 'X?' causes a cycle in the struct layout // public X? recursiveFld; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "recursiveFld").WithArguments("X.recursiveFld", "X?") ); } [Fact] public void StructParameterlessCtorNotPublic() { string source = @" public struct X { private X() { } } public struct X1 { X1() { } } "; CreateCompilation(source, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (4,13): error CS8773: Feature 'parameterless struct constructors' is not available in C# 9.0. Please use language version 10.0 or greater. // private X() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "X").WithArguments("parameterless struct constructors", "10.0").WithLocation(4, 13), // (4,13): error CS8938: The parameterless struct constructor must be 'public'. // private X() Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "X").WithLocation(4, 13), // (11,5): error CS8773: Feature 'parameterless struct constructors' is not available in C# 9.0. Please use language version 10.0 or greater. // X1() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "X1").WithArguments("parameterless struct constructors", "10.0").WithLocation(11, 5), // (11,5): error CS8938: The parameterless struct constructor must be 'public'. // X1() Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "X1").WithLocation(11, 5)); CreateCompilation(source).VerifyDiagnostics( // (4,13): error CS8918: The parameterless struct constructor must be 'public'. // private X() Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "X").WithLocation(4, 13), // (11,5): error CS8918: The parameterless struct constructor must be 'public'. // X1() Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "X1").WithLocation(11, 5)); } [Fact] public void StructNonAutoPropertyInitializer() { var text = @"struct S { public int I { get { throw null; } set {} } = 9; }"; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (3,16): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // public int I { get { throw null; } set {} } = 9; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "I").WithArguments("struct field initializers", "10.0").WithLocation(3, 16), // (3,16): error CS8050: Only auto-implemented properties can have initializers. // public int I { get { throw null; } set {} } = 9; Diagnostic(ErrorCode.ERR_InitializerOnNonAutoProperty, "I").WithArguments("S.I").WithLocation(3, 16)); comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,16): error CS8050: Only auto-implemented properties can have initializers. // public int I { get { throw null; } set {} } = 9; Diagnostic(ErrorCode.ERR_InitializerOnNonAutoProperty, "I").WithArguments("S.I").WithLocation(3, 16)); } } }
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/EditorFeatures/VisualBasicTest/Recommendations/ArrayStatements/PreserveKeywordRecommenderTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.ArrayStatements Public Class PreserveKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PreserveNotInMethodBodyTest() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Preserve") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PreserveAfterReDimStatementTest() VerifyRecommendationsContain(<MethodBody>ReDim | </MethodBody>, "Preserve") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PreserveNotAfterReDimPreserveTest() VerifyRecommendationsMissing(<ClassDeclaration>ReDim Preserve |</ClassDeclaration>, "Preserve") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PreserveNotAfterWeirdBrokenReDimTest() VerifyRecommendationsMissing(<MethodBody>ReDim x, ReDim |</MethodBody>, "Preserve") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PreserveInSingleLineLambdaTest() VerifyRecommendationsContain(<MethodBody>Dim x = Sub() ReDim |</MethodBody>, "Preserve") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterEolTest() VerifyRecommendationsMissing( <MethodBody>ReDim | </MethodBody>, "Preserve") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTest() VerifyRecommendationsContain( <MethodBody>ReDim _ | </MethodBody>, "Preserve") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTestCommentsAfterLineContinuation() VerifyRecommendationsContain( <MethodBody>ReDim _ ' Test | </MethodBody>, "Preserve") 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. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.ArrayStatements Public Class PreserveKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PreserveNotInMethodBodyTest() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Preserve") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PreserveAfterReDimStatementTest() VerifyRecommendationsContain(<MethodBody>ReDim | </MethodBody>, "Preserve") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PreserveNotAfterReDimPreserveTest() VerifyRecommendationsMissing(<ClassDeclaration>ReDim Preserve |</ClassDeclaration>, "Preserve") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PreserveNotAfterWeirdBrokenReDimTest() VerifyRecommendationsMissing(<MethodBody>ReDim x, ReDim |</MethodBody>, "Preserve") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PreserveInSingleLineLambdaTest() VerifyRecommendationsContain(<MethodBody>Dim x = Sub() ReDim |</MethodBody>, "Preserve") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterEolTest() VerifyRecommendationsMissing( <MethodBody>ReDim | </MethodBody>, "Preserve") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTest() VerifyRecommendationsContain( <MethodBody>ReDim _ | </MethodBody>, "Preserve") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTestCommentsAfterLineContinuation() VerifyRecommendationsContain( <MethodBody>ReDim _ ' Test | </MethodBody>, "Preserve") End Sub End Class End Namespace
-1
dotnet/roslyn
55,905
Track duplicate hintNames as they are added
Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
chsienki
2021-08-25T23:54:05Z
2021-09-01T04:43:07Z
d88b01d990378202966607bdb781505a24ec8bfc
4d11231ec6a083ba3b2033ea03189fce18c18ec0
Track duplicate hintNames as they are added. Fixes https://github.com/dotnet/roslyn/issues/54185 In V1 we threw an exception at the point where a duplicate hint name was added. In V2 we were not throwing until we combined all the outputs, meaning a generator had no way of catching and responding to it. This change restores the immediate exception behavior _within the same output node_. This means V1 generators will function as before, as the emulation layer executes them within a single node. V2 generators will have a slightly different behaviour, as we don't know about duplicates until we combine all the outputs (and some may be cached etc). But the author won't see any difference until they have multiple output nodes, so even most ports to V2 should continue to work as written.
./src/Analyzers/Core/Analyzers/UseConditionalExpression/ForAssignment/UseConditionalExpressionForAssignmentHelpers.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; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis.UseConditionalExpression { internal static class UseConditionalExpressionForAssignmentHelpers { public static bool TryMatchPattern( ISyntaxFacts syntaxFacts, IConditionalOperation ifOperation, [NotNullWhen(true)] out IOperation trueStatement, [NotNullWhen(true)] out IOperation? falseStatement, out ISimpleAssignmentOperation? trueAssignment, out ISimpleAssignmentOperation? falseAssignment) { falseAssignment = null; trueStatement = ifOperation.WhenTrue; falseStatement = ifOperation.WhenFalse; trueStatement = UseConditionalExpressionHelpers.UnwrapSingleStatementBlock(trueStatement); falseStatement = UseConditionalExpressionHelpers.UnwrapSingleStatementBlock(falseStatement); if (!TryGetAssignmentOrThrow(trueStatement, out trueAssignment, out var trueThrow) || !TryGetAssignmentOrThrow(falseStatement, out falseAssignment, out var falseThrow)) { return false; } var anyAssignment = trueAssignment ?? falseAssignment; if (UseConditionalExpressionHelpers.HasInconvertibleThrowStatement( syntaxFacts, anyAssignment?.IsRef == true, trueThrow, falseThrow)) { return false; } // The left side of both assignment statements has to be syntactically identical (modulo // trivia differences). if (trueAssignment != null && falseAssignment != null && !syntaxFacts.AreEquivalent(trueAssignment.Target.Syntax, falseAssignment.Target.Syntax)) { return false; } return UseConditionalExpressionHelpers.CanConvert( syntaxFacts, ifOperation, trueStatement, falseStatement); } private static bool TryGetAssignmentOrThrow( [NotNullWhen(true)] IOperation? statement, out ISimpleAssignmentOperation? assignment, out IThrowOperation? throwOperation) { assignment = null; throwOperation = null; if (statement is IThrowOperation throwOp) { throwOperation = throwOp; // We can only convert a `throw expr` to a throw expression, not `throw;` return throwOperation.Exception != null; } // Both the WhenTrue and WhenFalse statements must be of the form: // target = value; if (statement is IExpressionStatementOperation exprStatement && exprStatement.Operation is ISimpleAssignmentOperation assignmentOp && assignmentOp.Target != null) { assignment = assignmentOp; return true; } 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.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis.UseConditionalExpression { internal static class UseConditionalExpressionForAssignmentHelpers { public static bool TryMatchPattern( ISyntaxFacts syntaxFacts, IConditionalOperation ifOperation, [NotNullWhen(true)] out IOperation trueStatement, [NotNullWhen(true)] out IOperation? falseStatement, out ISimpleAssignmentOperation? trueAssignment, out ISimpleAssignmentOperation? falseAssignment) { falseAssignment = null; trueStatement = ifOperation.WhenTrue; falseStatement = ifOperation.WhenFalse; trueStatement = UseConditionalExpressionHelpers.UnwrapSingleStatementBlock(trueStatement); falseStatement = UseConditionalExpressionHelpers.UnwrapSingleStatementBlock(falseStatement); if (!TryGetAssignmentOrThrow(trueStatement, out trueAssignment, out var trueThrow) || !TryGetAssignmentOrThrow(falseStatement, out falseAssignment, out var falseThrow)) { return false; } var anyAssignment = trueAssignment ?? falseAssignment; if (UseConditionalExpressionHelpers.HasInconvertibleThrowStatement( syntaxFacts, anyAssignment?.IsRef == true, trueThrow, falseThrow)) { return false; } // The left side of both assignment statements has to be syntactically identical (modulo // trivia differences). if (trueAssignment != null && falseAssignment != null && !syntaxFacts.AreEquivalent(trueAssignment.Target.Syntax, falseAssignment.Target.Syntax)) { return false; } return UseConditionalExpressionHelpers.CanConvert( syntaxFacts, ifOperation, trueStatement, falseStatement); } private static bool TryGetAssignmentOrThrow( [NotNullWhen(true)] IOperation? statement, out ISimpleAssignmentOperation? assignment, out IThrowOperation? throwOperation) { assignment = null; throwOperation = null; if (statement is IThrowOperation throwOp) { throwOperation = throwOp; // We can only convert a `throw expr` to a throw expression, not `throw;` return throwOperation.Exception != null; } // Both the WhenTrue and WhenFalse statements must be of the form: // target = value; if (statement is IExpressionStatementOperation exprStatement && exprStatement.Operation is ISimpleAssignmentOperation assignmentOp && assignmentOp.Target != null) { assignment = assignmentOp; return true; } return false; } } }
-1
dotnet/roslyn
55,898
Include edit session runtime capabilities in telemetry data
tmat
2021-08-25T21:41:02Z
2021-08-26T20:00:14Z
52b1b5784bf719114d698ed5fa4f82d6da30059f
dd121d37f386e689310de5dc039c08406d4dd0b2
Include edit session runtime capabilities in telemetry data.
./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", "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", "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" }, _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" }, _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" }, _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", "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", "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", "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", "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", "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" }, _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", "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] 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", "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", }, _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" }, _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", "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() { 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 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())); 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); 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); 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 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())); solution = solution.WithDocumentText(documentIdA, SourceText.From(source2, Encoding.UTF8)); var result = await hotReload.EmitSolutionUpdateAsync(solution, true, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Equal(1, result.updates.Length); solution = solution.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, 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); 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] 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() { 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 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())); 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); 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); 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 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())); solution = solution.WithDocumentText(documentIdA, SourceText.From(source2, Encoding.UTF8)); var result = await hotReload.EmitSolutionUpdateAsync(solution, true, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Equal(1, result.updates.Length); solution = solution.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, 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); hotReload.EndSession(); } } }
1
dotnet/roslyn
55,898
Include edit session runtime capabilities in telemetry data
tmat
2021-08-25T21:41:02Z
2021-08-26T20:00:14Z
52b1b5784bf719114d698ed5fa4f82d6da30059f
dd121d37f386e689310de5dc039c08406d4dd0b2
Include edit session runtime capabilities in telemetry data.
./src/Features/Core/Portable/EditAndContinue/DebuggingSession.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.IO; using System.Linq; using System.Reflection.Metadata; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Represents a debugging session. /// </summary> internal sealed class DebuggingSession : IDisposable { private readonly Func<Project, CompilationOutputs> _compilationOutputsProvider; private readonly CancellationTokenSource _cancellationSource = new(); /// <summary> /// MVIDs read from the assembly built for given project id. /// </summary> private readonly Dictionary<ProjectId, (Guid Mvid, Diagnostic Error)> _projectModuleIds = new(); private readonly Dictionary<Guid, ProjectId> _moduleIds = new(); private readonly object _projectModuleIdsGuard = new(); /// <summary> /// The current baseline for given project id. /// The baseline is updated when changes are committed at the end of edit session. /// The backing module readers of initial baselines need to be kept alive -- store them in /// <see cref="_initialBaselineModuleReaders"/> and dispose them at the end of the debugging session. /// </summary> /// <remarks> /// The baseline of each updated project is linked to its initial baseline that reads from the on-disk metadata and PDB. /// Therefore once an initial baseline is created it needs to be kept alive till the end of the debugging session, /// even when it's replaced in <see cref="_projectEmitBaselines"/> by a newer baseline. /// </remarks> private readonly Dictionary<ProjectId, EmitBaseline> _projectEmitBaselines = new(); private readonly List<IDisposable> _initialBaselineModuleReaders = new(); private readonly object _projectEmitBaselinesGuard = new(); /// <summary> /// To avoid accessing metadata/symbol readers that have been disposed, /// read lock is acquired before every operation that may access a baseline module/symbol reader /// and write lock when the baseline readers are being disposed. /// </summary> private readonly ReaderWriterLockSlim _baselineAccessLock = new(); private bool _isDisposed; internal EditSession EditSession { get; private set; } private readonly HashSet<Guid> _modulesPreparedForUpdate = new(); private readonly object _modulesPreparedForUpdateGuard = new(); internal readonly DebuggingSessionId Id; /// <summary> /// The solution captured when the debugging session entered run mode (application debugging started), /// or the solution which the last changes committed to the debuggee at the end of edit session were calculated from. /// The solution reflecting the current state of the modules loaded in the debugee. /// </summary> internal readonly CommittedSolution LastCommittedSolution; internal readonly IManagedEditAndContinueDebuggerService DebuggerService; /// <summary> /// True if the diagnostics produced by the session should be reported to the diagnotic analyzer. /// </summary> internal readonly bool ReportDiagnostics; private readonly DebuggingSessionTelemetry _telemetry = new(); private readonly EditSessionTelemetry _editSessionTelemetry = new(); private PendingSolutionUpdate? _pendingUpdate; private Action<DebuggingSessionTelemetry.Data> _reportTelemetry; #pragma warning disable IDE0052 // Remove unread private members /// <summary> /// Last array of module updates generated during the debugging session. /// Useful for crash dump diagnostics. /// </summary> private ImmutableArray<ManagedModuleUpdate> _lastModuleUpdatesLog; #pragma warning restore internal DebuggingSession( DebuggingSessionId id, Solution solution, IManagedEditAndContinueDebuggerService debuggerService, Func<Project, CompilationOutputs> compilationOutputsProvider, IEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>> initialDocumentStates, bool reportDiagnostics) { _compilationOutputsProvider = compilationOutputsProvider; _reportTelemetry = ReportTelemetry; Id = id; DebuggerService = debuggerService; LastCommittedSolution = new CommittedSolution(this, solution, initialDocumentStates); EditSession = new EditSession(this, nonRemappableRegions: ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty, _editSessionTelemetry, inBreakState: false); ReportDiagnostics = reportDiagnostics; } public void Dispose() { Debug.Assert(!_isDisposed); _isDisposed = true; _cancellationSource.Cancel(); _cancellationSource.Dispose(); // Wait for all operations on baseline to finish before we dispose the readers. _baselineAccessLock.EnterWriteLock(); foreach (var reader in GetBaselineModuleReaders()) { reader.Dispose(); } _baselineAccessLock.ExitWriteLock(); _baselineAccessLock.Dispose(); } internal void ThrowIfDisposed() { if (_isDisposed) throw new ObjectDisposedException(nameof(DebuggingSession)); } internal Task OnSourceFileUpdatedAsync(Document document) => LastCommittedSolution.OnSourceFileUpdatedAsync(document, _cancellationSource.Token); private void StorePendingUpdate(Solution solution, SolutionUpdate update) { var previousPendingUpdate = Interlocked.Exchange(ref _pendingUpdate, new PendingSolutionUpdate( solution, update.EmitBaselines, update.ModuleUpdates.Updates, update.NonRemappableRegions)); // commit/discard was not called: Contract.ThrowIfFalse(previousPendingUpdate == null); } private PendingSolutionUpdate RetrievePendingUpdate() { var pendingUpdate = Interlocked.Exchange(ref _pendingUpdate, null); Contract.ThrowIfNull(pendingUpdate); return pendingUpdate; } private void EndEditSession(out ImmutableArray<DocumentId> documentsToReanalyze) { documentsToReanalyze = EditSession.GetDocumentsWithReportedDiagnostics(); var editSessionTelemetryData = EditSession.Telemetry.GetDataAndClear(); _telemetry.LogEditSession(editSessionTelemetryData); } public void EndSession(out ImmutableArray<DocumentId> documentsToReanalyze, out DebuggingSessionTelemetry.Data telemetryData) { ThrowIfDisposed(); EndEditSession(out documentsToReanalyze); telemetryData = _telemetry.GetDataAndClear(); _reportTelemetry(telemetryData); Dispose(); } public void BreakStateChanged(bool inBreakState, out ImmutableArray<DocumentId> documentsToReanalyze) => RestartEditSession(nonRemappableRegions: null, inBreakState, out documentsToReanalyze); internal void RestartEditSession(ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>? nonRemappableRegions, bool inBreakState, out ImmutableArray<DocumentId> documentsToReanalyze) { ThrowIfDisposed(); EndEditSession(out documentsToReanalyze); EditSession = new EditSession(this, nonRemappableRegions ?? EditSession.NonRemappableRegions, EditSession.Telemetry, inBreakState); } private ImmutableArray<IDisposable> GetBaselineModuleReaders() { lock (_projectEmitBaselinesGuard) { return _initialBaselineModuleReaders.ToImmutableArrayOrEmpty(); } } internal CompilationOutputs GetCompilationOutputs(Project project) => _compilationOutputsProvider(project); private bool AddModulePreparedForUpdate(Guid mvid) { lock (_modulesPreparedForUpdateGuard) { return _modulesPreparedForUpdate.Add(mvid); } } /// <summary> /// Reads the MVID of a compiled project. /// </summary> /// <returns> /// An MVID and an error message to report, in case an IO exception occurred while reading the binary. /// The MVID is default if either project not built, or an it can't be read from the module binary. /// </returns> internal async Task<(Guid Mvid, Diagnostic? Error)> GetProjectModuleIdAsync(Project project, CancellationToken cancellationToken) { lock (_projectModuleIdsGuard) { if (_projectModuleIds.TryGetValue(project.Id, out var id)) { return id; } } (Guid Mvid, Diagnostic? Error) ReadMvid() { var outputs = GetCompilationOutputs(project); try { return (outputs.ReadAssemblyModuleVersionId(), Error: null); } catch (Exception e) when (e is FileNotFoundException or DirectoryNotFoundException) { return (Mvid: Guid.Empty, Error: null); } catch (Exception e) { var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); return (Mvid: Guid.Empty, Error: Diagnostic.Create(descriptor, Location.None, new[] { outputs.AssemblyDisplayPath, e.Message })); } } var newId = await Task.Run(ReadMvid, cancellationToken).ConfigureAwait(false); lock (_projectModuleIdsGuard) { if (_projectModuleIds.TryGetValue(project.Id, out var id)) { return id; } _moduleIds[newId.Mvid] = project.Id; return _projectModuleIds[project.Id] = newId; } } private bool TryGetProjectId(Guid moduleId, [NotNullWhen(true)] out ProjectId? projectId) { lock (_projectModuleIdsGuard) { return _moduleIds.TryGetValue(moduleId, out projectId); } } /// <summary> /// Get <see cref="EmitBaseline"/> for given project. /// </summary> /// <returns>True unless the project outputs can't be read.</returns> internal bool TryGetOrCreateEmitBaseline(Project project, out ImmutableArray<Diagnostic> diagnostics, [NotNullWhen(true)] out EmitBaseline? baseline, [NotNullWhen(true)] out ReaderWriterLockSlim? baselineAccessLock) { baselineAccessLock = _baselineAccessLock; lock (_projectEmitBaselinesGuard) { if (_projectEmitBaselines.TryGetValue(project.Id, out baseline)) { diagnostics = ImmutableArray<Diagnostic>.Empty; return true; } } var outputs = GetCompilationOutputs(project); if (!TryCreateInitialBaseline(outputs, project.Id, out diagnostics, out var newBaseline, out var debugInfoReaderProvider, out var metadataReaderProvider)) { // Unable to read the DLL/PDB at this point (it might be open by another process). // Don't cache the failure so that the user can attempt to apply changes again. return false; } lock (_projectEmitBaselinesGuard) { if (_projectEmitBaselines.TryGetValue(project.Id, out baseline)) { metadataReaderProvider.Dispose(); debugInfoReaderProvider.Dispose(); return true; } _projectEmitBaselines[project.Id] = newBaseline; _initialBaselineModuleReaders.Add(metadataReaderProvider); _initialBaselineModuleReaders.Add(debugInfoReaderProvider); } baseline = newBaseline; return true; } private static unsafe bool TryCreateInitialBaseline( CompilationOutputs compilationOutputs, ProjectId projectId, out ImmutableArray<Diagnostic> diagnostics, [NotNullWhen(true)] out EmitBaseline? baseline, [NotNullWhen(true)] out DebugInformationReaderProvider? debugInfoReaderProvider, [NotNullWhen(true)] out MetadataReaderProvider? metadataReaderProvider) { // Read the metadata and symbols from the disk. Close the files as soon as we are done emitting the delta to minimize // the time when they are being locked. Since we need to use the baseline that is produced by delta emit for the subsequent // delta emit we need to keep the module metadata and symbol info backing the symbols of the baseline alive in memory. // Alternatively, we could drop the data once we are done with emitting the delta and re-emit the baseline again // when we need it next time and the module is loaded. diagnostics = default; baseline = null; debugInfoReaderProvider = null; metadataReaderProvider = null; var success = false; var fileBeingRead = compilationOutputs.PdbDisplayPath; try { debugInfoReaderProvider = compilationOutputs.OpenPdb(); if (debugInfoReaderProvider == null) { throw new FileNotFoundException(); } var debugInfoReader = debugInfoReaderProvider.CreateEditAndContinueMethodDebugInfoReader(); fileBeingRead = compilationOutputs.AssemblyDisplayPath; metadataReaderProvider = compilationOutputs.OpenAssemblyMetadata(prefetch: true); if (metadataReaderProvider == null) { throw new FileNotFoundException(); } var metadataReader = metadataReaderProvider.GetMetadataReader(); var moduleMetadata = ModuleMetadata.CreateFromMetadata((IntPtr)metadataReader.MetadataPointer, metadataReader.MetadataLength); baseline = EmitBaseline.CreateInitialBaseline( moduleMetadata, debugInfoReader.GetDebugInfo, debugInfoReader.GetLocalSignature, debugInfoReader.IsPortable); success = true; return true; } catch (Exception e) { EditAndContinueWorkspaceService.Log.Write("Failed to create baseline for '{0}': {1}", projectId, e.Message); var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); diagnostics = ImmutableArray.Create(Diagnostic.Create(descriptor, Location.None, new[] { fileBeingRead, e.Message })); } finally { if (!success) { debugInfoReaderProvider?.Dispose(); metadataReaderProvider?.Dispose(); } } return false; } private static ImmutableDictionary<K, ImmutableArray<V>> GroupToImmutableDictionary<K, V>(IEnumerable<IGrouping<K, V>> items) where K : notnull { var builder = ImmutableDictionary.CreateBuilder<K, ImmutableArray<V>>(); foreach (var item in items) { builder.Add(item.Key, item.ToImmutableArray()); } return builder.ToImmutable(); } public async ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { try { if (_isDisposed) { return ImmutableArray<Diagnostic>.Empty; } // Not a C# or VB project. var project = document.Project; if (!project.SupportsEditAndContinue()) { return ImmutableArray<Diagnostic>.Empty; } // Document does not compile to the assembly (e.g. cshtml files, .g.cs files generated for completion only) if (!document.DocumentState.SupportsEditAndContinue()) { return ImmutableArray<Diagnostic>.Empty; } // Do not analyze documents (and report diagnostics) of projects that have not been built. // Allow user to make any changes in these documents, they won't be applied within the current debugging session. // Do not report the file read error - it might be an intermittent issue. The error will be reported when the // change is attempted to be applied. var (mvid, _) = await GetProjectModuleIdAsync(project, cancellationToken).ConfigureAwait(false); if (mvid == Guid.Empty) { return ImmutableArray<Diagnostic>.Empty; } var (oldDocument, oldDocumentState) = await LastCommittedSolution.GetDocumentAndStateAsync(document.Id, document, cancellationToken).ConfigureAwait(false); if (oldDocumentState is CommittedSolution.DocumentState.OutOfSync or CommittedSolution.DocumentState.Indeterminate or CommittedSolution.DocumentState.DesignTimeOnly) { // Do not report diagnostics for existing out-of-sync documents or design-time-only documents. return ImmutableArray<Diagnostic>.Empty; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldDocument, document, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (analysis.HasChanges) { // Once we detected a change in a document let the debugger know that the corresponding loaded module // is about to be updated, so that it can start initializing it for EnC update, reducing the amount of time applying // the change blocks the UI when the user "continues". if (AddModulePreparedForUpdate(mvid)) { // fire and forget: _ = Task.Run(() => DebuggerService.PrepareModuleForUpdateAsync(mvid, cancellationToken), cancellationToken); } } if (analysis.RudeEditErrors.IsEmpty) { return ImmutableArray<Diagnostic>.Empty; } EditSession.Telemetry.LogRudeEditDiagnostics(analysis.RudeEditErrors); // track the document, so that we can refresh or clean diagnostics at the end of edit session: EditSession.TrackDocumentWithReportedDiagnostics(document.Id); var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); return analysis.RudeEditErrors.SelectAsArray((e, t) => e.ToDiagnostic(t), tree); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return ImmutableArray<Diagnostic>.Empty; } } public async ValueTask<EmitSolutionUpdateResults> EmitSolutionUpdateAsync( Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { ThrowIfDisposed(); var solutionUpdate = await EditSession.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); LogSolutionUpdate(solutionUpdate); if (solutionUpdate.ModuleUpdates.Status == ManagedModuleUpdateStatus.Ready) { StorePendingUpdate(solution, solutionUpdate); } // Note that we may return empty deltas if all updates have been deferred. // The debugger will still call commit or discard on the update batch. return new EmitSolutionUpdateResults(solutionUpdate.ModuleUpdates, solutionUpdate.Diagnostics, solutionUpdate.DocumentsWithRudeEdits); } private void LogSolutionUpdate(SolutionUpdate update) { EditAndContinueWorkspaceService.Log.Write("Solution update status: {0}", ((int)update.ModuleUpdates.Status, typeof(ManagedModuleUpdateStatus))); if (update.ModuleUpdates.Updates.Length > 0) { var firstUpdate = update.ModuleUpdates.Updates[0]; EditAndContinueWorkspaceService.Log.Write("Solution update deltas: #{0} [types: #{1} (0x{2}:X8), methods: #{3} (0x{4}:X8)", update.ModuleUpdates.Updates.Length, firstUpdate.UpdatedTypes.Length, firstUpdate.UpdatedTypes.FirstOrDefault(), firstUpdate.UpdatedMethods.Length, firstUpdate.UpdatedMethods.FirstOrDefault()); } if (update.Diagnostics.Length > 0) { var firstProjectDiagnostic = update.Diagnostics[0]; EditAndContinueWorkspaceService.Log.Write("Solution update diagnostics: #{0} [{1}: {2}, ...]", update.Diagnostics.Length, firstProjectDiagnostic.ProjectId, firstProjectDiagnostic.Diagnostics[0]); } if (update.DocumentsWithRudeEdits.Length > 0) { var firstDocumentWithRudeEdits = update.DocumentsWithRudeEdits[0]; EditAndContinueWorkspaceService.Log.Write("Solution update documents with rude edits: #{0} [{1}: {2}, ...]", update.DocumentsWithRudeEdits.Length, firstDocumentWithRudeEdits.DocumentId, firstDocumentWithRudeEdits.Diagnostics[0].Kind); } _lastModuleUpdatesLog = update.ModuleUpdates.Updates; } public void CommitSolutionUpdate(out ImmutableArray<DocumentId> documentsToReanalyze) { ThrowIfDisposed(); var pendingUpdate = RetrievePendingUpdate(); // Save new non-remappable regions for the next edit session. // If no edits were made the pending list will be empty and we need to keep the previous regions. var newNonRemappableRegions = GroupToImmutableDictionary( from moduleRegions in pendingUpdate.NonRemappableRegions from region in moduleRegions.Regions group region.Region by new ManagedMethodId(moduleRegions.ModuleId, region.Method)); if (newNonRemappableRegions.IsEmpty) newNonRemappableRegions = null; // update baselines: lock (_projectEmitBaselinesGuard) { foreach (var (projectId, baseline) in pendingUpdate.EmitBaselines) { _projectEmitBaselines[projectId] = baseline; } } LastCommittedSolution.CommitSolution(pendingUpdate.Solution); // Restart edit session with no active statements (switching to run mode). RestartEditSession(newNonRemappableRegions, inBreakState: false, out documentsToReanalyze); } public void DiscardSolutionUpdate() { ThrowIfDisposed(); _ = RetrievePendingUpdate(); } public async ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { try { if (_isDisposed || !EditSession.InBreakState) { return default; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); using var _1 = PooledDictionary<string, ArrayBuilder<(ProjectId, int)>>.GetInstance(out var documentIndicesByMappedPath); using var _2 = PooledHashSet<ProjectId>.GetInstance(out var projectIds); // Construct map of mapped file path to a text document in the current solution // and a set of projects these documents are contained in. for (var i = 0; i < documentIds.Length; i++) { var documentId = documentIds[i]; var document = await solution.GetTextDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); if (document?.FilePath == null) { // document has been deleted or has no path (can't have an active statement anymore): continue; } // Multiple documents may have the same path (linked file). // The documents represent the files that #line directives map to. // Documents that have the same path must have different project id. documentIndicesByMappedPath.MultiAdd(document.FilePath, (documentId.ProjectId, i)); projectIds.Add(documentId.ProjectId); } using var _3 = PooledDictionary<ActiveStatement, ArrayBuilder<(DocumentId unmappedDocumentId, LinePositionSpan span)>>.GetInstance( out var activeStatementsInChangedDocuments); // Analyze changed documents in projects containing active statements: foreach (var projectId in projectIds) { var newProject = solution.GetRequiredProject(projectId); var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); await foreach (var documentId in EditSession.GetChangedDocumentsAsync(LastCommittedSolution, newProject, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); var newDocument = await solution.GetRequiredDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. continue; } var oldDocumentActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); var analysis = await analyzer.AnalyzeDocumentAsync( LastCommittedSolution.GetRequiredProject(documentId.ProjectId), EditSession.BaseActiveStatements, newDocument, newActiveStatementSpans: ImmutableArray<LinePositionSpan>.Empty, EditSession.Capabilities, cancellationToken).ConfigureAwait(false); // Document content did not change or unable to determine active statement spans in a document with syntax errors: if (!analysis.ActiveStatements.IsDefault) { for (var i = 0; i < oldDocumentActiveStatements.Length; i++) { // Note: It is possible that one active statement appears in multiple documents if the documents represent a linked file. // Example (old and new contents): // #if Condition #if Condition // #line 1 a.txt #line 1 a.txt // [|F(1);|] [|F(1000);|] // #else #else // #line 1 a.txt #line 1 a.txt // [|F(2);|] [|F(2);|] // #endif #endif // // In the new solution the AS spans are different depending on which document view of the same file we are looking at. // Different views correspond to different projects. activeStatementsInChangedDocuments.MultiAdd(oldDocumentActiveStatements[i].Statement, (analysis.DocumentId, analysis.ActiveStatements[i].Span)); } } } } using var _4 = ArrayBuilder<ImmutableArray<ActiveStatementSpan>>.GetInstance(out var spans); spans.AddMany(ImmutableArray<ActiveStatementSpan>.Empty, documentIds.Length); foreach (var (mappedPath, documentBaseActiveStatements) in baseActiveStatements.DocumentPathMap) { if (documentIndicesByMappedPath.TryGetValue(mappedPath, out var indices)) { // translate active statements from base solution to the new solution, if the documents they are contained in changed: foreach (var (projectId, index) in indices) { spans[index] = documentBaseActiveStatements.SelectAsArray( activeStatement => { LinePositionSpan span; DocumentId? unmappedDocumentId; if (activeStatementsInChangedDocuments.TryGetValue(activeStatement, out var newSpans)) { (unmappedDocumentId, span) = newSpans.Single(ns => ns.unmappedDocumentId.ProjectId == projectId); } else { span = activeStatement.Span; unmappedDocumentId = null; } return new ActiveStatementSpan(activeStatement.Ordinal, span, activeStatement.Flags, unmappedDocumentId); }); } } } documentIndicesByMappedPath.FreeValues(); activeStatementsInChangedDocuments.FreeValues(); return spans.ToImmutable(); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } public async ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(TextDocument mappedDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { try { if (_isDisposed || !EditSession.InBreakState || !mappedDocument.State.SupportsEditAndContinue()) { return ImmutableArray<ActiveStatementSpan>.Empty; } Contract.ThrowIfNull(mappedDocument.FilePath); var newProject = mappedDocument.Project; var newSolution = newProject.Solution; var oldProject = LastCommittedSolution.GetProject(newProject.Id); if (oldProject == null) { // project has been added, no changes in active statement spans: return ImmutableArray<ActiveStatementSpan>.Empty; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.DocumentPathMap.TryGetValue(mappedDocument.FilePath, out var oldMappedDocumentActiveStatements)) { // no active statements in this document return ImmutableArray<ActiveStatementSpan>.Empty; } var newDocumentActiveStatementSpans = await activeStatementSpanProvider(mappedDocument.Id, mappedDocument.FilePath, cancellationToken).ConfigureAwait(false); if (newDocumentActiveStatementSpans.IsEmpty) { return ImmutableArray<ActiveStatementSpan>.Empty; } var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); using var _ = ArrayBuilder<ActiveStatementSpan>.GetInstance(out var adjustedMappedSpans); // Start with the current locations of the tracking spans. adjustedMappedSpans.AddRange(newDocumentActiveStatementSpans); // Update tracking spans to the latest known locations of the active statements contained in changed documents based on their analysis. await foreach (var unmappedDocumentId in EditSession.GetChangedDocumentsAsync(LastCommittedSolution, newProject, cancellationToken).ConfigureAwait(false)) { var newUnmappedDocument = await newSolution.GetRequiredDocumentAsync(unmappedDocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var (oldUnmappedDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newUnmappedDocument.Id, newUnmappedDocument, cancellationToken).ConfigureAwait(false); if (oldUnmappedDocument == null) { // document out-of-date continue; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldUnmappedDocument, newUnmappedDocument, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); // Document content did not change or unable to determine active statement spans in a document with syntax errors: if (!analysis.ActiveStatements.IsDefault) { foreach (var activeStatement in analysis.ActiveStatements) { var i = adjustedMappedSpans.FindIndex((s, ordinal) => s.Ordinal == ordinal, activeStatement.Ordinal); if (i >= 0) { adjustedMappedSpans[i] = new ActiveStatementSpan(activeStatement.Ordinal, activeStatement.Span, activeStatement.Flags, unmappedDocumentId); } } } } return adjustedMappedSpans.ToImmutable(); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } public async ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { ThrowIfDisposed(); try { // It is allowed to call this method before entering or after exiting break mode. In fact, the VS debugger does so. // We return null since there the concept of active statement only makes sense during break mode. if (!EditSession.InBreakState) { return null; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement)) { return null; } var documentId = await FindChangedDocumentContainingUnmappedActiveStatementAsync(baseActiveStatements, instructionId.Method.Module, baseActiveStatement, solution, cancellationToken).ConfigureAwait(false); if (documentId == null) { // Active statement not found in any changed documents, return its last position: return baseActiveStatement.Span; } var newDocument = await solution.GetDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); if (newDocument == null) { // The document has been deleted. return null; } var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // document out-of-date return null; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldDocument, newDocument, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (!analysis.HasChanges) { // Document content did not change: return baseActiveStatement.Span; } if (analysis.HasSyntaxErrors) { // Unable to determine active statement spans in a document with syntax errors: return null; } Contract.ThrowIfTrue(analysis.ActiveStatements.IsDefault); return analysis.ActiveStatements.GetStatement(baseActiveStatement.Ordinal).Span; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } /// <summary> /// Called by the debugger to determine whether a non-leaf active statement is in an exception region, /// so it can determine whether the active statement can be remapped. This only happens when the EnC is about to apply changes. /// If the debugger determines we can remap active statements, the application of changes proceeds. /// /// TODO: remove (https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1310859) /// </summary> /// <returns> /// True if the instruction is located within an exception region, false if it is not, null if the instruction isn't an active statement in a changed method /// or the exception regions can't be determined. /// </returns> public async ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { ThrowIfDisposed(); try { if (!EditSession.InBreakState) { return null; } // This method is only called when the EnC is about to apply changes, at which point all active statements and // their exception regions will be needed. Hence it's not necessary to scope this query down to just the instruction // the debugger is interested at this point while not calculating the others. var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement)) { return null; } var documentId = await FindChangedDocumentContainingUnmappedActiveStatementAsync(baseActiveStatements, instructionId.Method.Module, baseActiveStatement, solution, cancellationToken).ConfigureAwait(false); if (documentId == null) { // the active statement is contained in an unchanged document, thus it doesn't matter whether it's in an exception region or not return null; } var newDocument = solution.GetRequiredDocument(documentId); var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. return null; } var analyzer = newDocument.Project.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldDocumentActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); return oldDocumentActiveStatements.GetStatement(baseActiveStatement.Ordinal).ExceptionRegions.IsActiveStatementCovered; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } private async Task<DocumentId?> FindChangedDocumentContainingUnmappedActiveStatementAsync( ActiveStatementsMap activeStatementsMap, Guid moduleId, ActiveStatement baseActiveStatement, Solution newSolution, CancellationToken cancellationToken) { try { DocumentId? documentId = null; if (TryGetProjectId(moduleId, out var projectId)) { var oldProject = LastCommittedSolution.GetProject(projectId); if (oldProject == null) { // project has been added (should have no active statements under normal circumstances) return null; } var newProject = newSolution.GetProject(projectId); if (newProject == null) { // project has been deleted return null; } documentId = await GetChangedDocumentContainingUnmappedActiveStatementAsync(activeStatementsMap, LastCommittedSolution, newProject, baseActiveStatement, cancellationToken).ConfigureAwait(false); } else { // Search for the document in all changed projects in the solution. using var documentFoundCancellationSource = new CancellationTokenSource(); using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(documentFoundCancellationSource.Token, cancellationToken); async Task GetTaskAsync(ProjectId projectId) { var newProject = newSolution.GetRequiredProject(projectId); var id = await GetChangedDocumentContainingUnmappedActiveStatementAsync(activeStatementsMap, LastCommittedSolution, newProject, baseActiveStatement, linkedTokenSource.Token).ConfigureAwait(false); Interlocked.CompareExchange(ref documentId, id, null); if (id != null) { documentFoundCancellationSource.Cancel(); } } var tasks = newSolution.ProjectIds.Select(GetTaskAsync); try { await Task.WhenAll(tasks).ConfigureAwait(false); } catch (OperationCanceledException) when (documentFoundCancellationSource.IsCancellationRequested) { // nop: cancelled because we found the document } } return documentId; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } // Enumerate all changed documents in the project whose module contains the active statement. // For each such document enumerate all #line directives to find which maps code to the span that contains the active statement. private static async ValueTask<DocumentId?> GetChangedDocumentContainingUnmappedActiveStatementAsync(ActiveStatementsMap baseActiveStatements, CommittedSolution oldSolution, Project newProject, ActiveStatement activeStatement, CancellationToken cancellationToken) { var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); await foreach (var documentId in EditSession.GetChangedDocumentsAsync(oldSolution, newProject, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); var newDocument = newProject.GetRequiredDocument(documentId); var (oldDocument, _) = await oldSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. return null; } var oldActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); if (oldActiveStatements.Any(s => s.Statement == activeStatement)) { return documentId; } } return null; } private static void ReportTelemetry(DebuggingSessionTelemetry.Data data) { // report telemetry (fire and forget): _ = Task.Run(() => LogTelemetry(data, Logger.Log, LogAggregator.GetNextId)); } private static void LogTelemetry(DebuggingSessionTelemetry.Data debugSessionData, Action<FunctionId, LogMessage> log, Func<int> getNextId) { const string SessionId = nameof(SessionId); const string EditSessionId = nameof(EditSessionId); var debugSessionId = getNextId(); log(FunctionId.Debugging_EncSession, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map["SessionCount"] = debugSessionData.EditSessionData.Count(session => session.InBreakState); map["EmptySessionCount"] = debugSessionData.EmptyEditSessionCount; map["HotReloadSessionCount"] = debugSessionData.EditSessionData.Count(session => !session.InBreakState); map["EmptyHotReloadSessionCount"] = debugSessionData.EmptyHotReloadEditSessionCount; })); foreach (var editSessionData in debugSessionData.EditSessionData) { var editSessionId = getNextId(); log(FunctionId.Debugging_EncSession_EditSession, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["HadCompilationErrors"] = editSessionData.HadCompilationErrors; map["HadRudeEdits"] = editSessionData.HadRudeEdits; map["HadValidChanges"] = editSessionData.HadValidChanges; map["HadValidInsignificantChanges"] = editSessionData.HadValidInsignificantChanges; map["RudeEditsCount"] = editSessionData.RudeEdits.Length; map["EmitDeltaErrorIdCount"] = editSessionData.EmitErrorIds.Length; map["InBreakState"] = editSessionData.InBreakState; })); foreach (var errorId in editSessionData.EmitErrorIds) { log(FunctionId.Debugging_EncSession_EditSession_EmitDeltaErrorId, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["ErrorId"] = errorId; })); } foreach (var (editKind, syntaxKind) in editSessionData.RudeEdits) { log(FunctionId.Debugging_EncSession_EditSession_RudeEdit, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["RudeEditKind"] = editKind; map["RudeEditSyntaxKind"] = syntaxKind; map["RudeEditBlocking"] = editSessionData.HadRudeEdits; })); } } } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly DebuggingSession _instance; public TestAccessor(DebuggingSession instance) => _instance = instance; public ImmutableHashSet<Guid> GetModulesPreparedForUpdate() { lock (_instance._modulesPreparedForUpdateGuard) { return _instance._modulesPreparedForUpdate.ToImmutableHashSet(); } } public EmitBaseline GetProjectEmitBaseline(ProjectId id) { lock (_instance._projectEmitBaselinesGuard) { return _instance._projectEmitBaselines[id]; } } public ImmutableArray<IDisposable> GetBaselineModuleReaders() => _instance.GetBaselineModuleReaders(); public PendingSolutionUpdate? GetPendingSolutionUpdate() => _instance._pendingUpdate; public void SetTelemetryLogger(Action<FunctionId, LogMessage> logger, Func<int> getNextId) => _instance._reportTelemetry = data => LogTelemetry(data, logger, getNextId); } } }
// Licensed to the .NET Foundation under one or more 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.IO; using System.Linq; using System.Reflection.Metadata; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Represents a debugging session. /// </summary> internal sealed class DebuggingSession : IDisposable { private readonly Func<Project, CompilationOutputs> _compilationOutputsProvider; private readonly CancellationTokenSource _cancellationSource = new(); /// <summary> /// MVIDs read from the assembly built for given project id. /// </summary> private readonly Dictionary<ProjectId, (Guid Mvid, Diagnostic Error)> _projectModuleIds = new(); private readonly Dictionary<Guid, ProjectId> _moduleIds = new(); private readonly object _projectModuleIdsGuard = new(); /// <summary> /// The current baseline for given project id. /// The baseline is updated when changes are committed at the end of edit session. /// The backing module readers of initial baselines need to be kept alive -- store them in /// <see cref="_initialBaselineModuleReaders"/> and dispose them at the end of the debugging session. /// </summary> /// <remarks> /// The baseline of each updated project is linked to its initial baseline that reads from the on-disk metadata and PDB. /// Therefore once an initial baseline is created it needs to be kept alive till the end of the debugging session, /// even when it's replaced in <see cref="_projectEmitBaselines"/> by a newer baseline. /// </remarks> private readonly Dictionary<ProjectId, EmitBaseline> _projectEmitBaselines = new(); private readonly List<IDisposable> _initialBaselineModuleReaders = new(); private readonly object _projectEmitBaselinesGuard = new(); /// <summary> /// To avoid accessing metadata/symbol readers that have been disposed, /// read lock is acquired before every operation that may access a baseline module/symbol reader /// and write lock when the baseline readers are being disposed. /// </summary> private readonly ReaderWriterLockSlim _baselineAccessLock = new(); private bool _isDisposed; internal EditSession EditSession { get; private set; } private readonly HashSet<Guid> _modulesPreparedForUpdate = new(); private readonly object _modulesPreparedForUpdateGuard = new(); internal readonly DebuggingSessionId Id; /// <summary> /// The solution captured when the debugging session entered run mode (application debugging started), /// or the solution which the last changes committed to the debuggee at the end of edit session were calculated from. /// The solution reflecting the current state of the modules loaded in the debugee. /// </summary> internal readonly CommittedSolution LastCommittedSolution; internal readonly IManagedEditAndContinueDebuggerService DebuggerService; /// <summary> /// True if the diagnostics produced by the session should be reported to the diagnotic analyzer. /// </summary> internal readonly bool ReportDiagnostics; private readonly DebuggingSessionTelemetry _telemetry = new(); private readonly EditSessionTelemetry _editSessionTelemetry = new(); private PendingSolutionUpdate? _pendingUpdate; private Action<DebuggingSessionTelemetry.Data> _reportTelemetry; #pragma warning disable IDE0052 // Remove unread private members /// <summary> /// Last array of module updates generated during the debugging session. /// Useful for crash dump diagnostics. /// </summary> private ImmutableArray<ManagedModuleUpdate> _lastModuleUpdatesLog; #pragma warning restore internal DebuggingSession( DebuggingSessionId id, Solution solution, IManagedEditAndContinueDebuggerService debuggerService, Func<Project, CompilationOutputs> compilationOutputsProvider, IEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>> initialDocumentStates, bool reportDiagnostics) { _compilationOutputsProvider = compilationOutputsProvider; _reportTelemetry = ReportTelemetry; Id = id; DebuggerService = debuggerService; LastCommittedSolution = new CommittedSolution(this, solution, initialDocumentStates); EditSession = new EditSession(this, nonRemappableRegions: ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty, _editSessionTelemetry, inBreakState: false); ReportDiagnostics = reportDiagnostics; } public void Dispose() { Debug.Assert(!_isDisposed); _isDisposed = true; _cancellationSource.Cancel(); _cancellationSource.Dispose(); // Wait for all operations on baseline to finish before we dispose the readers. _baselineAccessLock.EnterWriteLock(); foreach (var reader in GetBaselineModuleReaders()) { reader.Dispose(); } _baselineAccessLock.ExitWriteLock(); _baselineAccessLock.Dispose(); } internal void ThrowIfDisposed() { if (_isDisposed) throw new ObjectDisposedException(nameof(DebuggingSession)); } internal Task OnSourceFileUpdatedAsync(Document document) => LastCommittedSolution.OnSourceFileUpdatedAsync(document, _cancellationSource.Token); private void StorePendingUpdate(Solution solution, SolutionUpdate update) { var previousPendingUpdate = Interlocked.Exchange(ref _pendingUpdate, new PendingSolutionUpdate( solution, update.EmitBaselines, update.ModuleUpdates.Updates, update.NonRemappableRegions)); // commit/discard was not called: Contract.ThrowIfFalse(previousPendingUpdate == null); } private PendingSolutionUpdate RetrievePendingUpdate() { var pendingUpdate = Interlocked.Exchange(ref _pendingUpdate, null); Contract.ThrowIfNull(pendingUpdate); return pendingUpdate; } private void EndEditSession(out ImmutableArray<DocumentId> documentsToReanalyze) { documentsToReanalyze = EditSession.GetDocumentsWithReportedDiagnostics(); var editSessionTelemetryData = EditSession.Telemetry.GetDataAndClear(); _telemetry.LogEditSession(editSessionTelemetryData); } public void EndSession(out ImmutableArray<DocumentId> documentsToReanalyze, out DebuggingSessionTelemetry.Data telemetryData) { ThrowIfDisposed(); EndEditSession(out documentsToReanalyze); telemetryData = _telemetry.GetDataAndClear(); _reportTelemetry(telemetryData); Dispose(); } public void BreakStateChanged(bool inBreakState, out ImmutableArray<DocumentId> documentsToReanalyze) => RestartEditSession(nonRemappableRegions: null, inBreakState, out documentsToReanalyze); internal void RestartEditSession(ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>? nonRemappableRegions, bool inBreakState, out ImmutableArray<DocumentId> documentsToReanalyze) { ThrowIfDisposed(); EndEditSession(out documentsToReanalyze); EditSession = new EditSession(this, nonRemappableRegions ?? EditSession.NonRemappableRegions, EditSession.Telemetry, inBreakState); } private ImmutableArray<IDisposable> GetBaselineModuleReaders() { lock (_projectEmitBaselinesGuard) { return _initialBaselineModuleReaders.ToImmutableArrayOrEmpty(); } } internal CompilationOutputs GetCompilationOutputs(Project project) => _compilationOutputsProvider(project); private bool AddModulePreparedForUpdate(Guid mvid) { lock (_modulesPreparedForUpdateGuard) { return _modulesPreparedForUpdate.Add(mvid); } } /// <summary> /// Reads the MVID of a compiled project. /// </summary> /// <returns> /// An MVID and an error message to report, in case an IO exception occurred while reading the binary. /// The MVID is default if either project not built, or an it can't be read from the module binary. /// </returns> internal async Task<(Guid Mvid, Diagnostic? Error)> GetProjectModuleIdAsync(Project project, CancellationToken cancellationToken) { lock (_projectModuleIdsGuard) { if (_projectModuleIds.TryGetValue(project.Id, out var id)) { return id; } } (Guid Mvid, Diagnostic? Error) ReadMvid() { var outputs = GetCompilationOutputs(project); try { return (outputs.ReadAssemblyModuleVersionId(), Error: null); } catch (Exception e) when (e is FileNotFoundException or DirectoryNotFoundException) { return (Mvid: Guid.Empty, Error: null); } catch (Exception e) { var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); return (Mvid: Guid.Empty, Error: Diagnostic.Create(descriptor, Location.None, new[] { outputs.AssemblyDisplayPath, e.Message })); } } var newId = await Task.Run(ReadMvid, cancellationToken).ConfigureAwait(false); lock (_projectModuleIdsGuard) { if (_projectModuleIds.TryGetValue(project.Id, out var id)) { return id; } _moduleIds[newId.Mvid] = project.Id; return _projectModuleIds[project.Id] = newId; } } private bool TryGetProjectId(Guid moduleId, [NotNullWhen(true)] out ProjectId? projectId) { lock (_projectModuleIdsGuard) { return _moduleIds.TryGetValue(moduleId, out projectId); } } /// <summary> /// Get <see cref="EmitBaseline"/> for given project. /// </summary> /// <returns>True unless the project outputs can't be read.</returns> internal bool TryGetOrCreateEmitBaseline(Project project, out ImmutableArray<Diagnostic> diagnostics, [NotNullWhen(true)] out EmitBaseline? baseline, [NotNullWhen(true)] out ReaderWriterLockSlim? baselineAccessLock) { baselineAccessLock = _baselineAccessLock; lock (_projectEmitBaselinesGuard) { if (_projectEmitBaselines.TryGetValue(project.Id, out baseline)) { diagnostics = ImmutableArray<Diagnostic>.Empty; return true; } } var outputs = GetCompilationOutputs(project); if (!TryCreateInitialBaseline(outputs, project.Id, out diagnostics, out var newBaseline, out var debugInfoReaderProvider, out var metadataReaderProvider)) { // Unable to read the DLL/PDB at this point (it might be open by another process). // Don't cache the failure so that the user can attempt to apply changes again. return false; } lock (_projectEmitBaselinesGuard) { if (_projectEmitBaselines.TryGetValue(project.Id, out baseline)) { metadataReaderProvider.Dispose(); debugInfoReaderProvider.Dispose(); return true; } _projectEmitBaselines[project.Id] = newBaseline; _initialBaselineModuleReaders.Add(metadataReaderProvider); _initialBaselineModuleReaders.Add(debugInfoReaderProvider); } baseline = newBaseline; return true; } private static unsafe bool TryCreateInitialBaseline( CompilationOutputs compilationOutputs, ProjectId projectId, out ImmutableArray<Diagnostic> diagnostics, [NotNullWhen(true)] out EmitBaseline? baseline, [NotNullWhen(true)] out DebugInformationReaderProvider? debugInfoReaderProvider, [NotNullWhen(true)] out MetadataReaderProvider? metadataReaderProvider) { // Read the metadata and symbols from the disk. Close the files as soon as we are done emitting the delta to minimize // the time when they are being locked. Since we need to use the baseline that is produced by delta emit for the subsequent // delta emit we need to keep the module metadata and symbol info backing the symbols of the baseline alive in memory. // Alternatively, we could drop the data once we are done with emitting the delta and re-emit the baseline again // when we need it next time and the module is loaded. diagnostics = default; baseline = null; debugInfoReaderProvider = null; metadataReaderProvider = null; var success = false; var fileBeingRead = compilationOutputs.PdbDisplayPath; try { debugInfoReaderProvider = compilationOutputs.OpenPdb(); if (debugInfoReaderProvider == null) { throw new FileNotFoundException(); } var debugInfoReader = debugInfoReaderProvider.CreateEditAndContinueMethodDebugInfoReader(); fileBeingRead = compilationOutputs.AssemblyDisplayPath; metadataReaderProvider = compilationOutputs.OpenAssemblyMetadata(prefetch: true); if (metadataReaderProvider == null) { throw new FileNotFoundException(); } var metadataReader = metadataReaderProvider.GetMetadataReader(); var moduleMetadata = ModuleMetadata.CreateFromMetadata((IntPtr)metadataReader.MetadataPointer, metadataReader.MetadataLength); baseline = EmitBaseline.CreateInitialBaseline( moduleMetadata, debugInfoReader.GetDebugInfo, debugInfoReader.GetLocalSignature, debugInfoReader.IsPortable); success = true; return true; } catch (Exception e) { EditAndContinueWorkspaceService.Log.Write("Failed to create baseline for '{0}': {1}", projectId, e.Message); var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); diagnostics = ImmutableArray.Create(Diagnostic.Create(descriptor, Location.None, new[] { fileBeingRead, e.Message })); } finally { if (!success) { debugInfoReaderProvider?.Dispose(); metadataReaderProvider?.Dispose(); } } return false; } private static ImmutableDictionary<K, ImmutableArray<V>> GroupToImmutableDictionary<K, V>(IEnumerable<IGrouping<K, V>> items) where K : notnull { var builder = ImmutableDictionary.CreateBuilder<K, ImmutableArray<V>>(); foreach (var item in items) { builder.Add(item.Key, item.ToImmutableArray()); } return builder.ToImmutable(); } public async ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { try { if (_isDisposed) { return ImmutableArray<Diagnostic>.Empty; } // Not a C# or VB project. var project = document.Project; if (!project.SupportsEditAndContinue()) { return ImmutableArray<Diagnostic>.Empty; } // Document does not compile to the assembly (e.g. cshtml files, .g.cs files generated for completion only) if (!document.DocumentState.SupportsEditAndContinue()) { return ImmutableArray<Diagnostic>.Empty; } // Do not analyze documents (and report diagnostics) of projects that have not been built. // Allow user to make any changes in these documents, they won't be applied within the current debugging session. // Do not report the file read error - it might be an intermittent issue. The error will be reported when the // change is attempted to be applied. var (mvid, _) = await GetProjectModuleIdAsync(project, cancellationToken).ConfigureAwait(false); if (mvid == Guid.Empty) { return ImmutableArray<Diagnostic>.Empty; } var (oldDocument, oldDocumentState) = await LastCommittedSolution.GetDocumentAndStateAsync(document.Id, document, cancellationToken).ConfigureAwait(false); if (oldDocumentState is CommittedSolution.DocumentState.OutOfSync or CommittedSolution.DocumentState.Indeterminate or CommittedSolution.DocumentState.DesignTimeOnly) { // Do not report diagnostics for existing out-of-sync documents or design-time-only documents. return ImmutableArray<Diagnostic>.Empty; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldDocument, document, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (analysis.HasChanges) { // Once we detected a change in a document let the debugger know that the corresponding loaded module // is about to be updated, so that it can start initializing it for EnC update, reducing the amount of time applying // the change blocks the UI when the user "continues". if (AddModulePreparedForUpdate(mvid)) { // fire and forget: _ = Task.Run(() => DebuggerService.PrepareModuleForUpdateAsync(mvid, cancellationToken), cancellationToken); } } if (analysis.RudeEditErrors.IsEmpty) { return ImmutableArray<Diagnostic>.Empty; } EditSession.Telemetry.LogRudeEditDiagnostics(analysis.RudeEditErrors); // track the document, so that we can refresh or clean diagnostics at the end of edit session: EditSession.TrackDocumentWithReportedDiagnostics(document.Id); var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); return analysis.RudeEditErrors.SelectAsArray((e, t) => e.ToDiagnostic(t), tree); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return ImmutableArray<Diagnostic>.Empty; } } public async ValueTask<EmitSolutionUpdateResults> EmitSolutionUpdateAsync( Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { ThrowIfDisposed(); var solutionUpdate = await EditSession.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); LogSolutionUpdate(solutionUpdate); if (solutionUpdate.ModuleUpdates.Status == ManagedModuleUpdateStatus.Ready) { StorePendingUpdate(solution, solutionUpdate); } // Note that we may return empty deltas if all updates have been deferred. // The debugger will still call commit or discard on the update batch. return new EmitSolutionUpdateResults(solutionUpdate.ModuleUpdates, solutionUpdate.Diagnostics, solutionUpdate.DocumentsWithRudeEdits); } private void LogSolutionUpdate(SolutionUpdate update) { EditAndContinueWorkspaceService.Log.Write("Solution update status: {0}", ((int)update.ModuleUpdates.Status, typeof(ManagedModuleUpdateStatus))); if (update.ModuleUpdates.Updates.Length > 0) { var firstUpdate = update.ModuleUpdates.Updates[0]; EditAndContinueWorkspaceService.Log.Write("Solution update deltas: #{0} [types: #{1} (0x{2}:X8), methods: #{3} (0x{4}:X8)", update.ModuleUpdates.Updates.Length, firstUpdate.UpdatedTypes.Length, firstUpdate.UpdatedTypes.FirstOrDefault(), firstUpdate.UpdatedMethods.Length, firstUpdate.UpdatedMethods.FirstOrDefault()); } if (update.Diagnostics.Length > 0) { var firstProjectDiagnostic = update.Diagnostics[0]; EditAndContinueWorkspaceService.Log.Write("Solution update diagnostics: #{0} [{1}: {2}, ...]", update.Diagnostics.Length, firstProjectDiagnostic.ProjectId, firstProjectDiagnostic.Diagnostics[0]); } if (update.DocumentsWithRudeEdits.Length > 0) { var firstDocumentWithRudeEdits = update.DocumentsWithRudeEdits[0]; EditAndContinueWorkspaceService.Log.Write("Solution update documents with rude edits: #{0} [{1}: {2}, ...]", update.DocumentsWithRudeEdits.Length, firstDocumentWithRudeEdits.DocumentId, firstDocumentWithRudeEdits.Diagnostics[0].Kind); } _lastModuleUpdatesLog = update.ModuleUpdates.Updates; } public void CommitSolutionUpdate(out ImmutableArray<DocumentId> documentsToReanalyze) { ThrowIfDisposed(); var pendingUpdate = RetrievePendingUpdate(); // Save new non-remappable regions for the next edit session. // If no edits were made the pending list will be empty and we need to keep the previous regions. var newNonRemappableRegions = GroupToImmutableDictionary( from moduleRegions in pendingUpdate.NonRemappableRegions from region in moduleRegions.Regions group region.Region by new ManagedMethodId(moduleRegions.ModuleId, region.Method)); if (newNonRemappableRegions.IsEmpty) newNonRemappableRegions = null; // update baselines: lock (_projectEmitBaselinesGuard) { foreach (var (projectId, baseline) in pendingUpdate.EmitBaselines) { _projectEmitBaselines[projectId] = baseline; } } LastCommittedSolution.CommitSolution(pendingUpdate.Solution); // Restart edit session with no active statements (switching to run mode). RestartEditSession(newNonRemappableRegions, inBreakState: false, out documentsToReanalyze); } public void DiscardSolutionUpdate() { ThrowIfDisposed(); _ = RetrievePendingUpdate(); } public async ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { try { if (_isDisposed || !EditSession.InBreakState) { return default; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); using var _1 = PooledDictionary<string, ArrayBuilder<(ProjectId, int)>>.GetInstance(out var documentIndicesByMappedPath); using var _2 = PooledHashSet<ProjectId>.GetInstance(out var projectIds); // Construct map of mapped file path to a text document in the current solution // and a set of projects these documents are contained in. for (var i = 0; i < documentIds.Length; i++) { var documentId = documentIds[i]; var document = await solution.GetTextDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); if (document?.FilePath == null) { // document has been deleted or has no path (can't have an active statement anymore): continue; } // Multiple documents may have the same path (linked file). // The documents represent the files that #line directives map to. // Documents that have the same path must have different project id. documentIndicesByMappedPath.MultiAdd(document.FilePath, (documentId.ProjectId, i)); projectIds.Add(documentId.ProjectId); } using var _3 = PooledDictionary<ActiveStatement, ArrayBuilder<(DocumentId unmappedDocumentId, LinePositionSpan span)>>.GetInstance( out var activeStatementsInChangedDocuments); // Analyze changed documents in projects containing active statements: foreach (var projectId in projectIds) { var newProject = solution.GetRequiredProject(projectId); var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); await foreach (var documentId in EditSession.GetChangedDocumentsAsync(LastCommittedSolution, newProject, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); var newDocument = await solution.GetRequiredDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. continue; } var oldDocumentActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); var analysis = await analyzer.AnalyzeDocumentAsync( LastCommittedSolution.GetRequiredProject(documentId.ProjectId), EditSession.BaseActiveStatements, newDocument, newActiveStatementSpans: ImmutableArray<LinePositionSpan>.Empty, EditSession.Capabilities, cancellationToken).ConfigureAwait(false); // Document content did not change or unable to determine active statement spans in a document with syntax errors: if (!analysis.ActiveStatements.IsDefault) { for (var i = 0; i < oldDocumentActiveStatements.Length; i++) { // Note: It is possible that one active statement appears in multiple documents if the documents represent a linked file. // Example (old and new contents): // #if Condition #if Condition // #line 1 a.txt #line 1 a.txt // [|F(1);|] [|F(1000);|] // #else #else // #line 1 a.txt #line 1 a.txt // [|F(2);|] [|F(2);|] // #endif #endif // // In the new solution the AS spans are different depending on which document view of the same file we are looking at. // Different views correspond to different projects. activeStatementsInChangedDocuments.MultiAdd(oldDocumentActiveStatements[i].Statement, (analysis.DocumentId, analysis.ActiveStatements[i].Span)); } } } } using var _4 = ArrayBuilder<ImmutableArray<ActiveStatementSpan>>.GetInstance(out var spans); spans.AddMany(ImmutableArray<ActiveStatementSpan>.Empty, documentIds.Length); foreach (var (mappedPath, documentBaseActiveStatements) in baseActiveStatements.DocumentPathMap) { if (documentIndicesByMappedPath.TryGetValue(mappedPath, out var indices)) { // translate active statements from base solution to the new solution, if the documents they are contained in changed: foreach (var (projectId, index) in indices) { spans[index] = documentBaseActiveStatements.SelectAsArray( activeStatement => { LinePositionSpan span; DocumentId? unmappedDocumentId; if (activeStatementsInChangedDocuments.TryGetValue(activeStatement, out var newSpans)) { (unmappedDocumentId, span) = newSpans.Single(ns => ns.unmappedDocumentId.ProjectId == projectId); } else { span = activeStatement.Span; unmappedDocumentId = null; } return new ActiveStatementSpan(activeStatement.Ordinal, span, activeStatement.Flags, unmappedDocumentId); }); } } } documentIndicesByMappedPath.FreeValues(); activeStatementsInChangedDocuments.FreeValues(); return spans.ToImmutable(); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } public async ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(TextDocument mappedDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { try { if (_isDisposed || !EditSession.InBreakState || !mappedDocument.State.SupportsEditAndContinue()) { return ImmutableArray<ActiveStatementSpan>.Empty; } Contract.ThrowIfNull(mappedDocument.FilePath); var newProject = mappedDocument.Project; var newSolution = newProject.Solution; var oldProject = LastCommittedSolution.GetProject(newProject.Id); if (oldProject == null) { // project has been added, no changes in active statement spans: return ImmutableArray<ActiveStatementSpan>.Empty; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.DocumentPathMap.TryGetValue(mappedDocument.FilePath, out var oldMappedDocumentActiveStatements)) { // no active statements in this document return ImmutableArray<ActiveStatementSpan>.Empty; } var newDocumentActiveStatementSpans = await activeStatementSpanProvider(mappedDocument.Id, mappedDocument.FilePath, cancellationToken).ConfigureAwait(false); if (newDocumentActiveStatementSpans.IsEmpty) { return ImmutableArray<ActiveStatementSpan>.Empty; } var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); using var _ = ArrayBuilder<ActiveStatementSpan>.GetInstance(out var adjustedMappedSpans); // Start with the current locations of the tracking spans. adjustedMappedSpans.AddRange(newDocumentActiveStatementSpans); // Update tracking spans to the latest known locations of the active statements contained in changed documents based on their analysis. await foreach (var unmappedDocumentId in EditSession.GetChangedDocumentsAsync(LastCommittedSolution, newProject, cancellationToken).ConfigureAwait(false)) { var newUnmappedDocument = await newSolution.GetRequiredDocumentAsync(unmappedDocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var (oldUnmappedDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newUnmappedDocument.Id, newUnmappedDocument, cancellationToken).ConfigureAwait(false); if (oldUnmappedDocument == null) { // document out-of-date continue; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldUnmappedDocument, newUnmappedDocument, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); // Document content did not change or unable to determine active statement spans in a document with syntax errors: if (!analysis.ActiveStatements.IsDefault) { foreach (var activeStatement in analysis.ActiveStatements) { var i = adjustedMappedSpans.FindIndex((s, ordinal) => s.Ordinal == ordinal, activeStatement.Ordinal); if (i >= 0) { adjustedMappedSpans[i] = new ActiveStatementSpan(activeStatement.Ordinal, activeStatement.Span, activeStatement.Flags, unmappedDocumentId); } } } } return adjustedMappedSpans.ToImmutable(); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } public async ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { ThrowIfDisposed(); try { // It is allowed to call this method before entering or after exiting break mode. In fact, the VS debugger does so. // We return null since there the concept of active statement only makes sense during break mode. if (!EditSession.InBreakState) { return null; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement)) { return null; } var documentId = await FindChangedDocumentContainingUnmappedActiveStatementAsync(baseActiveStatements, instructionId.Method.Module, baseActiveStatement, solution, cancellationToken).ConfigureAwait(false); if (documentId == null) { // Active statement not found in any changed documents, return its last position: return baseActiveStatement.Span; } var newDocument = await solution.GetDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); if (newDocument == null) { // The document has been deleted. return null; } var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // document out-of-date return null; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldDocument, newDocument, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (!analysis.HasChanges) { // Document content did not change: return baseActiveStatement.Span; } if (analysis.HasSyntaxErrors) { // Unable to determine active statement spans in a document with syntax errors: return null; } Contract.ThrowIfTrue(analysis.ActiveStatements.IsDefault); return analysis.ActiveStatements.GetStatement(baseActiveStatement.Ordinal).Span; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } /// <summary> /// Called by the debugger to determine whether a non-leaf active statement is in an exception region, /// so it can determine whether the active statement can be remapped. This only happens when the EnC is about to apply changes. /// If the debugger determines we can remap active statements, the application of changes proceeds. /// /// TODO: remove (https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1310859) /// </summary> /// <returns> /// True if the instruction is located within an exception region, false if it is not, null if the instruction isn't an active statement in a changed method /// or the exception regions can't be determined. /// </returns> public async ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { ThrowIfDisposed(); try { if (!EditSession.InBreakState) { return null; } // This method is only called when the EnC is about to apply changes, at which point all active statements and // their exception regions will be needed. Hence it's not necessary to scope this query down to just the instruction // the debugger is interested at this point while not calculating the others. var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement)) { return null; } var documentId = await FindChangedDocumentContainingUnmappedActiveStatementAsync(baseActiveStatements, instructionId.Method.Module, baseActiveStatement, solution, cancellationToken).ConfigureAwait(false); if (documentId == null) { // the active statement is contained in an unchanged document, thus it doesn't matter whether it's in an exception region or not return null; } var newDocument = solution.GetRequiredDocument(documentId); var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. return null; } var analyzer = newDocument.Project.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldDocumentActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); return oldDocumentActiveStatements.GetStatement(baseActiveStatement.Ordinal).ExceptionRegions.IsActiveStatementCovered; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } private async Task<DocumentId?> FindChangedDocumentContainingUnmappedActiveStatementAsync( ActiveStatementsMap activeStatementsMap, Guid moduleId, ActiveStatement baseActiveStatement, Solution newSolution, CancellationToken cancellationToken) { try { DocumentId? documentId = null; if (TryGetProjectId(moduleId, out var projectId)) { var oldProject = LastCommittedSolution.GetProject(projectId); if (oldProject == null) { // project has been added (should have no active statements under normal circumstances) return null; } var newProject = newSolution.GetProject(projectId); if (newProject == null) { // project has been deleted return null; } documentId = await GetChangedDocumentContainingUnmappedActiveStatementAsync(activeStatementsMap, LastCommittedSolution, newProject, baseActiveStatement, cancellationToken).ConfigureAwait(false); } else { // Search for the document in all changed projects in the solution. using var documentFoundCancellationSource = new CancellationTokenSource(); using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(documentFoundCancellationSource.Token, cancellationToken); async Task GetTaskAsync(ProjectId projectId) { var newProject = newSolution.GetRequiredProject(projectId); var id = await GetChangedDocumentContainingUnmappedActiveStatementAsync(activeStatementsMap, LastCommittedSolution, newProject, baseActiveStatement, linkedTokenSource.Token).ConfigureAwait(false); Interlocked.CompareExchange(ref documentId, id, null); if (id != null) { documentFoundCancellationSource.Cancel(); } } var tasks = newSolution.ProjectIds.Select(GetTaskAsync); try { await Task.WhenAll(tasks).ConfigureAwait(false); } catch (OperationCanceledException) when (documentFoundCancellationSource.IsCancellationRequested) { // nop: cancelled because we found the document } } return documentId; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } // Enumerate all changed documents in the project whose module contains the active statement. // For each such document enumerate all #line directives to find which maps code to the span that contains the active statement. private static async ValueTask<DocumentId?> GetChangedDocumentContainingUnmappedActiveStatementAsync(ActiveStatementsMap baseActiveStatements, CommittedSolution oldSolution, Project newProject, ActiveStatement activeStatement, CancellationToken cancellationToken) { var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); await foreach (var documentId in EditSession.GetChangedDocumentsAsync(oldSolution, newProject, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); var newDocument = newProject.GetRequiredDocument(documentId); var (oldDocument, _) = await oldSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. return null; } var oldActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); if (oldActiveStatements.Any(s => s.Statement == activeStatement)) { return documentId; } } return null; } private static void ReportTelemetry(DebuggingSessionTelemetry.Data data) { // report telemetry (fire and forget): _ = Task.Run(() => LogTelemetry(data, Logger.Log, LogAggregator.GetNextId)); } private static void LogTelemetry(DebuggingSessionTelemetry.Data debugSessionData, Action<FunctionId, LogMessage> log, Func<int> getNextId) { const string SessionId = nameof(SessionId); const string EditSessionId = nameof(EditSessionId); var debugSessionId = getNextId(); log(FunctionId.Debugging_EncSession, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map["SessionCount"] = debugSessionData.EditSessionData.Count(session => session.InBreakState); map["EmptySessionCount"] = debugSessionData.EmptyEditSessionCount; map["HotReloadSessionCount"] = debugSessionData.EditSessionData.Count(session => !session.InBreakState); map["EmptyHotReloadSessionCount"] = debugSessionData.EmptyHotReloadEditSessionCount; })); foreach (var editSessionData in debugSessionData.EditSessionData) { var editSessionId = getNextId(); log(FunctionId.Debugging_EncSession_EditSession, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["HadCompilationErrors"] = editSessionData.HadCompilationErrors; map["HadRudeEdits"] = editSessionData.HadRudeEdits; map["HadValidChanges"] = editSessionData.HadValidChanges; map["HadValidInsignificantChanges"] = editSessionData.HadValidInsignificantChanges; map["RudeEditsCount"] = editSessionData.RudeEdits.Length; map["EmitDeltaErrorIdCount"] = editSessionData.EmitErrorIds.Length; map["InBreakState"] = editSessionData.InBreakState; map["Capabilities"] = (int)editSessionData.Capabilities; })); foreach (var errorId in editSessionData.EmitErrorIds) { log(FunctionId.Debugging_EncSession_EditSession_EmitDeltaErrorId, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["ErrorId"] = errorId; })); } foreach (var (editKind, syntaxKind) in editSessionData.RudeEdits) { log(FunctionId.Debugging_EncSession_EditSession_RudeEdit, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["RudeEditKind"] = editKind; map["RudeEditSyntaxKind"] = syntaxKind; map["RudeEditBlocking"] = editSessionData.HadRudeEdits; })); } } } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly DebuggingSession _instance; public TestAccessor(DebuggingSession instance) => _instance = instance; public ImmutableHashSet<Guid> GetModulesPreparedForUpdate() { lock (_instance._modulesPreparedForUpdateGuard) { return _instance._modulesPreparedForUpdate.ToImmutableHashSet(); } } public EmitBaseline GetProjectEmitBaseline(ProjectId id) { lock (_instance._projectEmitBaselinesGuard) { return _instance._projectEmitBaselines[id]; } } public ImmutableArray<IDisposable> GetBaselineModuleReaders() => _instance.GetBaselineModuleReaders(); public PendingSolutionUpdate? GetPendingSolutionUpdate() => _instance._pendingUpdate; public void SetTelemetryLogger(Action<FunctionId, LogMessage> logger, Func<int> getNextId) => _instance._reportTelemetry = data => LogTelemetry(data, logger, getNextId); } } }
1
dotnet/roslyn
55,898
Include edit session runtime capabilities in telemetry data
tmat
2021-08-25T21:41:02Z
2021-08-26T20:00:14Z
52b1b5784bf719114d698ed5fa4f82d6da30059f
dd121d37f386e689310de5dc039c08406d4dd0b2
Include edit session runtime capabilities in telemetry data.
./src/Features/Core/Portable/EditAndContinue/EditSession.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.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class EditSession { internal readonly DebuggingSession DebuggingSession; internal readonly EditSessionTelemetry Telemetry; // Maps active statement instructions reported by the debugger to their latest spans that might not yet have been applied // (remapping not triggered yet). Consumed by the next edit session and updated when changes are committed at the end of the edit session. // // Consider a function F containing a call to function G. While G is being executed, F is updated a couple of times (in two edit sessions) // before the thread returns from G and is remapped to the latest version of F. At the start of the second edit session, // the active instruction reported by the debugger is still at the original location since function F has not been remapped yet (G has not returned yet). // // '>' indicates an active statement instruction for non-leaf frame reported by the debugger. // v1 - before first edit, G executing // v2 - after first edit, G still executing // v3 - after second edit and G returned // // F v1: F v2: F v3: // 0: nop 0: nop 0: nop // 1> G() 1> nop 1: nop // 2: nop 2: G() 2: nop // 3: nop 3: nop 3> G() // // When entering a break state we query the debugger for current active statements. // The returned statements reflect the current state of the threads in the runtime. // When a change is successfully applied we remember changes in active statement spans. // These changes are passed to the next edit session. // We use them to map the spans for active statements returned by the debugger. // // In the above case the sequence of events is // 1st break: get active statements returns (F, v=1, il=1, span1) the active statement is up-to-date // 1st apply: detected span change for active statement (F, v=1, il=1): span1->span2 // 2nd break: previously updated statements contains (F, v=1, il=1)->span2 // get active statements returns (F, v=1, il=1, span1) which is mapped to (F, v=1, il=1, span2) using previously updated statements // 2nd apply: detected span change for active statement (F, v=1, il=1): span2->span3 // 3rd break: previously updated statements contains (F, v=1, il=1)->span3 // get active statements returns (F, v=3, il=3, span3) the active statement is up-to-date // internal readonly ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> NonRemappableRegions; /// <summary> /// Gets the capabilities of the runtime with respect to applying code changes. /// Retrieved lazily from <see cref="DebuggingSession.DebuggerService"/> since they are only needed when changes are detected in the solution. /// </summary> internal readonly AsyncLazy<EditAndContinueCapabilities> Capabilities; /// <summary> /// Map of base active statements. /// Calculated lazily based on info retrieved from <see cref="DebuggingSession.DebuggerService"/> since it is only needed when changes are detected in the solution. /// </summary> internal readonly AsyncLazy<ActiveStatementsMap> BaseActiveStatements; /// <summary> /// Cache of document EnC analyses. /// </summary> internal readonly EditAndContinueDocumentAnalysesCache Analyses; /// <summary> /// True for Edit and Continue edit sessions - when the application is in break state. /// False for Hot Reload edit sessions - when the application is running. /// </summary> internal readonly bool InBreakState; /// <summary> /// A <see cref="DocumentId"/> is added whenever EnC analyzer reports /// rude edits or module diagnostics. At the end of the session we ask the diagnostic analyzer to reanalyze /// the documents to clean up the diagnostics. /// </summary> private readonly HashSet<DocumentId> _documentsWithReportedDiagnostics = new(); private readonly object _documentsWithReportedDiagnosticsGuard = new(); internal EditSession( DebuggingSession debuggingSession, ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> nonRemappableRegions, EditSessionTelemetry telemetry, bool inBreakState) { DebuggingSession = debuggingSession; NonRemappableRegions = nonRemappableRegions; Telemetry = telemetry; InBreakState = inBreakState; BaseActiveStatements = inBreakState ? new AsyncLazy<ActiveStatementsMap>(GetBaseActiveStatementsAsync, cacheResult: true) : new AsyncLazy<ActiveStatementsMap>(ActiveStatementsMap.Empty); Capabilities = new AsyncLazy<EditAndContinueCapabilities>(GetCapabilitiesAsync, cacheResult: true); Analyses = new EditAndContinueDocumentAnalysesCache(BaseActiveStatements, Capabilities); } /// <summary> /// The compiler has various scenarios that will cause it to synthesize things that might not be covered /// by existing rude edits, but we still need to ensure the runtime supports them before we proceed. /// </summary> private async Task<Diagnostic?> GetUnsupportedChangesDiagnosticAsync(EmitDifferenceResult emitResult, CancellationToken cancellationToken) { Debug.Assert(emitResult.Success); Debug.Assert(emitResult.Baseline is not null); var capabilities = await Capabilities.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { // If the runtime doesn't support adding new types then we expect every row number for any type that is // emitted will be less than or equal to the number of rows in the original metadata. var highestEmittedTypeDefRow = emitResult.ChangedTypes.Max(t => MetadataTokens.GetRowNumber(t)); var highestExistingTypeDefRow = emitResult.Baseline.OriginalMetadata.GetMetadataReader().GetTableRowCount(TableIndex.TypeDef); if (highestEmittedTypeDefRow > highestExistingTypeDefRow) { var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.AddingTypeRuntimeCapabilityRequired); return Diagnostic.Create(descriptor, Location.None); } } return null; } /// <summary> /// Errors to be reported when a project is updated but the corresponding module does not support EnC. /// </summary> /// <returns><see langword="default"/> if the module is not loaded.</returns> public async Task<ImmutableArray<Diagnostic>?> GetModuleDiagnosticsAsync(Guid mvid, string projectDisplayName, CancellationToken cancellationToken) { var availability = await DebuggingSession.DebuggerService.GetAvailabilityAsync(mvid, cancellationToken).ConfigureAwait(false); if (availability.Status == ManagedEditAndContinueAvailabilityStatus.ModuleNotLoaded) { return null; } if (availability.Status == ManagedEditAndContinueAvailabilityStatus.Available) { return ImmutableArray<Diagnostic>.Empty; } var descriptor = EditAndContinueDiagnosticDescriptors.GetModuleDiagnosticDescriptor(availability.Status); return ImmutableArray.Create(Diagnostic.Create(descriptor, Location.None, new[] { projectDisplayName, availability.LocalizedMessage })); } private async Task<EditAndContinueCapabilities> GetCapabilitiesAsync(CancellationToken cancellationToken) { try { var capabilities = await DebuggingSession.DebuggerService.GetCapabilitiesAsync(cancellationToken).ConfigureAwait(false); return EditAndContinueCapabilitiesParser.Parse(capabilities); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return EditAndContinueCapabilities.Baseline; } } private async Task<ActiveStatementsMap> GetBaseActiveStatementsAsync(CancellationToken cancellationToken) { try { // Last committed solution reflects the state of the source that is in sync with the binaries that are loaded in the debuggee. var debugInfos = await DebuggingSession.DebuggerService.GetActiveStatementsAsync(cancellationToken).ConfigureAwait(false); return ActiveStatementsMap.Create(debugInfos, NonRemappableRegions); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return ActiveStatementsMap.Empty; } } private static async Task PopulateChangedAndAddedDocumentsAsync(CommittedSolution oldSolution, Project newProject, ArrayBuilder<Document> changedOrAddedDocuments, CancellationToken cancellationToken) { changedOrAddedDocuments.Clear(); if (!newProject.SupportsEditAndContinue()) { return; } var oldProject = oldSolution.GetProject(newProject.Id); // When debugging session is started some projects might not have been loaded to the workspace yet. // We capture the base solution. Edits in files that are in projects that haven't been loaded won't be applied // and will result in source mismatch when the user steps into them. // // TODO (https://github.com/dotnet/roslyn/issues/1204): // hook up the debugger reported error, check that the project has not been loaded and report a better error. // Here, we assume these projects are not modified. if (oldProject == null) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not loaded", newProject.Id.DebugName, newProject.Id); return; } if (oldProject.State == newProject.State) { return; } foreach (var documentId in newProject.State.DocumentStates.GetChangedStateIds(oldProject.State.DocumentStates, ignoreUnchangedContent: true)) { var document = newProject.GetRequiredDocument(documentId); if (document.State.Attributes.DesignTimeOnly) { continue; } // Check if the currently observed document content has changed compared to the base document content. // This is an important optimization that aims to avoid IO while stepping in sources that have not changed. // // We may be comparing out-of-date committed document content but we only make a decision based on that content // if it matches the current content. If the current content is equal to baseline content that does not match // the debuggee then the workspace has not observed the change made to the file on disk since baseline was captured // (there had to be one as the content doesn't match). When we are about to apply changes it is ok to ignore this // document because the user does not see the change yet in the buffer (if the doc is open) and won't be confused // if it is not applied yet. The change will be applied later after it's observed by the workspace. var baseSource = await oldProject.GetRequiredDocument(documentId).GetTextAsync(cancellationToken).ConfigureAwait(false); var source = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (baseSource.ContentEquals(source)) { continue; } changedOrAddedDocuments.Add(document); } foreach (var documentId in newProject.State.DocumentStates.GetAddedStateIds(oldProject.State.DocumentStates)) { var document = newProject.GetRequiredDocument(documentId); if (document.State.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(document); } // TODO: support document removal/rename (see https://github.com/dotnet/roslyn/issues/41144, https://github.com/dotnet/roslyn/issues/49013). if (changedOrAddedDocuments.IsEmpty() && !HasChangesThatMayAffectSourceGenerators(oldProject.State, newProject.State)) { // Based on the above assumption there are no changes in source generated files. return; } cancellationToken.ThrowIfCancellationRequested(); var oldSourceGeneratedDocumentStates = await oldProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(oldProject.State, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var newSourceGeneratedDocumentStates = await newProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(newProject.State, cancellationToken).ConfigureAwait(false); foreach (var documentId in newSourceGeneratedDocumentStates.GetChangedStateIds(oldSourceGeneratedDocumentStates, ignoreUnchangedContent: true)) { var newState = newSourceGeneratedDocumentStates.GetRequiredState(documentId); if (newState.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(newProject.GetOrCreateSourceGeneratedDocument(newState)); } foreach (var documentId in newSourceGeneratedDocumentStates.GetAddedStateIds(oldSourceGeneratedDocumentStates)) { var newState = newSourceGeneratedDocumentStates.GetRequiredState(documentId); if (newState.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(newProject.GetOrCreateSourceGeneratedDocument(newState)); } } internal static async IAsyncEnumerable<DocumentId> GetChangedDocumentsAsync(CommittedSolution oldSolution, Project newProject, [EnumeratorCancellation] CancellationToken cancellationToken) { var oldProject = oldSolution.GetRequiredProject(newProject.Id); if (!newProject.SupportsEditAndContinue() || oldProject.State == newProject.State) { yield break; } foreach (var documentId in newProject.State.DocumentStates.GetChangedStateIds(oldProject.State.DocumentStates, ignoreUnchangedContent: true)) { yield return documentId; } if (!HasChangesThatMayAffectSourceGenerators(oldProject.State, newProject.State)) { // Based on the above assumption there are no changes in source generated files. yield break; } cancellationToken.ThrowIfCancellationRequested(); var oldSourceGeneratedDocumentStates = await oldProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(oldProject.State, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var newSourceGeneratedDocumentStates = await newProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(newProject.State, cancellationToken).ConfigureAwait(false); foreach (var documentId in newSourceGeneratedDocumentStates.GetChangedStateIds(oldSourceGeneratedDocumentStates, ignoreUnchangedContent: true)) { yield return documentId; } } /// <summary> /// Given the following assumptions: /// - source generators are deterministic, /// - source documents, metadata references and compilation options have not changed, /// - additional documents have not changed, /// - analyzer config documents have not changed, /// the outputs of source generators will not change. /// /// Currently it's not possible to change compilation options (Project System is readonly during debugging). /// </summary> private static bool HasChangesThatMayAffectSourceGenerators(ProjectState oldProject, ProjectState newProject) => newProject.DocumentStates.HasAnyStateChanges(oldProject.DocumentStates) || newProject.AdditionalDocumentStates.HasAnyStateChanges(oldProject.AdditionalDocumentStates) || newProject.AnalyzerConfigDocumentStates.HasAnyStateChanges(oldProject.AnalyzerConfigDocumentStates); private async Task<(ImmutableArray<DocumentAnalysisResults> results, ImmutableArray<Diagnostic> diagnostics)> AnalyzeDocumentsAsync( ArrayBuilder<Document> changedOrAddedDocuments, ActiveStatementSpanProvider newDocumentActiveStatementSpanProvider, CancellationToken cancellationToken) { using var _1 = ArrayBuilder<Diagnostic>.GetInstance(out var documentDiagnostics); using var _2 = ArrayBuilder<(Document? oldDocument, Document newDocument)>.GetInstance(out var documents); foreach (var newDocument in changedOrAddedDocuments) { var (oldDocument, oldDocumentState) = await DebuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken, reloadOutOfSyncDocument: true).ConfigureAwait(false); switch (oldDocumentState) { case CommittedSolution.DocumentState.DesignTimeOnly: break; case CommittedSolution.DocumentState.Indeterminate: case CommittedSolution.DocumentState.OutOfSync: var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor((oldDocumentState == CommittedSolution.DocumentState.Indeterminate) ? EditAndContinueErrorCode.UnableToReadSourceFileOrPdb : EditAndContinueErrorCode.DocumentIsOutOfSyncWithDebuggee); documentDiagnostics.Add(Diagnostic.Create(descriptor, Location.Create(newDocument.FilePath!, textSpan: default, lineSpan: default), new[] { newDocument.FilePath })); break; case CommittedSolution.DocumentState.MatchesBuildOutput: // Include the document regardless of whether the module it was built into has been loaded or not. // If the module has been built it might get loaded later during the debugging session, // at which point we apply all changes that have been made to the project so far. documents.Add((oldDocument, newDocument)); break; default: throw ExceptionUtilities.UnexpectedValue(oldDocumentState); } } var analyses = await Analyses.GetDocumentAnalysesAsync(DebuggingSession.LastCommittedSolution, documents, newDocumentActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); return (analyses, documentDiagnostics.ToImmutable()); } internal ImmutableArray<DocumentId> GetDocumentsWithReportedDiagnostics() { lock (_documentsWithReportedDiagnosticsGuard) { return ImmutableArray.CreateRange(_documentsWithReportedDiagnostics); } } internal void TrackDocumentWithReportedDiagnostics(DocumentId documentId) { lock (_documentsWithReportedDiagnosticsGuard) { _documentsWithReportedDiagnostics.Add(documentId); } } /// <summary> /// Determines whether projects contain any changes that might need to be applied. /// Checks only projects containing a given <paramref name="sourceFilePath"/> or all projects of the solution if <paramref name="sourceFilePath"/> is null. /// Invoked by the debugger on every step. It is critical for stepping performance that this method returns as fast as possible in absence of changes. /// </summary> public async ValueTask<bool> HasChangesAsync(Solution solution, ActiveStatementSpanProvider solutionActiveStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { try { var baseSolution = DebuggingSession.LastCommittedSolution; if (baseSolution.HasNoChanges(solution)) { return false; } // TODO: source generated files? var projects = (sourceFilePath == null) ? solution.Projects : from documentId in solution.GetDocumentIdsWithFilePath(sourceFilePath) select solution.GetProject(documentId.ProjectId)!; using var _ = ArrayBuilder<Document>.GetInstance(out var changedOrAddedDocuments); foreach (var project in projects) { await PopulateChangedAndAddedDocumentsAsync(baseSolution, project, changedOrAddedDocuments, cancellationToken).ConfigureAwait(false); if (changedOrAddedDocuments.IsEmpty()) { continue; } // Check MVID before analyzing documents as the analysis needs to read the PDB which will likely fail if we can't even read the MVID. var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(project, cancellationToken).ConfigureAwait(false); if (mvidReadError != null) { // Can't read MVID. This might be an intermittent failure, so don't report it here. // Report the project as containing changes, so that we proceed to EmitSolutionUpdateAsync where we report the error if it still persists. EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not built", project.Id.DebugName, project.Id); return true; } if (mvid == Guid.Empty) { // Project not built. We ignore any changes made in its sources. EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not built", project.Id.DebugName, project.Id); continue; } var (changedDocumentAnalyses, documentDiagnostics) = await AnalyzeDocumentsAsync(changedOrAddedDocuments, solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (documentDiagnostics.Any()) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: out-of-sync documents present (diagnostic: '{2}')", project.Id.DebugName, project.Id, documentDiagnostics[0]); // Although we do not apply changes in out-of-sync/indeterminate documents we report that changes are present, // so that the debugger triggers emit of updates. There we check if these documents are still in a bad state and report warnings // that any changes in such documents are not applied. return true; } var projectSummary = GetProjectAnalysisSymmary(changedDocumentAnalyses); if (projectSummary != ProjectAnalysisSummary.NoChanges) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: {2}", project.Id.DebugName, project.Id, projectSummary); return true; } } return false; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private static ProjectAnalysisSummary GetProjectAnalysisSymmary(ImmutableArray<DocumentAnalysisResults> documentAnalyses) { var hasChanges = false; var hasSignificantValidChanges = false; foreach (var analysis in documentAnalyses) { // skip documents that actually were not changed: if (!analysis.HasChanges) { continue; } // rude edit detection wasn't completed due to errors that prevent us from analyzing the document: if (analysis.HasChangesAndSyntaxErrors) { return ProjectAnalysisSummary.CompilationErrors; } // rude edits detected: if (!analysis.RudeEditErrors.IsEmpty) { return ProjectAnalysisSummary.RudeEdits; } hasChanges = true; hasSignificantValidChanges |= analysis.HasSignificantValidChanges; } if (!hasChanges) { // we get here if a document is closed and reopen without any actual change: return ProjectAnalysisSummary.NoChanges; } if (!hasSignificantValidChanges) { return ProjectAnalysisSummary.ValidInsignificantChanges; } return ProjectAnalysisSummary.ValidChanges; } internal static async ValueTask<ProjectChanges> GetProjectChangesAsync( ActiveStatementsMap baseActiveStatements, Compilation oldCompilation, Compilation newCompilation, Project oldProject, Project newProject, ImmutableArray<DocumentAnalysisResults> changedDocumentAnalyses, CancellationToken cancellationToken) { try { using var _1 = ArrayBuilder<SemanticEditInfo>.GetInstance(out var allEdits); using var _2 = ArrayBuilder<SequencePointUpdates>.GetInstance(out var allLineEdits); using var _3 = ArrayBuilder<DocumentActiveStatementChanges>.GetInstance(out var activeStatementsInChangedDocuments); var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); foreach (var analysis in changedDocumentAnalyses) { if (!analysis.HasSignificantValidChanges) { continue; } // we shouldn't be asking for deltas in presence of errors: Contract.ThrowIfTrue(analysis.HasChangesAndErrors); // Active statements are calculated if document changed and has no syntax errors: Contract.ThrowIfTrue(analysis.ActiveStatements.IsDefault); allEdits.AddRange(analysis.SemanticEdits); allLineEdits.AddRange(analysis.LineEdits); if (analysis.ActiveStatements.Length > 0) { var oldDocument = await oldProject.GetDocumentAsync(analysis.DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var oldActiveStatements = (oldDocument == null) ? ImmutableArray<UnmappedActiveStatement>.Empty : await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); activeStatementsInChangedDocuments.Add(new(oldActiveStatements, analysis.ActiveStatements, analysis.ExceptionRegions)); } } MergePartialEdits(oldCompilation, newCompilation, allEdits, out var mergedEdits, out var addedSymbols, cancellationToken); return new ProjectChanges( mergedEdits, allLineEdits.ToImmutable(), addedSymbols, activeStatementsInChangedDocuments.ToImmutable()); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } internal static void MergePartialEdits( Compilation oldCompilation, Compilation newCompilation, IReadOnlyList<SemanticEditInfo> edits, out ImmutableArray<SemanticEdit> mergedEdits, out ImmutableHashSet<ISymbol> addedSymbols, CancellationToken cancellationToken) { using var _0 = ArrayBuilder<SemanticEdit>.GetInstance(edits.Count, out var mergedEditsBuilder); using var _1 = PooledHashSet<ISymbol>.GetInstance(out var addedSymbolsBuilder); using var _2 = ArrayBuilder<(ISymbol? oldSymbol, ISymbol? newSymbol)>.GetInstance(edits.Count, out var resolvedSymbols); foreach (var edit in edits) { SymbolKeyResolution oldResolution; if (edit.Kind is SemanticEditKind.Update or SemanticEditKind.Delete) { oldResolution = edit.Symbol.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken); Contract.ThrowIfNull(oldResolution.Symbol); } else { oldResolution = default; } SymbolKeyResolution newResolution; if (edit.Kind is SemanticEditKind.Update or SemanticEditKind.Insert or SemanticEditKind.Replace) { newResolution = edit.Symbol.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken); Contract.ThrowIfNull(newResolution.Symbol); } else { newResolution = default; } resolvedSymbols.Add((oldResolution.Symbol, newResolution.Symbol)); } for (var i = 0; i < edits.Count; i++) { var edit = edits[i]; if (edit.PartialType == null) { var (oldSymbol, newSymbol) = resolvedSymbols[i]; if (edit.Kind == SemanticEditKind.Insert) { Contract.ThrowIfNull(newSymbol); addedSymbolsBuilder.Add(newSymbol); } mergedEditsBuilder.Add(new SemanticEdit( edit.Kind, oldSymbol: oldSymbol, newSymbol: newSymbol, syntaxMap: edit.SyntaxMap, preserveLocalVariables: edit.SyntaxMap != null)); } } // no partial type merging needed: if (edits.Count == mergedEditsBuilder.Count) { mergedEdits = mergedEditsBuilder.ToImmutable(); addedSymbols = addedSymbolsBuilder.ToImmutableHashSet(); return; } // Calculate merged syntax map for each partial type symbol: var symbolKeyComparer = SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: true); var mergedSyntaxMaps = new Dictionary<SymbolKey, Func<SyntaxNode, SyntaxNode?>?>(symbolKeyComparer); var editsByPartialType = edits .Where(edit => edit.PartialType != null) .GroupBy(edit => edit.PartialType!.Value, symbolKeyComparer); foreach (var partialTypeEdits in editsByPartialType) { // Either all edits have syntax map or none has. Debug.Assert( partialTypeEdits.All(edit => edit.SyntaxMapTree != null && edit.SyntaxMap != null) || partialTypeEdits.All(edit => edit.SyntaxMapTree == null && edit.SyntaxMap == null)); Func<SyntaxNode, SyntaxNode?>? mergedSyntaxMap; if (partialTypeEdits.First().SyntaxMap != null) { var newTrees = partialTypeEdits.SelectAsArray(edit => edit.SyntaxMapTree!); var syntaxMaps = partialTypeEdits.SelectAsArray(edit => edit.SyntaxMap!); mergedSyntaxMap = node => syntaxMaps[newTrees.IndexOf(node.SyntaxTree)](node); } else { mergedSyntaxMap = null; } mergedSyntaxMaps.Add(partialTypeEdits.Key, mergedSyntaxMap); } // Deduplicate edits based on their target symbol and use merged syntax map calculated above for a given partial type. using var _3 = PooledHashSet<ISymbol>.GetInstance(out var visitedSymbols); for (var i = 0; i < edits.Count; i++) { var edit = edits[i]; if (edit.PartialType != null) { var (oldSymbol, newSymbol) = resolvedSymbols[i]; if (visitedSymbols.Add(newSymbol ?? oldSymbol!)) { var syntaxMap = mergedSyntaxMaps[edit.PartialType.Value]; mergedEditsBuilder.Add(new SemanticEdit(edit.Kind, oldSymbol, newSymbol, syntaxMap, preserveLocalVariables: syntaxMap != null)); } } } mergedEdits = mergedEditsBuilder.ToImmutable(); addedSymbols = addedSymbolsBuilder.ToImmutableHashSet(); } public async ValueTask<SolutionUpdate> EmitSolutionUpdateAsync(Solution solution, ActiveStatementSpanProvider solutionActiveStatementSpanProvider, CancellationToken cancellationToken) { try { using var _1 = ArrayBuilder<ManagedModuleUpdate>.GetInstance(out var deltas); using var _2 = ArrayBuilder<(Guid ModuleId, ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)>)>.GetInstance(out var nonRemappableRegions); using var _3 = ArrayBuilder<(ProjectId, EmitBaseline)>.GetInstance(out var emitBaselines); using var _4 = ArrayBuilder<(ProjectId, ImmutableArray<Diagnostic>)>.GetInstance(out var diagnostics); using var _5 = ArrayBuilder<Document>.GetInstance(out var changedOrAddedDocuments); using var _6 = ArrayBuilder<(DocumentId, ImmutableArray<RudeEditDiagnostic>)>.GetInstance(out var documentsWithRudeEdits); var oldSolution = DebuggingSession.LastCommittedSolution; var isBlocked = false; foreach (var newProject in solution.Projects) { await PopulateChangedAndAddedDocumentsAsync(oldSolution, newProject, changedOrAddedDocuments, cancellationToken).ConfigureAwait(false); if (changedOrAddedDocuments.IsEmpty()) { continue; } var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(newProject, cancellationToken).ConfigureAwait(false); if (mvidReadError != null) { // The error hasn't been reported by GetDocumentDiagnosticsAsync since it might have been intermittent. // The MVID is required for emit so we consider the error permanent and report it here. // Bail before analyzing documents as the analysis needs to read the PDB which will likely fail if we can't even read the MVID. diagnostics.Add((newProject.Id, ImmutableArray.Create(mvidReadError))); Telemetry.LogProjectAnalysisSummary(ProjectAnalysisSummary.ValidChanges, ImmutableArray.Create(mvidReadError.Descriptor.Id), InBreakState); isBlocked = true; continue; } if (mvid == Guid.Empty) { EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]: project not built", newProject.Id.DebugName, newProject.Id); continue; } // PopulateChangedAndAddedDocumentsAsync returns no changes if base project does not exist var oldProject = oldSolution.GetProject(newProject.Id); Contract.ThrowIfNull(oldProject); // Ensure that all changed documents are in-sync. Once a document is in-sync it can't get out-of-sync. // Therefore, results of further computations based on base snapshots of changed documents can't be invalidated by // incoming events updating the content of out-of-sync documents. // // If in past we concluded that a document is out-of-sync, attempt to check one more time before we block apply. // The source file content might have been updated since the last time we checked. // // TODO (investigate): https://github.com/dotnet/roslyn/issues/38866 // It is possible that the result of Rude Edit semantic analysis of an unchanged document will change if there // another document is updated. If we encounter a significant case of this we should consider caching such a result per project, // rather then per document. Also, we might be observing an older semantics if the document that is causing the change is out-of-sync -- // e.g. the binary was built with an overload C.M(object), but a generator updated class C to also contain C.M(string), // which change we have not observed yet. Then call-sites of C.M in a changed document observed by the analysis will be seen as C.M(object) // instead of the true C.M(string). var (changedDocumentAnalyses, documentDiagnostics) = await AnalyzeDocumentsAsync(changedOrAddedDocuments, solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (documentDiagnostics.Any()) { // The diagnostic hasn't been reported by GetDocumentDiagnosticsAsync since out-of-sync documents are likely to be synchronized // before the changes are attempted to be applied. If we still have any out-of-sync documents we report warnings and ignore changes in them. // If in future the file is updated so that its content matches the PDB checksum, the document transitions to a matching state, // and we consider any further changes to it for application. diagnostics.Add((newProject.Id, documentDiagnostics)); } // The capability of a module to apply edits may change during edit session if the user attaches debugger to // an additional process that doesn't support EnC (or detaches from such process). Before we apply edits // we need to check with the debugger. var (moduleDiagnostics, isModuleLoaded) = await GetModuleDiagnosticsAsync(mvid, newProject.Name, cancellationToken).ConfigureAwait(false); var isModuleEncBlocked = isModuleLoaded && !moduleDiagnostics.IsEmpty; if (isModuleEncBlocked) { diagnostics.Add((newProject.Id, moduleDiagnostics)); isBlocked = true; } var projectSummary = GetProjectAnalysisSymmary(changedDocumentAnalyses); if (projectSummary == ProjectAnalysisSummary.CompilationErrors) { isBlocked = true; } else if (projectSummary == ProjectAnalysisSummary.RudeEdits) { foreach (var analysis in changedDocumentAnalyses) { if (analysis.RudeEditErrors.Length > 0) { documentsWithRudeEdits.Add((analysis.DocumentId, analysis.RudeEditErrors)); Telemetry.LogRudeEditDiagnostics(analysis.RudeEditErrors); } } isBlocked = true; } if (isModuleEncBlocked || projectSummary != ProjectAnalysisSummary.ValidChanges) { Telemetry.LogProjectAnalysisSummary(projectSummary, moduleDiagnostics.NullToEmpty().SelectAsArray(d => d.Descriptor.Id), InBreakState); continue; } if (!DebuggingSession.TryGetOrCreateEmitBaseline(newProject, out var createBaselineDiagnostics, out var baseline, out var baselineAccessLock)) { Debug.Assert(!createBaselineDiagnostics.IsEmpty); // Report diagnosics even when the module is never going to be loaded (e.g. in multi-targeting scenario, where only one framework being debugged). // This is consistent with reporting compilation errors - the IDE reports them for all TFMs regardless of what framework the app is running on. diagnostics.Add((newProject.Id, createBaselineDiagnostics)); Telemetry.LogProjectAnalysisSummary(projectSummary, createBaselineDiagnostics, InBreakState); isBlocked = true; continue; } EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]", newProject.Id.DebugName, newProject.Id); var oldCompilation = await oldProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var newCompilation = await newProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(oldCompilation); Contract.ThrowIfNull(newCompilation); var oldActiveStatementsMap = await BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); var projectChanges = await GetProjectChangesAsync(oldActiveStatementsMap, oldCompilation, newCompilation, oldProject, newProject, changedDocumentAnalyses, cancellationToken).ConfigureAwait(false); using var pdbStream = SerializableBytes.CreateWritableStream(); using var metadataStream = SerializableBytes.CreateWritableStream(); using var ilStream = SerializableBytes.CreateWritableStream(); // project must support compilations since it supports EnC Contract.ThrowIfNull(newCompilation); EmitDifferenceResult emitResult; // The lock protects underlying baseline readers from being disposed while emitting delta. // If the lock is disposed at this point the session has been incorrectly disposed while operations on it are in progress. using (baselineAccessLock.DisposableRead()) { DebuggingSession.ThrowIfDisposed(); emitResult = newCompilation.EmitDifference( baseline, projectChanges.SemanticEdits, projectChanges.AddedSymbols.Contains, metadataStream, ilStream, pdbStream, cancellationToken); } if (emitResult.Success) { Contract.ThrowIfNull(emitResult.Baseline); var unsupportedChangesDiagnostic = await GetUnsupportedChangesDiagnosticAsync(emitResult, cancellationToken).ConfigureAwait(false); if (unsupportedChangesDiagnostic is not null) { diagnostics.Add((newProject.Id, ImmutableArray.Create(unsupportedChangesDiagnostic))); isBlocked = true; } else { var updatedMethodTokens = emitResult.UpdatedMethods.SelectAsArray(h => MetadataTokens.GetToken(h)); var changedTypeTokens = emitResult.ChangedTypes.SelectAsArray(h => MetadataTokens.GetToken(h)); // Determine all active statements whose span changed and exception region span deltas. GetActiveStatementAndExceptionRegionSpans( mvid, oldActiveStatementsMap, updatedMethodTokens, NonRemappableRegions, projectChanges.ActiveStatementChanges, out var activeStatementsInUpdatedMethods, out var moduleNonRemappableRegions, out var exceptionRegionUpdates); deltas.Add(new ManagedModuleUpdate( mvid, ilStream.ToImmutableArray(), metadataStream.ToImmutableArray(), pdbStream.ToImmutableArray(), projectChanges.LineChanges, updatedMethodTokens, changedTypeTokens, activeStatementsInUpdatedMethods, exceptionRegionUpdates)); nonRemappableRegions.Add((mvid, moduleNonRemappableRegions)); emitBaselines.Add((newProject.Id, emitResult.Baseline)); } } else { // error isBlocked = true; } // TODO: https://github.com/dotnet/roslyn/issues/36061 // We should only report diagnostics from emit phase. // Syntax and semantic diagnostics are already reported by the diagnostic analyzer. // Currently we do not have means to distinguish between diagnostics reported from compilation and emit phases. // Querying diagnostics of the entire compilation or just the updated files migth be slow. // In fact, it is desirable to allow emitting deltas for symbols affected by the change while allowing untouched // method bodies to have errors. if (!emitResult.Diagnostics.IsEmpty) { diagnostics.Add((newProject.Id, emitResult.Diagnostics)); } Telemetry.LogProjectAnalysisSummary(projectSummary, emitResult.Diagnostics, InBreakState); } var update = isBlocked ? SolutionUpdate.Blocked(diagnostics.ToImmutable(), documentsWithRudeEdits.ToImmutable()) : new SolutionUpdate( new ManagedModuleUpdates( (deltas.Count > 0) ? ManagedModuleUpdateStatus.Ready : ManagedModuleUpdateStatus.None, deltas.ToImmutable()), nonRemappableRegions.ToImmutable(), emitBaselines.ToImmutable(), diagnostics.ToImmutable(), documentsWithRudeEdits.ToImmutable()); return update; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } // internal for testing internal static void GetActiveStatementAndExceptionRegionSpans( Guid moduleId, ActiveStatementsMap oldActiveStatementMap, ImmutableArray<int> updatedMethodTokens, ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> previousNonRemappableRegions, ImmutableArray<DocumentActiveStatementChanges> activeStatementsInChangedDocuments, out ImmutableArray<ManagedActiveStatementUpdate> activeStatementsInUpdatedMethods, out ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)> nonRemappableRegions, out ImmutableArray<ManagedExceptionRegionUpdate> exceptionRegionUpdates) { using var _1 = PooledDictionary<(ManagedModuleMethodId MethodId, SourceFileSpan BaseSpan), SourceFileSpan>.GetInstance(out var changedNonRemappableSpans); var activeStatementsInUpdatedMethodsBuilder = ArrayBuilder<ManagedActiveStatementUpdate>.GetInstance(); var nonRemappableRegionsBuilder = ArrayBuilder<(ManagedModuleMethodId Method, NonRemappableRegion Region)>.GetInstance(); // Process active statements and their exception regions in changed documents of this project/module: foreach (var (oldActiveStatements, newActiveStatements, newExceptionRegions) in activeStatementsInChangedDocuments) { Debug.Assert(oldActiveStatements.Length == newExceptionRegions.Length); Debug.Assert(newActiveStatements.Length == newExceptionRegions.Length); for (var i = 0; i < newActiveStatements.Length; i++) { var (_, oldActiveStatement, oldActiveStatementExceptionRegions) = oldActiveStatements[i]; var newActiveStatement = newActiveStatements[i]; var newActiveStatementExceptionRegions = newExceptionRegions[i]; var instructionId = newActiveStatement.InstructionId; var methodId = instructionId.Method.Method; var isMethodUpdated = updatedMethodTokens.Contains(methodId.Token); if (isMethodUpdated) { activeStatementsInUpdatedMethodsBuilder.Add(new ManagedActiveStatementUpdate(methodId, instructionId.ILOffset, newActiveStatement.Span.ToSourceSpan())); } Debug.Assert(!oldActiveStatement.IsStale); // Adds a region with specified PDB spans. void AddNonRemappableRegion(SourceFileSpan oldSpan, SourceFileSpan newSpan, bool isExceptionRegion) { // it is a rude edit to change the path of the region span: Debug.Assert(oldSpan.Path == newSpan.Path); // The up-to-date flag is copied when new active statement is created from the corresponding old one. Debug.Assert(oldActiveStatement.IsMethodUpToDate == newActiveStatement.IsMethodUpToDate); if (oldActiveStatement.IsMethodUpToDate) { // Start tracking non-remappable regions for active statements in methods that were up-to-date // when break state was entered and now being updated (regardless of whether the active span changed or not). if (isMethodUpdated) { var lineDelta = oldSpan.Span.GetLineDelta(newSpan: newSpan.Span); nonRemappableRegionsBuilder.Add((methodId, new NonRemappableRegion(oldSpan, lineDelta, isExceptionRegion))); } else if (!isExceptionRegion) { // If the method has been up-to-date and it is not updated now then either the active statement span has not changed, // or the entire method containing it moved. In neither case do we need to start tracking non-remapable region // for the active statement since movement of whole method bodies (if any) is handled only on PDB level without // triggering any remapping on the IL level. // // That said, we still add a non-remappable region for this active statement, so that we know in future sessions // that this active statement existed and its span has not changed. We don't report these regions to the debugger, // but we use them to map active statement spans to the baseline snapshots of following edit sessions. nonRemappableRegionsBuilder.Add((methodId, new NonRemappableRegion(oldSpan, lineDelta: 0, isExceptionRegion: false))); } } else if (oldSpan.Span != newSpan.Span) { // The method is not up-to-date hence we might have a previous non-remappable span mapping that needs to be brought forward to the new snapshot. changedNonRemappableSpans[(methodId, oldSpan)] = newSpan; } } AddNonRemappableRegion(oldActiveStatement.FileSpan, newActiveStatement.FileSpan, isExceptionRegion: false); // The spans of the exception regions are known (non-default) for active statements in changed documents // as we ensured earlier that all changed documents are in-sync. for (var j = 0; j < oldActiveStatementExceptionRegions.Spans.Length; j++) { AddNonRemappableRegion(oldActiveStatementExceptionRegions.Spans[j], newActiveStatementExceptionRegions[j], isExceptionRegion: true); } } } activeStatementsInUpdatedMethods = activeStatementsInUpdatedMethodsBuilder.ToImmutableAndFree(); // Gather all active method instances contained in this project/module that are not up-to-date: using var _2 = PooledHashSet<ManagedModuleMethodId>.GetInstance(out var unremappedActiveMethods); foreach (var (instruction, baseActiveStatement) in oldActiveStatementMap.InstructionMap) { if (moduleId == instruction.Method.Module && !baseActiveStatement.IsMethodUpToDate) { unremappedActiveMethods.Add(instruction.Method.Method); } } // Update previously calculated non-remappable region mappings. // These map to the old snapshot and we need them to map to the new snapshot, which will be the baseline for the next session. if (unremappedActiveMethods.Count > 0) { foreach (var (methodInstance, regionsInMethod) in previousNonRemappableRegions) { // Skip non-remappable regions that belong to method instances that are from a different module. if (methodInstance.Module != moduleId) { continue; } // Skip no longer active methods - all active statements in these method instances have been remapped to newer versions. // New active statement can't appear in a stale method instance since such instance can't be invoked. if (!unremappedActiveMethods.Contains(methodInstance.Method)) { continue; } foreach (var region in regionsInMethod) { // We have calculated changes against a base snapshot (last break state): var baseSpan = region.Span.AddLineDelta(region.LineDelta); NonRemappableRegion newRegion; if (changedNonRemappableSpans.TryGetValue((methodInstance.Method, baseSpan), out var newSpan)) { // all spans must be of the same size: Debug.Assert(newSpan.Span.End.Line - newSpan.Span.Start.Line == baseSpan.Span.End.Line - baseSpan.Span.Start.Line); Debug.Assert(region.Span.Span.End.Line - region.Span.Span.Start.Line == baseSpan.Span.End.Line - baseSpan.Span.Start.Line); Debug.Assert(newSpan.Path == region.Span.Path); newRegion = region.WithLineDelta(region.Span.Span.GetLineDelta(newSpan: newSpan.Span)); } else { newRegion = region; } nonRemappableRegionsBuilder.Add((methodInstance.Method, newRegion)); } } } nonRemappableRegions = nonRemappableRegionsBuilder.ToImmutableAndFree(); // Note: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1319289 // // The update should include the file name, otherwise it is not possible for the debugger to find // the right IL span of the exception handler in case when multiple handlers in the same method // have the same mapped span but different mapped file name: // // try { active statement } // #line 20 "bar" // catch (IOException) { } // #line 20 "baz" // catch (Exception) { } // // The range span in exception region updates is the new span. Deltas are inverse. // old = new + delta // new = old – delta exceptionRegionUpdates = nonRemappableRegions.SelectAsArray( r => r.Region.IsExceptionRegion, r => new ManagedExceptionRegionUpdate( r.Method, -r.Region.LineDelta, r.Region.Span.AddLineDelta(r.Region.LineDelta).Span.ToSourceSpan())); } } }
// Licensed to the .NET Foundation under one or more 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.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class EditSession { internal readonly DebuggingSession DebuggingSession; internal readonly EditSessionTelemetry Telemetry; // Maps active statement instructions reported by the debugger to their latest spans that might not yet have been applied // (remapping not triggered yet). Consumed by the next edit session and updated when changes are committed at the end of the edit session. // // Consider a function F containing a call to function G. While G is being executed, F is updated a couple of times (in two edit sessions) // before the thread returns from G and is remapped to the latest version of F. At the start of the second edit session, // the active instruction reported by the debugger is still at the original location since function F has not been remapped yet (G has not returned yet). // // '>' indicates an active statement instruction for non-leaf frame reported by the debugger. // v1 - before first edit, G executing // v2 - after first edit, G still executing // v3 - after second edit and G returned // // F v1: F v2: F v3: // 0: nop 0: nop 0: nop // 1> G() 1> nop 1: nop // 2: nop 2: G() 2: nop // 3: nop 3: nop 3> G() // // When entering a break state we query the debugger for current active statements. // The returned statements reflect the current state of the threads in the runtime. // When a change is successfully applied we remember changes in active statement spans. // These changes are passed to the next edit session. // We use them to map the spans for active statements returned by the debugger. // // In the above case the sequence of events is // 1st break: get active statements returns (F, v=1, il=1, span1) the active statement is up-to-date // 1st apply: detected span change for active statement (F, v=1, il=1): span1->span2 // 2nd break: previously updated statements contains (F, v=1, il=1)->span2 // get active statements returns (F, v=1, il=1, span1) which is mapped to (F, v=1, il=1, span2) using previously updated statements // 2nd apply: detected span change for active statement (F, v=1, il=1): span2->span3 // 3rd break: previously updated statements contains (F, v=1, il=1)->span3 // get active statements returns (F, v=3, il=3, span3) the active statement is up-to-date // internal readonly ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> NonRemappableRegions; /// <summary> /// Gets the capabilities of the runtime with respect to applying code changes. /// Retrieved lazily from <see cref="DebuggingSession.DebuggerService"/> since they are only needed when changes are detected in the solution. /// </summary> internal readonly AsyncLazy<EditAndContinueCapabilities> Capabilities; /// <summary> /// Map of base active statements. /// Calculated lazily based on info retrieved from <see cref="DebuggingSession.DebuggerService"/> since it is only needed when changes are detected in the solution. /// </summary> internal readonly AsyncLazy<ActiveStatementsMap> BaseActiveStatements; /// <summary> /// Cache of document EnC analyses. /// </summary> internal readonly EditAndContinueDocumentAnalysesCache Analyses; /// <summary> /// True for Edit and Continue edit sessions - when the application is in break state. /// False for Hot Reload edit sessions - when the application is running. /// </summary> internal readonly bool InBreakState; /// <summary> /// A <see cref="DocumentId"/> is added whenever EnC analyzer reports /// rude edits or module diagnostics. At the end of the session we ask the diagnostic analyzer to reanalyze /// the documents to clean up the diagnostics. /// </summary> private readonly HashSet<DocumentId> _documentsWithReportedDiagnostics = new(); private readonly object _documentsWithReportedDiagnosticsGuard = new(); internal EditSession( DebuggingSession debuggingSession, ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> nonRemappableRegions, EditSessionTelemetry telemetry, bool inBreakState) { DebuggingSession = debuggingSession; NonRemappableRegions = nonRemappableRegions; Telemetry = telemetry; InBreakState = inBreakState; BaseActiveStatements = inBreakState ? new AsyncLazy<ActiveStatementsMap>(GetBaseActiveStatementsAsync, cacheResult: true) : new AsyncLazy<ActiveStatementsMap>(ActiveStatementsMap.Empty); Capabilities = new AsyncLazy<EditAndContinueCapabilities>(GetCapabilitiesAsync, cacheResult: true); Analyses = new EditAndContinueDocumentAnalysesCache(BaseActiveStatements, Capabilities); } /// <summary> /// The compiler has various scenarios that will cause it to synthesize things that might not be covered /// by existing rude edits, but we still need to ensure the runtime supports them before we proceed. /// </summary> private async Task<Diagnostic?> GetUnsupportedChangesDiagnosticAsync(EmitDifferenceResult emitResult, CancellationToken cancellationToken) { Debug.Assert(emitResult.Success); Debug.Assert(emitResult.Baseline is not null); var capabilities = await Capabilities.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { // If the runtime doesn't support adding new types then we expect every row number for any type that is // emitted will be less than or equal to the number of rows in the original metadata. var highestEmittedTypeDefRow = emitResult.ChangedTypes.Max(t => MetadataTokens.GetRowNumber(t)); var highestExistingTypeDefRow = emitResult.Baseline.OriginalMetadata.GetMetadataReader().GetTableRowCount(TableIndex.TypeDef); if (highestEmittedTypeDefRow > highestExistingTypeDefRow) { var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.AddingTypeRuntimeCapabilityRequired); return Diagnostic.Create(descriptor, Location.None); } } return null; } /// <summary> /// Errors to be reported when a project is updated but the corresponding module does not support EnC. /// </summary> /// <returns><see langword="default"/> if the module is not loaded.</returns> public async Task<ImmutableArray<Diagnostic>?> GetModuleDiagnosticsAsync(Guid mvid, string projectDisplayName, CancellationToken cancellationToken) { var availability = await DebuggingSession.DebuggerService.GetAvailabilityAsync(mvid, cancellationToken).ConfigureAwait(false); if (availability.Status == ManagedEditAndContinueAvailabilityStatus.ModuleNotLoaded) { return null; } if (availability.Status == ManagedEditAndContinueAvailabilityStatus.Available) { return ImmutableArray<Diagnostic>.Empty; } var descriptor = EditAndContinueDiagnosticDescriptors.GetModuleDiagnosticDescriptor(availability.Status); return ImmutableArray.Create(Diagnostic.Create(descriptor, Location.None, new[] { projectDisplayName, availability.LocalizedMessage })); } private async Task<EditAndContinueCapabilities> GetCapabilitiesAsync(CancellationToken cancellationToken) { try { var capabilities = await DebuggingSession.DebuggerService.GetCapabilitiesAsync(cancellationToken).ConfigureAwait(false); return EditAndContinueCapabilitiesParser.Parse(capabilities); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return EditAndContinueCapabilities.Baseline; } } private async Task<ActiveStatementsMap> GetBaseActiveStatementsAsync(CancellationToken cancellationToken) { try { // Last committed solution reflects the state of the source that is in sync with the binaries that are loaded in the debuggee. var debugInfos = await DebuggingSession.DebuggerService.GetActiveStatementsAsync(cancellationToken).ConfigureAwait(false); return ActiveStatementsMap.Create(debugInfos, NonRemappableRegions); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return ActiveStatementsMap.Empty; } } private static async Task PopulateChangedAndAddedDocumentsAsync(CommittedSolution oldSolution, Project newProject, ArrayBuilder<Document> changedOrAddedDocuments, CancellationToken cancellationToken) { changedOrAddedDocuments.Clear(); if (!newProject.SupportsEditAndContinue()) { return; } var oldProject = oldSolution.GetProject(newProject.Id); // When debugging session is started some projects might not have been loaded to the workspace yet. // We capture the base solution. Edits in files that are in projects that haven't been loaded won't be applied // and will result in source mismatch when the user steps into them. // // TODO (https://github.com/dotnet/roslyn/issues/1204): // hook up the debugger reported error, check that the project has not been loaded and report a better error. // Here, we assume these projects are not modified. if (oldProject == null) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not loaded", newProject.Id.DebugName, newProject.Id); return; } if (oldProject.State == newProject.State) { return; } foreach (var documentId in newProject.State.DocumentStates.GetChangedStateIds(oldProject.State.DocumentStates, ignoreUnchangedContent: true)) { var document = newProject.GetRequiredDocument(documentId); if (document.State.Attributes.DesignTimeOnly) { continue; } // Check if the currently observed document content has changed compared to the base document content. // This is an important optimization that aims to avoid IO while stepping in sources that have not changed. // // We may be comparing out-of-date committed document content but we only make a decision based on that content // if it matches the current content. If the current content is equal to baseline content that does not match // the debuggee then the workspace has not observed the change made to the file on disk since baseline was captured // (there had to be one as the content doesn't match). When we are about to apply changes it is ok to ignore this // document because the user does not see the change yet in the buffer (if the doc is open) and won't be confused // if it is not applied yet. The change will be applied later after it's observed by the workspace. var baseSource = await oldProject.GetRequiredDocument(documentId).GetTextAsync(cancellationToken).ConfigureAwait(false); var source = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (baseSource.ContentEquals(source)) { continue; } changedOrAddedDocuments.Add(document); } foreach (var documentId in newProject.State.DocumentStates.GetAddedStateIds(oldProject.State.DocumentStates)) { var document = newProject.GetRequiredDocument(documentId); if (document.State.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(document); } // TODO: support document removal/rename (see https://github.com/dotnet/roslyn/issues/41144, https://github.com/dotnet/roslyn/issues/49013). if (changedOrAddedDocuments.IsEmpty() && !HasChangesThatMayAffectSourceGenerators(oldProject.State, newProject.State)) { // Based on the above assumption there are no changes in source generated files. return; } cancellationToken.ThrowIfCancellationRequested(); var oldSourceGeneratedDocumentStates = await oldProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(oldProject.State, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var newSourceGeneratedDocumentStates = await newProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(newProject.State, cancellationToken).ConfigureAwait(false); foreach (var documentId in newSourceGeneratedDocumentStates.GetChangedStateIds(oldSourceGeneratedDocumentStates, ignoreUnchangedContent: true)) { var newState = newSourceGeneratedDocumentStates.GetRequiredState(documentId); if (newState.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(newProject.GetOrCreateSourceGeneratedDocument(newState)); } foreach (var documentId in newSourceGeneratedDocumentStates.GetAddedStateIds(oldSourceGeneratedDocumentStates)) { var newState = newSourceGeneratedDocumentStates.GetRequiredState(documentId); if (newState.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(newProject.GetOrCreateSourceGeneratedDocument(newState)); } } internal static async IAsyncEnumerable<DocumentId> GetChangedDocumentsAsync(CommittedSolution oldSolution, Project newProject, [EnumeratorCancellation] CancellationToken cancellationToken) { var oldProject = oldSolution.GetRequiredProject(newProject.Id); if (!newProject.SupportsEditAndContinue() || oldProject.State == newProject.State) { yield break; } foreach (var documentId in newProject.State.DocumentStates.GetChangedStateIds(oldProject.State.DocumentStates, ignoreUnchangedContent: true)) { yield return documentId; } if (!HasChangesThatMayAffectSourceGenerators(oldProject.State, newProject.State)) { // Based on the above assumption there are no changes in source generated files. yield break; } cancellationToken.ThrowIfCancellationRequested(); var oldSourceGeneratedDocumentStates = await oldProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(oldProject.State, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var newSourceGeneratedDocumentStates = await newProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(newProject.State, cancellationToken).ConfigureAwait(false); foreach (var documentId in newSourceGeneratedDocumentStates.GetChangedStateIds(oldSourceGeneratedDocumentStates, ignoreUnchangedContent: true)) { yield return documentId; } } /// <summary> /// Given the following assumptions: /// - source generators are deterministic, /// - source documents, metadata references and compilation options have not changed, /// - additional documents have not changed, /// - analyzer config documents have not changed, /// the outputs of source generators will not change. /// /// Currently it's not possible to change compilation options (Project System is readonly during debugging). /// </summary> private static bool HasChangesThatMayAffectSourceGenerators(ProjectState oldProject, ProjectState newProject) => newProject.DocumentStates.HasAnyStateChanges(oldProject.DocumentStates) || newProject.AdditionalDocumentStates.HasAnyStateChanges(oldProject.AdditionalDocumentStates) || newProject.AnalyzerConfigDocumentStates.HasAnyStateChanges(oldProject.AnalyzerConfigDocumentStates); private async Task<(ImmutableArray<DocumentAnalysisResults> results, ImmutableArray<Diagnostic> diagnostics)> AnalyzeDocumentsAsync( ArrayBuilder<Document> changedOrAddedDocuments, ActiveStatementSpanProvider newDocumentActiveStatementSpanProvider, CancellationToken cancellationToken) { using var _1 = ArrayBuilder<Diagnostic>.GetInstance(out var documentDiagnostics); using var _2 = ArrayBuilder<(Document? oldDocument, Document newDocument)>.GetInstance(out var documents); foreach (var newDocument in changedOrAddedDocuments) { var (oldDocument, oldDocumentState) = await DebuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken, reloadOutOfSyncDocument: true).ConfigureAwait(false); switch (oldDocumentState) { case CommittedSolution.DocumentState.DesignTimeOnly: break; case CommittedSolution.DocumentState.Indeterminate: case CommittedSolution.DocumentState.OutOfSync: var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor((oldDocumentState == CommittedSolution.DocumentState.Indeterminate) ? EditAndContinueErrorCode.UnableToReadSourceFileOrPdb : EditAndContinueErrorCode.DocumentIsOutOfSyncWithDebuggee); documentDiagnostics.Add(Diagnostic.Create(descriptor, Location.Create(newDocument.FilePath!, textSpan: default, lineSpan: default), new[] { newDocument.FilePath })); break; case CommittedSolution.DocumentState.MatchesBuildOutput: // Include the document regardless of whether the module it was built into has been loaded or not. // If the module has been built it might get loaded later during the debugging session, // at which point we apply all changes that have been made to the project so far. documents.Add((oldDocument, newDocument)); break; default: throw ExceptionUtilities.UnexpectedValue(oldDocumentState); } } var analyses = await Analyses.GetDocumentAnalysesAsync(DebuggingSession.LastCommittedSolution, documents, newDocumentActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); return (analyses, documentDiagnostics.ToImmutable()); } internal ImmutableArray<DocumentId> GetDocumentsWithReportedDiagnostics() { lock (_documentsWithReportedDiagnosticsGuard) { return ImmutableArray.CreateRange(_documentsWithReportedDiagnostics); } } internal void TrackDocumentWithReportedDiagnostics(DocumentId documentId) { lock (_documentsWithReportedDiagnosticsGuard) { _documentsWithReportedDiagnostics.Add(documentId); } } /// <summary> /// Determines whether projects contain any changes that might need to be applied. /// Checks only projects containing a given <paramref name="sourceFilePath"/> or all projects of the solution if <paramref name="sourceFilePath"/> is null. /// Invoked by the debugger on every step. It is critical for stepping performance that this method returns as fast as possible in absence of changes. /// </summary> public async ValueTask<bool> HasChangesAsync(Solution solution, ActiveStatementSpanProvider solutionActiveStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { try { var baseSolution = DebuggingSession.LastCommittedSolution; if (baseSolution.HasNoChanges(solution)) { return false; } // TODO: source generated files? var projects = (sourceFilePath == null) ? solution.Projects : from documentId in solution.GetDocumentIdsWithFilePath(sourceFilePath) select solution.GetProject(documentId.ProjectId)!; using var _ = ArrayBuilder<Document>.GetInstance(out var changedOrAddedDocuments); foreach (var project in projects) { await PopulateChangedAndAddedDocumentsAsync(baseSolution, project, changedOrAddedDocuments, cancellationToken).ConfigureAwait(false); if (changedOrAddedDocuments.IsEmpty()) { continue; } // Check MVID before analyzing documents as the analysis needs to read the PDB which will likely fail if we can't even read the MVID. var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(project, cancellationToken).ConfigureAwait(false); if (mvidReadError != null) { // Can't read MVID. This might be an intermittent failure, so don't report it here. // Report the project as containing changes, so that we proceed to EmitSolutionUpdateAsync where we report the error if it still persists. EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not built", project.Id.DebugName, project.Id); return true; } if (mvid == Guid.Empty) { // Project not built. We ignore any changes made in its sources. EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not built", project.Id.DebugName, project.Id); continue; } var (changedDocumentAnalyses, documentDiagnostics) = await AnalyzeDocumentsAsync(changedOrAddedDocuments, solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (documentDiagnostics.Any()) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: out-of-sync documents present (diagnostic: '{2}')", project.Id.DebugName, project.Id, documentDiagnostics[0]); // Although we do not apply changes in out-of-sync/indeterminate documents we report that changes are present, // so that the debugger triggers emit of updates. There we check if these documents are still in a bad state and report warnings // that any changes in such documents are not applied. return true; } var projectSummary = GetProjectAnalysisSymmary(changedDocumentAnalyses); if (projectSummary != ProjectAnalysisSummary.NoChanges) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: {2}", project.Id.DebugName, project.Id, projectSummary); return true; } } return false; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private static ProjectAnalysisSummary GetProjectAnalysisSymmary(ImmutableArray<DocumentAnalysisResults> documentAnalyses) { var hasChanges = false; var hasSignificantValidChanges = false; foreach (var analysis in documentAnalyses) { // skip documents that actually were not changed: if (!analysis.HasChanges) { continue; } // rude edit detection wasn't completed due to errors that prevent us from analyzing the document: if (analysis.HasChangesAndSyntaxErrors) { return ProjectAnalysisSummary.CompilationErrors; } // rude edits detected: if (!analysis.RudeEditErrors.IsEmpty) { return ProjectAnalysisSummary.RudeEdits; } hasChanges = true; hasSignificantValidChanges |= analysis.HasSignificantValidChanges; } if (!hasChanges) { // we get here if a document is closed and reopen without any actual change: return ProjectAnalysisSummary.NoChanges; } if (!hasSignificantValidChanges) { return ProjectAnalysisSummary.ValidInsignificantChanges; } return ProjectAnalysisSummary.ValidChanges; } internal static async ValueTask<ProjectChanges> GetProjectChangesAsync( ActiveStatementsMap baseActiveStatements, Compilation oldCompilation, Compilation newCompilation, Project oldProject, Project newProject, ImmutableArray<DocumentAnalysisResults> changedDocumentAnalyses, CancellationToken cancellationToken) { try { using var _1 = ArrayBuilder<SemanticEditInfo>.GetInstance(out var allEdits); using var _2 = ArrayBuilder<SequencePointUpdates>.GetInstance(out var allLineEdits); using var _3 = ArrayBuilder<DocumentActiveStatementChanges>.GetInstance(out var activeStatementsInChangedDocuments); var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); foreach (var analysis in changedDocumentAnalyses) { if (!analysis.HasSignificantValidChanges) { continue; } // we shouldn't be asking for deltas in presence of errors: Contract.ThrowIfTrue(analysis.HasChangesAndErrors); // Active statements are calculated if document changed and has no syntax errors: Contract.ThrowIfTrue(analysis.ActiveStatements.IsDefault); allEdits.AddRange(analysis.SemanticEdits); allLineEdits.AddRange(analysis.LineEdits); if (analysis.ActiveStatements.Length > 0) { var oldDocument = await oldProject.GetDocumentAsync(analysis.DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var oldActiveStatements = (oldDocument == null) ? ImmutableArray<UnmappedActiveStatement>.Empty : await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); activeStatementsInChangedDocuments.Add(new(oldActiveStatements, analysis.ActiveStatements, analysis.ExceptionRegions)); } } MergePartialEdits(oldCompilation, newCompilation, allEdits, out var mergedEdits, out var addedSymbols, cancellationToken); return new ProjectChanges( mergedEdits, allLineEdits.ToImmutable(), addedSymbols, activeStatementsInChangedDocuments.ToImmutable()); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } internal static void MergePartialEdits( Compilation oldCompilation, Compilation newCompilation, IReadOnlyList<SemanticEditInfo> edits, out ImmutableArray<SemanticEdit> mergedEdits, out ImmutableHashSet<ISymbol> addedSymbols, CancellationToken cancellationToken) { using var _0 = ArrayBuilder<SemanticEdit>.GetInstance(edits.Count, out var mergedEditsBuilder); using var _1 = PooledHashSet<ISymbol>.GetInstance(out var addedSymbolsBuilder); using var _2 = ArrayBuilder<(ISymbol? oldSymbol, ISymbol? newSymbol)>.GetInstance(edits.Count, out var resolvedSymbols); foreach (var edit in edits) { SymbolKeyResolution oldResolution; if (edit.Kind is SemanticEditKind.Update or SemanticEditKind.Delete) { oldResolution = edit.Symbol.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken); Contract.ThrowIfNull(oldResolution.Symbol); } else { oldResolution = default; } SymbolKeyResolution newResolution; if (edit.Kind is SemanticEditKind.Update or SemanticEditKind.Insert or SemanticEditKind.Replace) { newResolution = edit.Symbol.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken); Contract.ThrowIfNull(newResolution.Symbol); } else { newResolution = default; } resolvedSymbols.Add((oldResolution.Symbol, newResolution.Symbol)); } for (var i = 0; i < edits.Count; i++) { var edit = edits[i]; if (edit.PartialType == null) { var (oldSymbol, newSymbol) = resolvedSymbols[i]; if (edit.Kind == SemanticEditKind.Insert) { Contract.ThrowIfNull(newSymbol); addedSymbolsBuilder.Add(newSymbol); } mergedEditsBuilder.Add(new SemanticEdit( edit.Kind, oldSymbol: oldSymbol, newSymbol: newSymbol, syntaxMap: edit.SyntaxMap, preserveLocalVariables: edit.SyntaxMap != null)); } } // no partial type merging needed: if (edits.Count == mergedEditsBuilder.Count) { mergedEdits = mergedEditsBuilder.ToImmutable(); addedSymbols = addedSymbolsBuilder.ToImmutableHashSet(); return; } // Calculate merged syntax map for each partial type symbol: var symbolKeyComparer = SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: true); var mergedSyntaxMaps = new Dictionary<SymbolKey, Func<SyntaxNode, SyntaxNode?>?>(symbolKeyComparer); var editsByPartialType = edits .Where(edit => edit.PartialType != null) .GroupBy(edit => edit.PartialType!.Value, symbolKeyComparer); foreach (var partialTypeEdits in editsByPartialType) { // Either all edits have syntax map or none has. Debug.Assert( partialTypeEdits.All(edit => edit.SyntaxMapTree != null && edit.SyntaxMap != null) || partialTypeEdits.All(edit => edit.SyntaxMapTree == null && edit.SyntaxMap == null)); Func<SyntaxNode, SyntaxNode?>? mergedSyntaxMap; if (partialTypeEdits.First().SyntaxMap != null) { var newTrees = partialTypeEdits.SelectAsArray(edit => edit.SyntaxMapTree!); var syntaxMaps = partialTypeEdits.SelectAsArray(edit => edit.SyntaxMap!); mergedSyntaxMap = node => syntaxMaps[newTrees.IndexOf(node.SyntaxTree)](node); } else { mergedSyntaxMap = null; } mergedSyntaxMaps.Add(partialTypeEdits.Key, mergedSyntaxMap); } // Deduplicate edits based on their target symbol and use merged syntax map calculated above for a given partial type. using var _3 = PooledHashSet<ISymbol>.GetInstance(out var visitedSymbols); for (var i = 0; i < edits.Count; i++) { var edit = edits[i]; if (edit.PartialType != null) { var (oldSymbol, newSymbol) = resolvedSymbols[i]; if (visitedSymbols.Add(newSymbol ?? oldSymbol!)) { var syntaxMap = mergedSyntaxMaps[edit.PartialType.Value]; mergedEditsBuilder.Add(new SemanticEdit(edit.Kind, oldSymbol, newSymbol, syntaxMap, preserveLocalVariables: syntaxMap != null)); } } } mergedEdits = mergedEditsBuilder.ToImmutable(); addedSymbols = addedSymbolsBuilder.ToImmutableHashSet(); } public async ValueTask<SolutionUpdate> EmitSolutionUpdateAsync(Solution solution, ActiveStatementSpanProvider solutionActiveStatementSpanProvider, CancellationToken cancellationToken) { try { using var _1 = ArrayBuilder<ManagedModuleUpdate>.GetInstance(out var deltas); using var _2 = ArrayBuilder<(Guid ModuleId, ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)>)>.GetInstance(out var nonRemappableRegions); using var _3 = ArrayBuilder<(ProjectId, EmitBaseline)>.GetInstance(out var emitBaselines); using var _4 = ArrayBuilder<(ProjectId, ImmutableArray<Diagnostic>)>.GetInstance(out var diagnostics); using var _5 = ArrayBuilder<Document>.GetInstance(out var changedOrAddedDocuments); using var _6 = ArrayBuilder<(DocumentId, ImmutableArray<RudeEditDiagnostic>)>.GetInstance(out var documentsWithRudeEdits); var oldSolution = DebuggingSession.LastCommittedSolution; var isBlocked = false; foreach (var newProject in solution.Projects) { await PopulateChangedAndAddedDocumentsAsync(oldSolution, newProject, changedOrAddedDocuments, cancellationToken).ConfigureAwait(false); if (changedOrAddedDocuments.IsEmpty()) { continue; } var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(newProject, cancellationToken).ConfigureAwait(false); if (mvidReadError != null) { // The error hasn't been reported by GetDocumentDiagnosticsAsync since it might have been intermittent. // The MVID is required for emit so we consider the error permanent and report it here. // Bail before analyzing documents as the analysis needs to read the PDB which will likely fail if we can't even read the MVID. diagnostics.Add((newProject.Id, ImmutableArray.Create(mvidReadError))); Telemetry.LogProjectAnalysisSummary(ProjectAnalysisSummary.ValidChanges, ImmutableArray.Create(mvidReadError.Descriptor.Id), InBreakState); isBlocked = true; continue; } if (mvid == Guid.Empty) { EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]: project not built", newProject.Id.DebugName, newProject.Id); continue; } // PopulateChangedAndAddedDocumentsAsync returns no changes if base project does not exist var oldProject = oldSolution.GetProject(newProject.Id); Contract.ThrowIfNull(oldProject); // Ensure that all changed documents are in-sync. Once a document is in-sync it can't get out-of-sync. // Therefore, results of further computations based on base snapshots of changed documents can't be invalidated by // incoming events updating the content of out-of-sync documents. // // If in past we concluded that a document is out-of-sync, attempt to check one more time before we block apply. // The source file content might have been updated since the last time we checked. // // TODO (investigate): https://github.com/dotnet/roslyn/issues/38866 // It is possible that the result of Rude Edit semantic analysis of an unchanged document will change if there // another document is updated. If we encounter a significant case of this we should consider caching such a result per project, // rather then per document. Also, we might be observing an older semantics if the document that is causing the change is out-of-sync -- // e.g. the binary was built with an overload C.M(object), but a generator updated class C to also contain C.M(string), // which change we have not observed yet. Then call-sites of C.M in a changed document observed by the analysis will be seen as C.M(object) // instead of the true C.M(string). var (changedDocumentAnalyses, documentDiagnostics) = await AnalyzeDocumentsAsync(changedOrAddedDocuments, solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (documentDiagnostics.Any()) { // The diagnostic hasn't been reported by GetDocumentDiagnosticsAsync since out-of-sync documents are likely to be synchronized // before the changes are attempted to be applied. If we still have any out-of-sync documents we report warnings and ignore changes in them. // If in future the file is updated so that its content matches the PDB checksum, the document transitions to a matching state, // and we consider any further changes to it for application. diagnostics.Add((newProject.Id, documentDiagnostics)); } // The capability of a module to apply edits may change during edit session if the user attaches debugger to // an additional process that doesn't support EnC (or detaches from such process). Before we apply edits // we need to check with the debugger. var (moduleDiagnostics, isModuleLoaded) = await GetModuleDiagnosticsAsync(mvid, newProject.Name, cancellationToken).ConfigureAwait(false); var isModuleEncBlocked = isModuleLoaded && !moduleDiagnostics.IsEmpty; if (isModuleEncBlocked) { diagnostics.Add((newProject.Id, moduleDiagnostics)); isBlocked = true; } var projectSummary = GetProjectAnalysisSymmary(changedDocumentAnalyses); if (projectSummary == ProjectAnalysisSummary.CompilationErrors) { isBlocked = true; } else if (projectSummary == ProjectAnalysisSummary.RudeEdits) { foreach (var analysis in changedDocumentAnalyses) { if (analysis.RudeEditErrors.Length > 0) { documentsWithRudeEdits.Add((analysis.DocumentId, analysis.RudeEditErrors)); Telemetry.LogRudeEditDiagnostics(analysis.RudeEditErrors); } } isBlocked = true; } if (isModuleEncBlocked || projectSummary != ProjectAnalysisSummary.ValidChanges) { Telemetry.LogProjectAnalysisSummary(projectSummary, moduleDiagnostics.NullToEmpty().SelectAsArray(d => d.Descriptor.Id), InBreakState); continue; } if (!DebuggingSession.TryGetOrCreateEmitBaseline(newProject, out var createBaselineDiagnostics, out var baseline, out var baselineAccessLock)) { Debug.Assert(!createBaselineDiagnostics.IsEmpty); // Report diagnosics even when the module is never going to be loaded (e.g. in multi-targeting scenario, where only one framework being debugged). // This is consistent with reporting compilation errors - the IDE reports them for all TFMs regardless of what framework the app is running on. diagnostics.Add((newProject.Id, createBaselineDiagnostics)); Telemetry.LogProjectAnalysisSummary(projectSummary, createBaselineDiagnostics, InBreakState); isBlocked = true; continue; } EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]", newProject.Id.DebugName, newProject.Id); var oldCompilation = await oldProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var newCompilation = await newProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(oldCompilation); Contract.ThrowIfNull(newCompilation); var oldActiveStatementsMap = await BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); var projectChanges = await GetProjectChangesAsync(oldActiveStatementsMap, oldCompilation, newCompilation, oldProject, newProject, changedDocumentAnalyses, cancellationToken).ConfigureAwait(false); using var pdbStream = SerializableBytes.CreateWritableStream(); using var metadataStream = SerializableBytes.CreateWritableStream(); using var ilStream = SerializableBytes.CreateWritableStream(); // project must support compilations since it supports EnC Contract.ThrowIfNull(newCompilation); EmitDifferenceResult emitResult; // The lock protects underlying baseline readers from being disposed while emitting delta. // If the lock is disposed at this point the session has been incorrectly disposed while operations on it are in progress. using (baselineAccessLock.DisposableRead()) { DebuggingSession.ThrowIfDisposed(); emitResult = newCompilation.EmitDifference( baseline, projectChanges.SemanticEdits, projectChanges.AddedSymbols.Contains, metadataStream, ilStream, pdbStream, cancellationToken); } if (emitResult.Success) { Contract.ThrowIfNull(emitResult.Baseline); var unsupportedChangesDiagnostic = await GetUnsupportedChangesDiagnosticAsync(emitResult, cancellationToken).ConfigureAwait(false); if (unsupportedChangesDiagnostic is not null) { diagnostics.Add((newProject.Id, ImmutableArray.Create(unsupportedChangesDiagnostic))); isBlocked = true; } else { var updatedMethodTokens = emitResult.UpdatedMethods.SelectAsArray(h => MetadataTokens.GetToken(h)); var changedTypeTokens = emitResult.ChangedTypes.SelectAsArray(h => MetadataTokens.GetToken(h)); // Determine all active statements whose span changed and exception region span deltas. GetActiveStatementAndExceptionRegionSpans( mvid, oldActiveStatementsMap, updatedMethodTokens, NonRemappableRegions, projectChanges.ActiveStatementChanges, out var activeStatementsInUpdatedMethods, out var moduleNonRemappableRegions, out var exceptionRegionUpdates); deltas.Add(new ManagedModuleUpdate( mvid, ilStream.ToImmutableArray(), metadataStream.ToImmutableArray(), pdbStream.ToImmutableArray(), projectChanges.LineChanges, updatedMethodTokens, changedTypeTokens, activeStatementsInUpdatedMethods, exceptionRegionUpdates)); nonRemappableRegions.Add((mvid, moduleNonRemappableRegions)); emitBaselines.Add((newProject.Id, emitResult.Baseline)); } } else { // error isBlocked = true; } // TODO: https://github.com/dotnet/roslyn/issues/36061 // We should only report diagnostics from emit phase. // Syntax and semantic diagnostics are already reported by the diagnostic analyzer. // Currently we do not have means to distinguish between diagnostics reported from compilation and emit phases. // Querying diagnostics of the entire compilation or just the updated files migth be slow. // In fact, it is desirable to allow emitting deltas for symbols affected by the change while allowing untouched // method bodies to have errors. if (!emitResult.Diagnostics.IsEmpty) { diagnostics.Add((newProject.Id, emitResult.Diagnostics)); } Telemetry.LogProjectAnalysisSummary(projectSummary, emitResult.Diagnostics, InBreakState); } // log capabilities for edit sessions with changes or reported errors: if (isBlocked || deltas.Count > 0) { Telemetry.LogRuntimeCapabilities(await Capabilities.GetValueAsync(cancellationToken).ConfigureAwait(false)); } var update = isBlocked ? SolutionUpdate.Blocked(diagnostics.ToImmutable(), documentsWithRudeEdits.ToImmutable()) : new SolutionUpdate( new ManagedModuleUpdates( (deltas.Count > 0) ? ManagedModuleUpdateStatus.Ready : ManagedModuleUpdateStatus.None, deltas.ToImmutable()), nonRemappableRegions.ToImmutable(), emitBaselines.ToImmutable(), diagnostics.ToImmutable(), documentsWithRudeEdits.ToImmutable()); return update; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } // internal for testing internal static void GetActiveStatementAndExceptionRegionSpans( Guid moduleId, ActiveStatementsMap oldActiveStatementMap, ImmutableArray<int> updatedMethodTokens, ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> previousNonRemappableRegions, ImmutableArray<DocumentActiveStatementChanges> activeStatementsInChangedDocuments, out ImmutableArray<ManagedActiveStatementUpdate> activeStatementsInUpdatedMethods, out ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)> nonRemappableRegions, out ImmutableArray<ManagedExceptionRegionUpdate> exceptionRegionUpdates) { using var _1 = PooledDictionary<(ManagedModuleMethodId MethodId, SourceFileSpan BaseSpan), SourceFileSpan>.GetInstance(out var changedNonRemappableSpans); var activeStatementsInUpdatedMethodsBuilder = ArrayBuilder<ManagedActiveStatementUpdate>.GetInstance(); var nonRemappableRegionsBuilder = ArrayBuilder<(ManagedModuleMethodId Method, NonRemappableRegion Region)>.GetInstance(); // Process active statements and their exception regions in changed documents of this project/module: foreach (var (oldActiveStatements, newActiveStatements, newExceptionRegions) in activeStatementsInChangedDocuments) { Debug.Assert(oldActiveStatements.Length == newExceptionRegions.Length); Debug.Assert(newActiveStatements.Length == newExceptionRegions.Length); for (var i = 0; i < newActiveStatements.Length; i++) { var (_, oldActiveStatement, oldActiveStatementExceptionRegions) = oldActiveStatements[i]; var newActiveStatement = newActiveStatements[i]; var newActiveStatementExceptionRegions = newExceptionRegions[i]; var instructionId = newActiveStatement.InstructionId; var methodId = instructionId.Method.Method; var isMethodUpdated = updatedMethodTokens.Contains(methodId.Token); if (isMethodUpdated) { activeStatementsInUpdatedMethodsBuilder.Add(new ManagedActiveStatementUpdate(methodId, instructionId.ILOffset, newActiveStatement.Span.ToSourceSpan())); } Debug.Assert(!oldActiveStatement.IsStale); // Adds a region with specified PDB spans. void AddNonRemappableRegion(SourceFileSpan oldSpan, SourceFileSpan newSpan, bool isExceptionRegion) { // it is a rude edit to change the path of the region span: Debug.Assert(oldSpan.Path == newSpan.Path); // The up-to-date flag is copied when new active statement is created from the corresponding old one. Debug.Assert(oldActiveStatement.IsMethodUpToDate == newActiveStatement.IsMethodUpToDate); if (oldActiveStatement.IsMethodUpToDate) { // Start tracking non-remappable regions for active statements in methods that were up-to-date // when break state was entered and now being updated (regardless of whether the active span changed or not). if (isMethodUpdated) { var lineDelta = oldSpan.Span.GetLineDelta(newSpan: newSpan.Span); nonRemappableRegionsBuilder.Add((methodId, new NonRemappableRegion(oldSpan, lineDelta, isExceptionRegion))); } else if (!isExceptionRegion) { // If the method has been up-to-date and it is not updated now then either the active statement span has not changed, // or the entire method containing it moved. In neither case do we need to start tracking non-remapable region // for the active statement since movement of whole method bodies (if any) is handled only on PDB level without // triggering any remapping on the IL level. // // That said, we still add a non-remappable region for this active statement, so that we know in future sessions // that this active statement existed and its span has not changed. We don't report these regions to the debugger, // but we use them to map active statement spans to the baseline snapshots of following edit sessions. nonRemappableRegionsBuilder.Add((methodId, new NonRemappableRegion(oldSpan, lineDelta: 0, isExceptionRegion: false))); } } else if (oldSpan.Span != newSpan.Span) { // The method is not up-to-date hence we might have a previous non-remappable span mapping that needs to be brought forward to the new snapshot. changedNonRemappableSpans[(methodId, oldSpan)] = newSpan; } } AddNonRemappableRegion(oldActiveStatement.FileSpan, newActiveStatement.FileSpan, isExceptionRegion: false); // The spans of the exception regions are known (non-default) for active statements in changed documents // as we ensured earlier that all changed documents are in-sync. for (var j = 0; j < oldActiveStatementExceptionRegions.Spans.Length; j++) { AddNonRemappableRegion(oldActiveStatementExceptionRegions.Spans[j], newActiveStatementExceptionRegions[j], isExceptionRegion: true); } } } activeStatementsInUpdatedMethods = activeStatementsInUpdatedMethodsBuilder.ToImmutableAndFree(); // Gather all active method instances contained in this project/module that are not up-to-date: using var _2 = PooledHashSet<ManagedModuleMethodId>.GetInstance(out var unremappedActiveMethods); foreach (var (instruction, baseActiveStatement) in oldActiveStatementMap.InstructionMap) { if (moduleId == instruction.Method.Module && !baseActiveStatement.IsMethodUpToDate) { unremappedActiveMethods.Add(instruction.Method.Method); } } // Update previously calculated non-remappable region mappings. // These map to the old snapshot and we need them to map to the new snapshot, which will be the baseline for the next session. if (unremappedActiveMethods.Count > 0) { foreach (var (methodInstance, regionsInMethod) in previousNonRemappableRegions) { // Skip non-remappable regions that belong to method instances that are from a different module. if (methodInstance.Module != moduleId) { continue; } // Skip no longer active methods - all active statements in these method instances have been remapped to newer versions. // New active statement can't appear in a stale method instance since such instance can't be invoked. if (!unremappedActiveMethods.Contains(methodInstance.Method)) { continue; } foreach (var region in regionsInMethod) { // We have calculated changes against a base snapshot (last break state): var baseSpan = region.Span.AddLineDelta(region.LineDelta); NonRemappableRegion newRegion; if (changedNonRemappableSpans.TryGetValue((methodInstance.Method, baseSpan), out var newSpan)) { // all spans must be of the same size: Debug.Assert(newSpan.Span.End.Line - newSpan.Span.Start.Line == baseSpan.Span.End.Line - baseSpan.Span.Start.Line); Debug.Assert(region.Span.Span.End.Line - region.Span.Span.Start.Line == baseSpan.Span.End.Line - baseSpan.Span.Start.Line); Debug.Assert(newSpan.Path == region.Span.Path); newRegion = region.WithLineDelta(region.Span.Span.GetLineDelta(newSpan: newSpan.Span)); } else { newRegion = region; } nonRemappableRegionsBuilder.Add((methodInstance.Method, newRegion)); } } } nonRemappableRegions = nonRemappableRegionsBuilder.ToImmutableAndFree(); // Note: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1319289 // // The update should include the file name, otherwise it is not possible for the debugger to find // the right IL span of the exception handler in case when multiple handlers in the same method // have the same mapped span but different mapped file name: // // try { active statement } // #line 20 "bar" // catch (IOException) { } // #line 20 "baz" // catch (Exception) { } // // The range span in exception region updates is the new span. Deltas are inverse. // old = new + delta // new = old – delta exceptionRegionUpdates = nonRemappableRegions.SelectAsArray( r => r.Region.IsExceptionRegion, r => new ManagedExceptionRegionUpdate( r.Method, -r.Region.LineDelta, r.Region.Span.AddLineDelta(r.Region.LineDelta).Span.ToSourceSpan())); } } }
1
dotnet/roslyn
55,898
Include edit session runtime capabilities in telemetry data
tmat
2021-08-25T21:41:02Z
2021-08-26T20:00:14Z
52b1b5784bf719114d698ed5fa4f82d6da30059f
dd121d37f386e689310de5dc039c08406d4dd0b2
Include edit session runtime capabilities in telemetry data.
./src/Features/Core/Portable/EditAndContinue/EditSessionTelemetry.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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { // EncEditSessionInfo is populated on a background thread and then read from the UI thread internal sealed class EditSessionTelemetry { internal readonly struct Data { public readonly ImmutableArray<(ushort EditKind, ushort SyntaxKind)> RudeEdits; public readonly ImmutableArray<string> EmitErrorIds; public readonly bool HadCompilationErrors; public readonly bool HadRudeEdits; public readonly bool HadValidChanges; public readonly bool HadValidInsignificantChanges; public readonly bool InBreakState; public Data(EditSessionTelemetry telemetry) { RudeEdits = telemetry._rudeEdits.AsImmutable(); EmitErrorIds = telemetry._emitErrorIds.AsImmutable(); HadCompilationErrors = telemetry._hadCompilationErrors; HadRudeEdits = telemetry._hadRudeEdits; HadValidChanges = telemetry._hadValidChanges; HadValidInsignificantChanges = telemetry._hadValidInsignificantChanges; InBreakState = telemetry._inBreakState; } public bool IsEmpty => !(HadCompilationErrors || HadRudeEdits || HadValidChanges || HadValidInsignificantChanges); } private readonly object _guard = new(); private readonly HashSet<(ushort, ushort)> _rudeEdits = new(); private readonly HashSet<string> _emitErrorIds = new(); private bool _hadCompilationErrors; private bool _hadRudeEdits; private bool _hadValidChanges; private bool _hadValidInsignificantChanges; private bool _inBreakState; public Data GetDataAndClear() { lock (_guard) { var data = new Data(this); _rudeEdits.Clear(); _emitErrorIds.Clear(); _hadCompilationErrors = false; _hadRudeEdits = false; _hadValidChanges = false; _hadValidInsignificantChanges = false; _inBreakState = false; return data; } } public void LogProjectAnalysisSummary(ProjectAnalysisSummary summary, ImmutableArray<string> errorsIds, bool inBreakState) { lock (_guard) { _emitErrorIds.AddRange(errorsIds); _inBreakState = inBreakState; switch (summary) { case ProjectAnalysisSummary.NoChanges: break; case ProjectAnalysisSummary.CompilationErrors: _hadCompilationErrors = true; break; case ProjectAnalysisSummary.RudeEdits: _hadRudeEdits = true; break; case ProjectAnalysisSummary.ValidChanges: _hadValidChanges = true; break; case ProjectAnalysisSummary.ValidInsignificantChanges: _hadValidInsignificantChanges = true; break; default: throw ExceptionUtilities.UnexpectedValue(summary); } } } public void LogProjectAnalysisSummary(ProjectAnalysisSummary summary, ImmutableArray<Diagnostic> emitDiagnostics, bool inBreakState) => LogProjectAnalysisSummary(summary, emitDiagnostics.SelectAsArray(d => d.Severity == DiagnosticSeverity.Error, d => d.Id), inBreakState); public void LogRudeEditDiagnostics(ImmutableArray<RudeEditDiagnostic> diagnostics) { lock (_guard) { foreach (var diagnostic in diagnostics) { _rudeEdits.Add(((ushort)diagnostic.Kind, diagnostic.SyntaxKind)); } } } } }
// Licensed to the .NET Foundation under one or more 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { // EncEditSessionInfo is populated on a background thread and then read from the UI thread internal sealed class EditSessionTelemetry { internal readonly struct Data { public readonly ImmutableArray<(ushort EditKind, ushort SyntaxKind)> RudeEdits; public readonly ImmutableArray<string> EmitErrorIds; public readonly EditAndContinueCapabilities Capabilities; public readonly bool HadCompilationErrors; public readonly bool HadRudeEdits; public readonly bool HadValidChanges; public readonly bool HadValidInsignificantChanges; public readonly bool InBreakState; public readonly bool IsEmpty; public Data(EditSessionTelemetry telemetry) { RudeEdits = telemetry._rudeEdits.AsImmutable(); EmitErrorIds = telemetry._emitErrorIds.AsImmutable(); HadCompilationErrors = telemetry._hadCompilationErrors; HadRudeEdits = telemetry._hadRudeEdits; HadValidChanges = telemetry._hadValidChanges; HadValidInsignificantChanges = telemetry._hadValidInsignificantChanges; InBreakState = telemetry._inBreakState; Capabilities = telemetry._capabilities; IsEmpty = telemetry.IsEmpty; } } private readonly object _guard = new(); private readonly HashSet<(ushort, ushort)> _rudeEdits = new(); private readonly HashSet<string> _emitErrorIds = new(); private bool _hadCompilationErrors; private bool _hadRudeEdits; private bool _hadValidChanges; private bool _hadValidInsignificantChanges; private bool _inBreakState; private EditAndContinueCapabilities _capabilities; public Data GetDataAndClear() { lock (_guard) { var data = new Data(this); _rudeEdits.Clear(); _emitErrorIds.Clear(); _hadCompilationErrors = false; _hadRudeEdits = false; _hadValidChanges = false; _hadValidInsignificantChanges = false; _inBreakState = false; _capabilities = EditAndContinueCapabilities.None; return data; } } public bool IsEmpty => !(_hadCompilationErrors || _hadRudeEdits || _hadValidChanges || _hadValidInsignificantChanges); public void LogProjectAnalysisSummary(ProjectAnalysisSummary summary, ImmutableArray<string> errorsIds, bool inBreakState) { lock (_guard) { _emitErrorIds.AddRange(errorsIds); _inBreakState = inBreakState; switch (summary) { case ProjectAnalysisSummary.NoChanges: break; case ProjectAnalysisSummary.CompilationErrors: _hadCompilationErrors = true; break; case ProjectAnalysisSummary.RudeEdits: _hadRudeEdits = true; break; case ProjectAnalysisSummary.ValidChanges: _hadValidChanges = true; break; case ProjectAnalysisSummary.ValidInsignificantChanges: _hadValidInsignificantChanges = true; break; default: throw ExceptionUtilities.UnexpectedValue(summary); } } } public void LogProjectAnalysisSummary(ProjectAnalysisSummary summary, ImmutableArray<Diagnostic> emitDiagnostics, bool inBreakState) => LogProjectAnalysisSummary(summary, emitDiagnostics.SelectAsArray(d => d.Severity == DiagnosticSeverity.Error, d => d.Id), inBreakState); public void LogRudeEditDiagnostics(ImmutableArray<RudeEditDiagnostic> diagnostics) { lock (_guard) { foreach (var diagnostic in diagnostics) { _rudeEdits.Add(((ushort)diagnostic.Kind, diagnostic.SyntaxKind)); } } } public void LogRuntimeCapabilities(EditAndContinueCapabilities capabilities) { lock (_guard) { Debug.Assert(_capabilities == EditAndContinueCapabilities.None || _capabilities == capabilities); _capabilities = capabilities; } } } }
1
dotnet/roslyn
55,898
Include edit session runtime capabilities in telemetry data
tmat
2021-08-25T21:41:02Z
2021-08-26T20:00:14Z
52b1b5784bf719114d698ed5fa4f82d6da30059f
dd121d37f386e689310de5dc039c08406d4dd0b2
Include edit session runtime capabilities in telemetry data.
./src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.AddImports.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.ChangeSignature; using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities.ChangeSignature; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature { public partial class ChangeSignatureTests : AbstractChangeSignatureTests { [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameterAddsAllImports() { var markup = @" class C { void $$M() { } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex( new AddedParameter( null, "Dictionary<ConsoleColor, Task<AsyncOperation>>", "test", CallSiteKind.Todo), "System.Collections.Generic.Dictionary<System.ConsoleColor, System.Threading.Tasks.Task<System.ComponentModel.AsyncOperation>>")}; var updatedCode = @" using System; using System.Collections.Generic; using System.ComponentModel; using System.Threading.Tasks; class C { void M(Dictionary<ConsoleColor, Task<AsyncOperation>> test) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameterAddsOnlyMissingImports() { var markup = @" using System.ComponentModel; class C { void $$M() { } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex( new AddedParameter( null, "Dictionary<ConsoleColor, Task<AsyncOperation>>", "test", CallSiteKind.Todo), "System.Collections.Generic.Dictionary<System.ConsoleColor, System.Threading.Tasks.Task<System.ComponentModel.AsyncOperation>>")}; var updatedCode = @" using System; using System.Collections.Generic; using System.ComponentModel; using System.Threading.Tasks; class C { void M(Dictionary<ConsoleColor, Task<AsyncOperation>> test) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameterAddsImportsOnCascading() { var markup = @" using NS1; namespace NS1 { class B { public virtual void M() { } } } namespace NS2 { using System; using System.Collections.Generic; using System.ComponentModel; using System.Threading.Tasks; class D : B { public override void $$M() { } } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex( new AddedParameter( null, "Dictionary<ConsoleColor, Task<AsyncOperation>>", "test", CallSiteKind.Todo), "System.Collections.Generic.Dictionary<System.ConsoleColor, System.Threading.Tasks.Task<System.ComponentModel.AsyncOperation>>")}; var updatedCode = @" using System; using System.Collections.Generic; using System.ComponentModel; using System.Threading.Tasks; using NS1; namespace NS1 { class B { public virtual void M(Dictionary<ConsoleColor, Task<AsyncOperation>> test) { } } } namespace NS2 { using System; using System.Collections.Generic; using System.ComponentModel; using System.Threading.Tasks; class D : B { public override void M(Dictionary<ConsoleColor, Task<AsyncOperation>> test) { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); } } }
// Licensed to the .NET Foundation under one or more 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.ChangeSignature; using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities.ChangeSignature; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature { public partial class ChangeSignatureTests : AbstractChangeSignatureTests { [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameterAddsAllImports() { var markup = @" class C { void $$M() { } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex( new AddedParameter( null, "Dictionary<ConsoleColor, Task<AsyncOperation>>", "test", CallSiteKind.Todo), "System.Collections.Generic.Dictionary<System.ConsoleColor, System.Threading.Tasks.Task<System.ComponentModel.AsyncOperation>>")}; var updatedCode = @" using System; using System.Collections.Generic; using System.ComponentModel; using System.Threading.Tasks; class C { void M(Dictionary<ConsoleColor, Task<AsyncOperation>> test) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameterAddsOnlyMissingImports() { var markup = @" using System.ComponentModel; class C { void $$M() { } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex( new AddedParameter( null, "Dictionary<ConsoleColor, Task<AsyncOperation>>", "test", CallSiteKind.Todo), "System.Collections.Generic.Dictionary<System.ConsoleColor, System.Threading.Tasks.Task<System.ComponentModel.AsyncOperation>>")}; var updatedCode = @" using System; using System.Collections.Generic; using System.ComponentModel; using System.Threading.Tasks; class C { void M(Dictionary<ConsoleColor, Task<AsyncOperation>> test) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task AddParameterAddsImportsOnCascading() { var markup = @" using NS1; namespace NS1 { class B { public virtual void M() { } } } namespace NS2 { using System; using System.Collections.Generic; using System.ComponentModel; using System.Threading.Tasks; class D : B { public override void $$M() { } } }"; var updatedSignature = new[] { new AddedParameterOrExistingIndex( new AddedParameter( null, "Dictionary<ConsoleColor, Task<AsyncOperation>>", "test", CallSiteKind.Todo), "System.Collections.Generic.Dictionary<System.ConsoleColor, System.Threading.Tasks.Task<System.ComponentModel.AsyncOperation>>")}; var updatedCode = @" using System; using System.Collections.Generic; using System.ComponentModel; using System.Threading.Tasks; using NS1; namespace NS1 { class B { public virtual void M(Dictionary<ConsoleColor, Task<AsyncOperation>> test) { } } } namespace NS2 { using System; using System.Collections.Generic; using System.ComponentModel; using System.Threading.Tasks; class D : B { public override void M(Dictionary<ConsoleColor, Task<AsyncOperation>> test) { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode); } } }
-1
dotnet/roslyn
55,898
Include edit session runtime capabilities in telemetry data
tmat
2021-08-25T21:41:02Z
2021-08-26T20:00:14Z
52b1b5784bf719114d698ed5fa4f82d6da30059f
dd121d37f386e689310de5dc039c08406d4dd0b2
Include edit session runtime capabilities in telemetry data.
./src/Compilers/CSharp/Test/Symbol/Symbols/Source/ExpressionBodiedPropertyTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using System; using Xunit; using Microsoft.CodeAnalysis.Test.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Source { public sealed class ExpressionBodiedPropertyTests : CSharpTestBase { [Fact(Skip = "973907")] public void Syntax01() { // Language feature enabled by default var comp = CreateCompilation(@" class C { public int P => 1; }"); comp.VerifyDiagnostics(); } [Fact] public void Syntax02() { var comp = CreateCompilationWithMscorlib45(@" class C { public int P { get; } => 1; }"); comp.VerifyDiagnostics( // (4,5): error CS8056: Properties cannot combine accessor lists with expression bodies. // public int P { get; } => 1; Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, "public int P { get; } => 1;").WithLocation(4, 5) ); } [Fact] public void Syntax03() { var comp = CreateCompilation(@" interface C { int P => 1; }", parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,14): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // int P => 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "1").WithArguments("default interface implementation", "8.0").WithLocation(4, 14) ); } [Fact] public void Syntax04() { var comp = CreateCompilationWithMscorlib45(@" abstract class C { public abstract int P => 1; }"); comp.VerifyDiagnostics( // (4,28): error CS0500: 'C.P.get' cannot declare a body because it is marked abstract // public abstract int P => 1; Diagnostic(ErrorCode.ERR_AbstractHasBody, "1").WithArguments("C.P.get").WithLocation(4, 28)); } [Fact] public void Syntax05() { var comp = CreateCompilationWithMscorlib45(@" class C { public abstract int P => 1; }"); comp.VerifyDiagnostics( // (4,29): error CS0500: 'C.P.get' cannot declare a body because it is marked abstract // public abstract int P => 1; Diagnostic(ErrorCode.ERR_AbstractHasBody, "1").WithArguments("C.P.get").WithLocation(4, 29), // (4,29): error CS0513: 'C.P.get' is abstract but it is contained in non-abstract type 'C' // public abstract int P => 1; Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "1").WithArguments("C.P.get", "C").WithLocation(4, 29)); } [Fact] public void Syntax06() { var comp = CreateCompilationWithMscorlib45(@" abstract class C { abstract int P => 1; }"); comp.VerifyDiagnostics( // (4,17): error CS0621: 'C.P': virtual or abstract members cannot be private // abstract int P => 1; Diagnostic(ErrorCode.ERR_VirtualPrivate, "P").WithArguments("C.P").WithLocation(4, 17), // (4,22): error CS0500: 'C.P.get' cannot declare a body because it is marked abstract // abstract int P => 1; Diagnostic(ErrorCode.ERR_AbstractHasBody, "1").WithArguments("C.P.get").WithLocation(4, 22)); } [Fact] public void Syntax07() { // The '=' here parses as part of the expression body, not the property var comp = CreateCompilationWithMscorlib45(@" class C { public int P => 1 = 2; }"); comp.VerifyDiagnostics( // (4,21): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // public int P => 1 = 2; Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "1").WithLocation(4, 21)); } [Fact] public void Syntax08() { CreateCompilationWithMscorlib45(@" interface I { int P { get; }; }").VerifyDiagnostics( // (4,19): error CS1597: Semicolon after method or accessor block is not valid // int P { get; }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(4, 19)); } [Fact] public void Syntax09() { CreateCompilationWithMscorlib45(@" class C { int P => 2 }").VerifyDiagnostics( // (4,15): error CS1002: ; expected // int P => 2 Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(4, 15)); } [Fact] public void Syntax10() { CreateCompilationWithMscorlib45(@" interface I { int this[int i] }").VerifyDiagnostics( // (4,20): error CS1514: { expected // int this[int i] Diagnostic(ErrorCode.ERR_LbraceExpected, "").WithLocation(4, 20), // (5,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 2), // (4,9): error CS0548: 'I.this[int]': property or indexer must have at least one accessor // int this[int i] Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "this").WithArguments("I.this[int]").WithLocation(4, 9)); } [Fact] public void Syntax11() { CreateCompilationWithMscorlib45(@" interface I { int this[int i]; }").VerifyDiagnostics( // (4,20): error CS1514: { expected // int this[int i]; Diagnostic(ErrorCode.ERR_LbraceExpected, ";").WithLocation(4, 20), // (4,20): error CS1014: A get, set or init accessor expected // int this[int i]; Diagnostic(ErrorCode.ERR_GetOrSetExpected, ";").WithLocation(4, 20), // (5,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 2), // (4,9): error CS0548: 'I.this[int]': property or indexer must have at least one accessor // int this[int i]; Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "this").WithArguments("I.this[int]").WithLocation(4, 9)); } [Fact] public void Syntax12() { CreateCompilationWithMscorlib45(@" interface I { int this[int i] { get; }; }").VerifyDiagnostics( // (4,29): error CS1597: Semicolon after method or accessor block is not valid // int this[int i] { get; }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(4, 29)); } [Fact] public void Syntax13() { // End the property declaration at the semicolon after the accessor list CreateCompilationWithMscorlib45(@" class C { int P { get; set; }; => 2; }").VerifyDiagnostics( // (4,24): error CS1597: Semicolon after method or accessor block is not valid // int P { get; set; }; => 2; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(4, 24), // (4,26): error CS1519: Invalid token '=>' in class, record, struct, or interface member declaration // int P { get; set; }; => 2; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=>").WithArguments("=>").WithLocation(4, 26)); } [Fact] public void Syntax14() { CreateCompilationWithMscorlib45(@" class C { int this[int i] => 2 }").VerifyDiagnostics( // (4,25): error CS1002: ; expected // int this[int i] => 2 Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(4, 25)); } [Fact] public void LambdaTest01() { var comp = CreateCompilationWithMscorlib45(@" using System; class C { public Func<int, Func<int, int>> P => x => y => x + y; }"); comp.VerifyDiagnostics(); } [Fact] public void SimpleTest() { var text = @" class C { public int P => 2 * 2; public int this[int i, int j] => i * j * P; }"; var comp = CreateCompilationWithMscorlib45(text); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var c = global.GetTypeMember("C"); var p = c.GetMember<SourcePropertySymbol>("P"); Assert.Null(p.SetMethod); Assert.NotNull(p.GetMethod); Assert.False(p.GetMethod.IsImplicitlyDeclared); Assert.True(p.IsExpressionBodied); var indexer = c.GetMember<SourcePropertySymbol>("this[]"); Assert.Null(indexer.SetMethod); Assert.NotNull(indexer.GetMethod); Assert.False(indexer.GetMethod.IsImplicitlyDeclared); Assert.True(indexer.IsExpressionBodied); Assert.True(indexer.IsIndexer); Assert.Equal(2, indexer.ParameterCount); var i = indexer.Parameters[0]; Assert.Equal(SpecialType.System_Int32, i.Type.SpecialType); Assert.Equal("i", i.Name); var j = indexer.Parameters[1]; Assert.Equal(SpecialType.System_Int32, i.Type.SpecialType); Assert.Equal("j", j.Name); } [Fact] public void Override01() { var comp = CreateCompilationWithMscorlib45(@" class B { public virtual int P { get; set; } } class C : B { public override int P => 1; }").VerifyDiagnostics(); } [Fact] public void Override02() { CreateCompilationWithMscorlib45(@" class B { public int P => 10; public int this[int i] => i; } class C : B { public override int P => 20; public override int this[int i] => i * 2; }").VerifyDiagnostics( // (10,25): error CS0506: 'C.this[int]': cannot override inherited member 'B.this[int]' because it is not marked virtual, abstract, or override // public override int this[int i] => i * 2; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "this").WithArguments("C.this[int]", "B.this[int]").WithLocation(10, 25), // (9,25): error CS0506: 'C.P': cannot override inherited member 'B.P' because it is not marked virtual, abstract, or override // public override int P => 20; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "P").WithArguments("C.P", "B.P").WithLocation(9, 25)); } [Fact] public void Override03() { CreateCompilationWithMscorlib45(@" class B { public virtual int P => 10; public virtual int this[int i] => i; } class C : B { public override int P => 20; public override int this[int i] => i * 2; }").VerifyDiagnostics(); } [Fact] public void VoidExpression() { var comp = CreateCompilationWithMscorlib45(@" class C { public void P => System.Console.WriteLine(""goo""); }").VerifyDiagnostics( // (4,17): error CS0547: 'C.P': property or indexer cannot have void type // public void P => System.Console.WriteLine("goo"); Diagnostic(ErrorCode.ERR_PropertyCantHaveVoidType, "P").WithArguments("C.P").WithLocation(4, 17)); } [Fact] public void VoidExpression2() { var comp = CreateCompilationWithMscorlib45(@" class C { public int P => System.Console.WriteLine(""goo""); }").VerifyDiagnostics( // (4,21): error CS0029: Cannot implicitly convert type 'void' to 'int' // public int P => System.Console.WriteLine("goo"); Diagnostic(ErrorCode.ERR_NoImplicitConv, @"System.Console.WriteLine(""goo"")").WithArguments("void", "int").WithLocation(4, 21)); } [Fact] public void InterfaceImplementation01() { var comp = CreateCompilationWithMscorlib45(@" interface I { int P { get; } string Q { get; } } internal interface J { string Q { get; } } internal interface K { decimal D { get; } } class C : I, J, K { public int P => 10; string I.Q { get { return ""goo""; } } string J.Q { get { return ""bar""; } } public decimal D { get { return P; } } }"); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var i = global.GetTypeMember("I"); var j = global.GetTypeMember("J"); var k = global.GetTypeMember("K"); var c = global.GetTypeMember("C"); var iP = i.GetMember<SourcePropertySymbol>("P"); var prop = c.GetMember<SourcePropertySymbol>("P"); Assert.True(prop.IsReadOnly); var implements = prop.ContainingType.FindImplementationForInterfaceMember(iP); Assert.Equal(prop, implements); prop = (SourcePropertySymbol)c.GetProperty("I.Q"); Assert.True(prop.IsReadOnly); Assert.True(prop.IsExplicitInterfaceImplementation); prop = (SourcePropertySymbol)c.GetProperty("J.Q"); Assert.True(prop.IsReadOnly); Assert.True(prop.IsExplicitInterfaceImplementation); prop = c.GetMember<SourcePropertySymbol>("D"); Assert.True(prop.IsReadOnly); } [ClrOnlyFact] public void Emit01() { var comp = CreateCompilationWithMscorlib45(@" abstract class A { protected abstract string Z { get; } } abstract class B : A { protected sealed override string Z => ""goo""; protected abstract string Y { get; } } class C : B { public const int X = 2; public static int P => C.X * C.X; public int Q => X; private int R => P * Q; protected sealed override string Y => Z + R; public int this[int i] => R + i; public static void Main() { System.Console.WriteLine(C.X); System.Console.WriteLine(C.P); var c = new C(); System.Console.WriteLine(c.Q); System.Console.WriteLine(c.R); System.Console.WriteLine(c.Z); System.Console.WriteLine(c.Y); System.Console.WriteLine(c[10]); } }", options: TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.Internal)); var verifier = CompileAndVerify(comp, expectedOutput: @"2 4 2 8 goo goo8 18"); } [ClrOnlyFact] public void AccessorInheritsVisibility() { var comp = CreateCompilationWithMscorlib45(@" class C { private int P => 1; private int this[int i] => i; }", options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); Action<ModuleSymbol> srcValidator = m => { var c = m.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var p = c.GetMember<PropertySymbol>("P"); var indexer = c.Indexers[0]; Assert.Equal(Accessibility.Private, p.DeclaredAccessibility); Assert.Equal(Accessibility.Private, indexer.DeclaredAccessibility); }; var verifier = CompileAndVerify(comp, sourceSymbolValidator: srcValidator); } [Fact] public void StaticIndexer() { var comp = CreateCompilationWithMscorlib45(@" class C { static int this[int i] => i; }"); comp.VerifyDiagnostics( // (4,16): error CS0106: The modifier 'static' is not valid for this item // static int this[int i] => i; Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static").WithLocation(4, 16)); } [Fact] public void RefReturningExpressionBodiedProperty() { var comp = CreateCompilationWithMscorlib45(@" class C { int field = 0; public ref int P => ref field; }"); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var c = global.GetTypeMember("C"); var p = c.GetMember<SourcePropertySymbol>("P"); Assert.Null(p.SetMethod); Assert.NotNull(p.GetMethod); Assert.False(p.GetMethod.IsImplicitlyDeclared); Assert.True(p.IsExpressionBodied); Assert.Equal(RefKind.Ref, p.GetMethod.RefKind); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void RefReadonlyReturningExpressionBodiedProperty() { var comp = CreateCompilationWithMscorlib45(@" class C { int field = 0; public ref readonly int P => ref field; }"); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var c = global.GetTypeMember("C"); var p = c.GetMember<SourcePropertySymbol>("P"); Assert.Null(p.SetMethod); Assert.NotNull(p.GetMethod); Assert.False(p.GetMethod.IsImplicitlyDeclared); Assert.True(p.IsExpressionBodied); Assert.Equal(RefKind.RefReadOnly, p.GetMethod.RefKind); Assert.False(p.ReturnsByRef); Assert.False(p.GetMethod.ReturnsByRef); Assert.True(p.ReturnsByRefReadonly); Assert.True(p.GetMethod.ReturnsByRefReadonly); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void RefReadonlyReturningExpressionBodiedIndexer() { var comp = CreateCompilationWithMscorlib45(@" class C { int field = 0; public ref readonly int this[in int arg] => ref field; }"); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var c = global.GetTypeMember("C"); var p = c.GetMember<SourcePropertySymbol>("this[]"); Assert.Null(p.SetMethod); Assert.NotNull(p.GetMethod); Assert.False(p.GetMethod.IsImplicitlyDeclared); Assert.True(p.IsExpressionBodied); Assert.Equal(RefKind.RefReadOnly, p.GetMethod.RefKind); Assert.Equal(RefKind.In, p.GetMethod.Parameters[0].RefKind); Assert.False(p.ReturnsByRef); Assert.False(p.GetMethod.ReturnsByRef); Assert.True(p.ReturnsByRefReadonly); Assert.True(p.GetMethod.ReturnsByRefReadonly); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void RefReadonlyReturningExpressionBodiedIndexer1() { var comp = CreateCompilationWithMscorlib45(@" class C { int field = 0; public ref readonly int this[in int arg] => ref field; }"); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var c = global.GetTypeMember("C"); var p = c.GetMember<SourcePropertySymbol>("this[]"); Assert.Null(p.SetMethod); Assert.NotNull(p.GetMethod); Assert.False(p.GetMethod.IsImplicitlyDeclared); Assert.True(p.IsExpressionBodied); Assert.Equal(RefKind.RefReadOnly, p.GetMethod.RefKind); Assert.Equal(RefKind.In, p.GetMethod.Parameters[0].RefKind); Assert.False(p.ReturnsByRef); Assert.False(p.GetMethod.ReturnsByRef); Assert.True(p.ReturnsByRefReadonly); Assert.True(p.GetMethod.ReturnsByRefReadonly); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using System; using Xunit; using Microsoft.CodeAnalysis.Test.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Source { public sealed class ExpressionBodiedPropertyTests : CSharpTestBase { [Fact(Skip = "973907")] public void Syntax01() { // Language feature enabled by default var comp = CreateCompilation(@" class C { public int P => 1; }"); comp.VerifyDiagnostics(); } [Fact] public void Syntax02() { var comp = CreateCompilationWithMscorlib45(@" class C { public int P { get; } => 1; }"); comp.VerifyDiagnostics( // (4,5): error CS8056: Properties cannot combine accessor lists with expression bodies. // public int P { get; } => 1; Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, "public int P { get; } => 1;").WithLocation(4, 5) ); } [Fact] public void Syntax03() { var comp = CreateCompilation(@" interface C { int P => 1; }", parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,14): error CS8652: The feature 'default interface implementation' is not available in C# 7.0. Please use language version 8.0 or greater. // int P => 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "1").WithArguments("default interface implementation", "8.0").WithLocation(4, 14) ); } [Fact] public void Syntax04() { var comp = CreateCompilationWithMscorlib45(@" abstract class C { public abstract int P => 1; }"); comp.VerifyDiagnostics( // (4,28): error CS0500: 'C.P.get' cannot declare a body because it is marked abstract // public abstract int P => 1; Diagnostic(ErrorCode.ERR_AbstractHasBody, "1").WithArguments("C.P.get").WithLocation(4, 28)); } [Fact] public void Syntax05() { var comp = CreateCompilationWithMscorlib45(@" class C { public abstract int P => 1; }"); comp.VerifyDiagnostics( // (4,29): error CS0500: 'C.P.get' cannot declare a body because it is marked abstract // public abstract int P => 1; Diagnostic(ErrorCode.ERR_AbstractHasBody, "1").WithArguments("C.P.get").WithLocation(4, 29), // (4,29): error CS0513: 'C.P.get' is abstract but it is contained in non-abstract type 'C' // public abstract int P => 1; Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "1").WithArguments("C.P.get", "C").WithLocation(4, 29)); } [Fact] public void Syntax06() { var comp = CreateCompilationWithMscorlib45(@" abstract class C { abstract int P => 1; }"); comp.VerifyDiagnostics( // (4,17): error CS0621: 'C.P': virtual or abstract members cannot be private // abstract int P => 1; Diagnostic(ErrorCode.ERR_VirtualPrivate, "P").WithArguments("C.P").WithLocation(4, 17), // (4,22): error CS0500: 'C.P.get' cannot declare a body because it is marked abstract // abstract int P => 1; Diagnostic(ErrorCode.ERR_AbstractHasBody, "1").WithArguments("C.P.get").WithLocation(4, 22)); } [Fact] public void Syntax07() { // The '=' here parses as part of the expression body, not the property var comp = CreateCompilationWithMscorlib45(@" class C { public int P => 1 = 2; }"); comp.VerifyDiagnostics( // (4,21): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // public int P => 1 = 2; Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "1").WithLocation(4, 21)); } [Fact] public void Syntax08() { CreateCompilationWithMscorlib45(@" interface I { int P { get; }; }").VerifyDiagnostics( // (4,19): error CS1597: Semicolon after method or accessor block is not valid // int P { get; }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(4, 19)); } [Fact] public void Syntax09() { CreateCompilationWithMscorlib45(@" class C { int P => 2 }").VerifyDiagnostics( // (4,15): error CS1002: ; expected // int P => 2 Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(4, 15)); } [Fact] public void Syntax10() { CreateCompilationWithMscorlib45(@" interface I { int this[int i] }").VerifyDiagnostics( // (4,20): error CS1514: { expected // int this[int i] Diagnostic(ErrorCode.ERR_LbraceExpected, "").WithLocation(4, 20), // (5,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 2), // (4,9): error CS0548: 'I.this[int]': property or indexer must have at least one accessor // int this[int i] Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "this").WithArguments("I.this[int]").WithLocation(4, 9)); } [Fact] public void Syntax11() { CreateCompilationWithMscorlib45(@" interface I { int this[int i]; }").VerifyDiagnostics( // (4,20): error CS1514: { expected // int this[int i]; Diagnostic(ErrorCode.ERR_LbraceExpected, ";").WithLocation(4, 20), // (4,20): error CS1014: A get, set or init accessor expected // int this[int i]; Diagnostic(ErrorCode.ERR_GetOrSetExpected, ";").WithLocation(4, 20), // (5,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 2), // (4,9): error CS0548: 'I.this[int]': property or indexer must have at least one accessor // int this[int i]; Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "this").WithArguments("I.this[int]").WithLocation(4, 9)); } [Fact] public void Syntax12() { CreateCompilationWithMscorlib45(@" interface I { int this[int i] { get; }; }").VerifyDiagnostics( // (4,29): error CS1597: Semicolon after method or accessor block is not valid // int this[int i] { get; }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(4, 29)); } [Fact] public void Syntax13() { // End the property declaration at the semicolon after the accessor list CreateCompilationWithMscorlib45(@" class C { int P { get; set; }; => 2; }").VerifyDiagnostics( // (4,24): error CS1597: Semicolon after method or accessor block is not valid // int P { get; set; }; => 2; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(4, 24), // (4,26): error CS1519: Invalid token '=>' in class, record, struct, or interface member declaration // int P { get; set; }; => 2; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=>").WithArguments("=>").WithLocation(4, 26)); } [Fact] public void Syntax14() { CreateCompilationWithMscorlib45(@" class C { int this[int i] => 2 }").VerifyDiagnostics( // (4,25): error CS1002: ; expected // int this[int i] => 2 Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(4, 25)); } [Fact] public void LambdaTest01() { var comp = CreateCompilationWithMscorlib45(@" using System; class C { public Func<int, Func<int, int>> P => x => y => x + y; }"); comp.VerifyDiagnostics(); } [Fact] public void SimpleTest() { var text = @" class C { public int P => 2 * 2; public int this[int i, int j] => i * j * P; }"; var comp = CreateCompilationWithMscorlib45(text); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var c = global.GetTypeMember("C"); var p = c.GetMember<SourcePropertySymbol>("P"); Assert.Null(p.SetMethod); Assert.NotNull(p.GetMethod); Assert.False(p.GetMethod.IsImplicitlyDeclared); Assert.True(p.IsExpressionBodied); var indexer = c.GetMember<SourcePropertySymbol>("this[]"); Assert.Null(indexer.SetMethod); Assert.NotNull(indexer.GetMethod); Assert.False(indexer.GetMethod.IsImplicitlyDeclared); Assert.True(indexer.IsExpressionBodied); Assert.True(indexer.IsIndexer); Assert.Equal(2, indexer.ParameterCount); var i = indexer.Parameters[0]; Assert.Equal(SpecialType.System_Int32, i.Type.SpecialType); Assert.Equal("i", i.Name); var j = indexer.Parameters[1]; Assert.Equal(SpecialType.System_Int32, i.Type.SpecialType); Assert.Equal("j", j.Name); } [Fact] public void Override01() { var comp = CreateCompilationWithMscorlib45(@" class B { public virtual int P { get; set; } } class C : B { public override int P => 1; }").VerifyDiagnostics(); } [Fact] public void Override02() { CreateCompilationWithMscorlib45(@" class B { public int P => 10; public int this[int i] => i; } class C : B { public override int P => 20; public override int this[int i] => i * 2; }").VerifyDiagnostics( // (10,25): error CS0506: 'C.this[int]': cannot override inherited member 'B.this[int]' because it is not marked virtual, abstract, or override // public override int this[int i] => i * 2; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "this").WithArguments("C.this[int]", "B.this[int]").WithLocation(10, 25), // (9,25): error CS0506: 'C.P': cannot override inherited member 'B.P' because it is not marked virtual, abstract, or override // public override int P => 20; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "P").WithArguments("C.P", "B.P").WithLocation(9, 25)); } [Fact] public void Override03() { CreateCompilationWithMscorlib45(@" class B { public virtual int P => 10; public virtual int this[int i] => i; } class C : B { public override int P => 20; public override int this[int i] => i * 2; }").VerifyDiagnostics(); } [Fact] public void VoidExpression() { var comp = CreateCompilationWithMscorlib45(@" class C { public void P => System.Console.WriteLine(""goo""); }").VerifyDiagnostics( // (4,17): error CS0547: 'C.P': property or indexer cannot have void type // public void P => System.Console.WriteLine("goo"); Diagnostic(ErrorCode.ERR_PropertyCantHaveVoidType, "P").WithArguments("C.P").WithLocation(4, 17)); } [Fact] public void VoidExpression2() { var comp = CreateCompilationWithMscorlib45(@" class C { public int P => System.Console.WriteLine(""goo""); }").VerifyDiagnostics( // (4,21): error CS0029: Cannot implicitly convert type 'void' to 'int' // public int P => System.Console.WriteLine("goo"); Diagnostic(ErrorCode.ERR_NoImplicitConv, @"System.Console.WriteLine(""goo"")").WithArguments("void", "int").WithLocation(4, 21)); } [Fact] public void InterfaceImplementation01() { var comp = CreateCompilationWithMscorlib45(@" interface I { int P { get; } string Q { get; } } internal interface J { string Q { get; } } internal interface K { decimal D { get; } } class C : I, J, K { public int P => 10; string I.Q { get { return ""goo""; } } string J.Q { get { return ""bar""; } } public decimal D { get { return P; } } }"); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var i = global.GetTypeMember("I"); var j = global.GetTypeMember("J"); var k = global.GetTypeMember("K"); var c = global.GetTypeMember("C"); var iP = i.GetMember<SourcePropertySymbol>("P"); var prop = c.GetMember<SourcePropertySymbol>("P"); Assert.True(prop.IsReadOnly); var implements = prop.ContainingType.FindImplementationForInterfaceMember(iP); Assert.Equal(prop, implements); prop = (SourcePropertySymbol)c.GetProperty("I.Q"); Assert.True(prop.IsReadOnly); Assert.True(prop.IsExplicitInterfaceImplementation); prop = (SourcePropertySymbol)c.GetProperty("J.Q"); Assert.True(prop.IsReadOnly); Assert.True(prop.IsExplicitInterfaceImplementation); prop = c.GetMember<SourcePropertySymbol>("D"); Assert.True(prop.IsReadOnly); } [ClrOnlyFact] public void Emit01() { var comp = CreateCompilationWithMscorlib45(@" abstract class A { protected abstract string Z { get; } } abstract class B : A { protected sealed override string Z => ""goo""; protected abstract string Y { get; } } class C : B { public const int X = 2; public static int P => C.X * C.X; public int Q => X; private int R => P * Q; protected sealed override string Y => Z + R; public int this[int i] => R + i; public static void Main() { System.Console.WriteLine(C.X); System.Console.WriteLine(C.P); var c = new C(); System.Console.WriteLine(c.Q); System.Console.WriteLine(c.R); System.Console.WriteLine(c.Z); System.Console.WriteLine(c.Y); System.Console.WriteLine(c[10]); } }", options: TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.Internal)); var verifier = CompileAndVerify(comp, expectedOutput: @"2 4 2 8 goo goo8 18"); } [ClrOnlyFact] public void AccessorInheritsVisibility() { var comp = CreateCompilationWithMscorlib45(@" class C { private int P => 1; private int this[int i] => i; }", options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); Action<ModuleSymbol> srcValidator = m => { var c = m.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var p = c.GetMember<PropertySymbol>("P"); var indexer = c.Indexers[0]; Assert.Equal(Accessibility.Private, p.DeclaredAccessibility); Assert.Equal(Accessibility.Private, indexer.DeclaredAccessibility); }; var verifier = CompileAndVerify(comp, sourceSymbolValidator: srcValidator); } [Fact] public void StaticIndexer() { var comp = CreateCompilationWithMscorlib45(@" class C { static int this[int i] => i; }"); comp.VerifyDiagnostics( // (4,16): error CS0106: The modifier 'static' is not valid for this item // static int this[int i] => i; Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static").WithLocation(4, 16)); } [Fact] public void RefReturningExpressionBodiedProperty() { var comp = CreateCompilationWithMscorlib45(@" class C { int field = 0; public ref int P => ref field; }"); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var c = global.GetTypeMember("C"); var p = c.GetMember<SourcePropertySymbol>("P"); Assert.Null(p.SetMethod); Assert.NotNull(p.GetMethod); Assert.False(p.GetMethod.IsImplicitlyDeclared); Assert.True(p.IsExpressionBodied); Assert.Equal(RefKind.Ref, p.GetMethod.RefKind); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void RefReadonlyReturningExpressionBodiedProperty() { var comp = CreateCompilationWithMscorlib45(@" class C { int field = 0; public ref readonly int P => ref field; }"); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var c = global.GetTypeMember("C"); var p = c.GetMember<SourcePropertySymbol>("P"); Assert.Null(p.SetMethod); Assert.NotNull(p.GetMethod); Assert.False(p.GetMethod.IsImplicitlyDeclared); Assert.True(p.IsExpressionBodied); Assert.Equal(RefKind.RefReadOnly, p.GetMethod.RefKind); Assert.False(p.ReturnsByRef); Assert.False(p.GetMethod.ReturnsByRef); Assert.True(p.ReturnsByRefReadonly); Assert.True(p.GetMethod.ReturnsByRefReadonly); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void RefReadonlyReturningExpressionBodiedIndexer() { var comp = CreateCompilationWithMscorlib45(@" class C { int field = 0; public ref readonly int this[in int arg] => ref field; }"); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var c = global.GetTypeMember("C"); var p = c.GetMember<SourcePropertySymbol>("this[]"); Assert.Null(p.SetMethod); Assert.NotNull(p.GetMethod); Assert.False(p.GetMethod.IsImplicitlyDeclared); Assert.True(p.IsExpressionBodied); Assert.Equal(RefKind.RefReadOnly, p.GetMethod.RefKind); Assert.Equal(RefKind.In, p.GetMethod.Parameters[0].RefKind); Assert.False(p.ReturnsByRef); Assert.False(p.GetMethod.ReturnsByRef); Assert.True(p.ReturnsByRefReadonly); Assert.True(p.GetMethod.ReturnsByRefReadonly); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void RefReadonlyReturningExpressionBodiedIndexer1() { var comp = CreateCompilationWithMscorlib45(@" class C { int field = 0; public ref readonly int this[in int arg] => ref field; }"); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var c = global.GetTypeMember("C"); var p = c.GetMember<SourcePropertySymbol>("this[]"); Assert.Null(p.SetMethod); Assert.NotNull(p.GetMethod); Assert.False(p.GetMethod.IsImplicitlyDeclared); Assert.True(p.IsExpressionBodied); Assert.Equal(RefKind.RefReadOnly, p.GetMethod.RefKind); Assert.Equal(RefKind.In, p.GetMethod.Parameters[0].RefKind); Assert.False(p.ReturnsByRef); Assert.False(p.GetMethod.ReturnsByRef); Assert.True(p.ReturnsByRefReadonly); Assert.True(p.GetMethod.ReturnsByRefReadonly); } } }
-1
dotnet/roslyn
55,898
Include edit session runtime capabilities in telemetry data
tmat
2021-08-25T21:41:02Z
2021-08-26T20:00:14Z
52b1b5784bf719114d698ed5fa4f82d6da30059f
dd121d37f386e689310de5dc039c08406d4dd0b2
Include edit session runtime capabilities in telemetry data.
./src/Compilers/Core/Portable/DiagnosticAnalyzer/SuppressMessageInfo.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 struct SuppressMessageInfo { public string Id; public string Scope; public string Target; public string MessageId; public AttributeData 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. #nullable disable namespace Microsoft.CodeAnalysis.Diagnostics { internal struct SuppressMessageInfo { public string Id; public string Scope; public string Target; public string MessageId; public AttributeData Attribute; } }
-1
dotnet/roslyn
55,898
Include edit session runtime capabilities in telemetry data
tmat
2021-08-25T21:41:02Z
2021-08-26T20:00:14Z
52b1b5784bf719114d698ed5fa4f82d6da30059f
dd121d37f386e689310de5dc039c08406d4dd0b2
Include edit session runtime capabilities in telemetry data.
./src/Compilers/Test/Resources/Core/SymbolsTests/CustomModifiers/ModoptTestOrignal.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; // ildasm /out:ModoptTests.il ModoptTestOrignal.dll // notepad ModoptTests.il // * change "ModoptTestOrignal" to "ModoptTests" in .assembly & module sections // * add modopt modifiers // * remove numbers of at the end of M|Method // ilasm /dll /output:ModoptTests.dll ModoptTests.il namespace Metadata { public class LeastModoptsWinAmbiguous { // 2 public virtual byte M1(byte /*modopt*/ t, byte /*modopt*/ v) { return 22; } // 2 public virtual byte /*modopt*/ M2(byte /*modopt*/ t, byte v) { return 33; } public virtual byte /*modopt*/ GetByte() { return 6; } } public class LeastModoptsWin : LeastModoptsWinAmbiguous { // 2 public virtual byte /*modopt*/ /*modopt*/ M(byte t, byte v) { return 11; } // 1 public virtual byte /*modopt*/ M3(byte t, byte v) { return 51; } // 1 - modreq (Not participate in OR) public virtual byte /*modreq*/ M4(byte t, byte v) { return 44; } } public class ModoptPropAmbiguous { // 2 public virtual string /*modopt*/ /*modopt*/ P { get { return "2 modopts"; } } // 1 public virtual string /*modopt*/ P1 { get { return "1 modopt"; } } // not-in public virtual string /*modreq*/ P2 { get { return "1 modreq"; } } } // public interface IGooAmbiguous<T, R> { // not in R M(T /*modreq*/ t); // 1 R /*modopt*/ M1(T t); // 1 R M2(T /*modopt*/ t); } public interface IGoo { // 2 string /*modopt*/ M<T>(T /*modopt*/ t); // 1 string /*modopt*/ M1<T>(T t); } public class Modreq { public virtual void M(uint x) { Console.Write(x); } } }
// Licensed to the .NET Foundation under one or more 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; // ildasm /out:ModoptTests.il ModoptTestOrignal.dll // notepad ModoptTests.il // * change "ModoptTestOrignal" to "ModoptTests" in .assembly & module sections // * add modopt modifiers // * remove numbers of at the end of M|Method // ilasm /dll /output:ModoptTests.dll ModoptTests.il namespace Metadata { public class LeastModoptsWinAmbiguous { // 2 public virtual byte M1(byte /*modopt*/ t, byte /*modopt*/ v) { return 22; } // 2 public virtual byte /*modopt*/ M2(byte /*modopt*/ t, byte v) { return 33; } public virtual byte /*modopt*/ GetByte() { return 6; } } public class LeastModoptsWin : LeastModoptsWinAmbiguous { // 2 public virtual byte /*modopt*/ /*modopt*/ M(byte t, byte v) { return 11; } // 1 public virtual byte /*modopt*/ M3(byte t, byte v) { return 51; } // 1 - modreq (Not participate in OR) public virtual byte /*modreq*/ M4(byte t, byte v) { return 44; } } public class ModoptPropAmbiguous { // 2 public virtual string /*modopt*/ /*modopt*/ P { get { return "2 modopts"; } } // 1 public virtual string /*modopt*/ P1 { get { return "1 modopt"; } } // not-in public virtual string /*modreq*/ P2 { get { return "1 modreq"; } } } // public interface IGooAmbiguous<T, R> { // not in R M(T /*modreq*/ t); // 1 R /*modopt*/ M1(T t); // 1 R M2(T /*modopt*/ t); } public interface IGoo { // 2 string /*modopt*/ M<T>(T /*modopt*/ t); // 1 string /*modopt*/ M1<T>(T t); } public class Modreq { public virtual void M(uint x) { Console.Write(x); } } }
-1
dotnet/roslyn
55,898
Include edit session runtime capabilities in telemetry data
tmat
2021-08-25T21:41:02Z
2021-08-26T20:00:14Z
52b1b5784bf719114d698ed5fa4f82d6da30059f
dd121d37f386e689310de5dc039c08406d4dd0b2
Include edit session runtime capabilities in telemetry data.
./src/EditorFeatures/CSharp/Highlighting/KeywordHighlighters/YieldStatementHighlighter.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.ComponentModel.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.Implementation.Highlighting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters { [ExportHighlighter(LanguageNames.CSharp)] internal class YieldStatementHighlighter : AbstractKeywordHighlighter<YieldStatementSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public YieldStatementHighlighter() { } protected override void AddHighlights( YieldStatementSyntax yieldStatement, List<TextSpan> spans, CancellationToken cancellationToken) { var parent = yieldStatement .GetAncestorsOrThis<SyntaxNode>() .FirstOrDefault(n => n.IsReturnableConstruct()); if (parent == null) { return; } HighlightRelatedKeywords(parent, spans); } /// <summary> /// Finds all returns that are children of this node, and adds the appropriate spans to the spans list. /// </summary> private void HighlightRelatedKeywords(SyntaxNode node, List<TextSpan> spans) { switch (node) { case YieldStatementSyntax statement: spans.Add( TextSpan.FromBounds( statement.YieldKeyword.SpanStart, statement.ReturnOrBreakKeyword.Span.End)); spans.Add(EmptySpan(statement.SemicolonToken.Span.End)); break; default: foreach (var child in node.ChildNodesAndTokens()) { if (child.IsToken) continue; // Only recurse if we have anything to do if (!child.AsNode().IsReturnableConstruct()) { HighlightRelatedKeywords(child.AsNode(), spans); } } break; } } } }
// Licensed to the .NET Foundation under one or more 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.ComponentModel.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.Implementation.Highlighting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters { [ExportHighlighter(LanguageNames.CSharp)] internal class YieldStatementHighlighter : AbstractKeywordHighlighter<YieldStatementSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public YieldStatementHighlighter() { } protected override void AddHighlights( YieldStatementSyntax yieldStatement, List<TextSpan> spans, CancellationToken cancellationToken) { var parent = yieldStatement .GetAncestorsOrThis<SyntaxNode>() .FirstOrDefault(n => n.IsReturnableConstruct()); if (parent == null) { return; } HighlightRelatedKeywords(parent, spans); } /// <summary> /// Finds all returns that are children of this node, and adds the appropriate spans to the spans list. /// </summary> private void HighlightRelatedKeywords(SyntaxNode node, List<TextSpan> spans) { switch (node) { case YieldStatementSyntax statement: spans.Add( TextSpan.FromBounds( statement.YieldKeyword.SpanStart, statement.ReturnOrBreakKeyword.Span.End)); spans.Add(EmptySpan(statement.SemicolonToken.Span.End)); break; default: foreach (var child in node.ChildNodesAndTokens()) { if (child.IsToken) continue; // Only recurse if we have anything to do if (!child.AsNode().IsReturnableConstruct()) { HighlightRelatedKeywords(child.AsNode(), spans); } } break; } } } }
-1
dotnet/roslyn
55,898
Include edit session runtime capabilities in telemetry data
tmat
2021-08-25T21:41:02Z
2021-08-26T20:00:14Z
52b1b5784bf719114d698ed5fa4f82d6da30059f
dd121d37f386e689310de5dc039c08406d4dd0b2
Include edit session runtime capabilities in telemetry data.
./src/Workspaces/Core/Portable/Workspace/Solution/TextDocumentState.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 System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class TextDocumentState { protected readonly SolutionServices solutionServices; /// <summary> /// A direct reference to our source text. This is only kept around in specialized scenarios. /// Specifically, we keep this around when a document is opened. By providing this we can allow /// clients to easily get to the text of the document in a non-blocking fashion if that's all /// that they need. /// /// Note: this facility does not extend to getting the version as well. That's because the /// version of a document depends on both the current source contents and the contents from /// the previous version of the document. (i.e. if the contents are the same, then we will /// preserve the same version, otherwise we'll move the version forward). Because determining /// the version depends on comparing text, and because getting the old text may block, we /// do not have the ability to know the version of the document up front, and instead can /// only retrieve is asynchronously through <see cref="TextAndVersionSource"/>. /// </summary> protected readonly SourceText? sourceText; protected ValueSource<TextAndVersion> TextAndVersionSource { get; } // Checksums for this solution state private readonly ValueSource<DocumentStateChecksums> _lazyChecksums; public DocumentInfo.DocumentAttributes Attributes { get; } /// <summary> /// A <see cref="IDocumentServiceProvider"/> associated with this document /// </summary> public IDocumentServiceProvider Services { get; } protected TextDocumentState( SolutionServices solutionServices, IDocumentServiceProvider? documentServiceProvider, DocumentInfo.DocumentAttributes attributes, SourceText? sourceText, ValueSource<TextAndVersion> textAndVersionSource) { this.solutionServices = solutionServices; this.sourceText = sourceText; this.TextAndVersionSource = textAndVersionSource; Attributes = attributes; Services = documentServiceProvider ?? DefaultTextDocumentServiceProvider.Instance; // This constructor is called whenever we're creating a new TextDocumentState from another // TextDocumentState, and so we populate all the fields from the inputs. We will always create // a new AsyncLazy to compute the checksum though, and that's because there's no practical way for // the newly created TextDocumentState to have the same checksum as a previous TextDocumentState: // if we're creating a new state, it's because something changed, and we'll have to create a new checksum. _lazyChecksums = new AsyncLazy<DocumentStateChecksums>(ComputeChecksumsAsync, cacheResult: true); } public TextDocumentState(DocumentInfo info, SolutionServices services) : this(services, info.DocumentServiceProvider, info.Attributes, sourceText: null, textAndVersionSource: info.TextLoader != null ? CreateRecoverableText(info.TextLoader, info.Id, services) : CreateStrongText(TextAndVersion.Create(SourceText.From(string.Empty, Encoding.UTF8), VersionStamp.Default, info.FilePath))) { } public DocumentId Id => Attributes.Id; public string? FilePath => Attributes.FilePath; public IReadOnlyList<string> Folders => Attributes.Folders; public string Name => Attributes.Name; protected static ValueSource<TextAndVersion> CreateStrongText(TextAndVersion text) => new ConstantValueSource<TextAndVersion>(text); protected static ValueSource<TextAndVersion> CreateStrongText(TextLoader loader, DocumentId documentId, SolutionServices services) { return new AsyncLazy<TextAndVersion>( asynchronousComputeFunction: cancellationToken => loader.LoadTextAsync(services.Workspace, documentId, cancellationToken), synchronousComputeFunction: cancellationToken => loader.LoadTextSynchronously(services.Workspace, documentId, cancellationToken), cacheResult: true); } protected static ValueSource<TextAndVersion> CreateRecoverableText(TextAndVersion text, SolutionServices services) { var result = new RecoverableTextAndVersion(CreateStrongText(text), services.TemporaryStorage); // This RecoverableTextAndVersion is created directly from a TextAndVersion instance. In its initial state, // the RecoverableTextAndVersion keeps a strong reference to the initial TextAndVersion, and only // transitions to a weak reference backed by temporary storage after the first time GetValue (or // GetValueAsync) is called. Since we know we are creating a RecoverableTextAndVersion for the purpose of // avoiding problematic address space overhead, we call GetValue immediately to force the object to weakly // hold its data from the start. result.GetValue(); return result; } protected static ValueSource<TextAndVersion> CreateRecoverableText(TextLoader loader, DocumentId documentId, SolutionServices services) { return new RecoverableTextAndVersion( new AsyncLazy<TextAndVersion>( asynchronousComputeFunction: cancellationToken => loader.LoadTextAsync(services.Workspace, documentId, cancellationToken), synchronousComputeFunction: cancellationToken => loader.LoadTextSynchronously(services.Workspace, documentId, cancellationToken), cacheResult: false), services.TemporaryStorage); } public ITemporaryTextStorage? Storage { get { var recoverableText = this.TextAndVersionSource as RecoverableTextAndVersion; if (recoverableText == null) { return null; } return recoverableText.Storage; } } public bool TryGetText([NotNullWhen(returnValue: true)] out SourceText? text) { if (this.sourceText != null) { text = sourceText; return true; } if (this.TextAndVersionSource.TryGetValue(out var textAndVersion)) { text = textAndVersion.Text; return true; } else { text = null; return false; } } public bool TryGetTextVersion(out VersionStamp version) { // try fast path first if (this.TextAndVersionSource is ITextVersionable versionable) { return versionable.TryGetTextVersion(out version); } if (this.TextAndVersionSource.TryGetValue(out var textAndVersion)) { version = textAndVersion.Version; return true; } else { version = default; return false; } } public bool TryGetTextAndVersion([NotNullWhen(true)] out TextAndVersion? textAndVersion) => TextAndVersionSource.TryGetValue(out textAndVersion); public ValueTask<SourceText> GetTextAsync(CancellationToken cancellationToken) { if (sourceText != null) { return new ValueTask<SourceText>(sourceText); } if (TryGetText(out var text)) { return new ValueTask<SourceText>(text); } return SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync( static (self, cancellationToken) => self.GetTextAndVersionAsync(cancellationToken), static (textAndVersion, _) => textAndVersion.Text, this, cancellationToken); } public SourceText GetTextSynchronously(CancellationToken cancellationToken) { var textAndVersion = this.TextAndVersionSource.GetValue(cancellationToken); return textAndVersion.Text; } public VersionStamp GetTextVersionSynchronously(CancellationToken cancellationToken) { var textAndVersion = this.TextAndVersionSource.GetValue(cancellationToken); return textAndVersion.Version; } public async Task<VersionStamp> GetTextVersionAsync(CancellationToken cancellationToken) { // try fast path first if (TryGetTextVersion(out var version)) { return version; } var textAndVersion = await GetTextAndVersionAsync(cancellationToken).ConfigureAwait(false); return textAndVersion.Version; } public TextDocumentState UpdateText(TextAndVersion newTextAndVersion, PreservationMode mode) { var newTextSource = mode == PreservationMode.PreserveIdentity ? CreateStrongText(newTextAndVersion) : CreateRecoverableText(newTextAndVersion, this.solutionServices); return UpdateText(newTextSource, mode, incremental: true); } public TextDocumentState UpdateText(SourceText newText, PreservationMode mode) { var newVersion = GetNewerVersion(); var newTextAndVersion = TextAndVersion.Create(newText, newVersion, FilePath); return UpdateText(newTextAndVersion, mode); } public TextDocumentState UpdateText(TextLoader loader, PreservationMode mode) { // don't blow up on non-text documents. var newTextSource = mode == PreservationMode.PreserveIdentity ? CreateStrongText(loader, Id, solutionServices) : CreateRecoverableText(loader, Id, solutionServices); return UpdateText(newTextSource, mode, incremental: false); } protected virtual TextDocumentState UpdateText(ValueSource<TextAndVersion> newTextSource, PreservationMode mode, bool incremental) { return new TextDocumentState( this.solutionServices, this.Services, this.Attributes, sourceText: null, textAndVersionSource: newTextSource); } private ValueTask<TextAndVersion> GetTextAndVersionAsync(CancellationToken cancellationToken) { if (this.TextAndVersionSource.TryGetValue(out var textAndVersion)) { return new ValueTask<TextAndVersion>(textAndVersion); } else { return new ValueTask<TextAndVersion>(TextAndVersionSource.GetValueAsync(cancellationToken)); } } internal virtual async Task<Diagnostic?> GetLoadDiagnosticAsync(CancellationToken cancellationToken) => (await GetTextAndVersionAsync(cancellationToken).ConfigureAwait(false)).LoadDiagnostic; private VersionStamp GetNewerVersion() { if (this.TextAndVersionSource.TryGetValue(out var textAndVersion)) { return textAndVersion.Version.GetNewerVersion(); } return VersionStamp.Create(); } public virtual async Task<VersionStamp> GetTopLevelChangeTextVersionAsync(CancellationToken cancellationToken) { var textAndVersion = await this.TextAndVersionSource.GetValueAsync(cancellationToken).ConfigureAwait(false); return textAndVersion.Version; } /// <summary> /// Only checks if the source of the text has changed, no content check is done. /// </summary> public bool HasTextChanged(TextDocumentState oldState, bool ignoreUnchangeableDocument) { if (ignoreUnchangeableDocument && !oldState.CanApplyChange()) { return false; } return oldState.TextAndVersionSource != TextAndVersionSource; } public bool HasInfoChanged(TextDocumentState oldState) => oldState.Attributes != Attributes; } }
// Licensed to the .NET Foundation under one or more 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 System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class TextDocumentState { protected readonly SolutionServices solutionServices; /// <summary> /// A direct reference to our source text. This is only kept around in specialized scenarios. /// Specifically, we keep this around when a document is opened. By providing this we can allow /// clients to easily get to the text of the document in a non-blocking fashion if that's all /// that they need. /// /// Note: this facility does not extend to getting the version as well. That's because the /// version of a document depends on both the current source contents and the contents from /// the previous version of the document. (i.e. if the contents are the same, then we will /// preserve the same version, otherwise we'll move the version forward). Because determining /// the version depends on comparing text, and because getting the old text may block, we /// do not have the ability to know the version of the document up front, and instead can /// only retrieve is asynchronously through <see cref="TextAndVersionSource"/>. /// </summary> protected readonly SourceText? sourceText; protected ValueSource<TextAndVersion> TextAndVersionSource { get; } // Checksums for this solution state private readonly ValueSource<DocumentStateChecksums> _lazyChecksums; public DocumentInfo.DocumentAttributes Attributes { get; } /// <summary> /// A <see cref="IDocumentServiceProvider"/> associated with this document /// </summary> public IDocumentServiceProvider Services { get; } protected TextDocumentState( SolutionServices solutionServices, IDocumentServiceProvider? documentServiceProvider, DocumentInfo.DocumentAttributes attributes, SourceText? sourceText, ValueSource<TextAndVersion> textAndVersionSource) { this.solutionServices = solutionServices; this.sourceText = sourceText; this.TextAndVersionSource = textAndVersionSource; Attributes = attributes; Services = documentServiceProvider ?? DefaultTextDocumentServiceProvider.Instance; // This constructor is called whenever we're creating a new TextDocumentState from another // TextDocumentState, and so we populate all the fields from the inputs. We will always create // a new AsyncLazy to compute the checksum though, and that's because there's no practical way for // the newly created TextDocumentState to have the same checksum as a previous TextDocumentState: // if we're creating a new state, it's because something changed, and we'll have to create a new checksum. _lazyChecksums = new AsyncLazy<DocumentStateChecksums>(ComputeChecksumsAsync, cacheResult: true); } public TextDocumentState(DocumentInfo info, SolutionServices services) : this(services, info.DocumentServiceProvider, info.Attributes, sourceText: null, textAndVersionSource: info.TextLoader != null ? CreateRecoverableText(info.TextLoader, info.Id, services) : CreateStrongText(TextAndVersion.Create(SourceText.From(string.Empty, Encoding.UTF8), VersionStamp.Default, info.FilePath))) { } public DocumentId Id => Attributes.Id; public string? FilePath => Attributes.FilePath; public IReadOnlyList<string> Folders => Attributes.Folders; public string Name => Attributes.Name; protected static ValueSource<TextAndVersion> CreateStrongText(TextAndVersion text) => new ConstantValueSource<TextAndVersion>(text); protected static ValueSource<TextAndVersion> CreateStrongText(TextLoader loader, DocumentId documentId, SolutionServices services) { return new AsyncLazy<TextAndVersion>( asynchronousComputeFunction: cancellationToken => loader.LoadTextAsync(services.Workspace, documentId, cancellationToken), synchronousComputeFunction: cancellationToken => loader.LoadTextSynchronously(services.Workspace, documentId, cancellationToken), cacheResult: true); } protected static ValueSource<TextAndVersion> CreateRecoverableText(TextAndVersion text, SolutionServices services) { var result = new RecoverableTextAndVersion(CreateStrongText(text), services.TemporaryStorage); // This RecoverableTextAndVersion is created directly from a TextAndVersion instance. In its initial state, // the RecoverableTextAndVersion keeps a strong reference to the initial TextAndVersion, and only // transitions to a weak reference backed by temporary storage after the first time GetValue (or // GetValueAsync) is called. Since we know we are creating a RecoverableTextAndVersion for the purpose of // avoiding problematic address space overhead, we call GetValue immediately to force the object to weakly // hold its data from the start. result.GetValue(); return result; } protected static ValueSource<TextAndVersion> CreateRecoverableText(TextLoader loader, DocumentId documentId, SolutionServices services) { return new RecoverableTextAndVersion( new AsyncLazy<TextAndVersion>( asynchronousComputeFunction: cancellationToken => loader.LoadTextAsync(services.Workspace, documentId, cancellationToken), synchronousComputeFunction: cancellationToken => loader.LoadTextSynchronously(services.Workspace, documentId, cancellationToken), cacheResult: false), services.TemporaryStorage); } public ITemporaryTextStorage? Storage { get { var recoverableText = this.TextAndVersionSource as RecoverableTextAndVersion; if (recoverableText == null) { return null; } return recoverableText.Storage; } } public bool TryGetText([NotNullWhen(returnValue: true)] out SourceText? text) { if (this.sourceText != null) { text = sourceText; return true; } if (this.TextAndVersionSource.TryGetValue(out var textAndVersion)) { text = textAndVersion.Text; return true; } else { text = null; return false; } } public bool TryGetTextVersion(out VersionStamp version) { // try fast path first if (this.TextAndVersionSource is ITextVersionable versionable) { return versionable.TryGetTextVersion(out version); } if (this.TextAndVersionSource.TryGetValue(out var textAndVersion)) { version = textAndVersion.Version; return true; } else { version = default; return false; } } public bool TryGetTextAndVersion([NotNullWhen(true)] out TextAndVersion? textAndVersion) => TextAndVersionSource.TryGetValue(out textAndVersion); public ValueTask<SourceText> GetTextAsync(CancellationToken cancellationToken) { if (sourceText != null) { return new ValueTask<SourceText>(sourceText); } if (TryGetText(out var text)) { return new ValueTask<SourceText>(text); } return SpecializedTasks.TransformWithoutIntermediateCancellationExceptionAsync( static (self, cancellationToken) => self.GetTextAndVersionAsync(cancellationToken), static (textAndVersion, _) => textAndVersion.Text, this, cancellationToken); } public SourceText GetTextSynchronously(CancellationToken cancellationToken) { var textAndVersion = this.TextAndVersionSource.GetValue(cancellationToken); return textAndVersion.Text; } public VersionStamp GetTextVersionSynchronously(CancellationToken cancellationToken) { var textAndVersion = this.TextAndVersionSource.GetValue(cancellationToken); return textAndVersion.Version; } public async Task<VersionStamp> GetTextVersionAsync(CancellationToken cancellationToken) { // try fast path first if (TryGetTextVersion(out var version)) { return version; } var textAndVersion = await GetTextAndVersionAsync(cancellationToken).ConfigureAwait(false); return textAndVersion.Version; } public TextDocumentState UpdateText(TextAndVersion newTextAndVersion, PreservationMode mode) { var newTextSource = mode == PreservationMode.PreserveIdentity ? CreateStrongText(newTextAndVersion) : CreateRecoverableText(newTextAndVersion, this.solutionServices); return UpdateText(newTextSource, mode, incremental: true); } public TextDocumentState UpdateText(SourceText newText, PreservationMode mode) { var newVersion = GetNewerVersion(); var newTextAndVersion = TextAndVersion.Create(newText, newVersion, FilePath); return UpdateText(newTextAndVersion, mode); } public TextDocumentState UpdateText(TextLoader loader, PreservationMode mode) { // don't blow up on non-text documents. var newTextSource = mode == PreservationMode.PreserveIdentity ? CreateStrongText(loader, Id, solutionServices) : CreateRecoverableText(loader, Id, solutionServices); return UpdateText(newTextSource, mode, incremental: false); } protected virtual TextDocumentState UpdateText(ValueSource<TextAndVersion> newTextSource, PreservationMode mode, bool incremental) { return new TextDocumentState( this.solutionServices, this.Services, this.Attributes, sourceText: null, textAndVersionSource: newTextSource); } private ValueTask<TextAndVersion> GetTextAndVersionAsync(CancellationToken cancellationToken) { if (this.TextAndVersionSource.TryGetValue(out var textAndVersion)) { return new ValueTask<TextAndVersion>(textAndVersion); } else { return new ValueTask<TextAndVersion>(TextAndVersionSource.GetValueAsync(cancellationToken)); } } internal virtual async Task<Diagnostic?> GetLoadDiagnosticAsync(CancellationToken cancellationToken) => (await GetTextAndVersionAsync(cancellationToken).ConfigureAwait(false)).LoadDiagnostic; private VersionStamp GetNewerVersion() { if (this.TextAndVersionSource.TryGetValue(out var textAndVersion)) { return textAndVersion.Version.GetNewerVersion(); } return VersionStamp.Create(); } public virtual async Task<VersionStamp> GetTopLevelChangeTextVersionAsync(CancellationToken cancellationToken) { var textAndVersion = await this.TextAndVersionSource.GetValueAsync(cancellationToken).ConfigureAwait(false); return textAndVersion.Version; } /// <summary> /// Only checks if the source of the text has changed, no content check is done. /// </summary> public bool HasTextChanged(TextDocumentState oldState, bool ignoreUnchangeableDocument) { if (ignoreUnchangeableDocument && !oldState.CanApplyChange()) { return false; } return oldState.TextAndVersionSource != TextAndVersionSource; } public bool HasInfoChanged(TextDocumentState oldState) => oldState.Attributes != Attributes; } }
-1
dotnet/roslyn
55,898
Include edit session runtime capabilities in telemetry data
tmat
2021-08-25T21:41:02Z
2021-08-26T20:00:14Z
52b1b5784bf719114d698ed5fa4f82d6da30059f
dd121d37f386e689310de5dc039c08406d4dd0b2
Include edit session runtime capabilities in telemetry data.
./src/ExpressionEvaluator/CSharp/Test/ResultProvider/DynamicFlagsCustomTypeInfoTests.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.ObjectModel; using System.Linq; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class DynamicFlagsCustomTypeInfoTests : CSharpResultProviderTestBase { [Fact] public void ToBytes() { ValidateToBytes(new bool[0]); ValidateToBytes(new bool[] { false }); ValidateToBytes(new bool[] { true }, 0x01); ValidateToBytes(new bool[] { false, false }); ValidateToBytes(new bool[] { true, false }, 0x01); ValidateToBytes(new bool[] { false, true }, 0x02); ValidateToBytes(new bool[] { true, true }, 0x03); ValidateToBytes(new bool[] { false, false, true }, 0x04); ValidateToBytes(new bool[] { false, false, false, true }, 0x08); ValidateToBytes(new bool[] { false, false, false, false, true }, 0x10); ValidateToBytes(new bool[] { false, false, false, false, false, true }, 0x20); ValidateToBytes(new bool[] { false, false, false, false, false, false, true }, 0x40); ValidateToBytes(new bool[] { false, false, false, false, false, false, false, true }, 0x80); ValidateToBytes(new bool[] { false, false, false, false, false, false, false, false, true }, 0x00, 0x01); } [Fact] public void CopyTo() { ValidateCopyTo(new byte[0]); ValidateCopyTo(new byte[] { 0x00 }, false, false, false, false, false, false, false, false); ValidateCopyTo(new byte[] { 0x01 }, true, false, false, false, false, false, false, false); ValidateCopyTo(new byte[] { 0x02 }, false, true, false, false, false, false, false, false); ValidateCopyTo(new byte[] { 0x03 }, true, true, false, false, false, false, false, false); ValidateCopyTo(new byte[] { 0x04 }, false, false, true, false, false, false, false, false); ValidateCopyTo(new byte[] { 0x08 }, false, false, false, true, false, false, false, false); ValidateCopyTo(new byte[] { 0x10 }, false, false, false, false, true, false, false, false); ValidateCopyTo(new byte[] { 0x20 }, false, false, false, false, false, true, false, false); ValidateCopyTo(new byte[] { 0x40 }, false, false, false, false, false, false, true, false); ValidateCopyTo(new byte[] { 0x80 }, false, false, false, false, false, false, false, true); ValidateCopyTo(new byte[] { 0x00, 0x01 }, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false); } [Fact] public void EncodeAndDecode() { var encoded = CustomTypeInfo.Encode(null, null); Assert.Null(encoded); ReadOnlyCollection<byte> bytes; ReadOnlyCollection<string> names; // Exceed max bytes. bytes = GetBytesInRange(0, 256); encoded = CustomTypeInfo.Encode(bytes, null); Assert.Null(encoded); // Max bytes. bytes = GetBytesInRange(0, 255); encoded = CustomTypeInfo.Encode(bytes, null); Assert.Equal(256, encoded.Count); Assert.Equal(255, encoded[0]); ReadOnlyCollection<byte> dynamicFlags; ReadOnlyCollection<string> tupleElementNames; CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Equal(bytes, dynamicFlags); Assert.Null(tupleElementNames); // Empty dynamic flags collection bytes = new ReadOnlyCollection<byte>(new byte[0]); // ... with names. names = new ReadOnlyCollection<string>(new[] { "A" }); encoded = CustomTypeInfo.Encode(bytes, names); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Null(dynamicFlags); Assert.Equal(names, tupleElementNames); // ... without names. encoded = CustomTypeInfo.Encode(bytes, null); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Null(dynamicFlags); Assert.Null(tupleElementNames); // Empty names collection names = new ReadOnlyCollection<string>(new string[0]); // ... with dynamic flags. bytes = GetBytesInRange(0, 255); encoded = CustomTypeInfo.Encode(bytes, names); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Equal(bytes, dynamicFlags); Assert.Null(tupleElementNames); // ... without dynamic flags. encoded = CustomTypeInfo.Encode(null, names); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Null(dynamicFlags); Assert.Null(tupleElementNames); // Single null name names = new ReadOnlyCollection<string>(new string[] { null }); // ... with dynamic flags. bytes = GetBytesInRange(0, 255); encoded = CustomTypeInfo.Encode(bytes, names); Assert.Equal(255, encoded[0]); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Equal(bytes, dynamicFlags); Assert.Equal(names, tupleElementNames); // ... without dynamic flags. encoded = CustomTypeInfo.Encode(null, names); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Null(dynamicFlags); Assert.Equal(names, tupleElementNames); // Multiple names names = new ReadOnlyCollection<string>(new[] { null, "A", null, "B" }); // ... with dynamic flags. bytes = GetBytesInRange(0, 255); encoded = CustomTypeInfo.Encode(bytes, names); Assert.Equal(255, encoded[0]); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Equal(bytes, dynamicFlags); Assert.Equal(names, tupleElementNames); // ... without dynamic flags. encoded = CustomTypeInfo.Encode(null, names); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Null(dynamicFlags); Assert.Equal(names, tupleElementNames); } private static ReadOnlyCollection<byte> GetBytesInRange(int start, int length) { return new ReadOnlyCollection<byte>(Enumerable.Range(start, length).Select(i => (byte)(i % 256)).ToArray()); } [Fact] public void CustomTypeInfoConstructor() { ValidateCustomTypeInfo(); ValidateCustomTypeInfo(0x00); ValidateCustomTypeInfo(0x01); ValidateCustomTypeInfo(0x02); ValidateCustomTypeInfo(0x03); ValidateCustomTypeInfo(0x04); ValidateCustomTypeInfo(0x08); ValidateCustomTypeInfo(0x10); ValidateCustomTypeInfo(0x20); ValidateCustomTypeInfo(0x40); ValidateCustomTypeInfo(0x80); ValidateCustomTypeInfo(0x00, 0x01); } [Fact] public void CustomTypeInfoConstructor_OtherGuid() { var customTypeInfo = DkmClrCustomTypeInfo.Create(Guid.NewGuid(), new ReadOnlyCollection<byte>(new byte[] { 0x01 })); ReadOnlyCollection<byte> dynamicFlags; ReadOnlyCollection<string> tupleElementNames; CustomTypeInfo.Decode( customTypeInfo.PayloadTypeId, customTypeInfo.Payload, out dynamicFlags, out tupleElementNames); Assert.Null(dynamicFlags); Assert.Null(tupleElementNames); } [Fact] public void Indexer() { ValidateIndexer(null); ValidateIndexer(false); ValidateIndexer(true); ValidateIndexer(false, false); ValidateIndexer(false, true); ValidateIndexer(true, false); ValidateIndexer(true, true); ValidateIndexer(false, false, true); ValidateIndexer(false, false, false, true); ValidateIndexer(false, false, false, false, true); ValidateIndexer(false, false, false, false, false, true); ValidateIndexer(false, false, false, false, false, false, true); ValidateIndexer(false, false, false, false, false, false, false, true); ValidateIndexer(false, false, false, false, false, false, false, false, true); } [Fact] public void SkipOne() { ValidateBytes(DynamicFlagsCustomTypeInfo.SkipOne(null)); var dynamicFlagsCustomTypeInfo = new ReadOnlyCollection<byte>(new byte[] { 0x80 }); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x40); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x20); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x10); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x08); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x04); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x02); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x01); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo); dynamicFlagsCustomTypeInfo = new ReadOnlyCollection<byte>(new byte[] { 0x00, 0x02 }); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x00, 0x01); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x80, 0x00); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x40, 0x00); } private static void ValidateCustomTypeInfo(params byte[] payload) { Assert.NotNull(payload); var dkmClrCustomTypeInfo = CustomTypeInfo.Create(new ReadOnlyCollection<byte>(payload), null); Assert.Equal(CustomTypeInfo.PayloadTypeId, dkmClrCustomTypeInfo.PayloadTypeId); Assert.NotNull(dkmClrCustomTypeInfo.Payload); ReadOnlyCollection<byte> dynamicFlags; ReadOnlyCollection<string> tupleElementNames; CustomTypeInfo.Decode( dkmClrCustomTypeInfo.PayloadTypeId, dkmClrCustomTypeInfo.Payload, out dynamicFlags, out tupleElementNames); ValidateBytes(dynamicFlags, payload); Assert.Null(tupleElementNames); } private static void ValidateIndexer(params bool[] dynamicFlags) { if (dynamicFlags == null) { Assert.False(DynamicFlagsCustomTypeInfo.GetFlag(null, 0)); } else { var builder = ArrayBuilder<bool>.GetInstance(dynamicFlags.Length); builder.AddRange(dynamicFlags); var customTypeInfo = DynamicFlagsCustomTypeInfo.ToBytes(builder); builder.Free(); AssertEx.All(dynamicFlags.Select((f, i) => f == DynamicFlagsCustomTypeInfo.GetFlag(customTypeInfo, i)), x => x); Assert.False(DynamicFlagsCustomTypeInfo.GetFlag(customTypeInfo, dynamicFlags.Length)); } } private static void ValidateToBytes(bool[] dynamicFlags, params byte[] expectedBytes) { Assert.NotNull(dynamicFlags); Assert.NotNull(expectedBytes); var builder = ArrayBuilder<bool>.GetInstance(dynamicFlags.Length); builder.AddRange(dynamicFlags); var actualBytes = DynamicFlagsCustomTypeInfo.ToBytes(builder); builder.Free(); ValidateBytes(actualBytes, expectedBytes); } private static void ValidateCopyTo(byte[] dynamicFlags, params bool[] expectedFlags) { var builder = ArrayBuilder<bool>.GetInstance(); DynamicFlagsCustomTypeInfo.CopyTo(new ReadOnlyCollection<byte>(dynamicFlags), builder); var actualFlags = builder.ToArrayAndFree(); Assert.Equal(expectedFlags, actualFlags); } private static void ValidateBytes(ReadOnlyCollection<byte> actualBytes, params byte[] expectedBytes) { Assert.NotNull(expectedBytes); if (expectedBytes.Length == 0) { Assert.Null(actualBytes); } else { Assert.Equal(expectedBytes, actualBytes); } } } }
// Licensed to the .NET Foundation under one or more 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.ObjectModel; using System.Linq; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class DynamicFlagsCustomTypeInfoTests : CSharpResultProviderTestBase { [Fact] public void ToBytes() { ValidateToBytes(new bool[0]); ValidateToBytes(new bool[] { false }); ValidateToBytes(new bool[] { true }, 0x01); ValidateToBytes(new bool[] { false, false }); ValidateToBytes(new bool[] { true, false }, 0x01); ValidateToBytes(new bool[] { false, true }, 0x02); ValidateToBytes(new bool[] { true, true }, 0x03); ValidateToBytes(new bool[] { false, false, true }, 0x04); ValidateToBytes(new bool[] { false, false, false, true }, 0x08); ValidateToBytes(new bool[] { false, false, false, false, true }, 0x10); ValidateToBytes(new bool[] { false, false, false, false, false, true }, 0x20); ValidateToBytes(new bool[] { false, false, false, false, false, false, true }, 0x40); ValidateToBytes(new bool[] { false, false, false, false, false, false, false, true }, 0x80); ValidateToBytes(new bool[] { false, false, false, false, false, false, false, false, true }, 0x00, 0x01); } [Fact] public void CopyTo() { ValidateCopyTo(new byte[0]); ValidateCopyTo(new byte[] { 0x00 }, false, false, false, false, false, false, false, false); ValidateCopyTo(new byte[] { 0x01 }, true, false, false, false, false, false, false, false); ValidateCopyTo(new byte[] { 0x02 }, false, true, false, false, false, false, false, false); ValidateCopyTo(new byte[] { 0x03 }, true, true, false, false, false, false, false, false); ValidateCopyTo(new byte[] { 0x04 }, false, false, true, false, false, false, false, false); ValidateCopyTo(new byte[] { 0x08 }, false, false, false, true, false, false, false, false); ValidateCopyTo(new byte[] { 0x10 }, false, false, false, false, true, false, false, false); ValidateCopyTo(new byte[] { 0x20 }, false, false, false, false, false, true, false, false); ValidateCopyTo(new byte[] { 0x40 }, false, false, false, false, false, false, true, false); ValidateCopyTo(new byte[] { 0x80 }, false, false, false, false, false, false, false, true); ValidateCopyTo(new byte[] { 0x00, 0x01 }, false, false, false, false, false, false, false, false, true, false, false, false, false, false, false, false); } [Fact] public void EncodeAndDecode() { var encoded = CustomTypeInfo.Encode(null, null); Assert.Null(encoded); ReadOnlyCollection<byte> bytes; ReadOnlyCollection<string> names; // Exceed max bytes. bytes = GetBytesInRange(0, 256); encoded = CustomTypeInfo.Encode(bytes, null); Assert.Null(encoded); // Max bytes. bytes = GetBytesInRange(0, 255); encoded = CustomTypeInfo.Encode(bytes, null); Assert.Equal(256, encoded.Count); Assert.Equal(255, encoded[0]); ReadOnlyCollection<byte> dynamicFlags; ReadOnlyCollection<string> tupleElementNames; CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Equal(bytes, dynamicFlags); Assert.Null(tupleElementNames); // Empty dynamic flags collection bytes = new ReadOnlyCollection<byte>(new byte[0]); // ... with names. names = new ReadOnlyCollection<string>(new[] { "A" }); encoded = CustomTypeInfo.Encode(bytes, names); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Null(dynamicFlags); Assert.Equal(names, tupleElementNames); // ... without names. encoded = CustomTypeInfo.Encode(bytes, null); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Null(dynamicFlags); Assert.Null(tupleElementNames); // Empty names collection names = new ReadOnlyCollection<string>(new string[0]); // ... with dynamic flags. bytes = GetBytesInRange(0, 255); encoded = CustomTypeInfo.Encode(bytes, names); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Equal(bytes, dynamicFlags); Assert.Null(tupleElementNames); // ... without dynamic flags. encoded = CustomTypeInfo.Encode(null, names); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Null(dynamicFlags); Assert.Null(tupleElementNames); // Single null name names = new ReadOnlyCollection<string>(new string[] { null }); // ... with dynamic flags. bytes = GetBytesInRange(0, 255); encoded = CustomTypeInfo.Encode(bytes, names); Assert.Equal(255, encoded[0]); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Equal(bytes, dynamicFlags); Assert.Equal(names, tupleElementNames); // ... without dynamic flags. encoded = CustomTypeInfo.Encode(null, names); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Null(dynamicFlags); Assert.Equal(names, tupleElementNames); // Multiple names names = new ReadOnlyCollection<string>(new[] { null, "A", null, "B" }); // ... with dynamic flags. bytes = GetBytesInRange(0, 255); encoded = CustomTypeInfo.Encode(bytes, names); Assert.Equal(255, encoded[0]); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Equal(bytes, dynamicFlags); Assert.Equal(names, tupleElementNames); // ... without dynamic flags. encoded = CustomTypeInfo.Encode(null, names); CustomTypeInfo.Decode(CustomTypeInfo.PayloadTypeId, encoded, out dynamicFlags, out tupleElementNames); Assert.Null(dynamicFlags); Assert.Equal(names, tupleElementNames); } private static ReadOnlyCollection<byte> GetBytesInRange(int start, int length) { return new ReadOnlyCollection<byte>(Enumerable.Range(start, length).Select(i => (byte)(i % 256)).ToArray()); } [Fact] public void CustomTypeInfoConstructor() { ValidateCustomTypeInfo(); ValidateCustomTypeInfo(0x00); ValidateCustomTypeInfo(0x01); ValidateCustomTypeInfo(0x02); ValidateCustomTypeInfo(0x03); ValidateCustomTypeInfo(0x04); ValidateCustomTypeInfo(0x08); ValidateCustomTypeInfo(0x10); ValidateCustomTypeInfo(0x20); ValidateCustomTypeInfo(0x40); ValidateCustomTypeInfo(0x80); ValidateCustomTypeInfo(0x00, 0x01); } [Fact] public void CustomTypeInfoConstructor_OtherGuid() { var customTypeInfo = DkmClrCustomTypeInfo.Create(Guid.NewGuid(), new ReadOnlyCollection<byte>(new byte[] { 0x01 })); ReadOnlyCollection<byte> dynamicFlags; ReadOnlyCollection<string> tupleElementNames; CustomTypeInfo.Decode( customTypeInfo.PayloadTypeId, customTypeInfo.Payload, out dynamicFlags, out tupleElementNames); Assert.Null(dynamicFlags); Assert.Null(tupleElementNames); } [Fact] public void Indexer() { ValidateIndexer(null); ValidateIndexer(false); ValidateIndexer(true); ValidateIndexer(false, false); ValidateIndexer(false, true); ValidateIndexer(true, false); ValidateIndexer(true, true); ValidateIndexer(false, false, true); ValidateIndexer(false, false, false, true); ValidateIndexer(false, false, false, false, true); ValidateIndexer(false, false, false, false, false, true); ValidateIndexer(false, false, false, false, false, false, true); ValidateIndexer(false, false, false, false, false, false, false, true); ValidateIndexer(false, false, false, false, false, false, false, false, true); } [Fact] public void SkipOne() { ValidateBytes(DynamicFlagsCustomTypeInfo.SkipOne(null)); var dynamicFlagsCustomTypeInfo = new ReadOnlyCollection<byte>(new byte[] { 0x80 }); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x40); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x20); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x10); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x08); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x04); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x02); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x01); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo); dynamicFlagsCustomTypeInfo = new ReadOnlyCollection<byte>(new byte[] { 0x00, 0x02 }); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x00, 0x01); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x80, 0x00); dynamicFlagsCustomTypeInfo = DynamicFlagsCustomTypeInfo.SkipOne(dynamicFlagsCustomTypeInfo); ValidateBytes(dynamicFlagsCustomTypeInfo, 0x40, 0x00); } private static void ValidateCustomTypeInfo(params byte[] payload) { Assert.NotNull(payload); var dkmClrCustomTypeInfo = CustomTypeInfo.Create(new ReadOnlyCollection<byte>(payload), null); Assert.Equal(CustomTypeInfo.PayloadTypeId, dkmClrCustomTypeInfo.PayloadTypeId); Assert.NotNull(dkmClrCustomTypeInfo.Payload); ReadOnlyCollection<byte> dynamicFlags; ReadOnlyCollection<string> tupleElementNames; CustomTypeInfo.Decode( dkmClrCustomTypeInfo.PayloadTypeId, dkmClrCustomTypeInfo.Payload, out dynamicFlags, out tupleElementNames); ValidateBytes(dynamicFlags, payload); Assert.Null(tupleElementNames); } private static void ValidateIndexer(params bool[] dynamicFlags) { if (dynamicFlags == null) { Assert.False(DynamicFlagsCustomTypeInfo.GetFlag(null, 0)); } else { var builder = ArrayBuilder<bool>.GetInstance(dynamicFlags.Length); builder.AddRange(dynamicFlags); var customTypeInfo = DynamicFlagsCustomTypeInfo.ToBytes(builder); builder.Free(); AssertEx.All(dynamicFlags.Select((f, i) => f == DynamicFlagsCustomTypeInfo.GetFlag(customTypeInfo, i)), x => x); Assert.False(DynamicFlagsCustomTypeInfo.GetFlag(customTypeInfo, dynamicFlags.Length)); } } private static void ValidateToBytes(bool[] dynamicFlags, params byte[] expectedBytes) { Assert.NotNull(dynamicFlags); Assert.NotNull(expectedBytes); var builder = ArrayBuilder<bool>.GetInstance(dynamicFlags.Length); builder.AddRange(dynamicFlags); var actualBytes = DynamicFlagsCustomTypeInfo.ToBytes(builder); builder.Free(); ValidateBytes(actualBytes, expectedBytes); } private static void ValidateCopyTo(byte[] dynamicFlags, params bool[] expectedFlags) { var builder = ArrayBuilder<bool>.GetInstance(); DynamicFlagsCustomTypeInfo.CopyTo(new ReadOnlyCollection<byte>(dynamicFlags), builder); var actualFlags = builder.ToArrayAndFree(); Assert.Equal(expectedFlags, actualFlags); } private static void ValidateBytes(ReadOnlyCollection<byte> actualBytes, params byte[] expectedBytes) { Assert.NotNull(expectedBytes); if (expectedBytes.Length == 0) { Assert.Null(actualBytes); } else { Assert.Equal(expectedBytes, actualBytes); } } } }
-1
dotnet/roslyn
55,898
Include edit session runtime capabilities in telemetry data
tmat
2021-08-25T21:41:02Z
2021-08-26T20:00:14Z
52b1b5784bf719114d698ed5fa4f82d6da30059f
dd121d37f386e689310de5dc039c08406d4dd0b2
Include edit session runtime capabilities in telemetry data.
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_IsPatternOperator.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.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitIsPatternExpression(BoundIsPatternExpression node) { bool negated = node.IsNegated; BoundExpression result; if (canProduceLinearSequence(node.DecisionDag.RootNode, whenTrueLabel: node.WhenTrueLabel, whenFalseLabel: node.WhenFalseLabel)) { // If we can build a linear test sequence `(e1 && e2 && e3)` for the dag, do so. var isPatternRewriter = new IsPatternExpressionLinearLocalRewriter(node, this); result = isPatternRewriter.LowerIsPatternAsLinearTestSequence(node, whenTrueLabel: node.WhenTrueLabel, whenFalseLabel: node.WhenFalseLabel); isPatternRewriter.Free(); } else if (canProduceLinearSequence(node.DecisionDag.RootNode, whenTrueLabel: node.WhenFalseLabel, whenFalseLabel: node.WhenTrueLabel)) { // If we can build a linear test sequence with the whenTrue and whenFalse labels swapped, then negate the // result. This would typically arise when the source contains `e is not pattern`. negated = !negated; var isPatternRewriter = new IsPatternExpressionLinearLocalRewriter(node, this); result = isPatternRewriter.LowerIsPatternAsLinearTestSequence(node, whenTrueLabel: node.WhenFalseLabel, whenFalseLabel: node.WhenTrueLabel); isPatternRewriter.Free(); } else { // We need to lower a generalized dag, so we produce a label for the true and false branches and assign to a temporary containing the result. var isPatternRewriter = new IsPatternExpressionGeneralLocalRewriter(node.Syntax, this); result = isPatternRewriter.LowerGeneralIsPattern(node); isPatternRewriter.Free(); } if (negated) { result = this._factory.Not(result); } return result; // Can the given decision dag node, and its successors, be generated as a sequence of // linear tests with a single "golden" path to the true label and all other paths leading // to the false label? This occurs with an is-pattern expression that uses no "or" or "not" // pattern forms. static bool canProduceLinearSequence( BoundDecisionDagNode node, LabelSymbol whenTrueLabel, LabelSymbol whenFalseLabel) { while (true) { switch (node) { case BoundWhenDecisionDagNode w: Debug.Assert(w.WhenFalse is null); node = w.WhenTrue; break; case BoundLeafDecisionDagNode n: return n.Label == whenTrueLabel; case BoundEvaluationDecisionDagNode e: node = e.Next; break; case BoundTestDecisionDagNode t: bool falseFail = IsFailureNode(t.WhenFalse, whenFalseLabel); if (falseFail == IsFailureNode(t.WhenTrue, whenFalseLabel)) return false; node = falseFail ? t.WhenTrue : t.WhenFalse; break; default: throw ExceptionUtilities.UnexpectedValue(node); } } } } /// <summary> /// A local rewriter for lowering an is-pattern expression. This handles the general case by lowering /// the decision dag, and returning a "true" or "false" value as the result at the end. /// </summary> private sealed class IsPatternExpressionGeneralLocalRewriter : DecisionDagRewriter { private readonly ArrayBuilder<BoundStatement> _statements = ArrayBuilder<BoundStatement>.GetInstance(); public IsPatternExpressionGeneralLocalRewriter( SyntaxNode node, LocalRewriter localRewriter) : base(node, localRewriter, generateInstrumentation: false) { } protected override ArrayBuilder<BoundStatement> BuilderForSection(SyntaxNode section) => _statements; public new void Free() { base.Free(); _statements.Free(); } internal BoundExpression LowerGeneralIsPattern(BoundIsPatternExpression node) { _factory.Syntax = node.Syntax; var resultBuilder = ArrayBuilder<BoundStatement>.GetInstance(); var inputExpression = _localRewriter.VisitExpression(node.Expression); BoundDecisionDag decisionDag = ShareTempsIfPossibleAndEvaluateInput( node.DecisionDag, inputExpression, resultBuilder, out _); // lower the decision dag. ImmutableArray<BoundStatement> loweredDag = LowerDecisionDagCore(decisionDag); resultBuilder.Add(_factory.Block(loweredDag)); Debug.Assert(node.Type is { SpecialType: SpecialType.System_Boolean }); LocalSymbol resultTemp = _factory.SynthesizedLocal(node.Type, node.Syntax, kind: SynthesizedLocalKind.LoweringTemp); LabelSymbol afterIsPatternExpression = _factory.GenerateLabel("afterIsPatternExpression"); LabelSymbol trueLabel = node.WhenTrueLabel; LabelSymbol falseLabel = node.WhenFalseLabel; if (_statements.Count != 0) resultBuilder.Add(_factory.Block(_statements.ToArray())); resultBuilder.Add(_factory.Label(trueLabel)); resultBuilder.Add(_factory.Assignment(_factory.Local(resultTemp), _factory.Literal(true))); resultBuilder.Add(_factory.Goto(afterIsPatternExpression)); resultBuilder.Add(_factory.Label(falseLabel)); resultBuilder.Add(_factory.Assignment(_factory.Local(resultTemp), _factory.Literal(false))); resultBuilder.Add(_factory.Label(afterIsPatternExpression)); _localRewriter._needsSpilling = true; return _factory.SpillSequence(_tempAllocator.AllTemps().Add(resultTemp), resultBuilder.ToImmutableAndFree(), _factory.Local(resultTemp)); } } private static bool IsFailureNode(BoundDecisionDagNode node, LabelSymbol whenFalseLabel) { if (node is BoundWhenDecisionDagNode w) node = w.WhenTrue; return node is BoundLeafDecisionDagNode l && l.Label == whenFalseLabel; } private sealed class IsPatternExpressionLinearLocalRewriter : PatternLocalRewriter { /// <summary> /// Accumulates side-effects that come before the next conjunct. /// </summary> private readonly ArrayBuilder<BoundExpression> _sideEffectBuilder; /// <summary> /// Accumulates conjuncts (conditions that must all be true) for the translation. When a conjunct is added, /// elements of the _sideEffectBuilder, if any, should be added as part of a sequence expression for /// the conjunct being added. /// </summary> private readonly ArrayBuilder<BoundExpression> _conjunctBuilder; public IsPatternExpressionLinearLocalRewriter(BoundIsPatternExpression node, LocalRewriter localRewriter) : base(node.Syntax, localRewriter, generateInstrumentation: false) { _conjunctBuilder = ArrayBuilder<BoundExpression>.GetInstance(); _sideEffectBuilder = ArrayBuilder<BoundExpression>.GetInstance(); } public new void Free() { _conjunctBuilder.Free(); _sideEffectBuilder.Free(); base.Free(); } private void AddConjunct(BoundExpression test) { // When in error recovery, the generated code doesn't matter. if (test.Type?.IsErrorType() != false) return; Debug.Assert(test.Type.SpecialType == SpecialType.System_Boolean); if (_sideEffectBuilder.Count != 0) { test = _factory.Sequence(ImmutableArray<LocalSymbol>.Empty, _sideEffectBuilder.ToImmutable(), test); _sideEffectBuilder.Clear(); } _conjunctBuilder.Add(test); } /// <summary> /// Translate the single test into _sideEffectBuilder and _conjunctBuilder. /// </summary> private void LowerOneTest(BoundDagTest test, bool invert = false) { _factory.Syntax = test.Syntax; switch (test) { case BoundDagEvaluation eval: { var sideEffect = LowerEvaluation(eval); _sideEffectBuilder.Add(sideEffect); return; } case var _: { var testExpression = LowerTest(test); if (testExpression != null) { if (invert) testExpression = _factory.Not(testExpression); AddConjunct(testExpression); } return; } } } public BoundExpression LowerIsPatternAsLinearTestSequence( BoundIsPatternExpression isPatternExpression, LabelSymbol whenTrueLabel, LabelSymbol whenFalseLabel) { BoundDecisionDag decisionDag = isPatternExpression.DecisionDag; BoundExpression loweredInput = _localRewriter.VisitExpression(isPatternExpression.Expression); // The optimization of sharing pattern-matching temps with user variables can always apply to // an is-pattern expression because there is no when clause that could possibly intervene during // the execution of the pattern-matching automaton and change one of those variables. decisionDag = ShareTempsAndEvaluateInput(loweredInput, decisionDag, expr => _sideEffectBuilder.Add(expr), out _); var node = decisionDag.RootNode; return ProduceLinearTestSequence(node, whenTrueLabel, whenFalseLabel); } /// <summary> /// Translate an is-pattern expression into a sequence of tests separated by the control-flow-and operator. /// </summary> private BoundExpression ProduceLinearTestSequence( BoundDecisionDagNode node, LabelSymbol whenTrueLabel, LabelSymbol whenFalseLabel) { // We follow the "good" path in the decision dag. We depend on it being nicely linear in structure. // If we add "or" patterns that assumption breaks down. while (node.Kind != BoundKind.LeafDecisionDagNode && node.Kind != BoundKind.WhenDecisionDagNode) { switch (node) { case BoundEvaluationDecisionDagNode evalNode: { LowerOneTest(evalNode.Evaluation); node = evalNode.Next; } break; case BoundTestDecisionDagNode testNode: { if (testNode.WhenTrue is BoundEvaluationDecisionDagNode e && TryLowerTypeTestAndCast(testNode.Test, e.Evaluation, out BoundExpression? sideEffect, out BoundExpression? testExpression)) { _sideEffectBuilder.Add(sideEffect); AddConjunct(testExpression); node = e.Next; } else { bool invertTest = IsFailureNode(testNode.WhenTrue, whenFalseLabel); LowerOneTest(testNode.Test, invertTest); node = invertTest ? testNode.WhenFalse : testNode.WhenTrue; } } break; } } // When we get to "the end", it is a success node. switch (node) { case BoundLeafDecisionDagNode leafNode: Debug.Assert(leafNode.Label == whenTrueLabel); break; case BoundWhenDecisionDagNode whenNode: { Debug.Assert(whenNode.WhenExpression == null); Debug.Assert(whenNode.WhenTrue is BoundLeafDecisionDagNode d && d.Label == whenTrueLabel); foreach (BoundPatternBinding binding in whenNode.Bindings) { BoundExpression left = _localRewriter.VisitExpression(binding.VariableAccess); BoundExpression right = _tempAllocator.GetTemp(binding.TempContainingValue); if (left != right) { _sideEffectBuilder.Add(_factory.AssignmentExpression(left, right)); } } } break; default: throw ExceptionUtilities.UnexpectedValue(node.Kind); } if (_sideEffectBuilder.Count > 0 || _conjunctBuilder.Count == 0) { AddConjunct(_factory.Literal(true)); } Debug.Assert(_sideEffectBuilder.Count == 0); BoundExpression? result = null; foreach (BoundExpression conjunct in _conjunctBuilder) { result = (result == null) ? conjunct : _factory.LogicalAnd(result, conjunct); } _conjunctBuilder.Clear(); Debug.Assert(result != null); var allTemps = _tempAllocator.AllTemps(); if (allTemps.Length > 0) { result = _factory.Sequence(allTemps, ImmutableArray<BoundExpression>.Empty, result); } return 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. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitIsPatternExpression(BoundIsPatternExpression node) { bool negated = node.IsNegated; BoundExpression result; if (canProduceLinearSequence(node.DecisionDag.RootNode, whenTrueLabel: node.WhenTrueLabel, whenFalseLabel: node.WhenFalseLabel)) { // If we can build a linear test sequence `(e1 && e2 && e3)` for the dag, do so. var isPatternRewriter = new IsPatternExpressionLinearLocalRewriter(node, this); result = isPatternRewriter.LowerIsPatternAsLinearTestSequence(node, whenTrueLabel: node.WhenTrueLabel, whenFalseLabel: node.WhenFalseLabel); isPatternRewriter.Free(); } else if (canProduceLinearSequence(node.DecisionDag.RootNode, whenTrueLabel: node.WhenFalseLabel, whenFalseLabel: node.WhenTrueLabel)) { // If we can build a linear test sequence with the whenTrue and whenFalse labels swapped, then negate the // result. This would typically arise when the source contains `e is not pattern`. negated = !negated; var isPatternRewriter = new IsPatternExpressionLinearLocalRewriter(node, this); result = isPatternRewriter.LowerIsPatternAsLinearTestSequence(node, whenTrueLabel: node.WhenFalseLabel, whenFalseLabel: node.WhenTrueLabel); isPatternRewriter.Free(); } else { // We need to lower a generalized dag, so we produce a label for the true and false branches and assign to a temporary containing the result. var isPatternRewriter = new IsPatternExpressionGeneralLocalRewriter(node.Syntax, this); result = isPatternRewriter.LowerGeneralIsPattern(node); isPatternRewriter.Free(); } if (negated) { result = this._factory.Not(result); } return result; // Can the given decision dag node, and its successors, be generated as a sequence of // linear tests with a single "golden" path to the true label and all other paths leading // to the false label? This occurs with an is-pattern expression that uses no "or" or "not" // pattern forms. static bool canProduceLinearSequence( BoundDecisionDagNode node, LabelSymbol whenTrueLabel, LabelSymbol whenFalseLabel) { while (true) { switch (node) { case BoundWhenDecisionDagNode w: Debug.Assert(w.WhenFalse is null); node = w.WhenTrue; break; case BoundLeafDecisionDagNode n: return n.Label == whenTrueLabel; case BoundEvaluationDecisionDagNode e: node = e.Next; break; case BoundTestDecisionDagNode t: bool falseFail = IsFailureNode(t.WhenFalse, whenFalseLabel); if (falseFail == IsFailureNode(t.WhenTrue, whenFalseLabel)) return false; node = falseFail ? t.WhenTrue : t.WhenFalse; break; default: throw ExceptionUtilities.UnexpectedValue(node); } } } } /// <summary> /// A local rewriter for lowering an is-pattern expression. This handles the general case by lowering /// the decision dag, and returning a "true" or "false" value as the result at the end. /// </summary> private sealed class IsPatternExpressionGeneralLocalRewriter : DecisionDagRewriter { private readonly ArrayBuilder<BoundStatement> _statements = ArrayBuilder<BoundStatement>.GetInstance(); public IsPatternExpressionGeneralLocalRewriter( SyntaxNode node, LocalRewriter localRewriter) : base(node, localRewriter, generateInstrumentation: false) { } protected override ArrayBuilder<BoundStatement> BuilderForSection(SyntaxNode section) => _statements; public new void Free() { base.Free(); _statements.Free(); } internal BoundExpression LowerGeneralIsPattern(BoundIsPatternExpression node) { _factory.Syntax = node.Syntax; var resultBuilder = ArrayBuilder<BoundStatement>.GetInstance(); var inputExpression = _localRewriter.VisitExpression(node.Expression); BoundDecisionDag decisionDag = ShareTempsIfPossibleAndEvaluateInput( node.DecisionDag, inputExpression, resultBuilder, out _); // lower the decision dag. ImmutableArray<BoundStatement> loweredDag = LowerDecisionDagCore(decisionDag); resultBuilder.Add(_factory.Block(loweredDag)); Debug.Assert(node.Type is { SpecialType: SpecialType.System_Boolean }); LocalSymbol resultTemp = _factory.SynthesizedLocal(node.Type, node.Syntax, kind: SynthesizedLocalKind.LoweringTemp); LabelSymbol afterIsPatternExpression = _factory.GenerateLabel("afterIsPatternExpression"); LabelSymbol trueLabel = node.WhenTrueLabel; LabelSymbol falseLabel = node.WhenFalseLabel; if (_statements.Count != 0) resultBuilder.Add(_factory.Block(_statements.ToArray())); resultBuilder.Add(_factory.Label(trueLabel)); resultBuilder.Add(_factory.Assignment(_factory.Local(resultTemp), _factory.Literal(true))); resultBuilder.Add(_factory.Goto(afterIsPatternExpression)); resultBuilder.Add(_factory.Label(falseLabel)); resultBuilder.Add(_factory.Assignment(_factory.Local(resultTemp), _factory.Literal(false))); resultBuilder.Add(_factory.Label(afterIsPatternExpression)); _localRewriter._needsSpilling = true; return _factory.SpillSequence(_tempAllocator.AllTemps().Add(resultTemp), resultBuilder.ToImmutableAndFree(), _factory.Local(resultTemp)); } } private static bool IsFailureNode(BoundDecisionDagNode node, LabelSymbol whenFalseLabel) { if (node is BoundWhenDecisionDagNode w) node = w.WhenTrue; return node is BoundLeafDecisionDagNode l && l.Label == whenFalseLabel; } private sealed class IsPatternExpressionLinearLocalRewriter : PatternLocalRewriter { /// <summary> /// Accumulates side-effects that come before the next conjunct. /// </summary> private readonly ArrayBuilder<BoundExpression> _sideEffectBuilder; /// <summary> /// Accumulates conjuncts (conditions that must all be true) for the translation. When a conjunct is added, /// elements of the _sideEffectBuilder, if any, should be added as part of a sequence expression for /// the conjunct being added. /// </summary> private readonly ArrayBuilder<BoundExpression> _conjunctBuilder; public IsPatternExpressionLinearLocalRewriter(BoundIsPatternExpression node, LocalRewriter localRewriter) : base(node.Syntax, localRewriter, generateInstrumentation: false) { _conjunctBuilder = ArrayBuilder<BoundExpression>.GetInstance(); _sideEffectBuilder = ArrayBuilder<BoundExpression>.GetInstance(); } public new void Free() { _conjunctBuilder.Free(); _sideEffectBuilder.Free(); base.Free(); } private void AddConjunct(BoundExpression test) { // When in error recovery, the generated code doesn't matter. if (test.Type?.IsErrorType() != false) return; Debug.Assert(test.Type.SpecialType == SpecialType.System_Boolean); if (_sideEffectBuilder.Count != 0) { test = _factory.Sequence(ImmutableArray<LocalSymbol>.Empty, _sideEffectBuilder.ToImmutable(), test); _sideEffectBuilder.Clear(); } _conjunctBuilder.Add(test); } /// <summary> /// Translate the single test into _sideEffectBuilder and _conjunctBuilder. /// </summary> private void LowerOneTest(BoundDagTest test, bool invert = false) { _factory.Syntax = test.Syntax; switch (test) { case BoundDagEvaluation eval: { var sideEffect = LowerEvaluation(eval); _sideEffectBuilder.Add(sideEffect); return; } case var _: { var testExpression = LowerTest(test); if (testExpression != null) { if (invert) testExpression = _factory.Not(testExpression); AddConjunct(testExpression); } return; } } } public BoundExpression LowerIsPatternAsLinearTestSequence( BoundIsPatternExpression isPatternExpression, LabelSymbol whenTrueLabel, LabelSymbol whenFalseLabel) { BoundDecisionDag decisionDag = isPatternExpression.DecisionDag; BoundExpression loweredInput = _localRewriter.VisitExpression(isPatternExpression.Expression); // The optimization of sharing pattern-matching temps with user variables can always apply to // an is-pattern expression because there is no when clause that could possibly intervene during // the execution of the pattern-matching automaton and change one of those variables. decisionDag = ShareTempsAndEvaluateInput(loweredInput, decisionDag, expr => _sideEffectBuilder.Add(expr), out _); var node = decisionDag.RootNode; return ProduceLinearTestSequence(node, whenTrueLabel, whenFalseLabel); } /// <summary> /// Translate an is-pattern expression into a sequence of tests separated by the control-flow-and operator. /// </summary> private BoundExpression ProduceLinearTestSequence( BoundDecisionDagNode node, LabelSymbol whenTrueLabel, LabelSymbol whenFalseLabel) { // We follow the "good" path in the decision dag. We depend on it being nicely linear in structure. // If we add "or" patterns that assumption breaks down. while (node.Kind != BoundKind.LeafDecisionDagNode && node.Kind != BoundKind.WhenDecisionDagNode) { switch (node) { case BoundEvaluationDecisionDagNode evalNode: { LowerOneTest(evalNode.Evaluation); node = evalNode.Next; } break; case BoundTestDecisionDagNode testNode: { if (testNode.WhenTrue is BoundEvaluationDecisionDagNode e && TryLowerTypeTestAndCast(testNode.Test, e.Evaluation, out BoundExpression? sideEffect, out BoundExpression? testExpression)) { _sideEffectBuilder.Add(sideEffect); AddConjunct(testExpression); node = e.Next; } else { bool invertTest = IsFailureNode(testNode.WhenTrue, whenFalseLabel); LowerOneTest(testNode.Test, invertTest); node = invertTest ? testNode.WhenFalse : testNode.WhenTrue; } } break; } } // When we get to "the end", it is a success node. switch (node) { case BoundLeafDecisionDagNode leafNode: Debug.Assert(leafNode.Label == whenTrueLabel); break; case BoundWhenDecisionDagNode whenNode: { Debug.Assert(whenNode.WhenExpression == null); Debug.Assert(whenNode.WhenTrue is BoundLeafDecisionDagNode d && d.Label == whenTrueLabel); foreach (BoundPatternBinding binding in whenNode.Bindings) { BoundExpression left = _localRewriter.VisitExpression(binding.VariableAccess); BoundExpression right = _tempAllocator.GetTemp(binding.TempContainingValue); if (left != right) { _sideEffectBuilder.Add(_factory.AssignmentExpression(left, right)); } } } break; default: throw ExceptionUtilities.UnexpectedValue(node.Kind); } if (_sideEffectBuilder.Count > 0 || _conjunctBuilder.Count == 0) { AddConjunct(_factory.Literal(true)); } Debug.Assert(_sideEffectBuilder.Count == 0); BoundExpression? result = null; foreach (BoundExpression conjunct in _conjunctBuilder) { result = (result == null) ? conjunct : _factory.LogicalAnd(result, conjunct); } _conjunctBuilder.Clear(); Debug.Assert(result != null); var allTemps = _tempAllocator.AllTemps(); if (allTemps.Length > 0) { result = _factory.Sequence(allTemps, ImmutableArray<BoundExpression>.Empty, result); } return result; } } } }
-1
dotnet/roslyn
55,898
Include edit session runtime capabilities in telemetry data
tmat
2021-08-25T21:41:02Z
2021-08-26T20:00:14Z
52b1b5784bf719114d698ed5fa4f82d6da30059f
dd121d37f386e689310de5dc039c08406d4dd0b2
Include edit session runtime capabilities in telemetry data.
./src/Compilers/CSharp/Portable/Symbols/TypeUnification.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.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal static class TypeUnification { /// <summary> /// Determine whether there is any substitution of type parameters that will /// make two types identical. /// </summary> public static bool CanUnify(TypeSymbol t1, TypeSymbol t2) { if (TypeSymbol.Equals(t1, t2, TypeCompareKind.CLRSignatureCompareOptions)) { return true; } MutableTypeMap? substitution = null; bool result = CanUnifyHelper(t1, t2, ref substitution); #if DEBUG if (result && ((object)t1 != null && (object)t2 != null)) { var substituted1 = SubstituteAllTypeParameters(substitution, TypeWithAnnotations.Create(t1)); var substituted2 = SubstituteAllTypeParameters(substitution, TypeWithAnnotations.Create(t2)); Debug.Assert(substituted1.Type.Equals(substituted2.Type, TypeCompareKind.CLRSignatureCompareOptions)); Debug.Assert(substituted1.CustomModifiers.SequenceEqual(substituted2.CustomModifiers)); } #endif return result; } #if DEBUG private static TypeWithAnnotations SubstituteAllTypeParameters(AbstractTypeMap? substitution, TypeWithAnnotations type) { if (substitution != null) { TypeWithAnnotations previous; do { previous = type; type = type.SubstituteType(substitution); } while (!type.IsSameAs(previous)); } return type; } #endif private static bool CanUnifyHelper(TypeSymbol t1, TypeSymbol t2, ref MutableTypeMap? substitution) { return CanUnifyHelper(TypeWithAnnotations.Create(t1), TypeWithAnnotations.Create(t2), ref substitution); } /// <summary> /// Determine whether there is any substitution of type parameters that will /// make two types identical. /// </summary> /// <param name="t1">LHS</param> /// <param name="t2">RHS</param> /// <param name="substitution"> /// Substitutions performed so far (or null for none). /// Keys are type parameters, values are types (possibly type parameters). /// Will be updated with new substitutions by the callee. /// Should be ignored when false is returned. /// </param> /// <returns>True if there exists a type map such that Map(LHS) == Map(RHS).</returns> /// <remarks> /// Derived from Dev10's BSYMMGR::UnifyTypes. /// Two types will not unify if they have different custom modifiers. /// </remarks> private static bool CanUnifyHelper(TypeWithAnnotations t1, TypeWithAnnotations t2, ref MutableTypeMap? substitution) { if (!t1.HasType || !t2.HasType) { return t1.IsSameAs(t2); } if (substitution != null) { t1 = t1.SubstituteType(substitution); t2 = t2.SubstituteType(substitution); } if (TypeSymbol.Equals(t1.Type, t2.Type, TypeCompareKind.CLRSignatureCompareOptions) && t1.CustomModifiers.SequenceEqual(t2.CustomModifiers)) { return true; } // We can avoid a lot of redundant checks if we ensure that we only have to check // for type parameters on the LHS if (!t1.Type.IsTypeParameter() && t2.Type.IsTypeParameter()) { TypeWithAnnotations tmp = t1; t1 = t2; t2 = tmp; } // If t1 is not a type parameter, then neither is t2 Debug.Assert(t1.Type.IsTypeParameter() || !t2.Type.IsTypeParameter()); switch (t1.Type.Kind) { case SymbolKind.ArrayType: { if (t2.TypeKind != t1.TypeKind || !t2.CustomModifiers.SequenceEqual(t1.CustomModifiers)) { return false; } ArrayTypeSymbol at1 = (ArrayTypeSymbol)t1.Type; ArrayTypeSymbol at2 = (ArrayTypeSymbol)t2.Type; if (!at1.HasSameShapeAs(at2)) { return false; } return CanUnifyHelper(at1.ElementTypeWithAnnotations, at2.ElementTypeWithAnnotations, ref substitution); } case SymbolKind.PointerType: { if (t2.TypeKind != t1.TypeKind || !t2.CustomModifiers.SequenceEqual(t1.CustomModifiers)) { return false; } PointerTypeSymbol pt1 = (PointerTypeSymbol)t1.Type; PointerTypeSymbol pt2 = (PointerTypeSymbol)t2.Type; return CanUnifyHelper(pt1.PointedAtTypeWithAnnotations, pt2.PointedAtTypeWithAnnotations, ref substitution); } case SymbolKind.NamedType: case SymbolKind.ErrorType: { if (t2.TypeKind != t1.TypeKind || !t2.CustomModifiers.SequenceEqual(t1.CustomModifiers)) { return false; } NamedTypeSymbol nt1 = (NamedTypeSymbol)t1.Type; NamedTypeSymbol nt2 = (NamedTypeSymbol)t2.Type; if (!nt1.IsGenericType || !nt2.IsGenericType) { // Initial TypeSymbol.Equals(...) && CustomModifiers.SequenceEqual(...) failed above, // and custom modifiers compared equal in this case block, so the types must be distinct. Debug.Assert(!nt1.Equals(nt2, TypeCompareKind.CLRSignatureCompareOptions)); return false; } int arity = nt1.Arity; if (nt2.Arity != arity || !TypeSymbol.Equals(nt2.OriginalDefinition, nt1.OriginalDefinition, TypeCompareKind.ConsiderEverything)) { return false; } var nt1Arguments = nt1.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; var nt2Arguments = nt2.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; for (int i = 0; i < arity; i++) { if (!CanUnifyHelper(nt1Arguments[i], nt2Arguments[i], ref substitution)) { return false; } } // Note: Dev10 folds this into the loop since GetTypeArgsAll includes type args for containing types // TODO: Calling CanUnifyHelper for the containing type is an overkill, we simply need to go through type arguments for all containers. return (object)nt1.ContainingType == null || CanUnifyHelper(nt1.ContainingType, nt2.ContainingType, ref substitution); } case SymbolKind.TypeParameter: { // These substitutions are not allowed in C# if (t2.Type.IsPointerOrFunctionPointer() || t2.IsVoidType()) { return false; } TypeParameterSymbol tp1 = (TypeParameterSymbol)t1.Type; // Perform the "occurs check" - i.e. ensure that t2 doesn't contain t1 to avoid recursive types // Note: t2 can't be the same type param - we would have caught that with ReferenceEquals above if (Contains(t2.Type, tp1)) { return false; } if (t1.CustomModifiers.IsDefaultOrEmpty) { AddSubstitution(ref substitution, tp1, t2); return true; } if (t1.CustomModifiers.SequenceEqual(t2.CustomModifiers)) { AddSubstitution(ref substitution, tp1, TypeWithAnnotations.Create(t2.Type)); return true; } if (t1.CustomModifiers.Length < t2.CustomModifiers.Length && t1.CustomModifiers.SequenceEqual(t2.CustomModifiers.Take(t1.CustomModifiers.Length))) { AddSubstitution(ref substitution, tp1, TypeWithAnnotations.Create(t2.Type, customModifiers: ImmutableArray.Create(t2.CustomModifiers, t1.CustomModifiers.Length, t2.CustomModifiers.Length - t1.CustomModifiers.Length))); return true; } if (t2.Type.IsTypeParameter()) { var tp2 = (TypeParameterSymbol)t2.Type; if (t2.CustomModifiers.IsDefaultOrEmpty) { AddSubstitution(ref substitution, tp2, t1); return true; } if (t2.CustomModifiers.Length < t1.CustomModifiers.Length && t2.CustomModifiers.SequenceEqual(t1.CustomModifiers.Take(t2.CustomModifiers.Length))) { AddSubstitution(ref substitution, tp2, TypeWithAnnotations.Create(t1.Type, customModifiers: ImmutableArray.Create(t1.CustomModifiers, t2.CustomModifiers.Length, t1.CustomModifiers.Length - t2.CustomModifiers.Length))); return true; } } return false; } default: { return false; } } } private static void AddSubstitution(ref MutableTypeMap? substitution, TypeParameterSymbol tp1, TypeWithAnnotations t2) { if (substitution == null) { substitution = new MutableTypeMap(); } // MutableTypeMap.Add will throw if the key has already been added. However, // if t1 was already in the substitution, it would have been substituted at the // start of CanUnifyHelper and we wouldn't be here. substitution.Add(tp1, t2); } /// <summary> /// Return true if the given type contains the specified type parameter. /// </summary> private static bool Contains(TypeSymbol type, TypeParameterSymbol typeParam) { switch (type.Kind) { case SymbolKind.ArrayType: return Contains(((ArrayTypeSymbol)type).ElementType, typeParam); case SymbolKind.PointerType: return Contains(((PointerTypeSymbol)type).PointedAtType, typeParam); case SymbolKind.NamedType: case SymbolKind.ErrorType: { NamedTypeSymbol namedType = (NamedTypeSymbol)type; while ((object)namedType != null) { var typeParts = namedType.IsTupleType ? namedType.TupleElementTypesWithAnnotations : namedType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; foreach (TypeWithAnnotations typePart in typeParts) { if (Contains(typePart.Type, typeParam)) { return true; } } namedType = namedType.ContainingType; } return false; } case SymbolKind.TypeParameter: return TypeSymbol.Equals(type, typeParam, TypeCompareKind.ConsiderEverything); default: return false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal static class TypeUnification { /// <summary> /// Determine whether there is any substitution of type parameters that will /// make two types identical. /// </summary> public static bool CanUnify(TypeSymbol t1, TypeSymbol t2) { if (TypeSymbol.Equals(t1, t2, TypeCompareKind.CLRSignatureCompareOptions)) { return true; } MutableTypeMap? substitution = null; bool result = CanUnifyHelper(t1, t2, ref substitution); #if DEBUG if (result && ((object)t1 != null && (object)t2 != null)) { var substituted1 = SubstituteAllTypeParameters(substitution, TypeWithAnnotations.Create(t1)); var substituted2 = SubstituteAllTypeParameters(substitution, TypeWithAnnotations.Create(t2)); Debug.Assert(substituted1.Type.Equals(substituted2.Type, TypeCompareKind.CLRSignatureCompareOptions)); Debug.Assert(substituted1.CustomModifiers.SequenceEqual(substituted2.CustomModifiers)); } #endif return result; } #if DEBUG private static TypeWithAnnotations SubstituteAllTypeParameters(AbstractTypeMap? substitution, TypeWithAnnotations type) { if (substitution != null) { TypeWithAnnotations previous; do { previous = type; type = type.SubstituteType(substitution); } while (!type.IsSameAs(previous)); } return type; } #endif private static bool CanUnifyHelper(TypeSymbol t1, TypeSymbol t2, ref MutableTypeMap? substitution) { return CanUnifyHelper(TypeWithAnnotations.Create(t1), TypeWithAnnotations.Create(t2), ref substitution); } /// <summary> /// Determine whether there is any substitution of type parameters that will /// make two types identical. /// </summary> /// <param name="t1">LHS</param> /// <param name="t2">RHS</param> /// <param name="substitution"> /// Substitutions performed so far (or null for none). /// Keys are type parameters, values are types (possibly type parameters). /// Will be updated with new substitutions by the callee. /// Should be ignored when false is returned. /// </param> /// <returns>True if there exists a type map such that Map(LHS) == Map(RHS).</returns> /// <remarks> /// Derived from Dev10's BSYMMGR::UnifyTypes. /// Two types will not unify if they have different custom modifiers. /// </remarks> private static bool CanUnifyHelper(TypeWithAnnotations t1, TypeWithAnnotations t2, ref MutableTypeMap? substitution) { if (!t1.HasType || !t2.HasType) { return t1.IsSameAs(t2); } if (substitution != null) { t1 = t1.SubstituteType(substitution); t2 = t2.SubstituteType(substitution); } if (TypeSymbol.Equals(t1.Type, t2.Type, TypeCompareKind.CLRSignatureCompareOptions) && t1.CustomModifiers.SequenceEqual(t2.CustomModifiers)) { return true; } // We can avoid a lot of redundant checks if we ensure that we only have to check // for type parameters on the LHS if (!t1.Type.IsTypeParameter() && t2.Type.IsTypeParameter()) { TypeWithAnnotations tmp = t1; t1 = t2; t2 = tmp; } // If t1 is not a type parameter, then neither is t2 Debug.Assert(t1.Type.IsTypeParameter() || !t2.Type.IsTypeParameter()); switch (t1.Type.Kind) { case SymbolKind.ArrayType: { if (t2.TypeKind != t1.TypeKind || !t2.CustomModifiers.SequenceEqual(t1.CustomModifiers)) { return false; } ArrayTypeSymbol at1 = (ArrayTypeSymbol)t1.Type; ArrayTypeSymbol at2 = (ArrayTypeSymbol)t2.Type; if (!at1.HasSameShapeAs(at2)) { return false; } return CanUnifyHelper(at1.ElementTypeWithAnnotations, at2.ElementTypeWithAnnotations, ref substitution); } case SymbolKind.PointerType: { if (t2.TypeKind != t1.TypeKind || !t2.CustomModifiers.SequenceEqual(t1.CustomModifiers)) { return false; } PointerTypeSymbol pt1 = (PointerTypeSymbol)t1.Type; PointerTypeSymbol pt2 = (PointerTypeSymbol)t2.Type; return CanUnifyHelper(pt1.PointedAtTypeWithAnnotations, pt2.PointedAtTypeWithAnnotations, ref substitution); } case SymbolKind.NamedType: case SymbolKind.ErrorType: { if (t2.TypeKind != t1.TypeKind || !t2.CustomModifiers.SequenceEqual(t1.CustomModifiers)) { return false; } NamedTypeSymbol nt1 = (NamedTypeSymbol)t1.Type; NamedTypeSymbol nt2 = (NamedTypeSymbol)t2.Type; if (!nt1.IsGenericType || !nt2.IsGenericType) { // Initial TypeSymbol.Equals(...) && CustomModifiers.SequenceEqual(...) failed above, // and custom modifiers compared equal in this case block, so the types must be distinct. Debug.Assert(!nt1.Equals(nt2, TypeCompareKind.CLRSignatureCompareOptions)); return false; } int arity = nt1.Arity; if (nt2.Arity != arity || !TypeSymbol.Equals(nt2.OriginalDefinition, nt1.OriginalDefinition, TypeCompareKind.ConsiderEverything)) { return false; } var nt1Arguments = nt1.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; var nt2Arguments = nt2.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; for (int i = 0; i < arity; i++) { if (!CanUnifyHelper(nt1Arguments[i], nt2Arguments[i], ref substitution)) { return false; } } // Note: Dev10 folds this into the loop since GetTypeArgsAll includes type args for containing types // TODO: Calling CanUnifyHelper for the containing type is an overkill, we simply need to go through type arguments for all containers. return (object)nt1.ContainingType == null || CanUnifyHelper(nt1.ContainingType, nt2.ContainingType, ref substitution); } case SymbolKind.TypeParameter: { // These substitutions are not allowed in C# if (t2.Type.IsPointerOrFunctionPointer() || t2.IsVoidType()) { return false; } TypeParameterSymbol tp1 = (TypeParameterSymbol)t1.Type; // Perform the "occurs check" - i.e. ensure that t2 doesn't contain t1 to avoid recursive types // Note: t2 can't be the same type param - we would have caught that with ReferenceEquals above if (Contains(t2.Type, tp1)) { return false; } if (t1.CustomModifiers.IsDefaultOrEmpty) { AddSubstitution(ref substitution, tp1, t2); return true; } if (t1.CustomModifiers.SequenceEqual(t2.CustomModifiers)) { AddSubstitution(ref substitution, tp1, TypeWithAnnotations.Create(t2.Type)); return true; } if (t1.CustomModifiers.Length < t2.CustomModifiers.Length && t1.CustomModifiers.SequenceEqual(t2.CustomModifiers.Take(t1.CustomModifiers.Length))) { AddSubstitution(ref substitution, tp1, TypeWithAnnotations.Create(t2.Type, customModifiers: ImmutableArray.Create(t2.CustomModifiers, t1.CustomModifiers.Length, t2.CustomModifiers.Length - t1.CustomModifiers.Length))); return true; } if (t2.Type.IsTypeParameter()) { var tp2 = (TypeParameterSymbol)t2.Type; if (t2.CustomModifiers.IsDefaultOrEmpty) { AddSubstitution(ref substitution, tp2, t1); return true; } if (t2.CustomModifiers.Length < t1.CustomModifiers.Length && t2.CustomModifiers.SequenceEqual(t1.CustomModifiers.Take(t2.CustomModifiers.Length))) { AddSubstitution(ref substitution, tp2, TypeWithAnnotations.Create(t1.Type, customModifiers: ImmutableArray.Create(t1.CustomModifiers, t2.CustomModifiers.Length, t1.CustomModifiers.Length - t2.CustomModifiers.Length))); return true; } } return false; } default: { return false; } } } private static void AddSubstitution(ref MutableTypeMap? substitution, TypeParameterSymbol tp1, TypeWithAnnotations t2) { if (substitution == null) { substitution = new MutableTypeMap(); } // MutableTypeMap.Add will throw if the key has already been added. However, // if t1 was already in the substitution, it would have been substituted at the // start of CanUnifyHelper and we wouldn't be here. substitution.Add(tp1, t2); } /// <summary> /// Return true if the given type contains the specified type parameter. /// </summary> private static bool Contains(TypeSymbol type, TypeParameterSymbol typeParam) { switch (type.Kind) { case SymbolKind.ArrayType: return Contains(((ArrayTypeSymbol)type).ElementType, typeParam); case SymbolKind.PointerType: return Contains(((PointerTypeSymbol)type).PointedAtType, typeParam); case SymbolKind.NamedType: case SymbolKind.ErrorType: { NamedTypeSymbol namedType = (NamedTypeSymbol)type; while ((object)namedType != null) { var typeParts = namedType.IsTupleType ? namedType.TupleElementTypesWithAnnotations : namedType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; foreach (TypeWithAnnotations typePart in typeParts) { if (Contains(typePart.Type, typeParam)) { return true; } } namedType = namedType.ContainingType; } return false; } case SymbolKind.TypeParameter: return TypeSymbol.Equals(type, typeParam, TypeCompareKind.ConsiderEverything); default: return false; } } } }
-1
dotnet/roslyn
55,898
Include edit session runtime capabilities in telemetry data
tmat
2021-08-25T21:41:02Z
2021-08-26T20:00:14Z
52b1b5784bf719114d698ed5fa4f82d6da30059f
dd121d37f386e689310de5dc039c08406d4dd0b2
Include edit session runtime capabilities in telemetry data.
./src/VisualStudio/Xaml/Impl/Features/QuickInfo/IXamlQuickInfoService.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; using Microsoft.CodeAnalysis.Host; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.QuickInfo { internal interface IXamlQuickInfoService : ILanguageService { Task<XamlQuickInfo> GetQuickInfoAsync(TextDocument document, int position, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.QuickInfo { internal interface IXamlQuickInfoService : ILanguageService { Task<XamlQuickInfo> GetQuickInfoAsync(TextDocument document, int position, CancellationToken cancellationToken); } }
-1