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,408 | Update package references | CyrusNajmabadi | 2021-08-04T19:12:45Z | 2021-08-04T22:34:08Z | 967cf7cf7be8478cce7cda728217eab8504f2863 | d41ae79bb1a3f0deb2de2f3d67c976f795da9563 | Update package references. | ./src/VisualStudio/CSharp/Impl/ProjectSystemShim/CSharpProjectShim.IVsEditorFactoryNotify.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim
{
// The native project system requires that project sites implement IVsEditorFactoryNotify, and
// the project system stores an internal list of the interface pointers to them. The old editor
// factory would then call each implementation from it's own IVsEditorFactoryNotify methods.
// Since we now supply our own editor factory that doesn't do this, these methods will never be
// called. Still, we must implement the interface or we'll never load at all.
internal partial class CSharpProjectShim : IVsEditorFactoryNotify
{
public int NotifyDependentItemSaved(IVsHierarchy hier, uint itemidParent, string documentParentMoniker, uint itemidDpendent, string documentDependentMoniker)
=> throw new NotSupportedException();
public int NotifyItemAdded(uint grfEFN, IVsHierarchy hier, uint itemid, string documentId)
=> throw new NotSupportedException();
public int NotifyItemRenamed(IVsHierarchy hier, uint itemid, string documentOldMoniker, string documentNewMoniker)
=> throw new NotSupportedException();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim
{
// The native project system requires that project sites implement IVsEditorFactoryNotify, and
// the project system stores an internal list of the interface pointers to them. The old editor
// factory would then call each implementation from it's own IVsEditorFactoryNotify methods.
// Since we now supply our own editor factory that doesn't do this, these methods will never be
// called. Still, we must implement the interface or we'll never load at all.
internal partial class CSharpProjectShim : IVsEditorFactoryNotify
{
public int NotifyDependentItemSaved(IVsHierarchy hier, uint itemidParent, string documentParentMoniker, uint itemidDpendent, string documentDependentMoniker)
=> throw new NotSupportedException();
public int NotifyItemAdded(uint grfEFN, IVsHierarchy hier, uint itemid, string documentId)
=> throw new NotSupportedException();
public int NotifyItemRenamed(IVsHierarchy hier, uint itemid, string documentOldMoniker, string documentNewMoniker)
=> throw new NotSupportedException();
}
}
| -1 |
|
dotnet/roslyn | 55,408 | Update package references | CyrusNajmabadi | 2021-08-04T19:12:45Z | 2021-08-04T22:34:08Z | 967cf7cf7be8478cce7cda728217eab8504f2863 | d41ae79bb1a3f0deb2de2f3d67c976f795da9563 | Update package references. | ./src/EditorFeatures/Test2/FindReferences/FindReferencesTests.TypeParameterTypeSymbol.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.FindReferences
Partial Public Class FindReferencesTests
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestTypeParameter1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class C<{|Definition:$$T|}>
{
void Goo([|T|] t)
{
}
void Goo2(t t1)
{
}
}]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(23699, "https://github.com/dotnet/roslyn/issues/23699")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_LocalFunctionTypeParameter(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class C
{
void M()
{
void local<{|Definition:TPar$$am|}>([|TParam|] parameter)
{
}
}
}
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(23699, "https://github.com/dotnet/roslyn/issues/23699")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_LocalFunctionTypeParameter2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class C
{
void M()
{
void local<{|Definition:TParam|}>([|TPa$$ram|] parameter)
{
}
}
}
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(23699, "https://github.com/dotnet/roslyn/issues/23699")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_LocalFunctionTypeParameter3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class C
{
void M<{|Definition:TParam|}>()
{
void local([|TPa$$ram|] parameter)
{
}
}
}
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(23699, "https://github.com/dotnet/roslyn/issues/23699")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_LocalFunctionTypeParameter4(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class C
{
void M<{|Definition:TPa$$ram|}>()
{
void local([|TParam|] parameter)
{
}
}
}
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestTypeParameter2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
partial class C<{|Definition:$$T|}>
{
void Goo([|T|] t)
{
}
void Goo2(t t1)
{
}
}]]></Document>
<Document><![CDATA[
partial class C<{|Definition:T|}>
{
void Goo2([|T|] t)
{
}
}]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestTypeParameter3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
partial class C<{|Definition:$$T|}>
{
void Goo(X<[|T|]> t)
{
}
}
class D<T>
{
C<T> c;
}]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestGenericTypeArgsWithStaticCalls(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class {|Definition:G$$oo|} { void M() { Bar<[|Goo|]>.StaticDoSomething(); } }
class Bar<T> { public static void StaticDoSomething() { } }]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestTypeParameterCaseSensitivity(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
partial class C(of {|Definition:$$T|})
sub Goo(x as [|T|])
end sub
sub Goo1(x as [|t|])
end sub
end class</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(542598, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542598")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestMethodTypeParameterExplicitImplementation1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
interface I
{
T Goo<T>();
}
class A : I
{
[|$$T|] I.Goo<{|Definition:T|}>() { return default([|T|]); }
}
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(542598, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542598")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestMethodTypeParameterExplicitImplementation2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
interface I
{
T Goo<T>();
}
class A : I
{
[|T|] I.Goo<{|Definition:$$T|}>() { return default([|T|]); }
}
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(542598, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542598")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestMethodTypeParameterExplicitImplementation3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
interface I
{
T Goo<T>();
}
class A : I
{
[|T|] I.Goo<{|Definition:T|}>() { return default([|$$T|]); }
}
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Remote.Testing
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences
Partial Public Class FindReferencesTests
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestTypeParameter1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class C<{|Definition:$$T|}>
{
void Goo([|T|] t)
{
}
void Goo2(t t1)
{
}
}]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(23699, "https://github.com/dotnet/roslyn/issues/23699")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_LocalFunctionTypeParameter(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class C
{
void M()
{
void local<{|Definition:TPar$$am|}>([|TParam|] parameter)
{
}
}
}
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(23699, "https://github.com/dotnet/roslyn/issues/23699")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_LocalFunctionTypeParameter2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class C
{
void M()
{
void local<{|Definition:TParam|}>([|TPa$$ram|] parameter)
{
}
}
}
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(23699, "https://github.com/dotnet/roslyn/issues/23699")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_LocalFunctionTypeParameter3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class C
{
void M<{|Definition:TParam|}>()
{
void local([|TPa$$ram|] parameter)
{
}
}
}
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(23699, "https://github.com/dotnet/roslyn/issues/23699")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestCSharp_LocalFunctionTypeParameter4(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class C
{
void M<{|Definition:TPa$$ram|}>()
{
void local([|TParam|] parameter)
{
}
}
}
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestTypeParameter2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
partial class C<{|Definition:$$T|}>
{
void Goo([|T|] t)
{
}
void Goo2(t t1)
{
}
}]]></Document>
<Document><![CDATA[
partial class C<{|Definition:T|}>
{
void Goo2([|T|] t)
{
}
}]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestTypeParameter3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
partial class C<{|Definition:$$T|}>
{
void Goo(X<[|T|]> t)
{
}
}
class D<T>
{
C<T> c;
}]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestGenericTypeArgsWithStaticCalls(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class {|Definition:G$$oo|} { void M() { Bar<[|Goo|]>.StaticDoSomething(); } }
class Bar<T> { public static void StaticDoSomething() { } }]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestTypeParameterCaseSensitivity(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
partial class C(of {|Definition:$$T|})
sub Goo(x as [|T|])
end sub
sub Goo1(x as [|t|])
end sub
end class</Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(542598, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542598")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestMethodTypeParameterExplicitImplementation1(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
interface I
{
T Goo<T>();
}
class A : I
{
[|$$T|] I.Goo<{|Definition:T|}>() { return default([|T|]); }
}
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(542598, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542598")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestMethodTypeParameterExplicitImplementation2(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
interface I
{
T Goo<T>();
}
class A : I
{
[|T|] I.Goo<{|Definition:$$T|}>() { return default([|T|]); }
}
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
<WorkItem(542598, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542598")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)>
Public Async Function TestMethodTypeParameterExplicitImplementation3(kind As TestKind, host As TestHost) As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
interface I
{
T Goo<T>();
}
class A : I
{
[|T|] I.Goo<{|Definition:T|}>() { return default([|$$T|]); }
}
]]></Document>
</Project>
</Workspace>
Await TestAPIAndFeature(input, kind, host)
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,408 | Update package references | CyrusNajmabadi | 2021-08-04T19:12:45Z | 2021-08-04T22:34:08Z | 967cf7cf7be8478cce7cda728217eab8504f2863 | d41ae79bb1a3f0deb2de2f3d67c976f795da9563 | Update package references. | ./src/Compilers/CSharp/Test/Symbol/Symbols/Retargeting/RetargetExplicitInterfaceImplementation.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using static Roslyn.Test.Utilities.TestMetadata;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class RetargetExplicitInterfaceImplementation : CSharpTestBase
{
[Fact]
public void ExplicitInterfaceImplementationRetargeting()
{
var comp1 = CreateCompilation(
new AssemblyIdentity("Assembly1"),
new string[]
{ @"
public class C : Interface1
{
void Interface1.Method1() { }
void Interface1.Method2() { }
void Interface1.Method3(bool b) { }
void Interface1.Method4(Class1 c) { }
string Interface1.Property1 { get; set; }
string Interface1.Property2 { get; set; }
string Interface1.Property3 { get; set; }
Class1 Interface1.Property4 { get; set; }
string Interface1.this[string x] { get { return null; } set { } }
string Interface1.this[string x, string y] { get { return null; } set { } }
string Interface1.this[string x, string y, string z] { get { return null; } set { } }
Class1 Interface1.this[Class1 x, Class1 y, Class1 z, Class1 w] { get { return null; } set { } }
event System.Action Interface1.Event1 { add { } remove { } }
event System.Action Interface1.Event2 { add { } remove { } }
event System.Action Interface1.Event3 { add { } remove { } }
event Delegate1 Interface1.Event4 { add { } remove { } }
}
"
},
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.V1.MTTestLib1.dll,
});
comp1.VerifyDiagnostics();
var globalNamespace1 = comp1.GlobalNamespace;
var classC = globalNamespace1.GetTypeMembers("C").Single();
var interfaceV1 = globalNamespace1.GetTypeMembers("Interface1").Single();
var interfaceV1Method1 = (MethodSymbol)interfaceV1.GetMembers("Method1").Single();
var interfaceV1Method2 = (MethodSymbol)interfaceV1.GetMembers("Method2").Single();
var interfaceV1Method3 = (MethodSymbol)interfaceV1.GetMembers("Method3").Single();
var interfaceV1Method4 = (MethodSymbol)interfaceV1.GetMembers("Method4").Single();
var interfaceV1Property1 = (PropertySymbol)interfaceV1.GetMembers("Property1").Single();
var interfaceV1Property2 = (PropertySymbol)interfaceV1.GetMembers("Property2").Single();
var interfaceV1Property3 = (PropertySymbol)interfaceV1.GetMembers("Property3").Single();
var interfaceV1Property4 = (PropertySymbol)interfaceV1.GetMembers("Property4").Single();
var interfaceV1Indexer1 = FindIndexerWithParameterCount(interfaceV1, 1);
var interfaceV1Indexer2 = FindIndexerWithParameterCount(interfaceV1, 2);
var interfaceV1Indexer3 = FindIndexerWithParameterCount(interfaceV1, 3);
var interfaceV1Indexer4 = FindIndexerWithParameterCount(interfaceV1, 4);
var interfaceV1Event1 = (EventSymbol)interfaceV1.GetMembers("Event1").Single();
var interfaceV1Event2 = (EventSymbol)interfaceV1.GetMembers("Event2").Single();
var interfaceV1Event3 = (EventSymbol)interfaceV1.GetMembers("Event3").Single();
var interfaceV1Event4 = (EventSymbol)interfaceV1.GetMembers("Event4").Single();
foreach (var member in classC.GetMembers())
{
switch (member.Kind)
{
case SymbolKind.Method:
var method = (MethodSymbol)member;
if (method.MethodKind == MethodKind.ExplicitInterfaceImplementation)
{
Assert.Equal(interfaceV1, method.ExplicitInterfaceImplementations.Single().ContainingType);
}
break;
case SymbolKind.Property:
Assert.Equal(interfaceV1, ((PropertySymbol)member).ExplicitInterfaceImplementations.Single().ContainingType);
break;
case SymbolKind.Event:
Assert.Equal(interfaceV1, ((EventSymbol)member).ExplicitInterfaceImplementations.Single().ContainingType);
break;
case SymbolKind.ErrorType:
Assert.True(false);
break;
}
}
var comp2 = CreateCompilation(
new AssemblyIdentity("Assembly2"),
new string[]
{@"
public class D : C
{
}
"
},
new MetadataReference[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.V2.MTTestLib1.dll,
new CSharpCompilationReference(comp1)
});
Assert.False(comp2.GetDiagnostics().Any());
var globalNamespace2 = comp2.GlobalNamespace;
var interfaceV2 = globalNamespace2.GetTypeMembers("Interface1").Single();
Assert.NotSame(interfaceV1, interfaceV2);
var interfaceV2Method1 = (MethodSymbol)interfaceV2.GetMembers("Method1").Single();
//Method2 deleted
var interfaceV2Method3 = (MethodSymbol)interfaceV2.GetMembers("Method3").Single();
var interfaceV2Method4 = (MethodSymbol)interfaceV2.GetMembers("Method4").Single();
var interfaceV2Property1 = (PropertySymbol)interfaceV2.GetMembers("Property1").Single();
//Property2 deleted
var interfaceV2Property3 = (PropertySymbol)interfaceV2.GetMembers("Property3").Single();
var interfaceV2Property4 = (PropertySymbol)interfaceV2.GetMembers("Property4").Single();
var interfaceV2Indexer1 = FindIndexerWithParameterCount(interfaceV2, 1);
//Two-parameter indexer deleted
var interfaceV2Indexer3 = FindIndexerWithParameterCount(interfaceV2, 3);
var interfaceV2Indexer4 = FindIndexerWithParameterCount(interfaceV2, 4);
var interfaceV2Event1 = (EventSymbol)interfaceV2.GetMembers("Event1").Single();
//Event2 deleted
var interfaceV2Event3 = (EventSymbol)interfaceV2.GetMembers("Event3").Single();
var interfaceV2Event4 = (EventSymbol)interfaceV2.GetMembers("Event4").Single();
var classD = globalNamespace2.GetTypeMembers("D").Single();
var retargetedClassC = classD.BaseType();
Assert.IsType<RetargetingNamedTypeSymbol>(retargetedClassC);
Assert.Equal(interfaceV2, retargetedClassC.Interfaces().Single());
var retargetedClassCMethod1 = (MethodSymbol)retargetedClassC.GetMembers("Interface1.Method1").Single();
{
Assert.IsType<RetargetingMethodSymbol>(retargetedClassCMethod1);
Assert.Equal(MethodKind.ExplicitInterfaceImplementation, retargetedClassCMethod1.MethodKind);
var retargetedClassCMethod1Impl = retargetedClassCMethod1.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Method1, retargetedClassCMethod1Impl);
Assert.NotSame(interfaceV1Method1, retargetedClassCMethod1Impl);
Assert.Equal(retargetedClassCMethod1Impl.ToTestDisplayString(), interfaceV1Method1.ToTestDisplayString());
}
var retargetedClassCMethod2 = (MethodSymbol)retargetedClassC.GetMembers("Interface1.Method2").Single();
{
Assert.IsType<RetargetingMethodSymbol>(retargetedClassCMethod2);
Assert.Equal(MethodKind.ExplicitInterfaceImplementation, retargetedClassCMethod2.MethodKind);
//since the method is missing from V2 of the interface
Assert.False(retargetedClassCMethod2.ExplicitInterfaceImplementations.Any());
}
var retargetedClassCMethod3 = (MethodSymbol)retargetedClassC.GetMembers("Interface1.Method3").Single();
{
Assert.IsType<RetargetingMethodSymbol>(retargetedClassCMethod3);
Assert.Equal(MethodKind.ExplicitInterfaceImplementation, retargetedClassCMethod3.MethodKind);
//since the method has a different signature in V2 of the interface
Assert.False(retargetedClassCMethod3.ExplicitInterfaceImplementations.Any());
}
var retargetedClassCMethod4 = (MethodSymbol)retargetedClassC.GetMembers("Interface1.Method4").Single();
{
Assert.IsType<RetargetingMethodSymbol>(retargetedClassCMethod4);
Assert.Equal(MethodKind.ExplicitInterfaceImplementation, retargetedClassCMethod4.MethodKind);
var retargetedClassCMethod4Impl = retargetedClassCMethod4.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Method4, retargetedClassCMethod4Impl);
Assert.NotSame(interfaceV1Method4, retargetedClassCMethod4Impl);
Assert.Equal(retargetedClassCMethod4Impl.ToTestDisplayString(), interfaceV1Method4.ToTestDisplayString());
}
var retargetedClassCProperty1 = (PropertySymbol)retargetedClassC.GetMembers("Interface1.Property1").Single();
{
Assert.IsType<RetargetingPropertySymbol>(retargetedClassCProperty1);
var retargetedClassCProperty1Impl = retargetedClassCProperty1.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Property1, retargetedClassCProperty1Impl);
Assert.NotSame(interfaceV1Property1, retargetedClassCProperty1Impl);
Assert.Equal(retargetedClassCProperty1Impl.Name, interfaceV1Property1.Name);
Assert.Equal(retargetedClassCProperty1Impl.Type.ToTestDisplayString(), interfaceV1Property1.Type.ToTestDisplayString());
}
var retargetedClassCProperty2 = (PropertySymbol)retargetedClassC.GetMembers("Interface1.Property2").Single();
{
Assert.IsType<RetargetingPropertySymbol>(retargetedClassCProperty2);
//since the property is missing from V2 of the interface
Assert.False(retargetedClassCProperty2.ExplicitInterfaceImplementations.Any());
}
var retargetedClassCProperty3 = (PropertySymbol)retargetedClassC.GetMembers("Interface1.Property3").Single();
{
Assert.IsType<RetargetingPropertySymbol>(retargetedClassCProperty3);
//since the property has a different type in V2 of the interface
Assert.False(retargetedClassCProperty3.ExplicitInterfaceImplementations.Any());
}
var retargetedClassCProperty4 = (PropertySymbol)retargetedClassC.GetMembers("Interface1.Property4").Single();
{
Assert.IsType<RetargetingPropertySymbol>(retargetedClassCProperty4);
var retargetedClassCProperty4Impl = retargetedClassCProperty4.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Property4, retargetedClassCProperty4Impl);
Assert.NotSame(interfaceV1Property4, retargetedClassCProperty4Impl);
Assert.Equal(retargetedClassCProperty4Impl.Name, interfaceV1Property4.Name);
Assert.Equal(retargetedClassCProperty4Impl.Type.ToTestDisplayString(), interfaceV1Property4.Type.ToTestDisplayString());
}
var retargetedClassCIndexer1 = FindIndexerWithParameterCount(retargetedClassC, 1);
{
Assert.IsType<RetargetingPropertySymbol>(retargetedClassCIndexer1);
var retargetedClassCIndexer1Impl = retargetedClassCIndexer1.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Indexer1, retargetedClassCIndexer1Impl);
Assert.NotSame(interfaceV1Indexer1, retargetedClassCIndexer1Impl);
Assert.Equal(retargetedClassCIndexer1Impl.Name, interfaceV1Indexer1.Name);
Assert.Equal(retargetedClassCIndexer1Impl.Type.ToTestDisplayString(), interfaceV1Indexer1.Type.ToTestDisplayString());
}
var retargetedClassCIndexer2 = FindIndexerWithParameterCount(retargetedClassC, 2);
{
Assert.IsType<RetargetingPropertySymbol>(retargetedClassCIndexer2);
//since the property is missing from V2 of the interface
Assert.False(retargetedClassCIndexer2.ExplicitInterfaceImplementations.Any());
}
var retargetedClassCIndexer3 = FindIndexerWithParameterCount(retargetedClassC, 3);
{
Assert.IsType<RetargetingPropertySymbol>(retargetedClassCIndexer3);
//since the property has a different type in V2 of the interface
Assert.False(retargetedClassCIndexer3.ExplicitInterfaceImplementations.Any());
}
var retargetedClassCIndexer4 = FindIndexerWithParameterCount(retargetedClassC, 4);
{
Assert.IsType<RetargetingPropertySymbol>(retargetedClassCIndexer4);
var retargetedClassCIndexer4Impl = retargetedClassCIndexer4.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Indexer4, retargetedClassCIndexer4Impl);
Assert.NotSame(interfaceV1Indexer4, retargetedClassCIndexer4Impl);
Assert.Equal(retargetedClassCIndexer4Impl.Name, interfaceV1Indexer4.Name);
Assert.Equal(retargetedClassCIndexer4Impl.Type.ToTestDisplayString(), interfaceV1Indexer4.Type.ToTestDisplayString());
}
var retargetedClassCEvent1 = (EventSymbol)retargetedClassC.GetMembers("Interface1.Event1").Single();
{
Assert.IsType<RetargetingEventSymbol>(retargetedClassCEvent1);
var retargetedClassCEvent1Impl = retargetedClassCEvent1.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Event1, retargetedClassCEvent1Impl);
Assert.NotSame(interfaceV1Event1, retargetedClassCEvent1Impl);
Assert.Equal(retargetedClassCEvent1Impl.Name, interfaceV1Event1.Name);
Assert.Equal(retargetedClassCEvent1Impl.Type.ToTestDisplayString(), interfaceV1Event1.Type.ToTestDisplayString());
}
var retargetedClassCEvent2 = (EventSymbol)retargetedClassC.GetMembers("Interface1.Event2").Single();
{
Assert.IsType<RetargetingEventSymbol>(retargetedClassCEvent2);
//since the event is missing from V2 of the interface
Assert.False(retargetedClassCEvent2.ExplicitInterfaceImplementations.Any());
}
var retargetedClassCEvent3 = (EventSymbol)retargetedClassC.GetMembers("Interface1.Event3").Single();
{
Assert.IsType<RetargetingEventSymbol>(retargetedClassCEvent3);
//since the event has a different type in V2 of the interface
Assert.False(retargetedClassCEvent3.ExplicitInterfaceImplementations.Any());
}
var retargetedClassCEvent4 = (EventSymbol)retargetedClassC.GetMembers("Interface1.Event4").Single();
{
Assert.IsType<RetargetingEventSymbol>(retargetedClassCEvent4);
var retargetedClassCEvent4Impl = retargetedClassCEvent4.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Event4, retargetedClassCEvent4Impl);
Assert.NotSame(interfaceV1Event4, retargetedClassCEvent4Impl);
Assert.Equal(retargetedClassCEvent4Impl.Name, interfaceV1Event4.Name);
Assert.Equal(retargetedClassCEvent4Impl.Type.ToTestDisplayString(), interfaceV1Event4.Type.ToTestDisplayString());
}
}
private static PropertySymbol FindIndexerWithParameterCount(NamedTypeSymbol type, int parameterCount)
{
return type.GetMembers().Where(s => s.Kind == SymbolKind.Property).Cast<PropertySymbol>().Single(p => p.Parameters.Length == parameterCount);
}
[Fact]
public void ExplicitInterfaceImplementationRetargetingGeneric()
{
var comp1 = CreateCompilation(
new AssemblyIdentity("Assembly1"),
new string[]
{ @"
public class C1<S> : Interface2<S>
{
void Interface2<S>.Method1(S s) { }
S Interface2<S>.Property1 { get; set; }
event System.Action<S> Interface2<S>.Event1 { add { } remove { } }
}
public class C2 : Interface2<int>
{
void Interface2<int>.Method1(int i) { }
int Interface2<int>.Property1 { get; set; }
event System.Action<int> Interface2<int>.Event1 { add { } remove { } }
}
public class C3 : Interface2<Class1>
{
void Interface2<Class1>.Method1(Class1 c) { }
Class1 Interface2<Class1>.Property1 { get; set; }
event System.Action<Class1> Interface2<Class1>.Event1 { add { } remove { } }
}
"
},
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.V1.MTTestLib1.dll,
});
var d = comp1.GetDiagnostics();
Assert.False(comp1.GetDiagnostics().Any());
var globalNamespace1 = comp1.GlobalNamespace;
var classC1 = globalNamespace1.GetTypeMembers("C1").Single();
var classC2 = globalNamespace1.GetTypeMembers("C2").Single();
var classC3 = globalNamespace1.GetTypeMembers("C3").Single();
foreach (var diag in comp1.GetDiagnostics())
{
Console.WriteLine(diag);
}
var comp2 = CreateCompilation(
new AssemblyIdentity("Assembly2"),
new string[]
{@"
public class D1<R> : C1<R>
{
}
public class D2 : C2
{
}
public class D3 : C3
{
}
"
},
new MetadataReference[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.V2.MTTestLib1.dll,
new CSharpCompilationReference(comp1)
});
Assert.False(comp2.GetDiagnostics().Any());
var globalNamespace2 = comp2.GlobalNamespace;
var interfaceV2 = globalNamespace2.GetTypeMembers("Interface2").Single();
var interfaceV2Method1 = interfaceV2.GetMembers("Method1").Single();
var interfaceV2Property1 = interfaceV2.GetMembers("Property1").Single();
var interfaceV2Event1 = interfaceV2.GetMembers("Event1").Single();
var classD1 = globalNamespace2.GetTypeMembers("D1").Single();
var classD2 = globalNamespace2.GetTypeMembers("D2").Single();
var classD3 = globalNamespace2.GetTypeMembers("D3").Single();
var retargetedClassC1 = classD1.BaseType();
var retargetedClassC2 = classD2.BaseType();
var retargetedClassC3 = classD3.BaseType();
var retargetedClassC1Method1 = (MethodSymbol)retargetedClassC1.GetMembers("Interface2<S>.Method1").Single();
var retargetedClassC1Method1Impl = retargetedClassC1Method1.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Method1, retargetedClassC1Method1Impl.OriginalDefinition);
var retargetedClassC2Method1 = (MethodSymbol)retargetedClassC2.GetMembers("Interface2<System.Int32>.Method1").Single();
var retargetedClassC2Method1Impl = retargetedClassC2Method1.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Method1, retargetedClassC2Method1Impl.OriginalDefinition);
var retargetedClassC3Method1 = (MethodSymbol)retargetedClassC3.GetMembers("Interface2<Class1>.Method1").Single();
var retargetedClassC3Method1Impl = retargetedClassC3Method1.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Method1, retargetedClassC3Method1Impl.OriginalDefinition);
var retargetedClassC1Property1 = (PropertySymbol)retargetedClassC1.GetMembers("Interface2<S>.Property1").Single();
var retargetedClassC1Property1Impl = retargetedClassC1Property1.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Property1, retargetedClassC1Property1Impl.OriginalDefinition);
var retargetedClassC2Property1 = (PropertySymbol)retargetedClassC2.GetMembers("Interface2<System.Int32>.Property1").Single();
var retargetedClassC2Property1Impl = retargetedClassC2Property1.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Property1, retargetedClassC2Property1Impl.OriginalDefinition);
var retargetedClassC3Property1 = (PropertySymbol)retargetedClassC3.GetMembers("Interface2<Class1>.Property1").Single();
var retargetedClassC3Property1Impl = retargetedClassC3Property1.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Property1, retargetedClassC3Property1Impl.OriginalDefinition);
var retargetedClassC1Event1 = (EventSymbol)retargetedClassC1.GetMembers("Interface2<S>.Event1").Single();
var retargetedClassC1Event1Impl = retargetedClassC1Event1.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Event1, retargetedClassC1Event1Impl.OriginalDefinition);
var retargetedClassC2Event1 = (EventSymbol)retargetedClassC2.GetMembers("Interface2<System.Int32>.Event1").Single();
var retargetedClassC2Event1Impl = retargetedClassC2Event1.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Event1, retargetedClassC2Event1Impl.OriginalDefinition);
var retargetedClassC3Event1 = (EventSymbol)retargetedClassC3.GetMembers("Interface2<Class1>.Event1").Single();
var retargetedClassC3Event1Impl = retargetedClassC3Event1.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Event1, retargetedClassC3Event1Impl.OriginalDefinition);
}
[Fact]
public void ExplicitInterfaceImplementationRetargetingGenericType()
{
var source1 = @"
public class C1<T>
{
public interface I1
{
void M(T x);
}
}
";
var ref1 = CreateEmptyCompilation("").ToMetadataReference();
var compilation1 = CreateCompilation(source1, references: new[] { ref1 });
var source2 = @"
public class C2<U> : C1<U>.I1
{
void C1<U>.I1.M(U x) {}
}
";
var compilation2 = CreateCompilation(source2, references: new[] { compilation1.ToMetadataReference(), ref1, CreateEmptyCompilation("").ToMetadataReference() });
var compilation3 = CreateCompilation("", references: new[] { compilation1.ToMetadataReference(), compilation2.ToMetadataReference() });
Assert.NotSame(compilation2.GetTypeByMetadataName("C1`1"), compilation3.GetTypeByMetadataName("C1`1"));
var c2 = compilation3.GetTypeByMetadataName("C2`1");
Assert.IsType<RetargetingNamedTypeSymbol>(c2);
var m = c2.GetMethod("C1<U>.I1.M");
Assert.Equal(c2.Interfaces().Single().GetMethod("M"), m.ExplicitInterfaceImplementations.Single());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using static Roslyn.Test.Utilities.TestMetadata;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class RetargetExplicitInterfaceImplementation : CSharpTestBase
{
[Fact]
public void ExplicitInterfaceImplementationRetargeting()
{
var comp1 = CreateCompilation(
new AssemblyIdentity("Assembly1"),
new string[]
{ @"
public class C : Interface1
{
void Interface1.Method1() { }
void Interface1.Method2() { }
void Interface1.Method3(bool b) { }
void Interface1.Method4(Class1 c) { }
string Interface1.Property1 { get; set; }
string Interface1.Property2 { get; set; }
string Interface1.Property3 { get; set; }
Class1 Interface1.Property4 { get; set; }
string Interface1.this[string x] { get { return null; } set { } }
string Interface1.this[string x, string y] { get { return null; } set { } }
string Interface1.this[string x, string y, string z] { get { return null; } set { } }
Class1 Interface1.this[Class1 x, Class1 y, Class1 z, Class1 w] { get { return null; } set { } }
event System.Action Interface1.Event1 { add { } remove { } }
event System.Action Interface1.Event2 { add { } remove { } }
event System.Action Interface1.Event3 { add { } remove { } }
event Delegate1 Interface1.Event4 { add { } remove { } }
}
"
},
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.V1.MTTestLib1.dll,
});
comp1.VerifyDiagnostics();
var globalNamespace1 = comp1.GlobalNamespace;
var classC = globalNamespace1.GetTypeMembers("C").Single();
var interfaceV1 = globalNamespace1.GetTypeMembers("Interface1").Single();
var interfaceV1Method1 = (MethodSymbol)interfaceV1.GetMembers("Method1").Single();
var interfaceV1Method2 = (MethodSymbol)interfaceV1.GetMembers("Method2").Single();
var interfaceV1Method3 = (MethodSymbol)interfaceV1.GetMembers("Method3").Single();
var interfaceV1Method4 = (MethodSymbol)interfaceV1.GetMembers("Method4").Single();
var interfaceV1Property1 = (PropertySymbol)interfaceV1.GetMembers("Property1").Single();
var interfaceV1Property2 = (PropertySymbol)interfaceV1.GetMembers("Property2").Single();
var interfaceV1Property3 = (PropertySymbol)interfaceV1.GetMembers("Property3").Single();
var interfaceV1Property4 = (PropertySymbol)interfaceV1.GetMembers("Property4").Single();
var interfaceV1Indexer1 = FindIndexerWithParameterCount(interfaceV1, 1);
var interfaceV1Indexer2 = FindIndexerWithParameterCount(interfaceV1, 2);
var interfaceV1Indexer3 = FindIndexerWithParameterCount(interfaceV1, 3);
var interfaceV1Indexer4 = FindIndexerWithParameterCount(interfaceV1, 4);
var interfaceV1Event1 = (EventSymbol)interfaceV1.GetMembers("Event1").Single();
var interfaceV1Event2 = (EventSymbol)interfaceV1.GetMembers("Event2").Single();
var interfaceV1Event3 = (EventSymbol)interfaceV1.GetMembers("Event3").Single();
var interfaceV1Event4 = (EventSymbol)interfaceV1.GetMembers("Event4").Single();
foreach (var member in classC.GetMembers())
{
switch (member.Kind)
{
case SymbolKind.Method:
var method = (MethodSymbol)member;
if (method.MethodKind == MethodKind.ExplicitInterfaceImplementation)
{
Assert.Equal(interfaceV1, method.ExplicitInterfaceImplementations.Single().ContainingType);
}
break;
case SymbolKind.Property:
Assert.Equal(interfaceV1, ((PropertySymbol)member).ExplicitInterfaceImplementations.Single().ContainingType);
break;
case SymbolKind.Event:
Assert.Equal(interfaceV1, ((EventSymbol)member).ExplicitInterfaceImplementations.Single().ContainingType);
break;
case SymbolKind.ErrorType:
Assert.True(false);
break;
}
}
var comp2 = CreateCompilation(
new AssemblyIdentity("Assembly2"),
new string[]
{@"
public class D : C
{
}
"
},
new MetadataReference[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.V2.MTTestLib1.dll,
new CSharpCompilationReference(comp1)
});
Assert.False(comp2.GetDiagnostics().Any());
var globalNamespace2 = comp2.GlobalNamespace;
var interfaceV2 = globalNamespace2.GetTypeMembers("Interface1").Single();
Assert.NotSame(interfaceV1, interfaceV2);
var interfaceV2Method1 = (MethodSymbol)interfaceV2.GetMembers("Method1").Single();
//Method2 deleted
var interfaceV2Method3 = (MethodSymbol)interfaceV2.GetMembers("Method3").Single();
var interfaceV2Method4 = (MethodSymbol)interfaceV2.GetMembers("Method4").Single();
var interfaceV2Property1 = (PropertySymbol)interfaceV2.GetMembers("Property1").Single();
//Property2 deleted
var interfaceV2Property3 = (PropertySymbol)interfaceV2.GetMembers("Property3").Single();
var interfaceV2Property4 = (PropertySymbol)interfaceV2.GetMembers("Property4").Single();
var interfaceV2Indexer1 = FindIndexerWithParameterCount(interfaceV2, 1);
//Two-parameter indexer deleted
var interfaceV2Indexer3 = FindIndexerWithParameterCount(interfaceV2, 3);
var interfaceV2Indexer4 = FindIndexerWithParameterCount(interfaceV2, 4);
var interfaceV2Event1 = (EventSymbol)interfaceV2.GetMembers("Event1").Single();
//Event2 deleted
var interfaceV2Event3 = (EventSymbol)interfaceV2.GetMembers("Event3").Single();
var interfaceV2Event4 = (EventSymbol)interfaceV2.GetMembers("Event4").Single();
var classD = globalNamespace2.GetTypeMembers("D").Single();
var retargetedClassC = classD.BaseType();
Assert.IsType<RetargetingNamedTypeSymbol>(retargetedClassC);
Assert.Equal(interfaceV2, retargetedClassC.Interfaces().Single());
var retargetedClassCMethod1 = (MethodSymbol)retargetedClassC.GetMembers("Interface1.Method1").Single();
{
Assert.IsType<RetargetingMethodSymbol>(retargetedClassCMethod1);
Assert.Equal(MethodKind.ExplicitInterfaceImplementation, retargetedClassCMethod1.MethodKind);
var retargetedClassCMethod1Impl = retargetedClassCMethod1.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Method1, retargetedClassCMethod1Impl);
Assert.NotSame(interfaceV1Method1, retargetedClassCMethod1Impl);
Assert.Equal(retargetedClassCMethod1Impl.ToTestDisplayString(), interfaceV1Method1.ToTestDisplayString());
}
var retargetedClassCMethod2 = (MethodSymbol)retargetedClassC.GetMembers("Interface1.Method2").Single();
{
Assert.IsType<RetargetingMethodSymbol>(retargetedClassCMethod2);
Assert.Equal(MethodKind.ExplicitInterfaceImplementation, retargetedClassCMethod2.MethodKind);
//since the method is missing from V2 of the interface
Assert.False(retargetedClassCMethod2.ExplicitInterfaceImplementations.Any());
}
var retargetedClassCMethod3 = (MethodSymbol)retargetedClassC.GetMembers("Interface1.Method3").Single();
{
Assert.IsType<RetargetingMethodSymbol>(retargetedClassCMethod3);
Assert.Equal(MethodKind.ExplicitInterfaceImplementation, retargetedClassCMethod3.MethodKind);
//since the method has a different signature in V2 of the interface
Assert.False(retargetedClassCMethod3.ExplicitInterfaceImplementations.Any());
}
var retargetedClassCMethod4 = (MethodSymbol)retargetedClassC.GetMembers("Interface1.Method4").Single();
{
Assert.IsType<RetargetingMethodSymbol>(retargetedClassCMethod4);
Assert.Equal(MethodKind.ExplicitInterfaceImplementation, retargetedClassCMethod4.MethodKind);
var retargetedClassCMethod4Impl = retargetedClassCMethod4.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Method4, retargetedClassCMethod4Impl);
Assert.NotSame(interfaceV1Method4, retargetedClassCMethod4Impl);
Assert.Equal(retargetedClassCMethod4Impl.ToTestDisplayString(), interfaceV1Method4.ToTestDisplayString());
}
var retargetedClassCProperty1 = (PropertySymbol)retargetedClassC.GetMembers("Interface1.Property1").Single();
{
Assert.IsType<RetargetingPropertySymbol>(retargetedClassCProperty1);
var retargetedClassCProperty1Impl = retargetedClassCProperty1.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Property1, retargetedClassCProperty1Impl);
Assert.NotSame(interfaceV1Property1, retargetedClassCProperty1Impl);
Assert.Equal(retargetedClassCProperty1Impl.Name, interfaceV1Property1.Name);
Assert.Equal(retargetedClassCProperty1Impl.Type.ToTestDisplayString(), interfaceV1Property1.Type.ToTestDisplayString());
}
var retargetedClassCProperty2 = (PropertySymbol)retargetedClassC.GetMembers("Interface1.Property2").Single();
{
Assert.IsType<RetargetingPropertySymbol>(retargetedClassCProperty2);
//since the property is missing from V2 of the interface
Assert.False(retargetedClassCProperty2.ExplicitInterfaceImplementations.Any());
}
var retargetedClassCProperty3 = (PropertySymbol)retargetedClassC.GetMembers("Interface1.Property3").Single();
{
Assert.IsType<RetargetingPropertySymbol>(retargetedClassCProperty3);
//since the property has a different type in V2 of the interface
Assert.False(retargetedClassCProperty3.ExplicitInterfaceImplementations.Any());
}
var retargetedClassCProperty4 = (PropertySymbol)retargetedClassC.GetMembers("Interface1.Property4").Single();
{
Assert.IsType<RetargetingPropertySymbol>(retargetedClassCProperty4);
var retargetedClassCProperty4Impl = retargetedClassCProperty4.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Property4, retargetedClassCProperty4Impl);
Assert.NotSame(interfaceV1Property4, retargetedClassCProperty4Impl);
Assert.Equal(retargetedClassCProperty4Impl.Name, interfaceV1Property4.Name);
Assert.Equal(retargetedClassCProperty4Impl.Type.ToTestDisplayString(), interfaceV1Property4.Type.ToTestDisplayString());
}
var retargetedClassCIndexer1 = FindIndexerWithParameterCount(retargetedClassC, 1);
{
Assert.IsType<RetargetingPropertySymbol>(retargetedClassCIndexer1);
var retargetedClassCIndexer1Impl = retargetedClassCIndexer1.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Indexer1, retargetedClassCIndexer1Impl);
Assert.NotSame(interfaceV1Indexer1, retargetedClassCIndexer1Impl);
Assert.Equal(retargetedClassCIndexer1Impl.Name, interfaceV1Indexer1.Name);
Assert.Equal(retargetedClassCIndexer1Impl.Type.ToTestDisplayString(), interfaceV1Indexer1.Type.ToTestDisplayString());
}
var retargetedClassCIndexer2 = FindIndexerWithParameterCount(retargetedClassC, 2);
{
Assert.IsType<RetargetingPropertySymbol>(retargetedClassCIndexer2);
//since the property is missing from V2 of the interface
Assert.False(retargetedClassCIndexer2.ExplicitInterfaceImplementations.Any());
}
var retargetedClassCIndexer3 = FindIndexerWithParameterCount(retargetedClassC, 3);
{
Assert.IsType<RetargetingPropertySymbol>(retargetedClassCIndexer3);
//since the property has a different type in V2 of the interface
Assert.False(retargetedClassCIndexer3.ExplicitInterfaceImplementations.Any());
}
var retargetedClassCIndexer4 = FindIndexerWithParameterCount(retargetedClassC, 4);
{
Assert.IsType<RetargetingPropertySymbol>(retargetedClassCIndexer4);
var retargetedClassCIndexer4Impl = retargetedClassCIndexer4.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Indexer4, retargetedClassCIndexer4Impl);
Assert.NotSame(interfaceV1Indexer4, retargetedClassCIndexer4Impl);
Assert.Equal(retargetedClassCIndexer4Impl.Name, interfaceV1Indexer4.Name);
Assert.Equal(retargetedClassCIndexer4Impl.Type.ToTestDisplayString(), interfaceV1Indexer4.Type.ToTestDisplayString());
}
var retargetedClassCEvent1 = (EventSymbol)retargetedClassC.GetMembers("Interface1.Event1").Single();
{
Assert.IsType<RetargetingEventSymbol>(retargetedClassCEvent1);
var retargetedClassCEvent1Impl = retargetedClassCEvent1.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Event1, retargetedClassCEvent1Impl);
Assert.NotSame(interfaceV1Event1, retargetedClassCEvent1Impl);
Assert.Equal(retargetedClassCEvent1Impl.Name, interfaceV1Event1.Name);
Assert.Equal(retargetedClassCEvent1Impl.Type.ToTestDisplayString(), interfaceV1Event1.Type.ToTestDisplayString());
}
var retargetedClassCEvent2 = (EventSymbol)retargetedClassC.GetMembers("Interface1.Event2").Single();
{
Assert.IsType<RetargetingEventSymbol>(retargetedClassCEvent2);
//since the event is missing from V2 of the interface
Assert.False(retargetedClassCEvent2.ExplicitInterfaceImplementations.Any());
}
var retargetedClassCEvent3 = (EventSymbol)retargetedClassC.GetMembers("Interface1.Event3").Single();
{
Assert.IsType<RetargetingEventSymbol>(retargetedClassCEvent3);
//since the event has a different type in V2 of the interface
Assert.False(retargetedClassCEvent3.ExplicitInterfaceImplementations.Any());
}
var retargetedClassCEvent4 = (EventSymbol)retargetedClassC.GetMembers("Interface1.Event4").Single();
{
Assert.IsType<RetargetingEventSymbol>(retargetedClassCEvent4);
var retargetedClassCEvent4Impl = retargetedClassCEvent4.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Event4, retargetedClassCEvent4Impl);
Assert.NotSame(interfaceV1Event4, retargetedClassCEvent4Impl);
Assert.Equal(retargetedClassCEvent4Impl.Name, interfaceV1Event4.Name);
Assert.Equal(retargetedClassCEvent4Impl.Type.ToTestDisplayString(), interfaceV1Event4.Type.ToTestDisplayString());
}
}
private static PropertySymbol FindIndexerWithParameterCount(NamedTypeSymbol type, int parameterCount)
{
return type.GetMembers().Where(s => s.Kind == SymbolKind.Property).Cast<PropertySymbol>().Single(p => p.Parameters.Length == parameterCount);
}
[Fact]
public void ExplicitInterfaceImplementationRetargetingGeneric()
{
var comp1 = CreateCompilation(
new AssemblyIdentity("Assembly1"),
new string[]
{ @"
public class C1<S> : Interface2<S>
{
void Interface2<S>.Method1(S s) { }
S Interface2<S>.Property1 { get; set; }
event System.Action<S> Interface2<S>.Event1 { add { } remove { } }
}
public class C2 : Interface2<int>
{
void Interface2<int>.Method1(int i) { }
int Interface2<int>.Property1 { get; set; }
event System.Action<int> Interface2<int>.Event1 { add { } remove { } }
}
public class C3 : Interface2<Class1>
{
void Interface2<Class1>.Method1(Class1 c) { }
Class1 Interface2<Class1>.Property1 { get; set; }
event System.Action<Class1> Interface2<Class1>.Event1 { add { } remove { } }
}
"
},
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.V1.MTTestLib1.dll,
});
var d = comp1.GetDiagnostics();
Assert.False(comp1.GetDiagnostics().Any());
var globalNamespace1 = comp1.GlobalNamespace;
var classC1 = globalNamespace1.GetTypeMembers("C1").Single();
var classC2 = globalNamespace1.GetTypeMembers("C2").Single();
var classC3 = globalNamespace1.GetTypeMembers("C3").Single();
foreach (var diag in comp1.GetDiagnostics())
{
Console.WriteLine(diag);
}
var comp2 = CreateCompilation(
new AssemblyIdentity("Assembly2"),
new string[]
{@"
public class D1<R> : C1<R>
{
}
public class D2 : C2
{
}
public class D3 : C3
{
}
"
},
new MetadataReference[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.V2.MTTestLib1.dll,
new CSharpCompilationReference(comp1)
});
Assert.False(comp2.GetDiagnostics().Any());
var globalNamespace2 = comp2.GlobalNamespace;
var interfaceV2 = globalNamespace2.GetTypeMembers("Interface2").Single();
var interfaceV2Method1 = interfaceV2.GetMembers("Method1").Single();
var interfaceV2Property1 = interfaceV2.GetMembers("Property1").Single();
var interfaceV2Event1 = interfaceV2.GetMembers("Event1").Single();
var classD1 = globalNamespace2.GetTypeMembers("D1").Single();
var classD2 = globalNamespace2.GetTypeMembers("D2").Single();
var classD3 = globalNamespace2.GetTypeMembers("D3").Single();
var retargetedClassC1 = classD1.BaseType();
var retargetedClassC2 = classD2.BaseType();
var retargetedClassC3 = classD3.BaseType();
var retargetedClassC1Method1 = (MethodSymbol)retargetedClassC1.GetMembers("Interface2<S>.Method1").Single();
var retargetedClassC1Method1Impl = retargetedClassC1Method1.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Method1, retargetedClassC1Method1Impl.OriginalDefinition);
var retargetedClassC2Method1 = (MethodSymbol)retargetedClassC2.GetMembers("Interface2<System.Int32>.Method1").Single();
var retargetedClassC2Method1Impl = retargetedClassC2Method1.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Method1, retargetedClassC2Method1Impl.OriginalDefinition);
var retargetedClassC3Method1 = (MethodSymbol)retargetedClassC3.GetMembers("Interface2<Class1>.Method1").Single();
var retargetedClassC3Method1Impl = retargetedClassC3Method1.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Method1, retargetedClassC3Method1Impl.OriginalDefinition);
var retargetedClassC1Property1 = (PropertySymbol)retargetedClassC1.GetMembers("Interface2<S>.Property1").Single();
var retargetedClassC1Property1Impl = retargetedClassC1Property1.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Property1, retargetedClassC1Property1Impl.OriginalDefinition);
var retargetedClassC2Property1 = (PropertySymbol)retargetedClassC2.GetMembers("Interface2<System.Int32>.Property1").Single();
var retargetedClassC2Property1Impl = retargetedClassC2Property1.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Property1, retargetedClassC2Property1Impl.OriginalDefinition);
var retargetedClassC3Property1 = (PropertySymbol)retargetedClassC3.GetMembers("Interface2<Class1>.Property1").Single();
var retargetedClassC3Property1Impl = retargetedClassC3Property1.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Property1, retargetedClassC3Property1Impl.OriginalDefinition);
var retargetedClassC1Event1 = (EventSymbol)retargetedClassC1.GetMembers("Interface2<S>.Event1").Single();
var retargetedClassC1Event1Impl = retargetedClassC1Event1.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Event1, retargetedClassC1Event1Impl.OriginalDefinition);
var retargetedClassC2Event1 = (EventSymbol)retargetedClassC2.GetMembers("Interface2<System.Int32>.Event1").Single();
var retargetedClassC2Event1Impl = retargetedClassC2Event1.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Event1, retargetedClassC2Event1Impl.OriginalDefinition);
var retargetedClassC3Event1 = (EventSymbol)retargetedClassC3.GetMembers("Interface2<Class1>.Event1").Single();
var retargetedClassC3Event1Impl = retargetedClassC3Event1.ExplicitInterfaceImplementations.Single();
Assert.Same(interfaceV2Event1, retargetedClassC3Event1Impl.OriginalDefinition);
}
[Fact]
public void ExplicitInterfaceImplementationRetargetingGenericType()
{
var source1 = @"
public class C1<T>
{
public interface I1
{
void M(T x);
}
}
";
var ref1 = CreateEmptyCompilation("").ToMetadataReference();
var compilation1 = CreateCompilation(source1, references: new[] { ref1 });
var source2 = @"
public class C2<U> : C1<U>.I1
{
void C1<U>.I1.M(U x) {}
}
";
var compilation2 = CreateCompilation(source2, references: new[] { compilation1.ToMetadataReference(), ref1, CreateEmptyCompilation("").ToMetadataReference() });
var compilation3 = CreateCompilation("", references: new[] { compilation1.ToMetadataReference(), compilation2.ToMetadataReference() });
Assert.NotSame(compilation2.GetTypeByMetadataName("C1`1"), compilation3.GetTypeByMetadataName("C1`1"));
var c2 = compilation3.GetTypeByMetadataName("C2`1");
Assert.IsType<RetargetingNamedTypeSymbol>(c2);
var m = c2.GetMethod("C1<U>.I1.M");
Assert.Equal(c2.Interfaces().Single().GetMethod("M"), m.ExplicitInterfaceImplementations.Single());
}
}
}
| -1 |
|
dotnet/roslyn | 55,408 | Update package references | CyrusNajmabadi | 2021-08-04T19:12:45Z | 2021-08-04T22:34:08Z | 967cf7cf7be8478cce7cda728217eab8504f2863 | d41ae79bb1a3f0deb2de2f3d67c976f795da9563 | Update package references. | ./src/Compilers/VisualBasic/Test/Semantic/Compilation/MyTemplateTests.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.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class MyTemplateTests
Inherits BasicTestBase
Friend Shared Function GetMyTemplateTree(compilation As VisualBasicCompilation) As SyntaxTree
Dim MyTemplate As SyntaxTree = Nothing
For Each tree In compilation.AllSyntaxTrees
If tree.IsMyTemplate Then
' should be only one My template
Assert.Null(MyTemplate)
MyTemplate = tree
End If
Next
Return MyTemplate
End Function
<Fact()>
Public Sub LoadMyTemplate()
Dim sources = <compilation>
<file name="c.vb"><![CDATA[
Module M1
Sub Main
End Sub
End Class
]]></file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndReferences(sources,
references:={MsvbRef},
options:=TestOptions.ReleaseDll)
Dim MyTemplate = GetMyTemplateTree(compilation)
Assert.NotNull(MyTemplate)
Dim text = MyTemplate.GetText.ToString
Assert.Contains("Private ReadOnly m_Context As New Global.Microsoft.VisualBasic.MyServices.Internal.ContextValue(Of T)", text, StringComparison.Ordinal)
End Sub
<Fact()>
Public Sub LoadMyTemplateNoRuntime()
Dim sources = <compilation>
<file name="c.vb"><![CDATA[
Module M1
Sub Main
End Sub
End Class
]]></file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndReferences(sources,
references:={SystemCoreRef},
options:=TestOptions.ReleaseDll)
Dim MyTemplate = GetMyTemplateTree(compilation)
Dim text = MyTemplate.GetText.ToString
Assert.Contains("Private ReadOnly m_Context As New Global.Microsoft.VisualBasic.MyServices.Internal.ContextValue(Of T)", text, StringComparison.Ordinal)
End Sub
<Fact()>
Public Sub LoadMyTemplateRuntimeNotFile()
Dim sources = <compilation>
<file name="c.vb"><![CDATA[
Module M1
Sub Main
End Sub
End Class
]]></file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndReferences(sources,
references:={SystemCoreRef, MsvbRef},
options:=TestOptions.ReleaseDll)
Dim MyTemplate = GetMyTemplateTree(compilation)
Dim text = MyTemplate.GetText.ToString
Assert.Contains("Private ReadOnly m_Context As New Global.Microsoft.VisualBasic.MyServices.Internal.ContextValue(Of T)", text, StringComparison.Ordinal)
End Sub
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub MyConsoleApp()
Dim sources = <compilation>
<file name="c.vb"><![CDATA[
Imports System
Module Module1
Sub Main()
Console.WriteLine(My.Application.IsNetworkDeployed)
End Sub
End Module
]]></file>
</compilation>
Dim defines = PredefinedPreprocessorSymbols.AddPredefinedPreprocessorSymbols(OutputKind.ConsoleApplication)
defines = defines.Add(KeyValuePairUtil.Create("_MyType", CObj("Console")))
Dim parseOptions = New VisualBasicParseOptions(preprocessorSymbols:=defines)
Dim compilationOptions = TestOptions.ReleaseExe.WithParseOptions(parseOptions)
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(sources, options:=compilationOptions)
CompileAndVerify(compilation, expectedOutput:="False")
End Sub
<ConditionalFact(GetType(WindowsDesktopOnly), GetType(HasValidFonts), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub MyWinformApp()
Dim sources = <compilation>
<file name="c.vb"><![CDATA[
Imports System
Module m1
Function Test As String
Return My.Forms.Form1.Text
End Function
End Module
Public Class Form1
Private Sub Form1_Load( sender As Object, e As EventArgs) Handles MyBase.Load
Console.WriteLine(Test)
Me.Close
End Sub
End Class
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.SuspendLayout
'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6!, 13!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(292, 273)
Me.Name = "Form1"
Me.Text = "HelloWinform"
Me.WindowState = System.Windows.Forms.FormWindowState.Minimized
Me.ResumeLayout(false)
End Sub
End Class
]]></file>
</compilation>
Dim defines = PredefinedPreprocessorSymbols.AddPredefinedPreprocessorSymbols(OutputKind.WindowsApplication)
defines = defines.Add(KeyValuePairUtil.Create("_MyType", CObj("WindowsForms")))
Dim parseOptions = New VisualBasicParseOptions(preprocessorSymbols:=defines)
Dim compilationOptions = TestOptions.ReleaseExe.WithOutputKind(OutputKind.WindowsApplication).WithParseOptions(parseOptions).WithMainTypeName("Form1")
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sources, {SystemWindowsFormsRef, SystemDrawingRef}, compilationOptions)
compilation.VerifyDiagnostics()
CompileAndVerify(compilation, expectedOutput:="HelloWinform")
End Sub
<Fact()>
Public Sub MyApplicationSemanticInfo()
Dim sources = <compilation>
<file name="a.vb"><![CDATA[
Imports System
Module Module1
Sub Main()
Console.WriteLine(My.Application.IsNetworkDeployed)'BIND:"Application"
End Sub
End Module
]]></file>
</compilation>
Dim defines = PredefinedPreprocessorSymbols.AddPredefinedPreprocessorSymbols(OutputKind.ConsoleApplication)
defines = defines.Add(KeyValuePairUtil.Create("_MyType", CObj("Console")))
Dim parseOptions = New VisualBasicParseOptions(preprocessorSymbols:=defines)
Dim compilationOptions = TestOptions.ReleaseExe.WithParseOptions(parseOptions)
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(sources, options:=compilationOptions)
Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb")
Assert.Equal("My.MyApplication", semanticSummary.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind)
Assert.Equal("My.MyApplication", semanticSummary.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind)
Assert.Equal(CandidateReason.None, semanticSummary.CandidateReason)
Assert.Equal(0, semanticSummary.CandidateSymbols.Length)
Assert.Null(semanticSummary.Alias)
Assert.Equal(0, semanticSummary.MemberGroup.Length)
Assert.False(semanticSummary.ConstantValue.HasValue)
Dim sym = semanticSummary.Symbol
Assert.IsType(Of MyTemplateLocation)(sym.Locations(0))
Assert.True(sym.DeclaringSyntaxReferences.IsEmpty)
End Sub
<Fact()>
Public Sub MySettingExtraMember()
Dim sources = <compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
My.Application.Goo()'BIND:"Goo"
End Sub
End Module
Namespace My
Partial Class MyApplication
Public Function Goo() As Integer
Return 1
End Function
End Class
End Namespace
]]></file>
</compilation>
Dim defines = PredefinedPreprocessorSymbols.AddPredefinedPreprocessorSymbols(OutputKind.ConsoleApplication)
defines = defines.Add(KeyValuePairUtil.Create("_MyType", CObj("Console")))
Dim parseOptions = New VisualBasicParseOptions(preprocessorSymbols:=defines)
Dim compilationOptions = TestOptions.ReleaseExe.WithParseOptions(parseOptions)
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(sources, options:=compilationOptions)
Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb")
Assert.Null(semanticSummary.Type)
Assert.Null(semanticSummary.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind)
Assert.Equal("Function My.MyApplication.Goo() As System.Int32", semanticSummary.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Method, semanticSummary.Symbol.Kind)
Assert.Equal(0, semanticSummary.CandidateSymbols.Length)
Assert.Null(semanticSummary.Alias)
Assert.Equal(1, semanticSummary.MemberGroup.Length)
Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
Assert.Equal("Function My.MyApplication.Goo() As System.Int32", sortedMethodGroup(0).ToTestDisplayString())
Assert.False(semanticSummary.ConstantValue.HasValue)
Dim sym = semanticSummary.Symbol
Assert.IsType(Of SourceLocation)(sym.Locations(0))
Assert.Equal("Public Function Goo() As Integer", sym.DeclaringSyntaxReferences(0).GetSyntax().ToString())
Dim parent = sym.ContainingType
Assert.Equal(1, parent.Locations.OfType(Of SourceLocation).Count)
Assert.Equal(1, parent.Locations.OfType(Of MyTemplateLocation).Count)
Assert.Equal("Partial Class MyApplication", parent.DeclaringSyntaxReferences.Single.GetSyntax.ToString)
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.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class MyTemplateTests
Inherits BasicTestBase
Friend Shared Function GetMyTemplateTree(compilation As VisualBasicCompilation) As SyntaxTree
Dim MyTemplate As SyntaxTree = Nothing
For Each tree In compilation.AllSyntaxTrees
If tree.IsMyTemplate Then
' should be only one My template
Assert.Null(MyTemplate)
MyTemplate = tree
End If
Next
Return MyTemplate
End Function
<Fact()>
Public Sub LoadMyTemplate()
Dim sources = <compilation>
<file name="c.vb"><![CDATA[
Module M1
Sub Main
End Sub
End Class
]]></file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndReferences(sources,
references:={MsvbRef},
options:=TestOptions.ReleaseDll)
Dim MyTemplate = GetMyTemplateTree(compilation)
Assert.NotNull(MyTemplate)
Dim text = MyTemplate.GetText.ToString
Assert.Contains("Private ReadOnly m_Context As New Global.Microsoft.VisualBasic.MyServices.Internal.ContextValue(Of T)", text, StringComparison.Ordinal)
End Sub
<Fact()>
Public Sub LoadMyTemplateNoRuntime()
Dim sources = <compilation>
<file name="c.vb"><![CDATA[
Module M1
Sub Main
End Sub
End Class
]]></file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndReferences(sources,
references:={SystemCoreRef},
options:=TestOptions.ReleaseDll)
Dim MyTemplate = GetMyTemplateTree(compilation)
Dim text = MyTemplate.GetText.ToString
Assert.Contains("Private ReadOnly m_Context As New Global.Microsoft.VisualBasic.MyServices.Internal.ContextValue(Of T)", text, StringComparison.Ordinal)
End Sub
<Fact()>
Public Sub LoadMyTemplateRuntimeNotFile()
Dim sources = <compilation>
<file name="c.vb"><![CDATA[
Module M1
Sub Main
End Sub
End Class
]]></file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndReferences(sources,
references:={SystemCoreRef, MsvbRef},
options:=TestOptions.ReleaseDll)
Dim MyTemplate = GetMyTemplateTree(compilation)
Dim text = MyTemplate.GetText.ToString
Assert.Contains("Private ReadOnly m_Context As New Global.Microsoft.VisualBasic.MyServices.Internal.ContextValue(Of T)", text, StringComparison.Ordinal)
End Sub
<ConditionalFact(GetType(WindowsDesktopOnly), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub MyConsoleApp()
Dim sources = <compilation>
<file name="c.vb"><![CDATA[
Imports System
Module Module1
Sub Main()
Console.WriteLine(My.Application.IsNetworkDeployed)
End Sub
End Module
]]></file>
</compilation>
Dim defines = PredefinedPreprocessorSymbols.AddPredefinedPreprocessorSymbols(OutputKind.ConsoleApplication)
defines = defines.Add(KeyValuePairUtil.Create("_MyType", CObj("Console")))
Dim parseOptions = New VisualBasicParseOptions(preprocessorSymbols:=defines)
Dim compilationOptions = TestOptions.ReleaseExe.WithParseOptions(parseOptions)
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(sources, options:=compilationOptions)
CompileAndVerify(compilation, expectedOutput:="False")
End Sub
<ConditionalFact(GetType(WindowsDesktopOnly), GetType(HasValidFonts), Reason:="https://github.com/dotnet/roslyn/issues/28044")>
Public Sub MyWinformApp()
Dim sources = <compilation>
<file name="c.vb"><![CDATA[
Imports System
Module m1
Function Test As String
Return My.Forms.Form1.Text
End Function
End Module
Public Class Form1
Private Sub Form1_Load( sender As Object, e As EventArgs) Handles MyBase.Load
Console.WriteLine(Test)
Me.Close
End Sub
End Class
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.SuspendLayout
'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6!, 13!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(292, 273)
Me.Name = "Form1"
Me.Text = "HelloWinform"
Me.WindowState = System.Windows.Forms.FormWindowState.Minimized
Me.ResumeLayout(false)
End Sub
End Class
]]></file>
</compilation>
Dim defines = PredefinedPreprocessorSymbols.AddPredefinedPreprocessorSymbols(OutputKind.WindowsApplication)
defines = defines.Add(KeyValuePairUtil.Create("_MyType", CObj("WindowsForms")))
Dim parseOptions = New VisualBasicParseOptions(preprocessorSymbols:=defines)
Dim compilationOptions = TestOptions.ReleaseExe.WithOutputKind(OutputKind.WindowsApplication).WithParseOptions(parseOptions).WithMainTypeName("Form1")
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sources, {SystemWindowsFormsRef, SystemDrawingRef}, compilationOptions)
compilation.VerifyDiagnostics()
CompileAndVerify(compilation, expectedOutput:="HelloWinform")
End Sub
<Fact()>
Public Sub MyApplicationSemanticInfo()
Dim sources = <compilation>
<file name="a.vb"><![CDATA[
Imports System
Module Module1
Sub Main()
Console.WriteLine(My.Application.IsNetworkDeployed)'BIND:"Application"
End Sub
End Module
]]></file>
</compilation>
Dim defines = PredefinedPreprocessorSymbols.AddPredefinedPreprocessorSymbols(OutputKind.ConsoleApplication)
defines = defines.Add(KeyValuePairUtil.Create("_MyType", CObj("Console")))
Dim parseOptions = New VisualBasicParseOptions(preprocessorSymbols:=defines)
Dim compilationOptions = TestOptions.ReleaseExe.WithParseOptions(parseOptions)
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(sources, options:=compilationOptions)
Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb")
Assert.Equal("My.MyApplication", semanticSummary.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Class, semanticSummary.Type.TypeKind)
Assert.Equal("My.MyApplication", semanticSummary.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Class, semanticSummary.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind)
Assert.Equal(CandidateReason.None, semanticSummary.CandidateReason)
Assert.Equal(0, semanticSummary.CandidateSymbols.Length)
Assert.Null(semanticSummary.Alias)
Assert.Equal(0, semanticSummary.MemberGroup.Length)
Assert.False(semanticSummary.ConstantValue.HasValue)
Dim sym = semanticSummary.Symbol
Assert.IsType(Of MyTemplateLocation)(sym.Locations(0))
Assert.True(sym.DeclaringSyntaxReferences.IsEmpty)
End Sub
<Fact()>
Public Sub MySettingExtraMember()
Dim sources = <compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Module Module1
Sub Main()
My.Application.Goo()'BIND:"Goo"
End Sub
End Module
Namespace My
Partial Class MyApplication
Public Function Goo() As Integer
Return 1
End Function
End Class
End Namespace
]]></file>
</compilation>
Dim defines = PredefinedPreprocessorSymbols.AddPredefinedPreprocessorSymbols(OutputKind.ConsoleApplication)
defines = defines.Add(KeyValuePairUtil.Create("_MyType", CObj("Console")))
Dim parseOptions = New VisualBasicParseOptions(preprocessorSymbols:=defines)
Dim compilationOptions = TestOptions.ReleaseExe.WithParseOptions(parseOptions)
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(sources, options:=compilationOptions)
Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of IdentifierNameSyntax)(compilation, "a.vb")
Assert.Null(semanticSummary.Type)
Assert.Null(semanticSummary.ConvertedType)
Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind)
Assert.Equal("Function My.MyApplication.Goo() As System.Int32", semanticSummary.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.Method, semanticSummary.Symbol.Kind)
Assert.Equal(0, semanticSummary.CandidateSymbols.Length)
Assert.Null(semanticSummary.Alias)
Assert.Equal(1, semanticSummary.MemberGroup.Length)
Dim sortedMethodGroup = semanticSummary.MemberGroup.AsEnumerable().OrderBy(Function(s) s.ToTestDisplayString()).ToArray()
Assert.Equal("Function My.MyApplication.Goo() As System.Int32", sortedMethodGroup(0).ToTestDisplayString())
Assert.False(semanticSummary.ConstantValue.HasValue)
Dim sym = semanticSummary.Symbol
Assert.IsType(Of SourceLocation)(sym.Locations(0))
Assert.Equal("Public Function Goo() As Integer", sym.DeclaringSyntaxReferences(0).GetSyntax().ToString())
Dim parent = sym.ContainingType
Assert.Equal(1, parent.Locations.OfType(Of SourceLocation).Count)
Assert.Equal(1, parent.Locations.OfType(Of MyTemplateLocation).Count)
Assert.Equal("Partial Class MyApplication", parent.DeclaringSyntaxReferences.Single.GetSyntax.ToString)
End Sub
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,408 | Update package references | CyrusNajmabadi | 2021-08-04T19:12:45Z | 2021-08-04T22:34:08Z | 967cf7cf7be8478cce7cda728217eab8504f2863 | d41ae79bb1a3f0deb2de2f3d67c976f795da9563 | Update package references. | ./src/VisualStudio/CSharp/Impl/CodeModel/CSharpCodeModelServiceFactory.cs | // Licensed to the .NET Foundation under one or more 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.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel;
using Microsoft.VisualStudio.Text.Editor;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel
{
[ExportLanguageServiceFactory(typeof(ICodeModelService), LanguageNames.CSharp), Shared]
internal partial class CSharpCodeModelServiceFactory : ILanguageServiceFactory
{
private readonly IEditorOptionsFactoryService _editorOptionsFactoryService;
private readonly IEnumerable<IRefactorNotifyService> _refactorNotifyServices;
private readonly IThreadingContext _threadingContext;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpCodeModelServiceFactory(
IEditorOptionsFactoryService editorOptionsFactoryService,
[ImportMany] IEnumerable<IRefactorNotifyService> refactorNotifyServices,
IThreadingContext threadingContext)
{
_editorOptionsFactoryService = editorOptionsFactoryService;
_refactorNotifyServices = refactorNotifyServices;
_threadingContext = threadingContext;
}
public ILanguageService CreateLanguageService(HostLanguageServices provider)
=> new CSharpCodeModelService(provider, _editorOptionsFactoryService, _refactorNotifyServices, _threadingContext);
}
}
| // Licensed to the .NET Foundation under one or more 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.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel;
using Microsoft.VisualStudio.Text.Editor;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.CodeModel
{
[ExportLanguageServiceFactory(typeof(ICodeModelService), LanguageNames.CSharp), Shared]
internal partial class CSharpCodeModelServiceFactory : ILanguageServiceFactory
{
private readonly IEditorOptionsFactoryService _editorOptionsFactoryService;
private readonly IEnumerable<IRefactorNotifyService> _refactorNotifyServices;
private readonly IThreadingContext _threadingContext;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpCodeModelServiceFactory(
IEditorOptionsFactoryService editorOptionsFactoryService,
[ImportMany] IEnumerable<IRefactorNotifyService> refactorNotifyServices,
IThreadingContext threadingContext)
{
_editorOptionsFactoryService = editorOptionsFactoryService;
_refactorNotifyServices = refactorNotifyServices;
_threadingContext = threadingContext;
}
public ILanguageService CreateLanguageService(HostLanguageServices provider)
=> new CSharpCodeModelService(provider, _editorOptionsFactoryService, _refactorNotifyServices, _threadingContext);
}
}
| -1 |
|
dotnet/roslyn | 55,408 | Update package references | CyrusNajmabadi | 2021-08-04T19:12:45Z | 2021-08-04T22:34:08Z | 967cf7cf7be8478cce7cda728217eab8504f2863 | d41ae79bb1a3f0deb2de2f3d67c976f795da9563 | Update package references. | ./src/Compilers/VisualBasic/Test/Semantic/Semantics/UnaryOperators.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.IO
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.SpecialType
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Public Class UnaryOperators
Inherits BasicTestBase
<Fact>
<WorkItem(33564, "https://github.com/dotnet/roslyn/issues/33564")>
Public Sub Test1()
Dim source =
<compilation name="UnaryOperator1">
<file name="a.vb">
Option Strict Off
Module Module1
Sub Main()
Dim Bo As Boolean
Dim SB As SByte
Dim By As Byte
Dim Sh As Short
Dim US As UShort
Dim [In] As Integer
Dim UI As UInteger
Dim Lo As Long
Dim UL As ULong
Dim De As Decimal
Dim Si As Single
Dim [Do] As Double
Dim St As String
Dim Ob As Object
Dim Tc As System.TypeCode
Bo = False
SB = -1
By = 2
Sh = -3
US = 4
[In] = -5
UI = 6
Lo = -7
UL = 8
De = -9D
Si = 10
[Do] = -11
St = "12"
Ob = -13
System.Console.WriteLine("Unary Minus")
PrintResult(-Nothing)
PrintResult(-Bo)
PrintResult(-SB)
PrintResult(-By)
PrintResult(-Sh)
PrintResult(-US)
PrintResult(-[In])
PrintResult(-UI)
PrintResult(-Lo)
PrintResult(-UL)
PrintResult(-De)
PrintResult(-Si)
PrintResult(-[Do])
PrintResult(-St)
PrintResult(-Ob)
PrintResult(-Tc)
PrintResult(-True)
PrintResult(-False)
PrintResult(-System.SByte.MaxValue)
PrintResult(-System.Byte.MaxValue)
PrintResult(-14S)
PrintResult(-15US)
PrintResult(-16I)
PrintResult(-17UI)
PrintResult(-19L)
PrintResult(-20UL)
PrintResult(-System.Single.MaxValue)
PrintResult(-22.0)
PrintResult(-23D)
PrintResult(-"24")
System.Console.WriteLine("")
System.Console.WriteLine("Unary Plus")
PrintResult(+Nothing)
PrintResult(+Bo)
PrintResult(+SB)
PrintResult(+By)
PrintResult(+Sh)
PrintResult(+US)
PrintResult(+[In])
PrintResult(+UI)
PrintResult(+Lo)
PrintResult(+UL)
PrintResult(+De)
PrintResult(+Si)
PrintResult(+[Do])
PrintResult(+St)
PrintResult(+Ob)
PrintResult(+Tc)
PrintResult(+True)
PrintResult(+False)
PrintResult(+System.SByte.MaxValue)
PrintResult(+System.Byte.MaxValue)
PrintResult(+14S)
PrintResult(+15US)
PrintResult(+16I)
PrintResult(+17UI)
PrintResult(+19L)
PrintResult(+20UL)
PrintResult(+System.Single.MaxValue)
PrintResult(+22.0)
PrintResult(+23D)
PrintResult(+"24")
System.Console.WriteLine("")
System.Console.WriteLine("Logical Not")
PrintResult(Not Nothing)
PrintResult(Not Bo)
PrintResult(Not SB)
PrintResult(Not By)
PrintResult(Not Sh)
PrintResult(Not US)
PrintResult(Not [In])
PrintResult(Not UI)
PrintResult(Not Lo)
PrintResult(Not UL)
PrintResult(Not De)
PrintResult(Not Si)
PrintResult(Not [Do])
PrintResult(Not St)
PrintResult(Not Ob)
PrintResult(Not Tc)
PrintResult(Not True)
PrintResult(Not False)
PrintResult(Not System.SByte.MaxValue)
PrintResult(Not System.Byte.MaxValue)
PrintResult(Not 14S)
PrintResult(Not 15US)
PrintResult(Not 16I)
PrintResult(Not 17UI)
PrintResult(Not 19L)
PrintResult(Not 20UL)
PrintResult(Not 21.0F)
PrintResult(Not 22.0)
PrintResult(Not 23D)
PrintResult(Not "24")
End Sub
Sub PrintResult(val As Boolean)
System.Console.WriteLine("Boolean: {0}", val)
End Sub
Sub PrintResult(val As SByte)
System.Console.WriteLine("SByte: {0}", val)
End Sub
Sub PrintResult(val As Byte)
System.Console.WriteLine("Byte: {0}", val)
End Sub
Sub PrintResult(val As Short)
System.Console.WriteLine("Short: {0}", val)
End Sub
Sub PrintResult(val As UShort)
System.Console.WriteLine("UShort: {0}", val)
End Sub
Sub PrintResult(val As Integer)
System.Console.WriteLine("Integer: {0}", val)
End Sub
Sub PrintResult(val As UInteger)
System.Console.WriteLine("UInteger: {0}", val)
End Sub
Sub PrintResult(val As Long)
System.Console.WriteLine("Long: {0}", val)
End Sub
Sub PrintResult(val As ULong)
System.Console.WriteLine("ULong: {0}", val)
End Sub
Sub PrintResult(val As Decimal)
System.Console.WriteLine("Decimal: {0}", val)
End Sub
Sub PrintResult(val As Single)
System.Console.WriteLine("Single: {0}", val.ToString("G7", System.Globalization.CultureInfo.InvariantCulture))
End Sub
Sub PrintResult(val As Double)
System.Console.WriteLine("Double: {0}", val)
End Sub
'Sub PrintResult(val As Date)
' System.Console.WriteLine("Date: {0}", val)
'End Sub
Sub PrintResult(val As Char)
System.Console.WriteLine("Char: {0}", val)
End Sub
Sub PrintResult(val As String)
System.Console.WriteLine("String: ")
System.Console.WriteLine(val)
End Sub
Sub PrintResult(val As Object)
System.Console.WriteLine("Object: {0}", val)
End Sub
Sub PrintResult(val As System.TypeCode)
System.Console.WriteLine("TypeCode: {0}", val)
End Sub
End Module
</file>
</compilation>
Dim expected = <![CDATA[
Unary Minus
Integer: 0
Short: 0
SByte: 1
Short: -2
Short: 3
Integer: -4
Integer: 5
Long: -6
Long: 7
Decimal: -8
Decimal: 9
Single: -10
Double: 11
Double: -12
Object: 13
Integer: 0
Short: 1
Short: 0
SByte: -127
Short: -255
Short: -14
Integer: -15
Integer: -16
Long: -17
Long: -19
Decimal: -20
Single: -3.402823E+38
Double: -22
Decimal: -23
Double: -24
Unary Plus
Integer: 0
Short: 0
SByte: -1
Byte: 2
Short: -3
UShort: 4
Integer: -5
UInteger: 6
Long: -7
ULong: 8
Decimal: -9
Single: 10
Double: -11
Double: 12
Object: -13
Integer: 0
Short: -1
Short: 0
SByte: 127
Byte: 255
Short: 14
UShort: 15
Integer: 16
UInteger: 17
Long: 19
ULong: 20
Single: 3.402823E+38
Double: 22
Decimal: 23
Double: 24
Logical Not
Integer: -1
Boolean: True
SByte: 0
Byte: 253
Short: 2
UShort: 65531
Integer: 4
UInteger: 4294967289
Long: 6
ULong: 18446744073709551607
Long: 8
Long: -11
Long: 10
Long: -13
Object: 12
TypeCode: -1
Boolean: False
Boolean: True
SByte: -128
Byte: 0
Short: -15
UShort: 65520
Integer: -17
UInteger: 4294967278
Long: -20
ULong: 18446744073709551595
Long: -22
Long: -23
Long: -24
Long: -25
]]>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
Assert.True(c1.Options.CheckOverflow)
CompileAndVerify(c1, expected)
c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe.WithOverflowChecks(False))
Assert.False(c1.Options.CheckOverflow)
CompileAndVerify(c1, expected)
End Sub
<Fact>
Public Sub Test2()
Dim compilationDef =
<compilation name="Test2">
<file name="a.vb">
Option Strict On
Module Module1
Sub Main()
Dim Da As Date
Dim Ch As Char
Dim Ob As Object
Dim result As Object
result = -Da
result = -Ch
result = -Ob
result = +Da
result = +Ch
result = +Ob
result = Not Da
result = Not Ch
result = Not Ob
result = --Da
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(c1,
<expected>
BC30487: Operator '-' is not defined for type 'Date'.
result = -Da
~~~
BC30487: Operator '-' is not defined for type 'Char'.
result = -Ch
~~~
BC30038: Option Strict On prohibits operands of type Object for operator '-'.
result = -Ob
~~
BC42104: Variable 'Ob' is used before it has been assigned a value. A null reference exception could result at runtime.
result = -Ob
~~
BC30487: Operator '+' is not defined for type 'Date'.
result = +Da
~~~
BC30487: Operator '+' is not defined for type 'Char'.
result = +Ch
~~~
BC30038: Option Strict On prohibits operands of type Object for operator '+'.
result = +Ob
~~
BC30487: Operator 'Not' is not defined for type 'Date'.
result = Not Da
~~~~~~
BC30487: Operator 'Not' is not defined for type 'Char'.
result = Not Ch
~~~~~~
BC30038: Option Strict On prohibits operands of type Object for operator 'Not'.
result = Not Ob
~~
BC30487: Operator '-' is not defined for type 'Date'.
result = --Da
~~~
</expected>)
End Sub
<Fact>
Public Sub Test3()
Dim c1 = VisualBasicCompilation.Create("Test3",
syntaxTrees:={VisualBasicSyntaxTree.ParseText(
<text>
Option Strict Off
Module Module1
Interface I1
End Interface
Function Main() As I1
Dim result As Object
result = -Nothing
End Function
End Module</text>.Value
)},
references:=Nothing, options:=TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(c1,
<expected>
BC31091: Import of type 'Object' from assembly or module 'Test3.dll' failed.
Module Module1
~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor' is not defined.
Module Module1
~~~~~~~
BC30002: Type 'System.Object' is not defined.
Dim result As Object
~~~~~~
BC30002: Type 'System.Int32' is not defined.
result = -Nothing
~~~~~~~
BC42105: Function 'Main' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
End Function
~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub Test4()
Dim source =
<compilation name="UnaryOperator4">
<file name="a.vb">
Option Strict Off
Imports System
Module Module1
Sub Main()
Dim Ob As Object
Ob = -System.Byte.MinValue
Ob = -System.Byte.MaxValue
Ob = -System.SByte.MinValue
Ob = -System.SByte.MaxValue
Ob = -Int16.MinValue
Ob = -Int16.MaxValue
Ob = -UInt16.MaxValue
Ob = -UInt16.MinValue
Ob = -Int32.MinValue
Ob = -Int32.MaxValue
Ob = -UInt32.MaxValue
Ob = -UInt32.MinValue
Ob = -Int64.MinValue
Ob = -Int64.MaxValue
Ob = -UInt64.MaxValue
Ob = -UInt64.MinValue
Ob = -System.Decimal.MaxValue
Ob = -System.Decimal.MinValue
Ob = -System.Single.MaxValue
Ob = -System.Single.MinValue
Ob = -System.Double.MaxValue
Ob = -System.Double.MinValue
End Sub
End Module
</file>
</compilation>
Dim expected =
<expected>
BC30439: Constant expression not representable in type 'SByte'.
Ob = -System.SByte.MinValue
~~~~~~~~~~~~~~~~~~~~~~
BC30439: Constant expression not representable in type 'Short'.
Ob = -Int16.MinValue
~~~~~~~~~~~~~~~
BC30439: Constant expression not representable in type 'Integer'.
Ob = -Int32.MinValue
~~~~~~~~~~~~~~~
BC30439: Constant expression not representable in type 'Long'.
Ob = -Int64.MinValue
~~~~~~~~~~~~~~~
</expected>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
Assert.True(c1.Options.CheckOverflow)
CompilationUtils.AssertTheseDiagnostics(c1, expected)
Dim c2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe.WithOverflowChecks(False))
Assert.False(c2.Options.CheckOverflow)
CompilationUtils.AssertTheseDiagnostics(c2, expected)
End Sub
<Fact>
Public Sub Test5()
Dim compilationDef =
<compilation name="UnaryOperator2">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim Ob As Object = Nothing
Ob = -Ob
Ob = +Ob
Ob = Not Ob
End Sub
End Module
</file>
</compilation>
Dim expected =
<expected>
BC42019: Operands of type Object used for operator '-'; runtime errors could occur.
Ob = -Ob
~~
BC42019: Operands of type Object used for operator '+'; runtime errors could occur.
Ob = +Ob
~~
BC42019: Operands of type Object used for operator 'Not'; runtime errors could occur.
Ob = Not Ob
~~
</expected>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom))
Assert.Equal(OptionStrict.Custom, compilation.Options.OptionStrict)
CompilationUtils.AssertTheseDiagnostics(compilation, expected)
End Sub
<WorkItem(544620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544620")>
<Fact()>
Public Sub Bug13088()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module Program
Public Const Z1 As Integer = +2147483648 'BIND:"Public Const Z1 As Integer = +2147483648"
Public Const Z2 As Integer = (-(-2147483648)) 'BIND1:"Public Const Z2 As Integer = (-(-2147483648))"
Sub Main()
End Sub
End Module
]]></file>
</compilation>)
VerifyDiagnostics(compilation, Diagnostic(ERRID.ERR_ExpressionOverflow1, "+2147483648").WithArguments("Integer"),
Diagnostic(ERRID.ERR_ExpressionOverflow1, "(-(-2147483648))").WithArguments("Integer"))
Dim symbol = compilation.GlobalNamespace.GetTypeMembers("Program").Single.GetMembers("Z1").Single
Assert.False(DirectCast(symbol, FieldSymbol).HasConstantValue)
symbol = compilation.GlobalNamespace.GetTypeMembers("Program").Single.GetMembers("Z2").Single
Assert.False(DirectCast(symbol, FieldSymbol).HasConstantValue)
End Sub
<Fact()>
Public Sub IntrinsicSymbols()
Dim operators() As UnaryOperatorKind =
{
UnaryOperatorKind.Plus,
UnaryOperatorKind.Minus,
UnaryOperatorKind.Not
}
Dim opTokens = (From op In operators Select SyntaxFacts.GetText(OverloadResolution.GetOperatorTokenKind(op))).ToArray()
Dim typeNames() As String =
{
"System.Object",
"System.String",
"System.Double",
"System.SByte",
"System.Int16",
"System.Int32",
"System.Int64",
"System.Decimal",
"System.Single",
"System.Byte",
"System.UInt16",
"System.UInt32",
"System.UInt64",
"System.Boolean",
"System.Char",
"System.DateTime",
"System.TypeCode",
"System.StringComparison",
"System.Guid"
}
Dim builder As New System.Text.StringBuilder
Dim n As Integer = 0
For Each arg1 In typeNames
n += 1
builder.AppendFormat(
"Sub Test{1}(x1 as {0}, x2 as {0}?)" & vbCrLf, arg1, n)
Dim k As Integer = 0
For Each opToken In opTokens
builder.AppendFormat(
" Dim z{0}_1 = {1} x1" & vbCrLf &
" Dim z{0}_2 = {1} x2" & vbCrLf &
" If {1} x1" & vbCrLf &
" End If" & vbCrLf &
" If {1} x2" & vbCrLf &
" End If" & vbCrLf,
k, opToken)
k += 1
Next
builder.Append(
"End Sub" & vbCrLf)
Next
Dim source =
<compilation>
<file name="a.vb">
Class Module1
<%= New System.Xml.Linq.XCData(builder.ToString()) %>
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll.WithOverflowChecks(True))
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim nodes = (From node In tree.GetRoot().DescendantNodes()
Select node = TryCast(node, UnaryExpressionSyntax)
Where node IsNot Nothing).ToArray()
n = 0
For Each name In typeNames
Dim type = compilation.GetTypeByMetadataName(name)
For Each op In operators
TestIntrinsicSymbol(
op,
type,
compilation,
semanticModel,
nodes(n),
nodes(n + 1),
nodes(n + 2),
nodes(n + 3))
n += 4
Next
Next
Assert.Equal(n, nodes.Length)
End Sub
Private Sub TestIntrinsicSymbol(
op As UnaryOperatorKind,
type As TypeSymbol,
compilation As VisualBasicCompilation,
semanticModel As SemanticModel,
node1 As UnaryExpressionSyntax,
node2 As UnaryExpressionSyntax,
node3 As UnaryExpressionSyntax,
node4 As UnaryExpressionSyntax
)
Dim info1 As SymbolInfo = semanticModel.GetSymbolInfo(node1)
Assert.Equal(CandidateReason.None, info1.CandidateReason)
Assert.Equal(0, info1.CandidateSymbols.Length)
Dim symbol1 = DirectCast(info1.Symbol, MethodSymbol)
Dim symbol2 = semanticModel.GetSymbolInfo(node2).Symbol
Dim symbol3 = DirectCast(semanticModel.GetSymbolInfo(node3).Symbol, MethodSymbol)
Dim symbol4 = semanticModel.GetSymbolInfo(node4).Symbol
Assert.Equal(symbol1, symbol3)
If symbol1 IsNot Nothing Then
Assert.NotSame(symbol1, symbol3)
Assert.Equal(symbol1.GetHashCode(), symbol3.GetHashCode())
Assert.Equal(symbol1.Parameters(0), symbol3.Parameters(0))
Assert.Equal(symbol1.Parameters(0).GetHashCode(), symbol3.Parameters(0).GetHashCode())
End If
Assert.Equal(symbol2, symbol4)
Dim special As SpecialType = type.GetEnumUnderlyingTypeOrSelf().SpecialType
Dim resultType As SpecialType = OverloadResolution.ResolveNotLiftedIntrinsicUnaryOperator(op, special)
If resultType = SpecialType.None Then
Assert.Null(symbol1)
Assert.Null(symbol2)
Assert.Null(symbol3)
Assert.Null(symbol4)
Return
End If
Assert.NotNull(symbol1)
Dim containerName As String = compilation.GetSpecialType(resultType).ToTestDisplayString()
Dim returnName As String = containerName
If op = UnaryOperatorKind.Not AndAlso type.IsEnumType() Then
containerName = type.ToTestDisplayString()
returnName = containerName
End If
Assert.Equal(String.Format("Function {0}.{1}(value As {0}) As {2}",
containerName,
OverloadResolution.TryGetOperatorName(op),
returnName),
symbol1.ToTestDisplayString())
Assert.Equal(MethodKind.BuiltinOperator, symbol1.MethodKind)
Assert.True(symbol1.IsImplicitlyDeclared)
Assert.Equal(op = UnaryOperatorKind.Minus AndAlso symbol1.ContainingType.IsIntegralType(),
symbol1.IsCheckedBuiltin)
Assert.False(symbol1.IsGenericMethod)
Assert.False(symbol1.IsExtensionMethod)
Assert.False(symbol1.IsExternalMethod)
Assert.False(symbol1.CanBeReferencedByName)
Assert.Null(symbol1.DeclaringCompilation)
Assert.Equal(symbol1.Name, symbol1.MetadataName)
Assert.Same(symbol1.ContainingSymbol, symbol1.Parameters(0).Type)
Assert.Equal(0, symbol1.Locations.Length)
Assert.Null(symbol1.GetDocumentationCommentId)
Assert.Equal("", symbol1.GetDocumentationCommentXml)
Assert.True(symbol1.HasSpecialName)
Assert.True(symbol1.IsShared)
Assert.Equal(Accessibility.Public, symbol1.DeclaredAccessibility)
Assert.False(symbol1.IsOverloads)
Assert.False(symbol1.IsOverrides)
Assert.False(symbol1.IsOverridable)
Assert.False(symbol1.IsMustOverride)
Assert.False(symbol1.IsNotOverridable)
Assert.Equal(1, symbol1.ParameterCount)
Assert.Equal(0, symbol1.Parameters(0).Ordinal)
Dim otherSymbol = DirectCast(semanticModel.GetSymbolInfo(node1).Symbol, MethodSymbol)
Assert.Equal(symbol1, otherSymbol)
If type.IsValueType Then
Assert.Equal(symbol1, symbol2)
Return
End If
Assert.Null(symbol2)
End Sub
<Fact()>
Public Sub CheckedIntrinsicSymbols()
Dim source =
<compilation>
<file name="a.vb">
Class Module1
Sub Test(x as Integer)
Dim z1 = -x
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll.WithOverflowChecks(False))
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 = (From node In tree.GetRoot().DescendantNodes()
Select node = TryCast(node, UnaryExpressionSyntax)
Where node IsNot Nothing).Single()
Dim symbol1 = DirectCast(semanticModel.GetSymbolInfo(node1).Symbol, MethodSymbol)
Assert.False(symbol1.IsCheckedBuiltin)
compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOverflowChecks(True))
semanticModel = compilation.GetSemanticModel(tree)
Dim symbol2 = DirectCast(semanticModel.GetSymbolInfo(node1).Symbol, MethodSymbol)
Assert.True(symbol2.IsCheckedBuiltin)
Assert.NotEqual(symbol1, symbol2)
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.IO
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.SpecialType
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Public Class UnaryOperators
Inherits BasicTestBase
<Fact>
<WorkItem(33564, "https://github.com/dotnet/roslyn/issues/33564")>
Public Sub Test1()
Dim source =
<compilation name="UnaryOperator1">
<file name="a.vb">
Option Strict Off
Module Module1
Sub Main()
Dim Bo As Boolean
Dim SB As SByte
Dim By As Byte
Dim Sh As Short
Dim US As UShort
Dim [In] As Integer
Dim UI As UInteger
Dim Lo As Long
Dim UL As ULong
Dim De As Decimal
Dim Si As Single
Dim [Do] As Double
Dim St As String
Dim Ob As Object
Dim Tc As System.TypeCode
Bo = False
SB = -1
By = 2
Sh = -3
US = 4
[In] = -5
UI = 6
Lo = -7
UL = 8
De = -9D
Si = 10
[Do] = -11
St = "12"
Ob = -13
System.Console.WriteLine("Unary Minus")
PrintResult(-Nothing)
PrintResult(-Bo)
PrintResult(-SB)
PrintResult(-By)
PrintResult(-Sh)
PrintResult(-US)
PrintResult(-[In])
PrintResult(-UI)
PrintResult(-Lo)
PrintResult(-UL)
PrintResult(-De)
PrintResult(-Si)
PrintResult(-[Do])
PrintResult(-St)
PrintResult(-Ob)
PrintResult(-Tc)
PrintResult(-True)
PrintResult(-False)
PrintResult(-System.SByte.MaxValue)
PrintResult(-System.Byte.MaxValue)
PrintResult(-14S)
PrintResult(-15US)
PrintResult(-16I)
PrintResult(-17UI)
PrintResult(-19L)
PrintResult(-20UL)
PrintResult(-System.Single.MaxValue)
PrintResult(-22.0)
PrintResult(-23D)
PrintResult(-"24")
System.Console.WriteLine("")
System.Console.WriteLine("Unary Plus")
PrintResult(+Nothing)
PrintResult(+Bo)
PrintResult(+SB)
PrintResult(+By)
PrintResult(+Sh)
PrintResult(+US)
PrintResult(+[In])
PrintResult(+UI)
PrintResult(+Lo)
PrintResult(+UL)
PrintResult(+De)
PrintResult(+Si)
PrintResult(+[Do])
PrintResult(+St)
PrintResult(+Ob)
PrintResult(+Tc)
PrintResult(+True)
PrintResult(+False)
PrintResult(+System.SByte.MaxValue)
PrintResult(+System.Byte.MaxValue)
PrintResult(+14S)
PrintResult(+15US)
PrintResult(+16I)
PrintResult(+17UI)
PrintResult(+19L)
PrintResult(+20UL)
PrintResult(+System.Single.MaxValue)
PrintResult(+22.0)
PrintResult(+23D)
PrintResult(+"24")
System.Console.WriteLine("")
System.Console.WriteLine("Logical Not")
PrintResult(Not Nothing)
PrintResult(Not Bo)
PrintResult(Not SB)
PrintResult(Not By)
PrintResult(Not Sh)
PrintResult(Not US)
PrintResult(Not [In])
PrintResult(Not UI)
PrintResult(Not Lo)
PrintResult(Not UL)
PrintResult(Not De)
PrintResult(Not Si)
PrintResult(Not [Do])
PrintResult(Not St)
PrintResult(Not Ob)
PrintResult(Not Tc)
PrintResult(Not True)
PrintResult(Not False)
PrintResult(Not System.SByte.MaxValue)
PrintResult(Not System.Byte.MaxValue)
PrintResult(Not 14S)
PrintResult(Not 15US)
PrintResult(Not 16I)
PrintResult(Not 17UI)
PrintResult(Not 19L)
PrintResult(Not 20UL)
PrintResult(Not 21.0F)
PrintResult(Not 22.0)
PrintResult(Not 23D)
PrintResult(Not "24")
End Sub
Sub PrintResult(val As Boolean)
System.Console.WriteLine("Boolean: {0}", val)
End Sub
Sub PrintResult(val As SByte)
System.Console.WriteLine("SByte: {0}", val)
End Sub
Sub PrintResult(val As Byte)
System.Console.WriteLine("Byte: {0}", val)
End Sub
Sub PrintResult(val As Short)
System.Console.WriteLine("Short: {0}", val)
End Sub
Sub PrintResult(val As UShort)
System.Console.WriteLine("UShort: {0}", val)
End Sub
Sub PrintResult(val As Integer)
System.Console.WriteLine("Integer: {0}", val)
End Sub
Sub PrintResult(val As UInteger)
System.Console.WriteLine("UInteger: {0}", val)
End Sub
Sub PrintResult(val As Long)
System.Console.WriteLine("Long: {0}", val)
End Sub
Sub PrintResult(val As ULong)
System.Console.WriteLine("ULong: {0}", val)
End Sub
Sub PrintResult(val As Decimal)
System.Console.WriteLine("Decimal: {0}", val)
End Sub
Sub PrintResult(val As Single)
System.Console.WriteLine("Single: {0}", val.ToString("G7", System.Globalization.CultureInfo.InvariantCulture))
End Sub
Sub PrintResult(val As Double)
System.Console.WriteLine("Double: {0}", val)
End Sub
'Sub PrintResult(val As Date)
' System.Console.WriteLine("Date: {0}", val)
'End Sub
Sub PrintResult(val As Char)
System.Console.WriteLine("Char: {0}", val)
End Sub
Sub PrintResult(val As String)
System.Console.WriteLine("String: ")
System.Console.WriteLine(val)
End Sub
Sub PrintResult(val As Object)
System.Console.WriteLine("Object: {0}", val)
End Sub
Sub PrintResult(val As System.TypeCode)
System.Console.WriteLine("TypeCode: {0}", val)
End Sub
End Module
</file>
</compilation>
Dim expected = <![CDATA[
Unary Minus
Integer: 0
Short: 0
SByte: 1
Short: -2
Short: 3
Integer: -4
Integer: 5
Long: -6
Long: 7
Decimal: -8
Decimal: 9
Single: -10
Double: 11
Double: -12
Object: 13
Integer: 0
Short: 1
Short: 0
SByte: -127
Short: -255
Short: -14
Integer: -15
Integer: -16
Long: -17
Long: -19
Decimal: -20
Single: -3.402823E+38
Double: -22
Decimal: -23
Double: -24
Unary Plus
Integer: 0
Short: 0
SByte: -1
Byte: 2
Short: -3
UShort: 4
Integer: -5
UInteger: 6
Long: -7
ULong: 8
Decimal: -9
Single: 10
Double: -11
Double: 12
Object: -13
Integer: 0
Short: -1
Short: 0
SByte: 127
Byte: 255
Short: 14
UShort: 15
Integer: 16
UInteger: 17
Long: 19
ULong: 20
Single: 3.402823E+38
Double: 22
Decimal: 23
Double: 24
Logical Not
Integer: -1
Boolean: True
SByte: 0
Byte: 253
Short: 2
UShort: 65531
Integer: 4
UInteger: 4294967289
Long: 6
ULong: 18446744073709551607
Long: 8
Long: -11
Long: 10
Long: -13
Object: 12
TypeCode: -1
Boolean: False
Boolean: True
SByte: -128
Byte: 0
Short: -15
UShort: 65520
Integer: -17
UInteger: 4294967278
Long: -20
ULong: 18446744073709551595
Long: -22
Long: -23
Long: -24
Long: -25
]]>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
Assert.True(c1.Options.CheckOverflow)
CompileAndVerify(c1, expected)
c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe.WithOverflowChecks(False))
Assert.False(c1.Options.CheckOverflow)
CompileAndVerify(c1, expected)
End Sub
<Fact>
Public Sub Test2()
Dim compilationDef =
<compilation name="Test2">
<file name="a.vb">
Option Strict On
Module Module1
Sub Main()
Dim Da As Date
Dim Ch As Char
Dim Ob As Object
Dim result As Object
result = -Da
result = -Ch
result = -Ob
result = +Da
result = +Ch
result = +Ob
result = Not Da
result = Not Ch
result = Not Ob
result = --Da
End Sub
End Module
</file>
</compilation>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
CompilationUtils.AssertTheseDiagnostics(c1,
<expected>
BC30487: Operator '-' is not defined for type 'Date'.
result = -Da
~~~
BC30487: Operator '-' is not defined for type 'Char'.
result = -Ch
~~~
BC30038: Option Strict On prohibits operands of type Object for operator '-'.
result = -Ob
~~
BC42104: Variable 'Ob' is used before it has been assigned a value. A null reference exception could result at runtime.
result = -Ob
~~
BC30487: Operator '+' is not defined for type 'Date'.
result = +Da
~~~
BC30487: Operator '+' is not defined for type 'Char'.
result = +Ch
~~~
BC30038: Option Strict On prohibits operands of type Object for operator '+'.
result = +Ob
~~
BC30487: Operator 'Not' is not defined for type 'Date'.
result = Not Da
~~~~~~
BC30487: Operator 'Not' is not defined for type 'Char'.
result = Not Ch
~~~~~~
BC30038: Option Strict On prohibits operands of type Object for operator 'Not'.
result = Not Ob
~~
BC30487: Operator '-' is not defined for type 'Date'.
result = --Da
~~~
</expected>)
End Sub
<Fact>
Public Sub Test3()
Dim c1 = VisualBasicCompilation.Create("Test3",
syntaxTrees:={VisualBasicSyntaxTree.ParseText(
<text>
Option Strict Off
Module Module1
Interface I1
End Interface
Function Main() As I1
Dim result As Object
result = -Nothing
End Function
End Module</text>.Value
)},
references:=Nothing, options:=TestOptions.ReleaseDll)
CompilationUtils.AssertTheseDiagnostics(c1,
<expected>
BC31091: Import of type 'Object' from assembly or module 'Test3.dll' failed.
Module Module1
~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor' is not defined.
Module Module1
~~~~~~~
BC30002: Type 'System.Object' is not defined.
Dim result As Object
~~~~~~
BC30002: Type 'System.Int32' is not defined.
result = -Nothing
~~~~~~~
BC42105: Function 'Main' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
End Function
~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub Test4()
Dim source =
<compilation name="UnaryOperator4">
<file name="a.vb">
Option Strict Off
Imports System
Module Module1
Sub Main()
Dim Ob As Object
Ob = -System.Byte.MinValue
Ob = -System.Byte.MaxValue
Ob = -System.SByte.MinValue
Ob = -System.SByte.MaxValue
Ob = -Int16.MinValue
Ob = -Int16.MaxValue
Ob = -UInt16.MaxValue
Ob = -UInt16.MinValue
Ob = -Int32.MinValue
Ob = -Int32.MaxValue
Ob = -UInt32.MaxValue
Ob = -UInt32.MinValue
Ob = -Int64.MinValue
Ob = -Int64.MaxValue
Ob = -UInt64.MaxValue
Ob = -UInt64.MinValue
Ob = -System.Decimal.MaxValue
Ob = -System.Decimal.MinValue
Ob = -System.Single.MaxValue
Ob = -System.Single.MinValue
Ob = -System.Double.MaxValue
Ob = -System.Double.MinValue
End Sub
End Module
</file>
</compilation>
Dim expected =
<expected>
BC30439: Constant expression not representable in type 'SByte'.
Ob = -System.SByte.MinValue
~~~~~~~~~~~~~~~~~~~~~~
BC30439: Constant expression not representable in type 'Short'.
Ob = -Int16.MinValue
~~~~~~~~~~~~~~~
BC30439: Constant expression not representable in type 'Integer'.
Ob = -Int32.MinValue
~~~~~~~~~~~~~~~
BC30439: Constant expression not representable in type 'Long'.
Ob = -Int64.MinValue
~~~~~~~~~~~~~~~
</expected>
Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source)
Assert.True(c1.Options.CheckOverflow)
CompilationUtils.AssertTheseDiagnostics(c1, expected)
Dim c2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe.WithOverflowChecks(False))
Assert.False(c2.Options.CheckOverflow)
CompilationUtils.AssertTheseDiagnostics(c2, expected)
End Sub
<Fact>
Public Sub Test5()
Dim compilationDef =
<compilation name="UnaryOperator2">
<file name="a.vb">
Imports System
Module Module1
Sub Main()
Dim Ob As Object = Nothing
Ob = -Ob
Ob = +Ob
Ob = Not Ob
End Sub
End Module
</file>
</compilation>
Dim expected =
<expected>
BC42019: Operands of type Object used for operator '-'; runtime errors could occur.
Ob = -Ob
~~
BC42019: Operands of type Object used for operator '+'; runtime errors could occur.
Ob = +Ob
~~
BC42019: Operands of type Object used for operator 'Not'; runtime errors could occur.
Ob = Not Ob
~~
</expected>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom))
Assert.Equal(OptionStrict.Custom, compilation.Options.OptionStrict)
CompilationUtils.AssertTheseDiagnostics(compilation, expected)
End Sub
<WorkItem(544620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544620")>
<Fact()>
Public Sub Bug13088()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Module Program
Public Const Z1 As Integer = +2147483648 'BIND:"Public Const Z1 As Integer = +2147483648"
Public Const Z2 As Integer = (-(-2147483648)) 'BIND1:"Public Const Z2 As Integer = (-(-2147483648))"
Sub Main()
End Sub
End Module
]]></file>
</compilation>)
VerifyDiagnostics(compilation, Diagnostic(ERRID.ERR_ExpressionOverflow1, "+2147483648").WithArguments("Integer"),
Diagnostic(ERRID.ERR_ExpressionOverflow1, "(-(-2147483648))").WithArguments("Integer"))
Dim symbol = compilation.GlobalNamespace.GetTypeMembers("Program").Single.GetMembers("Z1").Single
Assert.False(DirectCast(symbol, FieldSymbol).HasConstantValue)
symbol = compilation.GlobalNamespace.GetTypeMembers("Program").Single.GetMembers("Z2").Single
Assert.False(DirectCast(symbol, FieldSymbol).HasConstantValue)
End Sub
<Fact()>
Public Sub IntrinsicSymbols()
Dim operators() As UnaryOperatorKind =
{
UnaryOperatorKind.Plus,
UnaryOperatorKind.Minus,
UnaryOperatorKind.Not
}
Dim opTokens = (From op In operators Select SyntaxFacts.GetText(OverloadResolution.GetOperatorTokenKind(op))).ToArray()
Dim typeNames() As String =
{
"System.Object",
"System.String",
"System.Double",
"System.SByte",
"System.Int16",
"System.Int32",
"System.Int64",
"System.Decimal",
"System.Single",
"System.Byte",
"System.UInt16",
"System.UInt32",
"System.UInt64",
"System.Boolean",
"System.Char",
"System.DateTime",
"System.TypeCode",
"System.StringComparison",
"System.Guid"
}
Dim builder As New System.Text.StringBuilder
Dim n As Integer = 0
For Each arg1 In typeNames
n += 1
builder.AppendFormat(
"Sub Test{1}(x1 as {0}, x2 as {0}?)" & vbCrLf, arg1, n)
Dim k As Integer = 0
For Each opToken In opTokens
builder.AppendFormat(
" Dim z{0}_1 = {1} x1" & vbCrLf &
" Dim z{0}_2 = {1} x2" & vbCrLf &
" If {1} x1" & vbCrLf &
" End If" & vbCrLf &
" If {1} x2" & vbCrLf &
" End If" & vbCrLf,
k, opToken)
k += 1
Next
builder.Append(
"End Sub" & vbCrLf)
Next
Dim source =
<compilation>
<file name="a.vb">
Class Module1
<%= New System.Xml.Linq.XCData(builder.ToString()) %>
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll.WithOverflowChecks(True))
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim nodes = (From node In tree.GetRoot().DescendantNodes()
Select node = TryCast(node, UnaryExpressionSyntax)
Where node IsNot Nothing).ToArray()
n = 0
For Each name In typeNames
Dim type = compilation.GetTypeByMetadataName(name)
For Each op In operators
TestIntrinsicSymbol(
op,
type,
compilation,
semanticModel,
nodes(n),
nodes(n + 1),
nodes(n + 2),
nodes(n + 3))
n += 4
Next
Next
Assert.Equal(n, nodes.Length)
End Sub
Private Sub TestIntrinsicSymbol(
op As UnaryOperatorKind,
type As TypeSymbol,
compilation As VisualBasicCompilation,
semanticModel As SemanticModel,
node1 As UnaryExpressionSyntax,
node2 As UnaryExpressionSyntax,
node3 As UnaryExpressionSyntax,
node4 As UnaryExpressionSyntax
)
Dim info1 As SymbolInfo = semanticModel.GetSymbolInfo(node1)
Assert.Equal(CandidateReason.None, info1.CandidateReason)
Assert.Equal(0, info1.CandidateSymbols.Length)
Dim symbol1 = DirectCast(info1.Symbol, MethodSymbol)
Dim symbol2 = semanticModel.GetSymbolInfo(node2).Symbol
Dim symbol3 = DirectCast(semanticModel.GetSymbolInfo(node3).Symbol, MethodSymbol)
Dim symbol4 = semanticModel.GetSymbolInfo(node4).Symbol
Assert.Equal(symbol1, symbol3)
If symbol1 IsNot Nothing Then
Assert.NotSame(symbol1, symbol3)
Assert.Equal(symbol1.GetHashCode(), symbol3.GetHashCode())
Assert.Equal(symbol1.Parameters(0), symbol3.Parameters(0))
Assert.Equal(symbol1.Parameters(0).GetHashCode(), symbol3.Parameters(0).GetHashCode())
End If
Assert.Equal(symbol2, symbol4)
Dim special As SpecialType = type.GetEnumUnderlyingTypeOrSelf().SpecialType
Dim resultType As SpecialType = OverloadResolution.ResolveNotLiftedIntrinsicUnaryOperator(op, special)
If resultType = SpecialType.None Then
Assert.Null(symbol1)
Assert.Null(symbol2)
Assert.Null(symbol3)
Assert.Null(symbol4)
Return
End If
Assert.NotNull(symbol1)
Dim containerName As String = compilation.GetSpecialType(resultType).ToTestDisplayString()
Dim returnName As String = containerName
If op = UnaryOperatorKind.Not AndAlso type.IsEnumType() Then
containerName = type.ToTestDisplayString()
returnName = containerName
End If
Assert.Equal(String.Format("Function {0}.{1}(value As {0}) As {2}",
containerName,
OverloadResolution.TryGetOperatorName(op),
returnName),
symbol1.ToTestDisplayString())
Assert.Equal(MethodKind.BuiltinOperator, symbol1.MethodKind)
Assert.True(symbol1.IsImplicitlyDeclared)
Assert.Equal(op = UnaryOperatorKind.Minus AndAlso symbol1.ContainingType.IsIntegralType(),
symbol1.IsCheckedBuiltin)
Assert.False(symbol1.IsGenericMethod)
Assert.False(symbol1.IsExtensionMethod)
Assert.False(symbol1.IsExternalMethod)
Assert.False(symbol1.CanBeReferencedByName)
Assert.Null(symbol1.DeclaringCompilation)
Assert.Equal(symbol1.Name, symbol1.MetadataName)
Assert.Same(symbol1.ContainingSymbol, symbol1.Parameters(0).Type)
Assert.Equal(0, symbol1.Locations.Length)
Assert.Null(symbol1.GetDocumentationCommentId)
Assert.Equal("", symbol1.GetDocumentationCommentXml)
Assert.True(symbol1.HasSpecialName)
Assert.True(symbol1.IsShared)
Assert.Equal(Accessibility.Public, symbol1.DeclaredAccessibility)
Assert.False(symbol1.IsOverloads)
Assert.False(symbol1.IsOverrides)
Assert.False(symbol1.IsOverridable)
Assert.False(symbol1.IsMustOverride)
Assert.False(symbol1.IsNotOverridable)
Assert.Equal(1, symbol1.ParameterCount)
Assert.Equal(0, symbol1.Parameters(0).Ordinal)
Dim otherSymbol = DirectCast(semanticModel.GetSymbolInfo(node1).Symbol, MethodSymbol)
Assert.Equal(symbol1, otherSymbol)
If type.IsValueType Then
Assert.Equal(symbol1, symbol2)
Return
End If
Assert.Null(symbol2)
End Sub
<Fact()>
Public Sub CheckedIntrinsicSymbols()
Dim source =
<compilation>
<file name="a.vb">
Class Module1
Sub Test(x as Integer)
Dim z1 = -x
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll.WithOverflowChecks(False))
Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single()
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node1 = (From node In tree.GetRoot().DescendantNodes()
Select node = TryCast(node, UnaryExpressionSyntax)
Where node IsNot Nothing).Single()
Dim symbol1 = DirectCast(semanticModel.GetSymbolInfo(node1).Symbol, MethodSymbol)
Assert.False(symbol1.IsCheckedBuiltin)
compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOverflowChecks(True))
semanticModel = compilation.GetSemanticModel(tree)
Dim symbol2 = DirectCast(semanticModel.GetSymbolInfo(node1).Symbol, MethodSymbol)
Assert.True(symbol2.IsCheckedBuiltin)
Assert.NotEqual(symbol1, symbol2)
End Sub
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,408 | Update package references | CyrusNajmabadi | 2021-08-04T19:12:45Z | 2021-08-04T22:34:08Z | 967cf7cf7be8478cce7cda728217eab8504f2863 | d41ae79bb1a3f0deb2de2f3d67c976f795da9563 | Update package references. | ./src/VisualStudio/IntegrationTest/IntegrationTests/Workspace/WorkspaceBase.cs | // Licensed to the .NET Foundation under one or more 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.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils;
#pragma warning disable xUnit1013 // currently there are public virtual methods that are overridden by derived types
namespace Roslyn.VisualStudio.IntegrationTests.Workspace
{
public abstract class WorkspaceBase : AbstractEditorTest
{
protected WorkspaceBase(VisualStudioInstanceFactory instanceFactory, string projectTemplate)
: base(instanceFactory, nameof(WorkspaceBase), projectTemplate)
{
DefaultProjectTemplate = projectTemplate;
}
protected override string LanguageName => LanguageNames.CSharp;
protected string DefaultProjectTemplate { get; }
public override async Task InitializeAsync()
{
await base.InitializeAsync().ConfigureAwait(true);
VisualStudio.Workspace.SetFullSolutionAnalysis(true);
}
public virtual void OpenCSharpThenVBSolution()
{
VisualStudio.Editor.SetText(@"using System; class Program { Exception e; }");
VisualStudio.Editor.PlaceCaret("Exception");
VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "class name");
VisualStudio.SolutionExplorer.CloseSolution();
VisualStudio.SolutionExplorer.CreateSolution(nameof(WorkspacesDesktop));
var testProj = new ProjectUtils.Project("TestProj");
VisualStudio.SolutionExplorer.AddProject(testProj, WellKnownProjectTemplates.ClassLibrary, languageName: LanguageNames.VisualBasic);
VisualStudio.SolutionExplorer.RestoreNuGetPackages(testProj);
VisualStudio.Editor.SetText(@"Imports System
Class Program
Private e As Exception
End Class");
VisualStudio.Editor.PlaceCaret("Exception");
VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "class name");
}
public virtual void MetadataReference()
{
var windowsBase = new ProjectUtils.AssemblyReference("WindowsBase");
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddMetadataReference(windowsBase, project);
VisualStudio.Editor.SetText("class C { System.Windows.Point p; }");
VisualStudio.Editor.PlaceCaret("Point");
VisualStudio.Editor.Verify.CurrentTokenType("struct name");
VisualStudio.SolutionExplorer.RemoveMetadataReference(windowsBase, project);
VisualStudio.Editor.Verify.CurrentTokenType("identifier");
}
public virtual void ProjectReference()
{
var project = new ProjectUtils.Project(ProjectName);
var csProj2 = new ProjectUtils.Project("CSProj2");
VisualStudio.SolutionExplorer.AddProject(csProj2, projectTemplate: DefaultProjectTemplate, languageName: LanguageName);
var projectName = new ProjectUtils.ProjectReference(ProjectName);
VisualStudio.SolutionExplorer.AddProjectReference(fromProjectName: csProj2, toProjectName: projectName);
VisualStudio.SolutionExplorer.RestoreNuGetPackages(csProj2);
VisualStudio.SolutionExplorer.AddFile(project, "Program.cs", open: true, contents: "public class Class1 { }");
VisualStudio.SolutionExplorer.AddFile(csProj2, "Program.cs", open: true, contents: "public class Class2 { Class1 c; }");
VisualStudio.SolutionExplorer.OpenFile(csProj2, "Program.cs");
VisualStudio.Editor.PlaceCaret("Class1");
VisualStudio.Editor.Verify.CurrentTokenType("class name");
VisualStudio.SolutionExplorer.RemoveProjectReference(projectReferenceName: projectName, projectName: csProj2);
VisualStudio.Editor.Verify.CurrentTokenType("identifier");
}
public virtual void ProjectProperties()
{
VisualStudio.Editor.SetText(@"Module Program
Sub Main()
Dim x = 42
M(x)
End Sub
Sub M(p As Integer)
End Sub
Sub M(p As Object)
End Sub
End Module");
VisualStudio.Editor.PlaceCaret("(x)", charsOffset: -1);
VisualStudio.Workspace.SetQuickInfo(true);
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.Workspace.SetOptionInfer(project.Name, true);
VisualStudio.Editor.InvokeQuickInfo();
Assert.Equal("Sub Program.M(p As Integer) (+ 1 overload)", VisualStudio.Editor.GetQuickInfo());
VisualStudio.Workspace.SetOptionInfer(project.Name, false);
VisualStudio.Editor.InvokeQuickInfo();
Assert.Equal("Sub Program.M(p As Object) (+ 1 overload)", VisualStudio.Editor.GetQuickInfo());
}
[WpfFact]
public void RenamingOpenFiles()
{
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddFile(project, "BeforeRename.cs", open: true);
// Verify we are connected to the project before...
Assert.Contains(ProjectName, VisualStudio.Editor.GetProjectNavBarItems());
VisualStudio.SolutionExplorer.RenameFile(project, "BeforeRename.cs", "AfterRename.cs");
// ...and after.
Assert.Contains(ProjectName, VisualStudio.Editor.GetProjectNavBarItems());
}
[WpfFact]
public virtual void RenamingOpenFilesViaDTE()
{
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddFile(project, "BeforeRename.cs", open: true);
// Verify we are connected to the project before...
Assert.Contains(ProjectName, VisualStudio.Editor.GetProjectNavBarItems());
VisualStudio.SolutionExplorer.RenameFileViaDTE(project, "BeforeRename.cs", "AfterRename.cs");
// ...and after.
Assert.Contains(ProjectName, VisualStudio.Editor.GetProjectNavBarItems());
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils;
#pragma warning disable xUnit1013 // currently there are public virtual methods that are overridden by derived types
namespace Roslyn.VisualStudio.IntegrationTests.Workspace
{
public abstract class WorkspaceBase : AbstractEditorTest
{
protected WorkspaceBase(VisualStudioInstanceFactory instanceFactory, string projectTemplate)
: base(instanceFactory, nameof(WorkspaceBase), projectTemplate)
{
DefaultProjectTemplate = projectTemplate;
}
protected override string LanguageName => LanguageNames.CSharp;
protected string DefaultProjectTemplate { get; }
public override async Task InitializeAsync()
{
await base.InitializeAsync().ConfigureAwait(true);
VisualStudio.Workspace.SetFullSolutionAnalysis(true);
}
public virtual void OpenCSharpThenVBSolution()
{
VisualStudio.Editor.SetText(@"using System; class Program { Exception e; }");
VisualStudio.Editor.PlaceCaret("Exception");
VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "class name");
VisualStudio.SolutionExplorer.CloseSolution();
VisualStudio.SolutionExplorer.CreateSolution(nameof(WorkspacesDesktop));
var testProj = new ProjectUtils.Project("TestProj");
VisualStudio.SolutionExplorer.AddProject(testProj, WellKnownProjectTemplates.ClassLibrary, languageName: LanguageNames.VisualBasic);
VisualStudio.SolutionExplorer.RestoreNuGetPackages(testProj);
VisualStudio.Editor.SetText(@"Imports System
Class Program
Private e As Exception
End Class");
VisualStudio.Editor.PlaceCaret("Exception");
VisualStudio.Editor.Verify.CurrentTokenType(tokenType: "class name");
}
public virtual void MetadataReference()
{
var windowsBase = new ProjectUtils.AssemblyReference("WindowsBase");
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddMetadataReference(windowsBase, project);
VisualStudio.Editor.SetText("class C { System.Windows.Point p; }");
VisualStudio.Editor.PlaceCaret("Point");
VisualStudio.Editor.Verify.CurrentTokenType("struct name");
VisualStudio.SolutionExplorer.RemoveMetadataReference(windowsBase, project);
VisualStudio.Editor.Verify.CurrentTokenType("identifier");
}
public virtual void ProjectReference()
{
var project = new ProjectUtils.Project(ProjectName);
var csProj2 = new ProjectUtils.Project("CSProj2");
VisualStudio.SolutionExplorer.AddProject(csProj2, projectTemplate: DefaultProjectTemplate, languageName: LanguageName);
var projectName = new ProjectUtils.ProjectReference(ProjectName);
VisualStudio.SolutionExplorer.AddProjectReference(fromProjectName: csProj2, toProjectName: projectName);
VisualStudio.SolutionExplorer.RestoreNuGetPackages(csProj2);
VisualStudio.SolutionExplorer.AddFile(project, "Program.cs", open: true, contents: "public class Class1 { }");
VisualStudio.SolutionExplorer.AddFile(csProj2, "Program.cs", open: true, contents: "public class Class2 { Class1 c; }");
VisualStudio.SolutionExplorer.OpenFile(csProj2, "Program.cs");
VisualStudio.Editor.PlaceCaret("Class1");
VisualStudio.Editor.Verify.CurrentTokenType("class name");
VisualStudio.SolutionExplorer.RemoveProjectReference(projectReferenceName: projectName, projectName: csProj2);
VisualStudio.Editor.Verify.CurrentTokenType("identifier");
}
public virtual void ProjectProperties()
{
VisualStudio.Editor.SetText(@"Module Program
Sub Main()
Dim x = 42
M(x)
End Sub
Sub M(p As Integer)
End Sub
Sub M(p As Object)
End Sub
End Module");
VisualStudio.Editor.PlaceCaret("(x)", charsOffset: -1);
VisualStudio.Workspace.SetQuickInfo(true);
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.Workspace.SetOptionInfer(project.Name, true);
VisualStudio.Editor.InvokeQuickInfo();
Assert.Equal("Sub Program.M(p As Integer) (+ 1 overload)", VisualStudio.Editor.GetQuickInfo());
VisualStudio.Workspace.SetOptionInfer(project.Name, false);
VisualStudio.Editor.InvokeQuickInfo();
Assert.Equal("Sub Program.M(p As Object) (+ 1 overload)", VisualStudio.Editor.GetQuickInfo());
}
[WpfFact]
public void RenamingOpenFiles()
{
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddFile(project, "BeforeRename.cs", open: true);
// Verify we are connected to the project before...
Assert.Contains(ProjectName, VisualStudio.Editor.GetProjectNavBarItems());
VisualStudio.SolutionExplorer.RenameFile(project, "BeforeRename.cs", "AfterRename.cs");
// ...and after.
Assert.Contains(ProjectName, VisualStudio.Editor.GetProjectNavBarItems());
}
[WpfFact]
public virtual void RenamingOpenFilesViaDTE()
{
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddFile(project, "BeforeRename.cs", open: true);
// Verify we are connected to the project before...
Assert.Contains(ProjectName, VisualStudio.Editor.GetProjectNavBarItems());
VisualStudio.SolutionExplorer.RenameFileViaDTE(project, "BeforeRename.cs", "AfterRename.cs");
// ...and after.
Assert.Contains(ProjectName, VisualStudio.Editor.GetProjectNavBarItems());
}
}
}
| -1 |
|
dotnet/roslyn | 55,408 | Update package references | CyrusNajmabadi | 2021-08-04T19:12:45Z | 2021-08-04T22:34:08Z | 967cf7cf7be8478cce7cda728217eab8504f2863 | d41ae79bb1a3f0deb2de2f3d67c976f795da9563 | Update package references. | ./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenTypeofTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.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.CodeGen
{
public class CodeGenTypeOfTests : CSharpTestBase
{
[Fact]
public void TestTypeofSimple()
{
var source = @"
class C
{
static void Main()
{
System.Console.WriteLine(typeof(C));
}
}";
var comp = CompileAndVerify(source, expectedOutput: "C");
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main", @"{
// Code size 16 (0x10)
.maxstack 1
IL_0000: ldtoken ""C""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: call ""void System.Console.WriteLine(object)""
IL_000f: ret
}");
}
[Fact]
public void TestTypeofNonGeneric()
{
var source = @"
namespace Source
{
class Class { }
struct Struct { }
enum Enum { e }
interface Interface { }
class StaticClass { }
}
class Program
{
static void Main()
{
// From source
System.Console.WriteLine(typeof(Source.Class));
System.Console.WriteLine(typeof(Source.Struct));
System.Console.WriteLine(typeof(Source.Enum));
System.Console.WriteLine(typeof(Source.Interface));
System.Console.WriteLine(typeof(Source.StaticClass));
// From metadata
System.Console.WriteLine(typeof(string));
System.Console.WriteLine(typeof(int));
System.Console.WriteLine(typeof(System.IO.FileMode));
System.Console.WriteLine(typeof(System.IFormattable));
System.Console.WriteLine(typeof(System.Math));
// Special
System.Console.WriteLine(typeof(void));
}
}";
var comp = CompileAndVerify(source, expectedOutput: @"
Source.Class
Source.Struct
Source.Enum
Source.Interface
Source.StaticClass
System.String
System.Int32
System.IO.FileMode
System.IFormattable
System.Math
System.Void");
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"{
// Code size 166 (0xa6)
.maxstack 1
IL_0000: ldtoken ""Source.Class""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: call ""void System.Console.WriteLine(object)""
IL_000f: ldtoken ""Source.Struct""
IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0019: call ""void System.Console.WriteLine(object)""
IL_001e: ldtoken ""Source.Enum""
IL_0023: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0028: call ""void System.Console.WriteLine(object)""
IL_002d: ldtoken ""Source.Interface""
IL_0032: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0037: call ""void System.Console.WriteLine(object)""
IL_003c: ldtoken ""Source.StaticClass""
IL_0041: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0046: call ""void System.Console.WriteLine(object)""
IL_004b: ldtoken ""string""
IL_0050: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0055: call ""void System.Console.WriteLine(object)""
IL_005a: ldtoken ""int""
IL_005f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0064: call ""void System.Console.WriteLine(object)""
IL_0069: ldtoken ""System.IO.FileMode""
IL_006e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0073: call ""void System.Console.WriteLine(object)""
IL_0078: ldtoken ""System.IFormattable""
IL_007d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0082: call ""void System.Console.WriteLine(object)""
IL_0087: ldtoken ""System.Math""
IL_008c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0091: call ""void System.Console.WriteLine(object)""
IL_0096: ldtoken ""void""
IL_009b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_00a0: call ""void System.Console.WriteLine(object)""
IL_00a5: ret
}");
}
[Fact]
public void TestTypeofGeneric()
{
var source = @"
class Class1<T> { }
class Class2<T, U> { }
class Program
{
static void Main()
{
System.Console.WriteLine(typeof(Class1<int>));
System.Console.WriteLine(typeof(Class1<Class1<int>>));
System.Console.WriteLine(typeof(Class2<int, long>));
System.Console.WriteLine(typeof(Class2<Class1<int>, Class1<long>>));
}
}";
var comp = CompileAndVerify(source, expectedOutput: @"
Class1`1[System.Int32]
Class1`1[Class1`1[System.Int32]]
Class2`2[System.Int32,System.Int64]
Class2`2[Class1`1[System.Int32],Class1`1[System.Int64]]");
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"{
// Code size 61 (0x3d)
.maxstack 1
IL_0000: ldtoken ""Class1<int>""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: call ""void System.Console.WriteLine(object)""
IL_000f: ldtoken ""Class1<Class1<int>>""
IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0019: call ""void System.Console.WriteLine(object)""
IL_001e: ldtoken ""Class2<int, long>""
IL_0023: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0028: call ""void System.Console.WriteLine(object)""
IL_002d: ldtoken ""Class2<Class1<int>, Class1<long>>""
IL_0032: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0037: call ""void System.Console.WriteLine(object)""
IL_003c: ret
}");
}
[Fact]
public void TestTypeofTypeParameter()
{
var source = @"
class Class<T>
{
public static void Print()
{
System.Console.WriteLine(typeof(T));
System.Console.WriteLine(typeof(Class<T>));
}
public static void Print<U>()
{
System.Console.WriteLine(typeof(U));
System.Console.WriteLine(typeof(Class<U>));
}
}
class Program
{
static void Main()
{
Class<int>.Print();
Class<Class<int>>.Print();
Class<int>.Print<long>();
Class<Class<int>>.Print<Class<long>>();
}
}";
var comp = CompileAndVerify(source, expectedOutput: @"
System.Int32
Class`1[System.Int32]
Class`1[System.Int32]
Class`1[Class`1[System.Int32]]
System.Int64
Class`1[System.Int64]
Class`1[System.Int64]
Class`1[Class`1[System.Int64]]");
comp.VerifyDiagnostics();
comp.VerifyIL("Class<T>.Print", @"{
// Code size 31 (0x1f)
.maxstack 1
IL_0000: ldtoken ""T""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: call ""void System.Console.WriteLine(object)""
IL_000f: ldtoken ""Class<T>""
IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0019: call ""void System.Console.WriteLine(object)""
IL_001e: ret
}");
comp.VerifyIL("Class<T>.Print<U>", @"{
// Code size 31 (0x1f)
.maxstack 1
IL_0000: ldtoken ""U""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: call ""void System.Console.WriteLine(object)""
IL_000f: ldtoken ""Class<U>""
IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0019: call ""void System.Console.WriteLine(object)""
IL_001e: ret
}");
}
[Fact]
public void TestTypeofUnboundGeneric()
{
var source = @"
class Class1<T> { }
class Class2<T, U> { }
class Program
{
static void Main()
{
System.Console.WriteLine(typeof(Class1<>));
System.Console.WriteLine(typeof(Class2<,>));
}
}";
var comp = CompileAndVerify(source, expectedOutput: @"
Class1`1[T]
Class2`2[T,U]");
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"{
// Code size 31 (0x1f)
.maxstack 1
IL_0000: ldtoken ""Class1<T>""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: call ""void System.Console.WriteLine(object)""
IL_000f: ldtoken ""Class2<T, U>""
IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0019: call ""void System.Console.WriteLine(object)""
IL_001e: ret
}");
}
[WorkItem(542581, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542581")]
[Fact]
public void TestTypeofInheritedNestedTypeThroughUnboundGeneric_01()
{
var source = @"
using System;
class D<T> : C, I1, I2<T, int> { }
interface I1 { }
interface I2<T, U> { }
class F<T> { public class E {} }
class G<T> : F<T>, I1, I2<T, int> { }
class H<T, U> { public class E {} }
class K<T> : H<T, int>{ }
class C
{
public class E { }
static void Main()
{
Console.WriteLine(typeof(D<>.E));
Console.WriteLine(typeof(D<>).BaseType);
var interfaces = typeof(D<>).GetInterfaces();
Console.WriteLine(interfaces[0]);
Console.WriteLine(interfaces[1]);
Console.WriteLine(typeof(G<>.E));
Console.WriteLine(typeof(G<>).BaseType);
interfaces = typeof(G<>).GetInterfaces();
Console.WriteLine(interfaces[0]);
Console.WriteLine(interfaces[1]);
Console.WriteLine(typeof(K<>.E));
Console.WriteLine(typeof(K<>).BaseType);
}
}";
var expected = @"C+E
C
I1
I2`2[T,System.Int32]
F`1+E[T]
F`1[T]
I1
I2`2[T,System.Int32]
H`2+E[T,U]
H`2[T,System.Int32]";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[WorkItem(542581, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542581")]
[WorkItem(9850, "https://github.com/dotnet/roslyn/issues/9850")]
[Fact]
public void TestTypeofInheritedNestedTypeThroughUnboundGeneric_02()
{
var source = @"
using System;
class C
{
public class E { }
public class E<V> { }
static void Main()
{
var t1 = typeof(D<>.E);
Console.WriteLine(t1);
var t2 = typeof(F<>.E);
var t3 = typeof(G<>.E);
Console.WriteLine(t2);
Console.WriteLine(t3);
Console.WriteLine(t2.Equals(t3));
var t4 = typeof(D<>.E<>);
Console.WriteLine(t4);
var t5 = typeof(F<>.E<>);
var t6 = typeof(G<>.E<>);
Console.WriteLine(t5);
Console.WriteLine(t6);
Console.WriteLine(t5.Equals(t6));
}
}
class C<U>
{
public class E { }
public class E<V> { }
}
class D<T> : C { }
class F<T> : C<T> { }
class G<T> : C<int> { }
";
var expected = @"C+E
C`1+E[U]
C`1+E[U]
True
C+E`1[V]
C`1+E`1[U,V]
C`1+E`1[U,V]
True";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[WorkItem(542581, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542581")]
[Fact]
public void TestTypeofInheritedNestedTypeThroughUnboundGeneric_Attribute()
{
var source = @"
using System;
[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
class TestAttribute : Attribute { public TestAttribute(System.Type type){} }
class D<T> : C, I1, I2<T, int> { }
interface I1 { }
interface I2<T, U> { }
class F<T> { public class E {} }
class G<T> : F<T>, I1, I2<T, int> { }
class H<T, U> { public class E {} }
class K<T> : H<T, int>{ }
[TestAttribute(typeof(D<>))]
[TestAttribute(typeof(D<>.E))]
[TestAttribute(typeof(G<>))]
[TestAttribute(typeof(G<>.E))]
[TestAttribute(typeof(K<>))]
[TestAttribute(typeof(K<>.E))]
class C
{
public class E { }
static void Main()
{
typeof(C).GetCustomAttributes(false);
}
}";
var comp = CompileAndVerify(source, expectedOutput: "");
}
[Fact]
public void TestTypeofArray()
{
var source = @"
class Class1<T> { }
class Program
{
static void Print<U>()
{
System.Console.WriteLine(typeof(int[]));
System.Console.WriteLine(typeof(int[,]));
System.Console.WriteLine(typeof(int[][]));
System.Console.WriteLine(typeof(U[]));
System.Console.WriteLine(typeof(Class1<U>[]));
System.Console.WriteLine(typeof(Class1<int>[]));
}
static void Main()
{
Print<long>();
}
}";
var comp = CompileAndVerify(source, expectedOutput: @"
System.Int32[]
System.Int32[,]
System.Int32[][]
System.Int64[]
Class1`1[System.Int64][]
Class1`1[System.Int32][]");
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Print<U>", @"{
// Code size 91 (0x5b)
.maxstack 1
IL_0000: ldtoken ""int[]""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: call ""void System.Console.WriteLine(object)""
IL_000f: ldtoken ""int[,]""
IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0019: call ""void System.Console.WriteLine(object)""
IL_001e: ldtoken ""int[][]""
IL_0023: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0028: call ""void System.Console.WriteLine(object)""
IL_002d: ldtoken ""U[]""
IL_0032: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0037: call ""void System.Console.WriteLine(object)""
IL_003c: ldtoken ""Class1<U>[]""
IL_0041: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0046: call ""void System.Console.WriteLine(object)""
IL_004b: ldtoken ""Class1<int>[]""
IL_0050: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0055: call ""void System.Console.WriteLine(object)""
IL_005a: ret
}");
}
[Fact]
public void TestTypeofNested()
{
var source = @"
class Outer<T>
{
public static void Print()
{
System.Console.WriteLine(typeof(Inner<>));
System.Console.WriteLine(typeof(Inner<T>));
System.Console.WriteLine(typeof(Inner<int>));
System.Console.WriteLine(typeof(Outer<>.Inner<>));
// System.Console.WriteLine(typeof(Outer<>.Inner<T>)); //CS7003
// System.Console.WriteLine(typeof(Outer<>.Inner<int>)); //CS7003
// System.Console.WriteLine(typeof(Outer<T>.Inner<>)); //CS7003
System.Console.WriteLine(typeof(Outer<T>.Inner<T>));
System.Console.WriteLine(typeof(Outer<T>.Inner<int>));
// System.Console.WriteLine(typeof(Outer<int>.Inner<>)); //CS7003
System.Console.WriteLine(typeof(Outer<int>.Inner<T>));
System.Console.WriteLine(typeof(Outer<int>.Inner<int>));
}
class Inner<U> { }
}
class Program
{
static void Main()
{
Outer<long>.Print();
}
}";
var comp = CompileAndVerify(source, expectedOutput: @"
Outer`1+Inner`1[T,U]
Outer`1+Inner`1[System.Int64,System.Int64]
Outer`1+Inner`1[System.Int64,System.Int32]
Outer`1+Inner`1[T,U]
Outer`1+Inner`1[System.Int64,System.Int64]
Outer`1+Inner`1[System.Int64,System.Int32]
Outer`1+Inner`1[System.Int32,System.Int64]
Outer`1+Inner`1[System.Int32,System.Int32]");
comp.VerifyDiagnostics();
comp.VerifyIL("Outer<T>.Print", @"{
// Code size 121 (0x79)
.maxstack 1
IL_0000: ldtoken ""Outer<T>.Inner<U>""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: call ""void System.Console.WriteLine(object)""
IL_000f: ldtoken ""Outer<T>.Inner<T>""
IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0019: call ""void System.Console.WriteLine(object)""
IL_001e: ldtoken ""Outer<T>.Inner<int>""
IL_0023: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0028: call ""void System.Console.WriteLine(object)""
IL_002d: ldtoken ""Outer<T>.Inner<U>""
IL_0032: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0037: call ""void System.Console.WriteLine(object)""
IL_003c: ldtoken ""Outer<T>.Inner<T>""
IL_0041: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0046: call ""void System.Console.WriteLine(object)""
IL_004b: ldtoken ""Outer<T>.Inner<int>""
IL_0050: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0055: call ""void System.Console.WriteLine(object)""
IL_005a: ldtoken ""Outer<int>.Inner<T>""
IL_005f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0064: call ""void System.Console.WriteLine(object)""
IL_0069: ldtoken ""Outer<int>.Inner<int>""
IL_006e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0073: call ""void System.Console.WriteLine(object)""
IL_0078: ret
}");
}
[Fact]
public void TestTypeofInLambda()
{
var source = @"
using System;
public class Outer<T>
{
public class Inner<U>
{
public Action Method<V>(V v)
{
return () =>
{
Console.WriteLine(v);
Console.WriteLine(typeof(T));
Console.WriteLine(typeof(U));
Console.WriteLine(typeof(V));
Console.WriteLine(typeof(Outer<>));
Console.WriteLine(typeof(Outer<T>));
Console.WriteLine(typeof(Outer<U>));
Console.WriteLine(typeof(Outer<V>));
Console.WriteLine(typeof(Inner<>));
Console.WriteLine(typeof(Inner<T>));
Console.WriteLine(typeof(Inner<U>));
Console.WriteLine(typeof(Inner<V>));
};
}
}
}
class Program
{
static void Main()
{
Action a = new Outer<int>.Inner<char>().Method<byte>(1);
a();
}
}";
var comp = CompileAndVerify(source, expectedOutput: @"
1
System.Int32
System.Char
System.Byte
Outer`1[T]
Outer`1[System.Int32]
Outer`1[System.Char]
Outer`1[System.Byte]
Outer`1+Inner`1[T,U]
Outer`1+Inner`1[System.Int32,System.Int32]
Outer`1+Inner`1[System.Int32,System.Char]
Outer`1+Inner`1[System.Int32,System.Byte]");
comp.VerifyDiagnostics();
}
[WorkItem(541600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541600")]
[Fact]
public void TestTypeOfAlias4TypeMemberOfGeneric()
{
var source = @"
using System;
using MyTestClass = TestClass<string>;
public class TestClass<T>
{
public enum TestEnum
{
First = 0,
}
}
public class mem178
{
public static int Main()
{
Console.Write(typeof(MyTestClass.TestEnum));
return 0;
}
}
";
CompileAndVerify(source, expectedOutput: @"TestClass`1+TestEnum[System.String]");
}
[WorkItem(541618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541618")]
[Fact]
public void TestTypeOfAlias5TypeMemberOfGeneric()
{
var source = @"
using OuterOfString = Outer<string>;
using OuterOfInt = Outer<int>;
public class Outer<T>
{
public class Inner<U> { }
}
public class Program
{
public static void Main()
{
System.Console.WriteLine(typeof(OuterOfString.Inner<>) == typeof(OuterOfInt.Inner<>));
}
}
";
// NOTE: this is the Dev10 output. Change to false if we decide to take a breaking change.
CompileAndVerify(source, expectedOutput: @"True");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
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.CodeGen
{
public class CodeGenTypeOfTests : CSharpTestBase
{
[Fact]
public void TestTypeofSimple()
{
var source = @"
class C
{
static void Main()
{
System.Console.WriteLine(typeof(C));
}
}";
var comp = CompileAndVerify(source, expectedOutput: "C");
comp.VerifyDiagnostics();
comp.VerifyIL("C.Main", @"{
// Code size 16 (0x10)
.maxstack 1
IL_0000: ldtoken ""C""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: call ""void System.Console.WriteLine(object)""
IL_000f: ret
}");
}
[Fact]
public void TestTypeofNonGeneric()
{
var source = @"
namespace Source
{
class Class { }
struct Struct { }
enum Enum { e }
interface Interface { }
class StaticClass { }
}
class Program
{
static void Main()
{
// From source
System.Console.WriteLine(typeof(Source.Class));
System.Console.WriteLine(typeof(Source.Struct));
System.Console.WriteLine(typeof(Source.Enum));
System.Console.WriteLine(typeof(Source.Interface));
System.Console.WriteLine(typeof(Source.StaticClass));
// From metadata
System.Console.WriteLine(typeof(string));
System.Console.WriteLine(typeof(int));
System.Console.WriteLine(typeof(System.IO.FileMode));
System.Console.WriteLine(typeof(System.IFormattable));
System.Console.WriteLine(typeof(System.Math));
// Special
System.Console.WriteLine(typeof(void));
}
}";
var comp = CompileAndVerify(source, expectedOutput: @"
Source.Class
Source.Struct
Source.Enum
Source.Interface
Source.StaticClass
System.String
System.Int32
System.IO.FileMode
System.IFormattable
System.Math
System.Void");
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"{
// Code size 166 (0xa6)
.maxstack 1
IL_0000: ldtoken ""Source.Class""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: call ""void System.Console.WriteLine(object)""
IL_000f: ldtoken ""Source.Struct""
IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0019: call ""void System.Console.WriteLine(object)""
IL_001e: ldtoken ""Source.Enum""
IL_0023: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0028: call ""void System.Console.WriteLine(object)""
IL_002d: ldtoken ""Source.Interface""
IL_0032: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0037: call ""void System.Console.WriteLine(object)""
IL_003c: ldtoken ""Source.StaticClass""
IL_0041: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0046: call ""void System.Console.WriteLine(object)""
IL_004b: ldtoken ""string""
IL_0050: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0055: call ""void System.Console.WriteLine(object)""
IL_005a: ldtoken ""int""
IL_005f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0064: call ""void System.Console.WriteLine(object)""
IL_0069: ldtoken ""System.IO.FileMode""
IL_006e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0073: call ""void System.Console.WriteLine(object)""
IL_0078: ldtoken ""System.IFormattable""
IL_007d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0082: call ""void System.Console.WriteLine(object)""
IL_0087: ldtoken ""System.Math""
IL_008c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0091: call ""void System.Console.WriteLine(object)""
IL_0096: ldtoken ""void""
IL_009b: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_00a0: call ""void System.Console.WriteLine(object)""
IL_00a5: ret
}");
}
[Fact]
public void TestTypeofGeneric()
{
var source = @"
class Class1<T> { }
class Class2<T, U> { }
class Program
{
static void Main()
{
System.Console.WriteLine(typeof(Class1<int>));
System.Console.WriteLine(typeof(Class1<Class1<int>>));
System.Console.WriteLine(typeof(Class2<int, long>));
System.Console.WriteLine(typeof(Class2<Class1<int>, Class1<long>>));
}
}";
var comp = CompileAndVerify(source, expectedOutput: @"
Class1`1[System.Int32]
Class1`1[Class1`1[System.Int32]]
Class2`2[System.Int32,System.Int64]
Class2`2[Class1`1[System.Int32],Class1`1[System.Int64]]");
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"{
// Code size 61 (0x3d)
.maxstack 1
IL_0000: ldtoken ""Class1<int>""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: call ""void System.Console.WriteLine(object)""
IL_000f: ldtoken ""Class1<Class1<int>>""
IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0019: call ""void System.Console.WriteLine(object)""
IL_001e: ldtoken ""Class2<int, long>""
IL_0023: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0028: call ""void System.Console.WriteLine(object)""
IL_002d: ldtoken ""Class2<Class1<int>, Class1<long>>""
IL_0032: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0037: call ""void System.Console.WriteLine(object)""
IL_003c: ret
}");
}
[Fact]
public void TestTypeofTypeParameter()
{
var source = @"
class Class<T>
{
public static void Print()
{
System.Console.WriteLine(typeof(T));
System.Console.WriteLine(typeof(Class<T>));
}
public static void Print<U>()
{
System.Console.WriteLine(typeof(U));
System.Console.WriteLine(typeof(Class<U>));
}
}
class Program
{
static void Main()
{
Class<int>.Print();
Class<Class<int>>.Print();
Class<int>.Print<long>();
Class<Class<int>>.Print<Class<long>>();
}
}";
var comp = CompileAndVerify(source, expectedOutput: @"
System.Int32
Class`1[System.Int32]
Class`1[System.Int32]
Class`1[Class`1[System.Int32]]
System.Int64
Class`1[System.Int64]
Class`1[System.Int64]
Class`1[Class`1[System.Int64]]");
comp.VerifyDiagnostics();
comp.VerifyIL("Class<T>.Print", @"{
// Code size 31 (0x1f)
.maxstack 1
IL_0000: ldtoken ""T""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: call ""void System.Console.WriteLine(object)""
IL_000f: ldtoken ""Class<T>""
IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0019: call ""void System.Console.WriteLine(object)""
IL_001e: ret
}");
comp.VerifyIL("Class<T>.Print<U>", @"{
// Code size 31 (0x1f)
.maxstack 1
IL_0000: ldtoken ""U""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: call ""void System.Console.WriteLine(object)""
IL_000f: ldtoken ""Class<U>""
IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0019: call ""void System.Console.WriteLine(object)""
IL_001e: ret
}");
}
[Fact]
public void TestTypeofUnboundGeneric()
{
var source = @"
class Class1<T> { }
class Class2<T, U> { }
class Program
{
static void Main()
{
System.Console.WriteLine(typeof(Class1<>));
System.Console.WriteLine(typeof(Class2<,>));
}
}";
var comp = CompileAndVerify(source, expectedOutput: @"
Class1`1[T]
Class2`2[T,U]");
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Main", @"{
// Code size 31 (0x1f)
.maxstack 1
IL_0000: ldtoken ""Class1<T>""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: call ""void System.Console.WriteLine(object)""
IL_000f: ldtoken ""Class2<T, U>""
IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0019: call ""void System.Console.WriteLine(object)""
IL_001e: ret
}");
}
[WorkItem(542581, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542581")]
[Fact]
public void TestTypeofInheritedNestedTypeThroughUnboundGeneric_01()
{
var source = @"
using System;
class D<T> : C, I1, I2<T, int> { }
interface I1 { }
interface I2<T, U> { }
class F<T> { public class E {} }
class G<T> : F<T>, I1, I2<T, int> { }
class H<T, U> { public class E {} }
class K<T> : H<T, int>{ }
class C
{
public class E { }
static void Main()
{
Console.WriteLine(typeof(D<>.E));
Console.WriteLine(typeof(D<>).BaseType);
var interfaces = typeof(D<>).GetInterfaces();
Console.WriteLine(interfaces[0]);
Console.WriteLine(interfaces[1]);
Console.WriteLine(typeof(G<>.E));
Console.WriteLine(typeof(G<>).BaseType);
interfaces = typeof(G<>).GetInterfaces();
Console.WriteLine(interfaces[0]);
Console.WriteLine(interfaces[1]);
Console.WriteLine(typeof(K<>.E));
Console.WriteLine(typeof(K<>).BaseType);
}
}";
var expected = @"C+E
C
I1
I2`2[T,System.Int32]
F`1+E[T]
F`1[T]
I1
I2`2[T,System.Int32]
H`2+E[T,U]
H`2[T,System.Int32]";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[WorkItem(542581, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542581")]
[WorkItem(9850, "https://github.com/dotnet/roslyn/issues/9850")]
[Fact]
public void TestTypeofInheritedNestedTypeThroughUnboundGeneric_02()
{
var source = @"
using System;
class C
{
public class E { }
public class E<V> { }
static void Main()
{
var t1 = typeof(D<>.E);
Console.WriteLine(t1);
var t2 = typeof(F<>.E);
var t3 = typeof(G<>.E);
Console.WriteLine(t2);
Console.WriteLine(t3);
Console.WriteLine(t2.Equals(t3));
var t4 = typeof(D<>.E<>);
Console.WriteLine(t4);
var t5 = typeof(F<>.E<>);
var t6 = typeof(G<>.E<>);
Console.WriteLine(t5);
Console.WriteLine(t6);
Console.WriteLine(t5.Equals(t6));
}
}
class C<U>
{
public class E { }
public class E<V> { }
}
class D<T> : C { }
class F<T> : C<T> { }
class G<T> : C<int> { }
";
var expected = @"C+E
C`1+E[U]
C`1+E[U]
True
C+E`1[V]
C`1+E`1[U,V]
C`1+E`1[U,V]
True";
var comp = CompileAndVerify(source, expectedOutput: expected);
comp.VerifyDiagnostics();
}
[WorkItem(542581, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542581")]
[Fact]
public void TestTypeofInheritedNestedTypeThroughUnboundGeneric_Attribute()
{
var source = @"
using System;
[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
class TestAttribute : Attribute { public TestAttribute(System.Type type){} }
class D<T> : C, I1, I2<T, int> { }
interface I1 { }
interface I2<T, U> { }
class F<T> { public class E {} }
class G<T> : F<T>, I1, I2<T, int> { }
class H<T, U> { public class E {} }
class K<T> : H<T, int>{ }
[TestAttribute(typeof(D<>))]
[TestAttribute(typeof(D<>.E))]
[TestAttribute(typeof(G<>))]
[TestAttribute(typeof(G<>.E))]
[TestAttribute(typeof(K<>))]
[TestAttribute(typeof(K<>.E))]
class C
{
public class E { }
static void Main()
{
typeof(C).GetCustomAttributes(false);
}
}";
var comp = CompileAndVerify(source, expectedOutput: "");
}
[Fact]
public void TestTypeofArray()
{
var source = @"
class Class1<T> { }
class Program
{
static void Print<U>()
{
System.Console.WriteLine(typeof(int[]));
System.Console.WriteLine(typeof(int[,]));
System.Console.WriteLine(typeof(int[][]));
System.Console.WriteLine(typeof(U[]));
System.Console.WriteLine(typeof(Class1<U>[]));
System.Console.WriteLine(typeof(Class1<int>[]));
}
static void Main()
{
Print<long>();
}
}";
var comp = CompileAndVerify(source, expectedOutput: @"
System.Int32[]
System.Int32[,]
System.Int32[][]
System.Int64[]
Class1`1[System.Int64][]
Class1`1[System.Int32][]");
comp.VerifyDiagnostics();
comp.VerifyIL("Program.Print<U>", @"{
// Code size 91 (0x5b)
.maxstack 1
IL_0000: ldtoken ""int[]""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: call ""void System.Console.WriteLine(object)""
IL_000f: ldtoken ""int[,]""
IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0019: call ""void System.Console.WriteLine(object)""
IL_001e: ldtoken ""int[][]""
IL_0023: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0028: call ""void System.Console.WriteLine(object)""
IL_002d: ldtoken ""U[]""
IL_0032: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0037: call ""void System.Console.WriteLine(object)""
IL_003c: ldtoken ""Class1<U>[]""
IL_0041: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0046: call ""void System.Console.WriteLine(object)""
IL_004b: ldtoken ""Class1<int>[]""
IL_0050: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0055: call ""void System.Console.WriteLine(object)""
IL_005a: ret
}");
}
[Fact]
public void TestTypeofNested()
{
var source = @"
class Outer<T>
{
public static void Print()
{
System.Console.WriteLine(typeof(Inner<>));
System.Console.WriteLine(typeof(Inner<T>));
System.Console.WriteLine(typeof(Inner<int>));
System.Console.WriteLine(typeof(Outer<>.Inner<>));
// System.Console.WriteLine(typeof(Outer<>.Inner<T>)); //CS7003
// System.Console.WriteLine(typeof(Outer<>.Inner<int>)); //CS7003
// System.Console.WriteLine(typeof(Outer<T>.Inner<>)); //CS7003
System.Console.WriteLine(typeof(Outer<T>.Inner<T>));
System.Console.WriteLine(typeof(Outer<T>.Inner<int>));
// System.Console.WriteLine(typeof(Outer<int>.Inner<>)); //CS7003
System.Console.WriteLine(typeof(Outer<int>.Inner<T>));
System.Console.WriteLine(typeof(Outer<int>.Inner<int>));
}
class Inner<U> { }
}
class Program
{
static void Main()
{
Outer<long>.Print();
}
}";
var comp = CompileAndVerify(source, expectedOutput: @"
Outer`1+Inner`1[T,U]
Outer`1+Inner`1[System.Int64,System.Int64]
Outer`1+Inner`1[System.Int64,System.Int32]
Outer`1+Inner`1[T,U]
Outer`1+Inner`1[System.Int64,System.Int64]
Outer`1+Inner`1[System.Int64,System.Int32]
Outer`1+Inner`1[System.Int32,System.Int64]
Outer`1+Inner`1[System.Int32,System.Int32]");
comp.VerifyDiagnostics();
comp.VerifyIL("Outer<T>.Print", @"{
// Code size 121 (0x79)
.maxstack 1
IL_0000: ldtoken ""Outer<T>.Inner<U>""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: call ""void System.Console.WriteLine(object)""
IL_000f: ldtoken ""Outer<T>.Inner<T>""
IL_0014: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0019: call ""void System.Console.WriteLine(object)""
IL_001e: ldtoken ""Outer<T>.Inner<int>""
IL_0023: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0028: call ""void System.Console.WriteLine(object)""
IL_002d: ldtoken ""Outer<T>.Inner<U>""
IL_0032: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0037: call ""void System.Console.WriteLine(object)""
IL_003c: ldtoken ""Outer<T>.Inner<T>""
IL_0041: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0046: call ""void System.Console.WriteLine(object)""
IL_004b: ldtoken ""Outer<T>.Inner<int>""
IL_0050: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0055: call ""void System.Console.WriteLine(object)""
IL_005a: ldtoken ""Outer<int>.Inner<T>""
IL_005f: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0064: call ""void System.Console.WriteLine(object)""
IL_0069: ldtoken ""Outer<int>.Inner<int>""
IL_006e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0073: call ""void System.Console.WriteLine(object)""
IL_0078: ret
}");
}
[Fact]
public void TestTypeofInLambda()
{
var source = @"
using System;
public class Outer<T>
{
public class Inner<U>
{
public Action Method<V>(V v)
{
return () =>
{
Console.WriteLine(v);
Console.WriteLine(typeof(T));
Console.WriteLine(typeof(U));
Console.WriteLine(typeof(V));
Console.WriteLine(typeof(Outer<>));
Console.WriteLine(typeof(Outer<T>));
Console.WriteLine(typeof(Outer<U>));
Console.WriteLine(typeof(Outer<V>));
Console.WriteLine(typeof(Inner<>));
Console.WriteLine(typeof(Inner<T>));
Console.WriteLine(typeof(Inner<U>));
Console.WriteLine(typeof(Inner<V>));
};
}
}
}
class Program
{
static void Main()
{
Action a = new Outer<int>.Inner<char>().Method<byte>(1);
a();
}
}";
var comp = CompileAndVerify(source, expectedOutput: @"
1
System.Int32
System.Char
System.Byte
Outer`1[T]
Outer`1[System.Int32]
Outer`1[System.Char]
Outer`1[System.Byte]
Outer`1+Inner`1[T,U]
Outer`1+Inner`1[System.Int32,System.Int32]
Outer`1+Inner`1[System.Int32,System.Char]
Outer`1+Inner`1[System.Int32,System.Byte]");
comp.VerifyDiagnostics();
}
[WorkItem(541600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541600")]
[Fact]
public void TestTypeOfAlias4TypeMemberOfGeneric()
{
var source = @"
using System;
using MyTestClass = TestClass<string>;
public class TestClass<T>
{
public enum TestEnum
{
First = 0,
}
}
public class mem178
{
public static int Main()
{
Console.Write(typeof(MyTestClass.TestEnum));
return 0;
}
}
";
CompileAndVerify(source, expectedOutput: @"TestClass`1+TestEnum[System.String]");
}
[WorkItem(541618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541618")]
[Fact]
public void TestTypeOfAlias5TypeMemberOfGeneric()
{
var source = @"
using OuterOfString = Outer<string>;
using OuterOfInt = Outer<int>;
public class Outer<T>
{
public class Inner<U> { }
}
public class Program
{
public static void Main()
{
System.Console.WriteLine(typeof(OuterOfString.Inner<>) == typeof(OuterOfInt.Inner<>));
}
}
";
// NOTE: this is the Dev10 output. Change to false if we decide to take a breaking change.
CompileAndVerify(source, expectedOutput: @"True");
}
}
}
| -1 |
|
dotnet/roslyn | 55,408 | Update package references | CyrusNajmabadi | 2021-08-04T19:12:45Z | 2021-08-04T22:34:08Z | 967cf7cf7be8478cce7cda728217eab8504f2863 | d41ae79bb1a3f0deb2de2f3d67c976f795da9563 | Update package references. | ./src/VisualStudio/Core/Impl/CodeModel/Collections/NodeSnapshot.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections
{
internal class NodeSnapshot : Snapshot
{
private readonly CodeModelState _state;
private readonly ComHandle<EnvDTE.FileCodeModel, FileCodeModel> _fileCodeModel;
private readonly SyntaxNode _parentNode;
private readonly AbstractCodeElement _parentElement;
private readonly ImmutableArray<SyntaxNode> _nodes;
public NodeSnapshot(
CodeModelState state,
ComHandle<EnvDTE.FileCodeModel, FileCodeModel> fileCodeModel,
SyntaxNode parentNode,
AbstractCodeElement parentElement,
ImmutableArray<SyntaxNode> nodes)
{
_state = state;
_fileCodeModel = fileCodeModel;
_parentNode = parentNode;
_parentElement = parentElement;
_nodes = nodes;
}
private ICodeModelService CodeModelService
{
get { return _state.CodeModelService; }
}
private FileCodeModel FileCodeModel
{
get { return _fileCodeModel.Object; }
}
private EnvDTE.CodeElement CreateCodeOptionsStatement(SyntaxNode node)
{
this.CodeModelService.GetOptionNameAndOrdinal(_parentNode, node, out var name, out var ordinal);
return CodeOptionsStatement.Create(_state, this.FileCodeModel, name, ordinal);
}
private EnvDTE.CodeElement CreateCodeImport(SyntaxNode node)
{
var name = this.CodeModelService.GetImportNamespaceOrType(node);
return CodeImport.Create(_state, this.FileCodeModel, _parentElement, name);
}
private EnvDTE.CodeElement CreateCodeAttribute(SyntaxNode node)
{
this.CodeModelService.GetAttributeNameAndOrdinal(_parentNode, node, out var name, out var ordinal);
return (EnvDTE.CodeElement)CodeAttribute.Create(_state, this.FileCodeModel, _parentElement, name, ordinal);
}
private EnvDTE.CodeElement CreateCodeParameter(SyntaxNode node)
{
Debug.Assert(_parentElement is AbstractCodeMember, "Parameters should always have an associated member!");
var name = this.CodeModelService.GetParameterName(node);
return (EnvDTE.CodeElement)CodeParameter.Create(_state, (AbstractCodeMember)_parentElement, name);
}
public override int Count
{
get { return _nodes.Length; }
}
public override EnvDTE.CodeElement this[int index]
{
get
{
if (index < 0 || index >= _nodes.Length)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
var node = _nodes[index];
if (this.CodeModelService.IsOptionNode(node))
{
return CreateCodeOptionsStatement(node);
}
else if (this.CodeModelService.IsImportNode(node))
{
return CreateCodeImport(node);
}
else if (this.CodeModelService.IsAttributeNode(node))
{
return CreateCodeAttribute(node);
}
else if (this.CodeModelService.IsParameterNode(node))
{
return CreateCodeParameter(node);
}
// The node must be something that the FileCodeModel can create.
return this.FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(node);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections
{
internal class NodeSnapshot : Snapshot
{
private readonly CodeModelState _state;
private readonly ComHandle<EnvDTE.FileCodeModel, FileCodeModel> _fileCodeModel;
private readonly SyntaxNode _parentNode;
private readonly AbstractCodeElement _parentElement;
private readonly ImmutableArray<SyntaxNode> _nodes;
public NodeSnapshot(
CodeModelState state,
ComHandle<EnvDTE.FileCodeModel, FileCodeModel> fileCodeModel,
SyntaxNode parentNode,
AbstractCodeElement parentElement,
ImmutableArray<SyntaxNode> nodes)
{
_state = state;
_fileCodeModel = fileCodeModel;
_parentNode = parentNode;
_parentElement = parentElement;
_nodes = nodes;
}
private ICodeModelService CodeModelService
{
get { return _state.CodeModelService; }
}
private FileCodeModel FileCodeModel
{
get { return _fileCodeModel.Object; }
}
private EnvDTE.CodeElement CreateCodeOptionsStatement(SyntaxNode node)
{
this.CodeModelService.GetOptionNameAndOrdinal(_parentNode, node, out var name, out var ordinal);
return CodeOptionsStatement.Create(_state, this.FileCodeModel, name, ordinal);
}
private EnvDTE.CodeElement CreateCodeImport(SyntaxNode node)
{
var name = this.CodeModelService.GetImportNamespaceOrType(node);
return CodeImport.Create(_state, this.FileCodeModel, _parentElement, name);
}
private EnvDTE.CodeElement CreateCodeAttribute(SyntaxNode node)
{
this.CodeModelService.GetAttributeNameAndOrdinal(_parentNode, node, out var name, out var ordinal);
return (EnvDTE.CodeElement)CodeAttribute.Create(_state, this.FileCodeModel, _parentElement, name, ordinal);
}
private EnvDTE.CodeElement CreateCodeParameter(SyntaxNode node)
{
Debug.Assert(_parentElement is AbstractCodeMember, "Parameters should always have an associated member!");
var name = this.CodeModelService.GetParameterName(node);
return (EnvDTE.CodeElement)CodeParameter.Create(_state, (AbstractCodeMember)_parentElement, name);
}
public override int Count
{
get { return _nodes.Length; }
}
public override EnvDTE.CodeElement this[int index]
{
get
{
if (index < 0 || index >= _nodes.Length)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
var node = _nodes[index];
if (this.CodeModelService.IsOptionNode(node))
{
return CreateCodeOptionsStatement(node);
}
else if (this.CodeModelService.IsImportNode(node))
{
return CreateCodeImport(node);
}
else if (this.CodeModelService.IsAttributeNode(node))
{
return CreateCodeAttribute(node);
}
else if (this.CodeModelService.IsParameterNode(node))
{
return CreateCodeParameter(node);
}
// The node must be something that the FileCodeModel can create.
return this.FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(node);
}
}
}
}
| -1 |
|
dotnet/roslyn | 55,408 | Update package references | CyrusNajmabadi | 2021-08-04T19:12:45Z | 2021-08-04T22:34:08Z | 967cf7cf7be8478cce7cda728217eab8504f2863 | d41ae79bb1a3f0deb2de2f3d67c976f795da9563 | Update package references. | ./src/Analyzers/VisualBasic/CodeFixes/UseCompoundAssignment/VisualBasicUseCompoundAssignmentCodeFixProvider.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.UseCompoundAssignment
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.UseCompoundAssignment
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.UseCompoundAssignment), [Shared]>
Friend Class VisualBasicUseCompoundAssignmentCodeFixProvider
Inherits AbstractUseCompoundAssignmentCodeFixProvider(Of SyntaxKind, AssignmentStatementSyntax, ExpressionSyntax)
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New()
MyBase.New(Kinds)
End Sub
Protected Overrides Function Token(kind As SyntaxKind) As SyntaxToken
Return SyntaxFactory.Token(kind)
End Function
Protected Overrides Function Assignment(
assignmentOpKind As SyntaxKind, left As ExpressionSyntax, syntaxToken As SyntaxToken, right As ExpressionSyntax) As AssignmentStatementSyntax
Return SyntaxFactory.AssignmentStatement(assignmentOpKind, left, syntaxToken, right)
End Function
Protected Overrides Function Increment(left As ExpressionSyntax, postfix As Boolean) As ExpressionSyntax
Throw ExceptionUtilities.Unreachable
End Function
Protected Overrides Function Decrement(left As ExpressionSyntax, postfix As Boolean) As ExpressionSyntax
Throw ExceptionUtilities.Unreachable
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports System.Diagnostics.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.UseCompoundAssignment
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.UseCompoundAssignment
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.UseCompoundAssignment), [Shared]>
Friend Class VisualBasicUseCompoundAssignmentCodeFixProvider
Inherits AbstractUseCompoundAssignmentCodeFixProvider(Of SyntaxKind, AssignmentStatementSyntax, ExpressionSyntax)
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New()
MyBase.New(Kinds)
End Sub
Protected Overrides Function Token(kind As SyntaxKind) As SyntaxToken
Return SyntaxFactory.Token(kind)
End Function
Protected Overrides Function Assignment(
assignmentOpKind As SyntaxKind, left As ExpressionSyntax, syntaxToken As SyntaxToken, right As ExpressionSyntax) As AssignmentStatementSyntax
Return SyntaxFactory.AssignmentStatement(assignmentOpKind, left, syntaxToken, right)
End Function
Protected Overrides Function Increment(left As ExpressionSyntax, postfix As Boolean) As ExpressionSyntax
Throw ExceptionUtilities.Unreachable
End Function
Protected Overrides Function Decrement(left As ExpressionSyntax, postfix As Boolean) As ExpressionSyntax
Throw ExceptionUtilities.Unreachable
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,408 | Update package references | CyrusNajmabadi | 2021-08-04T19:12:45Z | 2021-08-04T22:34:08Z | 967cf7cf7be8478cce7cda728217eab8504f2863 | d41ae79bb1a3f0deb2de2f3d67c976f795da9563 | Update package references. | ./src/Features/Core/Portable/CodeCleanup/AbstractCodeCleanupService.cs | // Licensed to the .NET Foundation under one or more 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.CodeFixes;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.RemoveUnnecessaryImports;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeCleanup
{
internal abstract class AbstractCodeCleanupService : ICodeCleanupService
{
private readonly ICodeFixService _codeFixService;
protected AbstractCodeCleanupService(ICodeFixService codeFixService)
{
_codeFixService = codeFixService;
}
protected abstract string OrganizeImportsDescription { get; }
protected abstract ImmutableArray<DiagnosticSet> GetDiagnosticSets();
public async Task<Document> CleanupAsync(
Document document,
EnabledDiagnosticOptions enabledDiagnostics,
IProgressTracker progressTracker,
CancellationToken cancellationToken)
{
// add one item for the 'format' action we'll do last
if (enabledDiagnostics.FormatDocument)
{
progressTracker.AddItems(1);
}
// and one for 'remove/sort usings' if we're going to run that.
var organizeUsings = enabledDiagnostics.OrganizeUsings.IsRemoveUnusedImportEnabled ||
enabledDiagnostics.OrganizeUsings.IsSortImportsEnabled;
if (organizeUsings)
{
progressTracker.AddItems(1);
}
document = await ApplyCodeFixesAsync(
document, enabledDiagnostics.Diagnostics, progressTracker, cancellationToken).ConfigureAwait(false);
// do the remove usings after code fix, as code fix might remove some code which can results in unused usings.
if (organizeUsings)
{
progressTracker.Description = this.OrganizeImportsDescription;
document = await RemoveSortUsingsAsync(
document, enabledDiagnostics.OrganizeUsings, cancellationToken).ConfigureAwait(false);
progressTracker.ItemCompleted();
}
if (enabledDiagnostics.FormatDocument)
{
progressTracker.Description = FeaturesResources.Formatting_document;
using (Logger.LogBlock(FunctionId.CodeCleanup_Format, cancellationToken))
{
document = await Formatter.FormatAsync(document, cancellationToken: cancellationToken).ConfigureAwait(false);
progressTracker.ItemCompleted();
}
}
return document;
}
private static async Task<Document> RemoveSortUsingsAsync(
Document document, OrganizeUsingsSet organizeUsingsSet, CancellationToken cancellationToken)
{
if (organizeUsingsSet.IsRemoveUnusedImportEnabled)
{
var removeUsingsService = document.GetLanguageService<IRemoveUnnecessaryImportsService>();
if (removeUsingsService != null)
{
using (Logger.LogBlock(FunctionId.CodeCleanup_RemoveUnusedImports, cancellationToken))
{
document = await removeUsingsService.RemoveUnnecessaryImportsAsync(document, cancellationToken).ConfigureAwait(false);
}
}
}
if (organizeUsingsSet.IsSortImportsEnabled)
{
using (Logger.LogBlock(FunctionId.CodeCleanup_SortImports, cancellationToken))
{
document = await Formatter.OrganizeImportsAsync(document, cancellationToken).ConfigureAwait(false);
}
}
return document;
}
private async Task<Document> ApplyCodeFixesAsync(
Document document, ImmutableArray<DiagnosticSet> enabledDiagnosticSets,
IProgressTracker progressTracker, CancellationToken cancellationToken)
{
// Add a progress item for each enabled option we're going to fixup.
progressTracker.AddItems(enabledDiagnosticSets.Length);
foreach (var diagnosticSet in enabledDiagnosticSets)
{
cancellationToken.ThrowIfCancellationRequested();
progressTracker.Description = diagnosticSet.Description;
document = await ApplyCodeFixesForSpecificDiagnosticIdsAsync(
document, diagnosticSet.DiagnosticIds, progressTracker, cancellationToken).ConfigureAwait(false);
// Mark this option as being completed.
progressTracker.ItemCompleted();
}
return document;
}
private async Task<Document> ApplyCodeFixesForSpecificDiagnosticIdsAsync(
Document document, ImmutableArray<string> diagnosticIds, IProgressTracker progressTracker, CancellationToken cancellationToken)
{
foreach (var diagnosticId in diagnosticIds)
{
using (Logger.LogBlock(FunctionId.CodeCleanup_ApplyCodeFixesAsync, diagnosticId, cancellationToken))
{
document = await _codeFixService.ApplyCodeFixesForSpecificDiagnosticIdAsync(
document, diagnosticId, progressTracker, cancellationToken).ConfigureAwait(false);
}
}
return document;
}
public EnabledDiagnosticOptions GetAllDiagnostics()
=> new EnabledDiagnosticOptions(formatDocument: true, GetDiagnosticSets(), new OrganizeUsingsSet(isRemoveUnusedImportEnabled: true, isSortImportsEnabled: 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.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.RemoveUnnecessaryImports;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeCleanup
{
internal abstract class AbstractCodeCleanupService : ICodeCleanupService
{
private readonly ICodeFixService _codeFixService;
protected AbstractCodeCleanupService(ICodeFixService codeFixService)
{
_codeFixService = codeFixService;
}
protected abstract string OrganizeImportsDescription { get; }
protected abstract ImmutableArray<DiagnosticSet> GetDiagnosticSets();
public async Task<Document> CleanupAsync(
Document document,
EnabledDiagnosticOptions enabledDiagnostics,
IProgressTracker progressTracker,
CancellationToken cancellationToken)
{
// add one item for the 'format' action we'll do last
if (enabledDiagnostics.FormatDocument)
{
progressTracker.AddItems(1);
}
// and one for 'remove/sort usings' if we're going to run that.
var organizeUsings = enabledDiagnostics.OrganizeUsings.IsRemoveUnusedImportEnabled ||
enabledDiagnostics.OrganizeUsings.IsSortImportsEnabled;
if (organizeUsings)
{
progressTracker.AddItems(1);
}
document = await ApplyCodeFixesAsync(
document, enabledDiagnostics.Diagnostics, progressTracker, cancellationToken).ConfigureAwait(false);
// do the remove usings after code fix, as code fix might remove some code which can results in unused usings.
if (organizeUsings)
{
progressTracker.Description = this.OrganizeImportsDescription;
document = await RemoveSortUsingsAsync(
document, enabledDiagnostics.OrganizeUsings, cancellationToken).ConfigureAwait(false);
progressTracker.ItemCompleted();
}
if (enabledDiagnostics.FormatDocument)
{
progressTracker.Description = FeaturesResources.Formatting_document;
using (Logger.LogBlock(FunctionId.CodeCleanup_Format, cancellationToken))
{
document = await Formatter.FormatAsync(document, cancellationToken: cancellationToken).ConfigureAwait(false);
progressTracker.ItemCompleted();
}
}
return document;
}
private static async Task<Document> RemoveSortUsingsAsync(
Document document, OrganizeUsingsSet organizeUsingsSet, CancellationToken cancellationToken)
{
if (organizeUsingsSet.IsRemoveUnusedImportEnabled)
{
var removeUsingsService = document.GetLanguageService<IRemoveUnnecessaryImportsService>();
if (removeUsingsService != null)
{
using (Logger.LogBlock(FunctionId.CodeCleanup_RemoveUnusedImports, cancellationToken))
{
document = await removeUsingsService.RemoveUnnecessaryImportsAsync(document, cancellationToken).ConfigureAwait(false);
}
}
}
if (organizeUsingsSet.IsSortImportsEnabled)
{
using (Logger.LogBlock(FunctionId.CodeCleanup_SortImports, cancellationToken))
{
document = await Formatter.OrganizeImportsAsync(document, cancellationToken).ConfigureAwait(false);
}
}
return document;
}
private async Task<Document> ApplyCodeFixesAsync(
Document document, ImmutableArray<DiagnosticSet> enabledDiagnosticSets,
IProgressTracker progressTracker, CancellationToken cancellationToken)
{
// Add a progress item for each enabled option we're going to fixup.
progressTracker.AddItems(enabledDiagnosticSets.Length);
foreach (var diagnosticSet in enabledDiagnosticSets)
{
cancellationToken.ThrowIfCancellationRequested();
progressTracker.Description = diagnosticSet.Description;
document = await ApplyCodeFixesForSpecificDiagnosticIdsAsync(
document, diagnosticSet.DiagnosticIds, progressTracker, cancellationToken).ConfigureAwait(false);
// Mark this option as being completed.
progressTracker.ItemCompleted();
}
return document;
}
private async Task<Document> ApplyCodeFixesForSpecificDiagnosticIdsAsync(
Document document, ImmutableArray<string> diagnosticIds, IProgressTracker progressTracker, CancellationToken cancellationToken)
{
foreach (var diagnosticId in diagnosticIds)
{
using (Logger.LogBlock(FunctionId.CodeCleanup_ApplyCodeFixesAsync, diagnosticId, cancellationToken))
{
document = await _codeFixService.ApplyCodeFixesForSpecificDiagnosticIdAsync(
document, diagnosticId, progressTracker, cancellationToken).ConfigureAwait(false);
}
}
return document;
}
public EnabledDiagnosticOptions GetAllDiagnostics()
=> new EnabledDiagnosticOptions(formatDocument: true, GetDiagnosticSets(), new OrganizeUsingsSet(isRemoveUnusedImportEnabled: true, isSortImportsEnabled: true));
}
}
| -1 |
|
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Compilers/CSharp/Test/Emit/Emit/EditAndContinue/EditAndContinueClosureTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
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.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests
{
public class EditAndContinueClosureTests : EditAndContinueTestBase
{
[Fact]
public void MethodToMethodWithClosure()
{
var source0 =
@"delegate object D();
class C
{
static object F(object o)
{
return o;
}
}";
var source1 =
@"delegate object D();
class C
{
static object F(object o)
{
return ((D)(() => o))();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F"), compilation1.GetMember<MethodSymbol>("C.F"))));
using (var md1 = diff1.GetMetadata())
{
var reader1 = md1.Reader;
// Field 'o'
// Methods: 'F', '.ctor', '<F>b__1'
// Type: display class
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(1, TableIndex.NestedClass, EditAndContinueOperation.Default));
}
}
[Fact]
public void MethodWithStaticLambda1()
{
var source0 = MarkedSource(@"
using System;
class C
{
void F()
{
Func<int> x = <N:0>() => 1</N:0>;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
void F()
{
Func<int> x = <N:0>() => 2</N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <F>b__0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithSwitchExpression()
{
var source0 = MarkedSource(@"
using System;
class C
{
int F(object o)
{
<N:0>return o switch
{
int i => new Func<int>(<N:1>() => i + 1</N:1>)(),
_ => 0
}</N:0>;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
int F(object o)
{
<N:0>return o switch
{
int i => new Func<int>(<N:1>() => i + 2</N:1>)(),
_ => 0
}</N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass0_0: {<i>5__2, <F>b__0}",
"C: {<>c__DisplayClass0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var x = Visualize(generation0.OriginalMetadata, md1);
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithNestedSwitchExpression()
{
var source0 = MarkedSource(@"
using System;
class C
{
int F(object o)
<N:0>{
<N:1>return o switch
{
int i => new Func<int>(<N:2>() => i + (int)o + i switch
{
1 => 1,
_ => new Func<int>(<N:3>() => (int)o + 1</N:3>)()
}</N:2>)(),
_ => 0
}</N:1>;
}</N:0>
}");
var source1 = MarkedSource(@"
using System;
class C
{
int F(object o)
<N:0>{
<N:1>return o switch
{
int i => new Func<int>(<N:2>() => i + (int)o + i switch
{
1 => 1,
_ => new Func<int>(<N:3>() => (int)o + 2</N:3>)()
}</N:2>)(),
_ => 0
}</N:1>;
}</N:0>
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0, <>c__DisplayClass0_1}",
"C.<>c__DisplayClass0_1: {<i>5__2, CS$<>8__locals2, <F>b__0}",
"C.<>c__DisplayClass0_0: {o, <>9__1, <F>b__1}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithStaticLocalFunction1()
{
var source0 = MarkedSource(@"
using System;
class C
{
void F()
{
<N:0>int x() => 1;</N:0>
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
void F()
{
<N:0>int x() => 2;</N:0>
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<F>g__x|0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithStaticLocalFunction_ChangeStatic()
{
var source0 = MarkedSource(@"
using System;
class C
{
void F()
{
<N:0>int x() => 1;</N:0>
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
void F()
{
<N:0>static int x() => 1;</N:0>
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var reader0 = md0.MetadataReader;
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<F>g__x|0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var localFunction0 = testData0.GetMethodData("C.<F>g__x|0_0").Method;
Assert.True(((Symbol)localFunction0).IsStatic);
var localFunction1 = diff1.TestData.GetMethodData("C.<F>g__x|0_0").Method;
Assert.True(((Symbol)localFunction1).IsStatic);
}
[Fact]
public void MethodWithStaticLambdaGeneric1()
{
var source0 = MarkedSource(@"
using System;
class C
{
void F<T>()
{
Func<T> x = <N:0>() => default(T)</N:0>;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
void F<T>()
{
Func<T> x = <N:0>() => default(T)</N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<>c__0}",
"C.<>c__0<T>: {<>9__0_0, <F>b__0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithStaticLocalFunctionGeneric1()
{
var source0 = MarkedSource(@"
using System;
class C
{
void F<T>()
{
<N:0>T x() => default(T);</N:0>
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
void F<T>()
{
<N:0>T x() => default(T);</N:0>
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<F>g__x|0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithThisOnlyClosure1()
{
var source0 = MarkedSource(@"
using System;
class C
{
int F(int a)
{
Func<int> x = <N:0>() => F(1)</N:0>;
return 1;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
int F(int a)
{
Func<int> x = <N:0>() => F(2)</N:0>;
return 2;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<F>b__0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithThisOnlyLocalFunctionClosure1()
{
var source0 = MarkedSource(@"
using System;
class C
{
int F(int a)
{
<N:0>int x() => F(1);</N:0>
return 1;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
int F(int a)
{
<N:0>int x() => F(2);</N:0>
return 2;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<F>g__x|0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithClosure1()
{
var source0 = MarkedSource(@"
using System;
class C
{
int F(int a)
<N:0>{</N:0>
Func<int> x = <N:1>() => F(a + 1)</N:1>;
return 1;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
int F(int a)
<N:0>{</N:0>
Func<int> x = <N:1>() => F(a + 2)</N:1>;
return 2;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass0_0: {<>4__this, a, <F>b__0}",
"C: {<>c__DisplayClass0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithNullable_AddingNullCheck()
{
var source0 = MarkedSource(@"
using System;
#nullable enable
class C
{
static T id<T>(T t) => t;
static T G<T>(Func<T> f) => f();
public void F(string? x)
<N:0>{</N:0>
var <N:1>y1</N:1> = new { A = id(x) };
var <N:2>y2</N:2> = G(<N:3>() => new { B = id(x) }</N:3>);
var <N:4>z</N:4> = G(<N:5>() => y1.A + y2.B</N:5>);
}
}", options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9));
var source1 = MarkedSource(@"
using System;
#nullable enable
class C
{
static T id<T>(T t) => t;
static T G<T>(Func<T> f) => f();
public void F(string? x)
<N:0>{</N:0>
if (x is null) throw new Exception();
var <N:1>y1</N:1> = new { A = id(x) };
var <N:2>y2</N:2> = G(<N:3>() => new { B = id(x) }</N:3>);
var <N:4>z</N:4> = G(<N:5>() => y1.A + y2.B</N:5>);
}
}", options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9));
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"Microsoft: {CodeAnalysis}",
"System.Runtime: {CompilerServices, CompilerServices}",
"<global namespace>: {Microsoft, System, System}",
"C: {<>c__DisplayClass2_0}",
"System: {Runtime, Runtime}",
"C.<>c__DisplayClass2_0: {x, y1, y2, <F>b__0, <F>b__1}",
"<>f__AnonymousType1<<B>j__TPar>: {Equals, GetHashCode, ToString}",
"System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.<>c__DisplayClass2_0.<F>b__1()", @"
{
// Code size 28 (0x1c)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""<anonymous type: string A> C.<>c__DisplayClass2_0.y1""
IL_0006: callvirt ""string <>f__AnonymousType0<string>.A.get""
IL_000b: ldarg.0
IL_000c: ldfld ""<anonymous type: string B> C.<>c__DisplayClass2_0.y2""
IL_0011: callvirt ""string <>f__AnonymousType1<string>.B.get""
IL_0016: call ""string string.Concat(string, string)""
IL_001b: ret
}");
diff1.VerifyIL("C.<>c__DisplayClass2_0.<F>b__0()", @"
{
// Code size 17 (0x11)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""string C.<>c__DisplayClass2_0.x""
IL_0006: call ""string C.id<string>(string)""
IL_000b: newobj ""<>f__AnonymousType1<string>..ctor(string)""
IL_0010: ret
}");
}
[Fact]
public void MethodWithLocalFunctionClosure1()
{
var source0 = MarkedSource(@"
using System;
class C
{
int F(int a)
<N:0>{</N:0>
<N:1>int x() => F(a + 1);</N:1>
return 1;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
int F(int a)
<N:0>{</N:0>
<N:1>int x() => F(a + 2);</N:1>
return 2;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<F>g__x|0_0, <>c__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {<>4__this, a}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void ConstructorWithClosure1()
{
var source0 = MarkedSource(@"
using System;
class D { public D(Func<int> f) { } }
class C : D
{
<N:0>public C(int a, int b)</N:0>
: base(<N:8>() => a</N:8>)
<N:1>{</N:1>
int c = 0;
Func<int> f1 = <N:2>() => a + 1</N:2>;
Func<int> f2 = <N:3>() => b + 2</N:3>;
Func<int> f3 = <N:4>() => c + 3</N:4>;
Func<int> f4 = <N:5>() => a + b + c</N:5>;
Func<int> f5 = <N:6>() => a + c</N:6>;
Func<int> f6 = <N:7>() => b + c</N:7>;
}
}");
var source1 = MarkedSource(@"
using System;
class D { public D(Func<int> f) { } }
class C : D
{
<N:0>public C(int a, int b)</N:0>
: base(<N:8>() => a * 10</N:8>)
<N:1>{</N:1>
int c = 0;
Func<int> f1 = <N:2>() => a * 10 + 1</N:2>;
Func<int> f2 = <N:3>() => b * 10 + 2</N:3>;
Func<int> f3 = <N:4>() => c * 10 + 3</N:4>;
Func<int> f4 = <N:5>() => a * 10 + b + c</N:5>;
Func<int> f5 = <N:6>() => a * 10 + c</N:6>;
Func<int> f6 = <N:7>() => b * 10 + c</N:7>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var ctor0 = compilation0.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single();
var ctor1 = compilation1.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single();
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0, <>c__DisplayClass0_1}",
"C.<>c__DisplayClass0_0: {a, b, <.ctor>b__0, <.ctor>b__1, <.ctor>b__2}",
"C.<>c__DisplayClass0_1: {c, CS$<>8__locals1, <.ctor>b__3, <.ctor>b__4, <.ctor>b__5, <.ctor>b__6}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void PartialClass()
{
var source0 = MarkedSource(@"
using System;
partial class C
{
Func<int> m1 = <N:0>() => 1</N:0>;
}
partial class C
{
Func<int> m2 = <N:1>() => 1</N:1>;
}
");
var source1 = MarkedSource(@"
using System;
partial class C
{
Func<int> m1 = <N:0>() => 10</N:0>;
}
partial class C
{
Func<int> m2 = <N:1>() => 10</N:1>;
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var ctor0 = compilation0.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single();
var ctor1 = compilation1.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single();
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__2_0, <>9__2_1, <.ctor>b__2_0, <.ctor>b__2_1}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default));
}
[Fact]
public void JoinAndGroupByClauses()
{
var source0 = MarkedSource(@"
using System.Linq;
class C
{
void F()
{
var result = <N:0>from a in new[] { 1, 2, 3 }</N:0>
<N:1>join b in new[] { 5 } on a + 1 equals b - 1</N:1>
<N:2>group</N:2> new { a, b = a + 5 } by new { c = a + 4 } into d
<N:3>select d.Key</N:3>;
}
}");
var source1 = MarkedSource(@"
using System.Linq;
class C
{
void F()
{
var result = <N:0>from a in new[] { 10, 20, 30 }</N:0>
<N:1>join b in new[] { 50 } on a + 10 equals b - 10</N:1>
<N:2>group</N:2> new { a, b = a + 50 } by new { c = a + 40 } into d
<N:3>select d.Key</N:3>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <>9__0_4, <>9__0_5, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3, <F>b__0_4, <F>b__0_5}",
"<>f__AnonymousType1<<c>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <b>j__TPar>: {Equals, GetHashCode, ToString}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates for lambdas:
CheckEncLogDefinitions(reader1,
Row(6, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(16, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(17, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(18, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(19, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(20, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(21, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.Param, EditAndContinueOperation.Default),
Row(7, TableIndex.Param, EditAndContinueOperation.Default),
Row(8, TableIndex.Param, EditAndContinueOperation.Default),
Row(9, TableIndex.Param, EditAndContinueOperation.Default),
Row(10, TableIndex.Param, EditAndContinueOperation.Default),
Row(11, TableIndex.Param, EditAndContinueOperation.Default),
Row(12, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void TransparentIdentifiers_FromClause()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var <N:10>result = <N:0>from a in new[] { 1 }</N:0>
<N:1>from b in <N:9>new[] { 1 }</N:9></N:1>
<N:2>where <N:7>Z(<N:5>() => a</N:5>) > 0</N:7></N:2>
<N:3>where <N:8>Z(<N:6>() => b</N:6>) > 0</N:8></N:3>
<N:4>select a</N:4></N:10>;
}
}");
var source1 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var <N:10>result = <N:0>from a in new[] { 1 }</N:0>
<N:1>from b in <N:9>new[] { 2 }</N:9></N:1>
<N:2>where <N:7>Z(<N:5>() => a</N:5>) > 1</N:7></N:2>
<N:3>where <N:8>Z(<N:6>() => b</N:6>) > 2</N:8></N:3>
<N:4>select a</N:4></N:10>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass1_1: {<>h__TransparentIdentifier0, <F>b__6}",
"C.<>c__DisplayClass1_0: {<>h__TransparentIdentifier0, <F>b__5}",
"C.<>c: {<>9__1_0, <>9__1_1, <>9__1_4, <F>b__1_0, <F>b__1_1, <F>b__1_4}",
"C: {<F>b__1_2, <F>b__1_3, <>c__DisplayClass1_0, <>c__DisplayClass1_1, <>c}",
"<>f__AnonymousType0<<a>j__TPar, <b>j__TPar>: {Equals, GetHashCode, ToString}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates for lambdas:
CheckEncLogDefinitions(reader1,
Row(7, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(8, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(9, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(15, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(18, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(19, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(20, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(6, TableIndex.Param, EditAndContinueOperation.Default),
Row(7, TableIndex.Param, EditAndContinueOperation.Default),
Row(8, TableIndex.Param, EditAndContinueOperation.Default),
Row(9, TableIndex.Param, EditAndContinueOperation.Default),
Row(10, TableIndex.Param, EditAndContinueOperation.Default),
Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void TransparentIdentifiers_LetClause()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var result = <N:0>from a in new[] { 1 }</N:0>
<N:1>let b = <N:2>Z(<N:3>() => a</N:3>)</N:2></N:1>
<N:4>select <N:5>a + b</N:5></N:4>;
}
}");
var source1 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var result = <N:0>from a in new[] { 1 }</N:0>
<N:1>let b = <N:2>Z(<N:3>() => a</N:3>) + 1</N:2></N:1>
<N:4>select <N:5>a + b</N:5></N:4>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C.<>c: {<>9__1_1, <F>b__1_1}",
"<>f__AnonymousType0<<a>j__TPar, <b>j__TPar>: {Equals, GetHashCode, ToString}",
"C.<>c__DisplayClass1_0: {a, <F>b__2}",
"C: {<F>b__1_0, <>c__DisplayClass1_0, <>c}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates for lambdas:
CheckEncLogDefinitions(reader1,
Row(6, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(7, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(15, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(6, TableIndex.Param, EditAndContinueOperation.Default),
Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void TransparentIdentifiers_JoinClause()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
public void F()
{
var result = <N:0>from a in <N:1>new[] { 1 }</N:1></N:0>
<N:2>join b in new[] { 3 } on
<N:3>Z(<N:4>() => <N:5>a + 1</N:5></N:4>)</N:3>
equals
<N:6>Z(<N:7>() => <N:8>b - 1</N:8></N:7>)</N:6></N:2>
<N:9>select <N:10>Z(<N:11>() => <N:12>a + b</N:12></N:11>)</N:10></N:9>;
}
}");
var source1 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
public void F()
{
var result = <N:0>from a in <N:1>new[] { 1 }</N:1></N:0>
<N:2>join b in new[] { 3 } on
<N:3>Z(<N:4>() => <N:5>a + 1</N:5></N:4>)</N:3>
equals
<N:6>Z(<N:7>() => <N:8>b - 1</N:8></N:7>)</N:6></N:2>
<N:9>select <N:10>Z(<N:11>() => <N:12>a - b</N:12></N:11>)</N:10></N:9>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass1_1: {b, <F>b__4}",
"C.<>c__DisplayClass1_2: {a, b, <F>b__5}",
"C.<>c__DisplayClass1_0: {a, <F>b__3}",
"C: {<F>b__1_0, <F>b__1_1, <F>b__1_2, <>c__DisplayClass1_0, <>c__DisplayClass1_1, <>c__DisplayClass1_2}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates for lambdas:
CheckEncLogDefinitions(reader1,
Row(6, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(7, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(8, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(9, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void TransparentIdentifiers_JoinIntoClause()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
public void F()
{
var result = <N:0>from a in <N:1>new[] { 1 }</N:1></N:0>
<N:2>join b in new[] { 3 } on
<N:3>a + 1</N:3> equals <N:4>b - 1</N:4>
into g</N:2>
<N:5>select <N:6>Z(<N:7>() => <N:8>g.First()</N:8></N:7>)</N:6></N:5>;
}
}");
var source1 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
public void F()
{
var result = <N:0>from a in <N:1>new[] { 1 }</N:1></N:0>
<N:2>join b in new[] { 3 } on
<N:3>a + 1</N:3> equals <N:4>b - 1</N:4>
into g</N:2>
<N:5>select <N:6>Z(<N:7>() => <N:8>g.Last()</N:8></N:7>)</N:6></N:5>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<F>b__1_2, <>c__DisplayClass1_0, <>c}",
"C.<>c: {<>9__1_0, <>9__1_1, <F>b__1_0, <F>b__1_1}",
"C.<>c__DisplayClass1_0: {g, <F>b__3}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates for lambdas:
CheckEncLogDefinitions(reader1,
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(5, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void TransparentIdentifiers_QueryContinuation()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
public void F()
{
var result = <N:0>from a in <N:1>new[] { 1 }</N:1></N:0>
<N:2>group a by <N:3>a + 1</N:3></N:2>
<N:4>into g
<N:5>select <N:6>Z(<N:7>() => <N:8>g.First()</N:8></N:7>)</N:6></N:5></N:4>;
}
}");
var source1 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
public void F()
{
var result = <N:0>from a in <N:1>new[] { 1 }</N:1></N:0>
<N:2>group a by <N:3>a + 1</N:3></N:2>
<N:4>into g
<N:5>select <N:6>Z(<N:7>() => <N:8>g.Last()</N:8></N:7>)</N:6></N:5></N:4>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<F>b__1_1, <>c__DisplayClass1_0, <>c}",
"C.<>c: {<>9__1_0, <F>b__1_0}",
"C.<>c__DisplayClass1_0: {g, <F>b__2}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates for lambdas:
CheckEncLogDefinitions(reader1,
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(5, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void Lambdas_UpdateAfterAdd()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(null);
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + 1</N:0>);
}
}");
var source2 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + 2</N:0>);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// new lambda "<F>b__0#1" has been added:
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0#1, <F>b__0#1}");
// added:
diff1.VerifyIL("C.<>c.<F>b__0#1", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0#1, <F>b__0#1}");
// updated:
diff2.VerifyIL("C.<>c.<F>b__0#1", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.2
IL_0002: add
IL_0003: ret
}
");
}
[Fact]
public void LocalFunctions_UpdateAfterAdd()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(null);
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
<N:0>int f(int a) => a + 1;</N:0>
return G(f);
}
}");
var source2 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
<N:0>int f(int a) => a + 2;</N:0>
return G(f);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// new lambda "<F>b__0#1" has been added:
diff1.VerifySynthesizedMembers(
"C: {<F>g__f|0#1}");
// added:
diff1.VerifyIL("C.<F>g__f|0#1(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<F>g__f|0#1}");
// updated:
diff2.VerifyIL("C.<F>g__f|0#1(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.2
IL_0002: add
IL_0003: ret
}
");
}
[Fact]
public void LocalFunctions_UpdateAfterAdd_NoDelegatePassing()
{
var source0 = MarkedSource(@"
using System;
class C
{
static object F()
{
return 0;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static object F()
{
<N:0>int f(int a) => a + 1;</N:0>
return 1;
}
}");
var source2 = MarkedSource(@"
using System;
class C
{
static object F()
{
<N:0>int f(int a) => a + 2;</N:0>
return 2;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// new lambda "<F>b__0#1" has been added:
diff1.VerifySynthesizedMembers(
"C: {<F>g__f|0#1}");
// added:
diff1.VerifyIL("C.<F>g__f|0#1(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<F>g__f|0#1}");
// updated:
diff2.VerifyIL("C.<F>g__f|0#1(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.2
IL_0002: add
IL_0003: ret
}
");
}
[Fact]
public void LambdasMultipleGenerations1()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + 1</N:0>);
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + 2</N:0>) + G(<N:1>b => b + 20</N:1>);
}
}");
var source2 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + 3</N:0>) + G(<N:1>b => b + 30</N:1>) + G(<N:2>c => c + 0x300</N:2>);
}
}");
var source3 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + 4</N:0>) + G(<N:1>b => b + 40</N:1>) + G(<N:2>c => c + 0x400</N:2>);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var compilation3 = compilation2.WithSource(source3.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var f3 = compilation3.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// new lambda "<F>b__1_1#1" has been added:
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__1_0, <>9__1_1#1, <F>b__1_0, <F>b__1_1#1}");
// updated:
diff1.VerifyIL("C.<>c.<F>b__1_0", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.2
IL_0002: add
IL_0003: ret
}
");
// added:
diff1.VerifyIL("C.<>c.<F>b__1_1#1", @"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.s 20
IL_0003: add
IL_0004: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
// new lambda "<F>b__1_2#2" has been added:
diff2.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__1_0, <>9__1_1#1, <>9__1_2#2, <F>b__1_0, <F>b__1_1#1, <F>b__1_2#2}");
// updated:
diff2.VerifyIL("C.<>c.<F>b__1_0", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.3
IL_0002: add
IL_0003: ret
}
");
// updated:
diff2.VerifyIL("C.<>c.<F>b__1_1#1", @"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.s 30
IL_0003: add
IL_0004: ret
}
");
// added:
diff2.VerifyIL("C.<>c.<F>b__1_2#2", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4 0x300
IL_0006: add
IL_0007: ret
}
");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f2, f3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables: true)));
diff3.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__1_0, <>9__1_1#1, <>9__1_2#2, <F>b__1_0, <F>b__1_1#1, <F>b__1_2#2}");
// updated:
diff3.VerifyIL("C.<>c.<F>b__1_0", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.4
IL_0002: add
IL_0003: ret
}
");
// updated:
diff3.VerifyIL("C.<>c.<F>b__1_1#1", @"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.s 40
IL_0003: add
IL_0004: ret
}
");
// updated:
diff3.VerifyIL("C.<>c.<F>b__1_2#2", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4 0x400
IL_0006: add
IL_0007: ret
}
");
}
[Fact]
public void LocalFunctionsMultipleGenerations1()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
<N:0>int f1(int a) => a + 1;</N:0>
return G(f1);
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
<N:0>int f1(int a) => a + 2;</N:0>
<N:1>int f2(int b) => b + 20;</N:1>
return G(f1) + G(f2);
}
}");
var source2 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
<N:0>int f1(int a) => a + 3;</N:0>
<N:1>int f2(int b) => b + 30;</N:1>
<N:2>int f3(int c) => c + 0x300;</N:2>
return G(f1) + G(f2) + G(f3);
}
}");
var source3 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
<N:0>int f1(int a) => a + 4;</N:0>
<N:1>int f2(int b) => b + 40;</N:1>
<N:2>int f3(int c) => c + 0x400;</N:2>
return G(f1) + G(f2) + G(f3);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var compilation3 = compilation2.WithSource(source3.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var f3 = compilation3.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C: {<F>g__f1|1_0, <F>g__f2|1_1#1}");
// updated:
diff1.VerifyIL("C.<F>g__f1|1_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.2
IL_0002: add
IL_0003: ret
}
");
// added:
diff1.VerifyIL("C.<F>g__f2|1_1#1(int)", @"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 20
IL_0003: add
IL_0004: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<F>g__f1|1_0, <F>g__f2|1_1#1, <F>g__f3|1_2#2}");
// updated:
diff2.VerifyIL("C.<F>g__f1|1_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.3
IL_0002: add
IL_0003: ret
}
");
// updated:
diff2.VerifyIL("C.<F>g__f2|1_1#1(int)", @"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 30
IL_0003: add
IL_0004: ret
}
");
// added:
diff2.VerifyIL("C.<F>g__f3|1_2#2(int)", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4 0x300
IL_0006: add
IL_0007: ret
}
");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f2, f3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables: true)));
diff3.VerifySynthesizedMembers(
"C: {<F>g__f1|1_0, <F>g__f2|1_1#1, <F>g__f3|1_2#2}");
// updated:
diff3.VerifyIL("C.<F>g__f1|1_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.4
IL_0002: add
IL_0003: ret
}
");
// updated:
diff3.VerifyIL("C.<F>g__f2|1_1#1(int)", @"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 40
IL_0003: add
IL_0004: ret
}
");
// updated:
diff3.VerifyIL("C.<F>g__f3|1_2#2(int)", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4 0x400
IL_0006: add
IL_0007: ret
}
");
}
[Fact, WorkItem(2284, "https://github.com/dotnet/roslyn/issues/2284")]
public void LambdasMultipleGenerations2()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
class C
{
private int[] _titles = new int[] { 1, 2 };
Action A;
private void F()
{
// edit 1
// var z = from title in _titles
// where title > 0
// select title;
A += <N:0>() =>
<N:1>{
Console.WriteLine(1);
// edit 2
// Console.WriteLine(2);
}</N:1></N:0>;
}
}");
var source1 = MarkedSource(@"
using System;
using System.Linq;
class C
{
private int[] _titles = new int[] { 1, 2 };
Action A;
private void F()
{
// edit 1
var <N:3>z = from title in _titles
<N:2>where title > 0</N:2>
select title</N:3>;
A += <N:0>() =>
<N:1>{
Console.WriteLine(1);
// edit 2
// Console.WriteLine(2);
}</N:1></N:0>;
}
}");
var source2 = MarkedSource(@"
using System;
using System.Linq;
class C
{
private int[] _titles = new int[] { 1, 2 };
Action A;
private void F()
{
// edit 1
var <N:3>z = from title in _titles
<N:2>where title > 0</N:2>
select title</N:3>;
A += <N:0>() =>
<N:1>{
Console.WriteLine(1);
// edit 2
Console.WriteLine(2);
}</N:1></N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// new lambda "<F>b__2_0#1" has been added:
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__2_0#1, <>9__2_0, <F>b__2_0#1, <F>b__2_0}");
// lambda body unchanged:
diff1.VerifyIL("C.<>c.<F>b__2_0", @"
{
// Code size 9 (0x9)
.maxstack 1
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: call ""void System.Console.WriteLine(int)""
IL_0007: nop
IL_0008: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
// no new members:
diff2.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__2_0#1, <>9__2_0, <F>b__2_0#1, <F>b__2_0}");
// lambda body updated:
diff2.VerifyIL("C.<>c.<F>b__2_0", @"
{
// Code size 16 (0x10)
.maxstack 1
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: call ""void System.Console.WriteLine(int)""
IL_0007: nop
IL_0008: ldc.i4.2
IL_0009: call ""void System.Console.WriteLine(int)""
IL_000e: nop
IL_000f: ret
}");
}
[Fact]
public void UniqueSynthesizedNames1()
{
var source0 = @"
using System;
public class C
{
public int F()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var source1 = @"
using System;
public class C
{
public int F(int x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
public int F()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var source2 = @"
using System;
public class C
{
public int F(int x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
public int F(byte x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
public int F()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A");
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var f_int1 = compilation1.GetMembers("C.F").Single(m => m.ToString() == "C.F(int)");
var f_byte2 = compilation2.GetMembers("C.F").Single(m => m.ToString() == "C.F(byte)");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>c__DisplayClass0_0", "<>c");
CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ".ctor", "<F>b__1", "<F>b__2", ".cctor", ".ctor", "<F>b__0_0");
CheckNames(reader0, reader0.GetFieldDefNames(), "<>4__this", "a", "<>9", "<>9__0_0");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f_int1)));
var reader1 = diff1.GetMetadata().Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>c__DisplayClass0#1_0#1");
CheckNames(new[] { reader0, reader1 }, reader1.GetMethodDefNames(), ".ctor", "F", ".ctor", "<F>b__1#1", "<F>b__2#1", "<F>b__0#1_0#1");
CheckNames(new[] { reader0, reader1 }, reader1.GetFieldDefNames(), "<>4__this", "a", "<>9__0#1_0#1");
diff1.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0#1_0#1, <>c}",
"C.<>c__DisplayClass0#1_0#1: {<>4__this, a, <F>b__1#1, <F>b__2#1}",
"C.<>c: {<>9__0#1_0#1, <F>b__0#1_0#1}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f_byte2)));
var reader2 = diff2.GetMetadata().Reader;
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>c__DisplayClass1#2_0#2");
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetMethodDefNames(), ".ctor", "F", ".ctor", "<F>b__1#2", "<F>b__2#2", "<F>b__1#2_0#2");
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetFieldDefNames(), "<>4__this", "a", "<>9__1#2_0#2");
}
[Fact]
public void UniqueSynthesizedNames1_Generic()
{
var source0 = @"
using System;
public class C
{
public int F<T>()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F<T>());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var source1 = @"
using System;
public class C
{
public int F<T>(int x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F<T>());
var f3 = new Func<int>(() => a);
return 2;
}
public int F<T>()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F<T>());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var source2 = @"
using System;
public class C
{
public int F<T>(int x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F<T>());
var f3 = new Func<int>(() => a);
return 2;
}
public int F<T>(byte x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F<T>());
var f3 = new Func<int>(() => a);
return 2;
}
public int F<T>()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F<T>());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A");
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var f_int1 = compilation1.GetMembers("C.F").Single(m => m.ToString() == "C.F<T>(int)");
var f_byte2 = compilation2.GetMembers("C.F").Single(m => m.ToString() == "C.F<T>(byte)");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>c__DisplayClass0_0`1", "<>c__0`1");
CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ".ctor", "<F>b__1", "<F>b__2", ".cctor", ".ctor", "<F>b__0_0");
CheckNames(reader0, reader0.GetFieldDefNames(), "<>4__this", "a", "<>9", "<>9__0_0");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f_int1)));
var reader1 = diff1.GetMetadata().Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>c__DisplayClass0#1_0#1`1", "<>c__0#1`1");
CheckNames(new[] { reader0, reader1 }, reader1.GetMethodDefNames(), "F", ".ctor", "<F>b__1#1", "<F>b__2#1", ".cctor", ".ctor", "<F>b__0#1_0#1");
CheckNames(new[] { reader0, reader1 }, reader1.GetFieldDefNames(), "<>4__this", "a", "<>9", "<>9__0#1_0#1");
diff1.VerifySynthesizedMembers(
"C.<>c__0#1<T>: {<>9__0#1_0#1, <F>b__0#1_0#1}",
"C: {<>c__DisplayClass0#1_0#1, <>c__0#1}",
"C.<>c__DisplayClass0#1_0#1<T>: {<>4__this, a, <F>b__1#1, <F>b__2#1}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f_byte2)));
var reader2 = diff2.GetMetadata().Reader;
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>c__DisplayClass1#2_0#2`1", "<>c__1#2`1");
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetMethodDefNames(), "F", ".ctor", "<F>b__1#2", "<F>b__2#2", ".cctor", ".ctor", "<F>b__1#2_0#2");
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetFieldDefNames(), "<>4__this", "a", "<>9", "<>9__1#2_0#2");
}
[Fact]
public void UniqueSynthesizedNames2()
{
var source0 = @"
using System;
public class C
{
public static void Main()
{
}
}";
var source1 = @"
using System;
public class C
{
public static void Main()
{
new C().F();
}
public int F()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var source2 = @"
using System;
public class C
{
public static void Main()
{
new C().F(1);
new C().F();
}
public int F(int x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
public int F()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var source3 = @"
using System;
public class C
{
public static void Main()
{
}
public int F(int x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
public int F()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A");
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var main0 = compilation0.GetMember<MethodSymbol>("C.Main");
var main1 = compilation1.GetMember<MethodSymbol>("C.Main");
var main2 = compilation2.GetMember<MethodSymbol>("C.Main");
var main3 = compilation3.GetMember<MethodSymbol>("C.Main");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f_int2 = compilation2.GetMembers("C.F").Single(m => m.ToString() == "C.F(int)");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f1),
SemanticEdit.Create(SemanticEditKind.Update, main0, main1, preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C.<>c: {<>9__1#1_0#1, <F>b__1#1_0#1}",
"C.<>c__DisplayClass1#1_0#1: {<>4__this, a, <F>b__1#1, <F>b__2#1}",
"C: {<>c__DisplayClass1#1_0#1, <>c}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f_int2),
SemanticEdit.Create(SemanticEditKind.Update, main1, main2, preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C.<>c__DisplayClass1#2_0#2: {<>4__this, a, <F>b__1#2, <F>b__2#2}",
"C: {<>c__DisplayClass1#2_0#2, <>c, <>c__DisplayClass1#1_0#1}",
"C.<>c: {<>9__1#2_0#2, <F>b__1#2_0#2, <>9__1#1_0#1, <F>b__1#1_0#1}",
"C.<>c__DisplayClass1#1_0#1: {<>4__this, a, <F>b__1#1, <F>b__2#1}");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, main2, main3, preserveLocalVariables: true)));
diff3.VerifySynthesizedMembers(
"C.<>c__DisplayClass1#1_0#1: {<>4__this, a, <F>b__1#1, <F>b__2#1}",
"C.<>c: {<>9__1#2_0#2, <F>b__1#2_0#2, <>9__1#1_0#1, <F>b__1#1_0#1}",
"C.<>c__DisplayClass1#2_0#2: {<>4__this, a, <F>b__1#2, <F>b__2#2}",
"C: {<>c__DisplayClass1#2_0#2, <>c, <>c__DisplayClass1#1_0#1}");
}
[Fact]
public void NestedLambdas()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + G(<N:1>b => 1</N:1>)</N:0>);
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + G(<N:1>b => 2</N:1>)</N:0>);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// 3 method updates:
// Note that even if the change is in the inner lambda such a change will usually impact sequence point
// spans in outer lambda and the method body. So although the IL doesn't change we usually need to update the outer methods.
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void LambdasInInitializers1()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
public int A = G(<N:0>a => a + 1</N:0>);
public C() : this(G(<N:1>a => a + 2</N:1>))
{
G(<N:2>a => a + 3</N:2>);
}
public C(int x)
{
G(<N:3>a => a + 4</N:3>);
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
public int A = G(<N:0>a => a - 1</N:0>);
public C() : this(G(<N:1>a => a - 2</N:1>))
{
G(<N:2>a => a - 3</N:2>);
}
public C(int x)
{
G(<N:3>a => a - 4</N:3>);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var ctor00 = compilation0.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor()");
var ctor10 = compilation0.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor(System.Int32 x)");
var ctor01 = compilation1.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor()");
var ctor11 = compilation1.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor(System.Int32 x)");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor00, ctor01, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true),
SemanticEdit.Create(SemanticEditKind.Update, ctor10, ctor11, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__2_0, <>9__2_1, <>9__3_0, <>9__3_1, <.ctor>b__2_0, <.ctor>b__2_1, <.ctor>b__3_0, <.ctor>b__3_1}");
diff1.VerifyIL("C.<>c.<.ctor>b__2_0", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.2
IL_0002: sub
IL_0003: ret
}");
diff1.VerifyIL("C.<>c.<.ctor>b__2_1", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.3
IL_0002: sub
IL_0003: ret
}");
diff1.VerifyIL("C.<>c.<.ctor>b__3_0", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.4
IL_0002: sub
IL_0003: ret
}");
diff1.VerifyIL("C.<>c.<.ctor>b__3_1", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: sub
IL_0003: ret
}");
}
[Fact]
public void LambdasInInitializers2()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
public int A = G(<N:0>a => { int <N:4>v1 = 1</N:4>; return 1; }</N:0>);
public C() : this(G(<N:1>a => { int <N:5>v2 = 1</N:5>; return 2; }</N:1>))
{
G(<N:2>a => { int <N:6>v3 = 1</N:6>; return 3; }</N:2>);
}
public C(int x)
{
G(<N:3>a => { int <N:7>v4 = 1</N:7>; return 4; }</N:3>);
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
public int A = G(<N:0>a => { int <N:4>v1 = 10</N:4>; return 1; }</N:0>);
public C() : this(G(<N:1>a => { int <N:5>v2 = 10</N:5>; return 2; }</N:1>))
{
G(<N:2>a => { int <N:6>v3 = 10</N:6>; return 3; }</N:2>);
}
public C(int x)
{
G(<N:3>a => { int <N:7>v4 = 10</N:7>; return 4; }</N:3>);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var ctor00 = compilation0.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor()");
var ctor10 = compilation0.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor(System.Int32 x)");
var ctor01 = compilation1.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor()");
var ctor11 = compilation1.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor(System.Int32 x)");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor00, ctor01, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true),
SemanticEdit.Create(SemanticEditKind.Update, ctor10, ctor11, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__2_0, <>9__2_1, <>9__3_0, <>9__3_1, <.ctor>b__2_0, <.ctor>b__2_1, <.ctor>b__3_0, <.ctor>b__3_1}");
diff1.VerifyIL("C.<>c.<.ctor>b__2_0", @"
{
// Code size 10 (0xa)
.maxstack 1
.locals init (int V_0, //v2
[int] V_1,
int V_2)
IL_0000: nop
IL_0001: ldc.i4.s 10
IL_0003: stloc.0
IL_0004: ldc.i4.2
IL_0005: stloc.2
IL_0006: br.s IL_0008
IL_0008: ldloc.2
IL_0009: ret
}");
diff1.VerifyIL("C.<>c.<.ctor>b__2_1", @"
{
// Code size 10 (0xa)
.maxstack 1
.locals init (int V_0, //v3
[int] V_1,
int V_2)
IL_0000: nop
IL_0001: ldc.i4.s 10
IL_0003: stloc.0
IL_0004: ldc.i4.3
IL_0005: stloc.2
IL_0006: br.s IL_0008
IL_0008: ldloc.2
IL_0009: ret
}");
diff1.VerifyIL("C.<>c.<.ctor>b__3_0", @"
{
// Code size 10 (0xa)
.maxstack 1
.locals init (int V_0, //v4
[int] V_1,
int V_2)
IL_0000: nop
IL_0001: ldc.i4.s 10
IL_0003: stloc.0
IL_0004: ldc.i4.4
IL_0005: stloc.2
IL_0006: br.s IL_0008
IL_0008: ldloc.2
IL_0009: ret
}");
diff1.VerifyIL("C.<>c.<.ctor>b__3_1", @"
{
// Code size 10 (0xa)
.maxstack 1
.locals init (int V_0, //v1
[int] V_1,
int V_2)
IL_0000: nop
IL_0001: ldc.i4.s 10
IL_0003: stloc.0
IL_0004: ldc.i4.1
IL_0005: stloc.2
IL_0006: br.s IL_0008
IL_0008: ldloc.2
IL_0009: ret
}");
}
[Fact]
public void UpdateParameterlessConstructorInPresenceOfFieldInitializersWithLambdas()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0>a => a + 1</N:0>);
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0>a => a + 1</N:0>);
int B = F(b => b + 1); // new field
public C() // new ctor
{
F(c => c + 1);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var b1 = compilation1.GetMember<FieldSymbol>("C.B");
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, b1),
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__2_0#1, <>9__2_0, <>9__2_2#1, <.ctor>b__2_0#1, <.ctor>b__2_0, <.ctor>b__2_2#1}");
diff1.VerifyIL("C..ctor", @"
{
// Code size 130 (0x82)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldsfld ""System.Func<int, int> C.<>c.<>9__2_0""
IL_0006: dup
IL_0007: brtrue.s IL_0020
IL_0009: pop
IL_000a: ldsfld ""C.<>c C.<>c.<>9""
IL_000f: ldftn ""int C.<>c.<.ctor>b__2_0(int)""
IL_0015: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_001a: dup
IL_001b: stsfld ""System.Func<int, int> C.<>c.<>9__2_0""
IL_0020: call ""int C.F(System.Func<int, int>)""
IL_0025: stfld ""int C.A""
IL_002a: ldarg.0
IL_002b: ldsfld ""System.Func<int, int> C.<>c.<>9__2_2#1""
IL_0030: dup
IL_0031: brtrue.s IL_004a
IL_0033: pop
IL_0034: ldsfld ""C.<>c C.<>c.<>9""
IL_0039: ldftn ""int C.<>c.<.ctor>b__2_2#1(int)""
IL_003f: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0044: dup
IL_0045: stsfld ""System.Func<int, int> C.<>c.<>9__2_2#1""
IL_004a: call ""int C.F(System.Func<int, int>)""
IL_004f: stfld ""int C.B""
IL_0054: ldarg.0
IL_0055: call ""object..ctor()""
IL_005a: nop
IL_005b: nop
IL_005c: ldsfld ""System.Func<int, int> C.<>c.<>9__2_0#1""
IL_0061: dup
IL_0062: brtrue.s IL_007b
IL_0064: pop
IL_0065: ldsfld ""C.<>c C.<>c.<>9""
IL_006a: ldftn ""int C.<>c.<.ctor>b__2_0#1(int)""
IL_0070: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0075: dup
IL_0076: stsfld ""System.Func<int, int> C.<>c.<>9__2_0#1""
IL_007b: call ""int C.F(System.Func<int, int>)""
IL_0080: pop
IL_0081: ret
}
");
}
[Fact(Skip = "2504"), WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")]
public void InsertConstructorInPresenceOfFieldInitializersWithLambdas()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0>a => a + 1</N:0>);
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0>a => a + 1</N:0>);
int B = F(b => b + 1); // new field
public C(int x) // new ctor
{
F(c => c + 1);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var b1 = compilation1.GetMember<FieldSymbol>("C.B");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, b1),
SemanticEdit.Create(SemanticEditKind.Insert, null, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C: {<> c}",
"C.<>c: {<>9__2_0#1, <>9__2_0, <>9__2_2#1, <.ctor>b__2_0#1, <.ctor>b__2_0, <.ctor>b__2_2#1}");
}
[Fact]
public void Queries_Select_Reduced1()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>where a > 0</N:1>
<N:2>select a</N:2></N:0>;
}
int[] array = null;
}
");
var source1 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>where a > 0</N:1>
<N:2>select a + 1</N:2></N:0>;
}
int[] array = null;
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// new lambda for Select(a => a + 1)
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1#1, <F>b__0_0, <F>b__0_1#1}");
diff1.VerifyIL("C.<>c.<F>b__0_1#1", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: ret
}
");
// old query:
v0.VerifyIL("C.F", @"
{
// Code size 45 (0x2d)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""bool C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_0026: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Where<int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_002b: stloc.0
IL_002c: ret
}
");
// new query:
diff1.VerifyIL("C.F", @"
{
// Code size 81 (0x51)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""bool C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_0026: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Where<int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_002b: ldsfld ""System.Func<int, int> C.<>c.<>9__0_1#1""
IL_0030: dup
IL_0031: brtrue.s IL_004a
IL_0033: pop
IL_0034: ldsfld ""C.<>c C.<>c.<>9""
IL_0039: ldftn ""int C.<>c.<F>b__0_1#1(int)""
IL_003f: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0044: dup
IL_0045: stsfld ""System.Func<int, int> C.<>c.<>9__0_1#1""
IL_004a: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_004f: stloc.0
IL_0050: ret
}
");
}
[Fact]
public void Queries_Select_Reduced2()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>where a > 0</N:1>
<N:2>select a + 1</N:2></N:0>;
}
int[] array = null;
}
");
var source1 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>where a > 0</N:1>
<N:2>select a</N:2></N:0>;
}
int[] array = null;
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// lambda for Select(a => a + 1) is gone
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <F>b__0_0}");
// old query:
v0.VerifyIL("C.F", @"
{
// Code size 81 (0x51)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""bool C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_0026: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Where<int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_002b: ldsfld ""System.Func<int, int> C.<>c.<>9__0_1""
IL_0030: dup
IL_0031: brtrue.s IL_004a
IL_0033: pop
IL_0034: ldsfld ""C.<>c C.<>c.<>9""
IL_0039: ldftn ""int C.<>c.<F>b__0_1(int)""
IL_003f: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0044: dup
IL_0045: stsfld ""System.Func<int, int> C.<>c.<>9__0_1""
IL_004a: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_004f: stloc.0
IL_0050: ret
}
");
// new query:
diff1.VerifyIL("C.F", @"
{
// Code size 45 (0x2d)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""bool C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_0026: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Where<int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_002b: stloc.0
IL_002c: ret
}
");
}
[Fact]
public void Queries_GroupBy_Reduced1()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>group a by a</N:1></N:0>;
}
int[] array = null;
}
");
var source1 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>group a + 1 by a</N:1></N:0>;
}
int[] array = null;
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// new lambda for GroupBy(..., a => a + 1)
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1#1, <F>b__0_0, <F>b__0_1#1}");
diff1.VerifyIL("C.<>c.<F>b__0_1#1", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: ret
}
");
// old query:
v0.VerifyIL("C.F", @"
{
// Code size 45 (0x2d)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""int C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_0026: call ""System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> System.Linq.Enumerable.GroupBy<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_002b: stloc.0
IL_002c: ret
}
");
// new query:
diff1.VerifyIL("C.F", @"
{
// Code size 76 (0x4c)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""int C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_0026: ldsfld ""System.Func<int, int> C.<>c.<>9__0_1#1""
IL_002b: dup
IL_002c: brtrue.s IL_0045
IL_002e: pop
IL_002f: ldsfld ""C.<>c C.<>c.<>9""
IL_0034: ldftn ""int C.<>c.<F>b__0_1#1(int)""
IL_003a: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_003f: dup
IL_0040: stsfld ""System.Func<int, int> C.<>c.<>9__0_1#1""
IL_0045: call ""System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> System.Linq.Enumerable.GroupBy<int, int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>, System.Func<int, int>)""
IL_004a: stloc.0
IL_004b: ret
}
");
}
[Fact]
public void Queries_GroupBy_Reduced2()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>group a + 1 by a</N:1></N:0>;
}
int[] array = null;
}
");
var source1 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>group a by a</N:1></N:0>;
}
int[] array = null;
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// lambda for GroupBy(..., a => a + 1) is gone
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <F>b__0_0}");
// old query:
v0.VerifyIL("C.F", @"
{
// Code size 76 (0x4c)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""int C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_0026: ldsfld ""System.Func<int, int> C.<>c.<>9__0_1""
IL_002b: dup
IL_002c: brtrue.s IL_0045
IL_002e: pop
IL_002f: ldsfld ""C.<>c C.<>c.<>9""
IL_0034: ldftn ""int C.<>c.<F>b__0_1(int)""
IL_003a: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_003f: dup
IL_0040: stsfld ""System.Func<int, int> C.<>c.<>9__0_1""
IL_0045: call ""System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> System.Linq.Enumerable.GroupBy<int, int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>, System.Func<int, int>)""
IL_004a: stloc.0
IL_004b: ret
}
");
// new query:
diff1.VerifyIL("C.F", @"
{
// Code size 45 (0x2d)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""int C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_0026: call ""System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> System.Linq.Enumerable.GroupBy<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_002b: stloc.0
IL_002c: ret
}
");
}
[Fact, WorkItem(1170899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1170899")]
public void CapturedAnonymousTypes1()
{
var source0 = MarkedSource(@"
using System;
class C
{
static void F()
<N:0>{
var <N:1>x = new { A = 1 }</N:1>;
var <N:2>y = new Func<int>(<N:3>() => x.A</N:3>)</N:2>;
Console.WriteLine(1);
}</N:0>
}
");
var source1 = MarkedSource(@"
using System;
class C
{
static void F()
<N:0>{
var <N:1>x = new { A = 1 }</N:1>;
var <N:2>y = new Func<int>(<N:3>() => x.A</N:3>)</N:2>;
Console.WriteLine(2);
}</N:0>
}
");
var source2 = MarkedSource(@"
using System;
class C
{
static void F()
<N:0>{
var <N:1>x = new { A = 1 }</N:1>;
var <N:2>y = new Func<int>(<N:3>() => x.A</N:3>)</N:2>;
Console.WriteLine(3);
}</N:0>
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
v0.VerifyIL("C.F", @"
{
// Code size 40 (0x28)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
System.Func<int> V_1) //y
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldc.i4.1
IL_0009: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_000e: stfld ""<anonymous type: int A> C.<>c__DisplayClass0_0.x""
IL_0013: ldloc.0
IL_0014: ldftn ""int C.<>c__DisplayClass0_0.<F>b__0()""
IL_001a: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001f: stloc.1
IL_0020: ldc.i4.1
IL_0021: call ""void System.Console.WriteLine(int)""
IL_0026: nop
IL_0027: ret
}");
var diff1 = compilation1.EmitDifference(generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {x, <F>b__0}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.F", @"
{
// Code size 40 (0x28)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
System.Func<int> V_1) //y
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldc.i4.1
IL_0009: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_000e: stfld ""<anonymous type: int A> C.<>c__DisplayClass0_0.x""
IL_0013: ldloc.0
IL_0014: ldftn ""int C.<>c__DisplayClass0_0.<F>b__0()""
IL_001a: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001f: stloc.1
IL_0020: ldc.i4.2
IL_0021: call ""void System.Console.WriteLine(int)""
IL_0026: nop
IL_0027: ret
}");
var diff2 = compilation2.EmitDifference(diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {x, <F>b__0}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", @"
{
// Code size 40 (0x28)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
System.Func<int> V_1) //y
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldc.i4.1
IL_0009: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_000e: stfld ""<anonymous type: int A> C.<>c__DisplayClass0_0.x""
IL_0013: ldloc.0
IL_0014: ldftn ""int C.<>c__DisplayClass0_0.<F>b__0()""
IL_001a: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001f: stloc.1
IL_0020: ldc.i4.3
IL_0021: call ""void System.Console.WriteLine(int)""
IL_0026: nop
IL_0027: ret
}");
}
[Fact, WorkItem(1170899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1170899")]
public void CapturedAnonymousTypes2()
{
var template = @"
using System;
class C
{
static void F()
<N:0>{
var x = new { X = <<VALUE>> };
Func<int> <N:2>y = <N:1>() => x.X</N:1></N:2>;
Console.WriteLine(y());
}</N:0>
}
";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
string expectedIL = @"
{
// Code size 45 (0x2d)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
System.Func<int> V_1) //y
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldc.i4.<<VALUE>>
IL_0009: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_000e: stfld ""<anonymous type: int X> C.<>c__DisplayClass0_0.x""
IL_0013: ldloc.0
IL_0014: ldftn ""int C.<>c__DisplayClass0_0.<F>b__0()""
IL_001a: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001f: stloc.1
IL_0020: ldloc.1
IL_0021: callvirt ""int System.Func<int>.Invoke()""
IL_0026: call ""void System.Console.WriteLine(int)""
IL_002b: nop
IL_002c: ret
}";
v0.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "0"));
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {x, <F>b__0}",
"<>f__AnonymousType0<<X>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "1"));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {x, <F>b__0}",
"<>f__AnonymousType0<<X>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2"));
}
[WorkItem(179990, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/179990")]
[Fact]
public void SynthesizedDelegates()
{
var template =
@"class C
{
static void F(dynamic d, out object x, object y)
<N:0>{
<<CALL>>;
}</N:0>
}";
var source0 = MarkedSource(template.Replace("<<CALL>>", "d.F(out x, new { })"));
var source1 = MarkedSource(template.Replace("<<CALL>>", "d.F(out x, new { y })"));
var source2 = MarkedSource(template.Replace("<<CALL>>", "d.F(new { y }, out x)"));
var compilation0 = CreateCompilationWithMscorlib40(new[] { source0.Tree }, references: new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
v0.VerifyIL("C.F",
@"{
// Code size 112 (0x70)
.maxstack 9
IL_0000: nop
IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>> C.<>o__0.<>p__0""
IL_0006: brfalse.s IL_000a
IL_0008: br.s IL_0053
IL_000a: ldc.i4 0x100
IL_000f: ldstr ""F""
IL_0014: ldnull
IL_0015: ldtoken ""C""
IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001f: ldc.i4.3
IL_0020: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_0025: dup
IL_0026: ldc.i4.0
IL_0027: ldc.i4.0
IL_0028: ldnull
IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_002e: stelem.ref
IL_002f: dup
IL_0030: ldc.i4.1
IL_0031: ldc.i4.s 17
IL_0033: ldnull
IL_0034: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0039: stelem.ref
IL_003a: dup
IL_003b: ldc.i4.2
IL_003c: ldc.i4.1
IL_003d: ldnull
IL_003e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0043: stelem.ref
IL_0044: 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_0049: call ""System.Runtime.CompilerServices.CallSite<<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>> System.Runtime.CompilerServices.CallSite<<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_004e: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>> C.<>o__0.<>p__0""
IL_0053: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>> C.<>o__0.<>p__0""
IL_0058: ldfld ""<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>> System.Runtime.CompilerServices.CallSite<<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>>.Target""
IL_005d: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>> C.<>o__0.<>p__0""
IL_0062: ldarg.0
IL_0063: ldarg.1
IL_0064: newobj ""<>f__AnonymousType0..ctor()""
IL_0069: callvirt ""void <>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic, ref object, <empty anonymous type>)""
IL_006e: nop
IL_006f: ret
}");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.F",
@"{
// Code size 113 (0x71)
.maxstack 9
IL_0000: nop
IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>> C.<>o__0#1.<>p__0""
IL_0006: brfalse.s IL_000a
IL_0008: br.s IL_0053
IL_000a: ldc.i4 0x100
IL_000f: ldstr ""F""
IL_0014: ldnull
IL_0015: ldtoken ""C""
IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001f: ldc.i4.3
IL_0020: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_0025: dup
IL_0026: ldc.i4.0
IL_0027: ldc.i4.0
IL_0028: ldnull
IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_002e: stelem.ref
IL_002f: dup
IL_0030: ldc.i4.1
IL_0031: ldc.i4.s 17
IL_0033: ldnull
IL_0034: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0039: stelem.ref
IL_003a: dup
IL_003b: ldc.i4.2
IL_003c: ldc.i4.1
IL_003d: ldnull
IL_003e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0043: stelem.ref
IL_0044: 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_0049: call ""System.Runtime.CompilerServices.CallSite<<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>> System.Runtime.CompilerServices.CallSite<<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_004e: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>> C.<>o__0#1.<>p__0""
IL_0053: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>> C.<>o__0#1.<>p__0""
IL_0058: ldfld ""<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>> System.Runtime.CompilerServices.CallSite<<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>>.Target""
IL_005d: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>> C.<>o__0#1.<>p__0""
IL_0062: ldarg.0
IL_0063: ldarg.1
IL_0064: ldarg.2
IL_0065: newobj ""<>f__AnonymousType1<object>..ctor(object)""
IL_006a: callvirt ""void <>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic, ref object, <anonymous type: object y>)""
IL_006f: nop
IL_0070: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifyIL("C.F",
@"{
// Code size 113 (0x71)
.maxstack 9
IL_0000: nop
IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>> C.<>o__0#2.<>p__0""
IL_0006: brfalse.s IL_000a
IL_0008: br.s IL_0053
IL_000a: ldc.i4 0x100
IL_000f: ldstr ""F""
IL_0014: ldnull
IL_0015: ldtoken ""C""
IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001f: ldc.i4.3
IL_0020: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_0025: dup
IL_0026: ldc.i4.0
IL_0027: ldc.i4.0
IL_0028: ldnull
IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_002e: stelem.ref
IL_002f: dup
IL_0030: ldc.i4.1
IL_0031: ldc.i4.1
IL_0032: ldnull
IL_0033: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0038: stelem.ref
IL_0039: dup
IL_003a: ldc.i4.2
IL_003b: ldc.i4.s 17
IL_003d: ldnull
IL_003e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0043: stelem.ref
IL_0044: 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_0049: call ""System.Runtime.CompilerServices.CallSite<<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>> System.Runtime.CompilerServices.CallSite<<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_004e: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>> C.<>o__0#2.<>p__0""
IL_0053: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>> C.<>o__0#2.<>p__0""
IL_0058: ldfld ""<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object> System.Runtime.CompilerServices.CallSite<<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>>.Target""
IL_005d: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>> C.<>o__0#2.<>p__0""
IL_0062: ldarg.0
IL_0063: ldarg.2
IL_0064: newobj ""<>f__AnonymousType1<object>..ctor(object)""
IL_0069: ldarg.1
IL_006a: callvirt ""void <>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, ref object)""
IL_006f: nop
IL_0070: ret
}");
}
[Fact]
public void TwoStructClosures()
{
var source0 = MarkedSource(@"
public class C
{
public void F()
<N:0>{</N:0>
int <N:1>x</N:1> = 0;
<N:2>{</N:2>
int <N:3>y</N:3> = 0;
// Captures two struct closures
<N:4>int L() => x + y;</N:4>
}
}
}");
var source1 = MarkedSource(@"
public class C
{
public void F()
<N:0>{</N:0>
int <N:1>x</N:1> = 0;
<N:2>{</N:2>
int <N:3>y</N:3> = 0;
// Captures two struct closures
<N:4>int L() => x + y + 1;</N:4>
}
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass0_0: {x}",
"C.<>c__DisplayClass0_1: {y}",
"C: {<F>g__L|0_0, <>c__DisplayClass0_0, <>c__DisplayClass0_1}");
v0.VerifyIL("C.<F>g__L|0_0(ref C.<>c__DisplayClass0_0, ref C.<>c__DisplayClass0_1)", @"
{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldarg.1
IL_0007: ldfld ""int C.<>c__DisplayClass0_1.y""
IL_000c: add
IL_000d: ret
}");
diff1.VerifyIL("C.<F>g__L|0_0(ref C.<>c__DisplayClass0_0, ref C.<>c__DisplayClass0_1)", @"
{
// Code size 16 (0x10)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldarg.1
IL_0007: ldfld ""int C.<>c__DisplayClass0_1.y""
IL_000c: add
IL_000d: ldc.i4.1
IL_000e: add
IL_000f: ret
}
");
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void ThisClosureAndStructClosure()
{
var source0 = MarkedSource(@"
public class C
{
int <N:0>x</N:0> = 0;
public void F()
<N:1>{</N:1>
int <N:2>y</N:2> = 0;
// This + struct closures
<N:3>int L() => x + y;</N:3>
L();
}
}");
var source1 = MarkedSource(@"
public class C
{
int <N:0>x</N:0> = 0;
public void F()
<N:1>{</N:1>
int <N:2>y</N:2> = 0;
// This + struct closures
<N:3>int L() => x + y + 1;</N:3>
L();
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass1_0: {<>4__this, y}",
"C: {<F>g__L|1_0, <>c__DisplayClass1_0}");
v0.VerifyIL("C.<F>g__L|1_0(ref C.<>c__DisplayClass1_0)", @"
{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.x""
IL_0006: ldarg.1
IL_0007: ldfld ""int C.<>c__DisplayClass1_0.y""
IL_000c: add
IL_000d: ret
}
");
diff1.VerifyIL("C.<F>g__L|1_0(ref C.<>c__DisplayClass1_0)", @"
{
// Code size 16 (0x10)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.x""
IL_0006: ldarg.1
IL_0007: ldfld ""int C.<>c__DisplayClass1_0.y""
IL_000c: add
IL_000d: ldc.i4.1
IL_000e: add
IL_000f: ret
}
");
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void ThisOnlyClosure()
{
var source0 = MarkedSource(@"
public class C
{
int <N:0>x</N:0> = 0;
public void F()
<N:1>{</N:1>
// This-only closure
<N:2>int L() => x;</N:2>
L();
}
}");
var source1 = MarkedSource(@"
public class C
{
int <N:0>x</N:0> = 0;
public void F()
<N:1>{</N:1>
// This-only closure
<N:2>int L() => x + 1;</N:2>
L();
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C: {<F>g__L|1_0}");
v0.VerifyIL("C.<F>g__L|1_0()", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""int C.x""
IL_0006: ret
}");
diff1.VerifyIL("C.<F>g__L|1_0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void LocatedInSameClosureEnvironment()
{
var source0 = MarkedSource(@"
using System;
public class C
{
public void F(int x)
<N:0>{</N:0>
Func<int> f = <N:1>() => x</N:1>;
// Located in same closure environment
<N:2>int L() => x;</N:2>
}
}");
var source1 = MarkedSource(@"
using System;
public class C
{
public void F(int x)
<N:0>{</N:0>
Func<int> f = <N:1>() => x</N:1>;
// Located in same closure environment
<N:2>int L() => x + 1;</N:2>
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass0_0: {x, <F>b__0, <F>g__L|1}",
"C: {<>c__DisplayClass0_0}");
v0.VerifyIL("C.<>c__DisplayClass0_0.<F>g__L|1()", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ret
}");
diff1.VerifyIL("C.<>c__DisplayClass0_0.<F>g__L|1()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void SameClassEnvironmentWithStruct()
{
var source0 = MarkedSource(@"
using System;
public class C
{
public void F(int x)
<N:0>{</N:0>
<N:1>{</N:1>
int <N:2>y</N:2> = 0;
Func<int> f = <N:3>() => x</N:3>;
// Same class environment, with struct env
<N:4>int L() => x + y;</N:4>
}
}
}");
var source1 = MarkedSource(@"
using System;
public class C
{
public void F(int x)
<N:0>{</N:0>
<N:1>{</N:1>
int <N:2>y</N:2> = 0;
Func<int> f = <N:3>() => x</N:3>;
// Same class environment, with struct env
<N:4>int L() => x + y + 1;</N:4>
}
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0, <>c__DisplayClass0_1}",
"C.<>c__DisplayClass0_0: {x, <F>b__0, <F>g__L|1}",
"C.<>c__DisplayClass0_1: {y}");
v0.VerifyIL("C.<>c__DisplayClass0_0.<F>g__L|1(ref C.<>c__DisplayClass0_1)", @"
{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldarg.1
IL_0007: ldfld ""int C.<>c__DisplayClass0_1.y""
IL_000c: add
IL_000d: ret
}");
diff1.VerifyIL("C.<>c__DisplayClass0_0.<F>g__L|1(ref C.<>c__DisplayClass0_1)", @"
{
// Code size 16 (0x10)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldarg.1
IL_0007: ldfld ""int C.<>c__DisplayClass0_1.y""
IL_000c: add
IL_000d: ldc.i4.1
IL_000e: add
IL_000f: ret
}
");
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void CaptureStructAndThroughClassEnvChain()
{
var source0 = MarkedSource(@"
using System;
public class C
{
public void F(int x)
<N:0>{</N:0>
<N:1>{</N:1>
int <N:2>y</N:2> = 0;
Func<int> f = <N:3>() => x</N:3>;
<N:4>{</N:4>
Func<int> f2 = <N:5>() => x + y</N:5>;
int <N:6>z</N:6> = 0;
// Capture struct and through class env chain
<N:7>int L() => x + y + z;</N:7>
}
}
}
}");
var source1 = MarkedSource(@"
using System;
public class C
{
public void F(int x)
<N:0>{</N:0>
<N:1>{</N:1>
int <N:2>y</N:2> = 0;
Func<int> f = <N:3>() => x</N:3>;
<N:4>{</N:4>
Func<int> f2 = <N:5>() => x + y</N:5>;
int <N:6>z</N:6> = 0;
// Capture struct and through class env chain
<N:7>int L() => x + y + z + 1;</N:7>
}
}
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass0_2: {z}",
"C.<>c__DisplayClass0_0: {x, <F>b__0}",
"C: {<>c__DisplayClass0_0, <>c__DisplayClass0_1, <>c__DisplayClass0_2}",
"C.<>c__DisplayClass0_1: {y, CS$<>8__locals1, <F>b__1, <F>g__L|2}");
v0.VerifyIL("C.<>c__DisplayClass0_1.<F>g__L|2(ref C.<>c__DisplayClass0_2)", @"
{
// Code size 26 (0x1a)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""C.<>c__DisplayClass0_0 C.<>c__DisplayClass0_1.CS$<>8__locals1""
IL_0006: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_000b: ldarg.0
IL_000c: ldfld ""int C.<>c__DisplayClass0_1.y""
IL_0011: add
IL_0012: ldarg.1
IL_0013: ldfld ""int C.<>c__DisplayClass0_2.z""
IL_0018: add
IL_0019: ret
}");
diff1.VerifyIL("C.<>c__DisplayClass0_1.<F>g__L|2(ref C.<>c__DisplayClass0_2)", @"
{
// Code size 28 (0x1c)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""C.<>c__DisplayClass0_0 C.<>c__DisplayClass0_1.CS$<>8__locals1""
IL_0006: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_000b: ldarg.0
IL_000c: ldfld ""int C.<>c__DisplayClass0_1.y""
IL_0011: add
IL_0012: ldarg.1
IL_0013: ldfld ""int C.<>c__DisplayClass0_2.z""
IL_0018: add
IL_0019: ldc.i4.1
IL_001a: add
IL_001b: ret
}
");
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void TopLevelStatement_Closure()
{
var source0 = MarkedSource(@"
<N:0>
using System;
Func<string> x = <N:1>() => args[0]</N:1>;
Console.WriteLine(x());
</N:0>
");
var source1 = MarkedSource(@"
<N:0>
using System;
Func<string> x = <N:1>() => args[1]</N:1>;
Console.WriteLine(x());
</N:0>
");
var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugExe);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("Program.<Main>$");
var f1 = compilation1.GetMember<MethodSymbol>("Program.<Main>$");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"Program.<>c__DisplayClass0_0: {args, <<Main>$>b__0}",
"Program: {<>c__DisplayClass0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.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.
#nullable disable
using System.Collections.Immutable;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
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.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests
{
public class EditAndContinueClosureTests : EditAndContinueTestBase
{
[Fact]
public void MethodToMethodWithClosure()
{
var source0 =
@"delegate object D();
class C
{
static object F(object o)
{
return o;
}
}";
var source1 =
@"delegate object D();
class C
{
static object F(object o)
{
return ((D)(() => o))();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F"), compilation1.GetMember<MethodSymbol>("C.F"))));
using (var md1 = diff1.GetMetadata())
{
var reader1 = md1.Reader;
// Field 'o'
// Methods: 'F', '.ctor', '<F>b__1'
// Type: display class
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(1, TableIndex.NestedClass, EditAndContinueOperation.Default));
}
}
[Fact]
public void MethodWithStaticLambda1()
{
var source0 = MarkedSource(@"
using System;
class C
{
void F()
{
Func<int> x = <N:0>() => 1</N:0>;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
void F()
{
Func<int> x = <N:0>() => 2</N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <F>b__0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithSwitchExpression()
{
var source0 = MarkedSource(@"
using System;
class C
{
int F(object o)
{
<N:0>return o switch
{
int i => new Func<int>(<N:1>() => i + 1</N:1>)(),
_ => 0
}</N:0>;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
int F(object o)
{
<N:0>return o switch
{
int i => new Func<int>(<N:1>() => i + 2</N:1>)(),
_ => 0
}</N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass0_0: {<i>5__2, <F>b__0}",
"C: {<>c__DisplayClass0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var x = Visualize(generation0.OriginalMetadata, md1);
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithNestedSwitchExpression()
{
var source0 = MarkedSource(@"
using System;
class C
{
int F(object o)
<N:0>{
<N:1>return o switch
{
int i => new Func<int>(<N:2>() => i + (int)o + i switch
{
1 => 1,
_ => new Func<int>(<N:3>() => (int)o + 1</N:3>)()
}</N:2>)(),
_ => 0
}</N:1>;
}</N:0>
}");
var source1 = MarkedSource(@"
using System;
class C
{
int F(object o)
<N:0>{
<N:1>return o switch
{
int i => new Func<int>(<N:2>() => i + (int)o + i switch
{
1 => 1,
_ => new Func<int>(<N:3>() => (int)o + 2</N:3>)()
}</N:2>)(),
_ => 0
}</N:1>;
}</N:0>
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0, <>c__DisplayClass0_1}",
"C.<>c__DisplayClass0_1: {<i>5__2, CS$<>8__locals2, <F>b__0}",
"C.<>c__DisplayClass0_0: {o, <>9__1, <F>b__1}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithStaticLocalFunction1()
{
var source0 = MarkedSource(@"
using System;
class C
{
void F()
{
<N:0>int x() => 1;</N:0>
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
void F()
{
<N:0>int x() => 2;</N:0>
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<F>g__x|0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithStaticLocalFunction_ChangeStatic()
{
var source0 = MarkedSource(@"
using System;
class C
{
void F()
{
<N:0>int x() => 1;</N:0>
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
void F()
{
<N:0>static int x() => 1;</N:0>
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var reader0 = md0.MetadataReader;
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<F>g__x|0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var localFunction0 = testData0.GetMethodData("C.<F>g__x|0_0").Method;
Assert.True(((Symbol)localFunction0).IsStatic);
var localFunction1 = diff1.TestData.GetMethodData("C.<F>g__x|0_0").Method;
Assert.True(((Symbol)localFunction1).IsStatic);
}
[Fact]
public void MethodWithStaticLambdaGeneric1()
{
var source0 = MarkedSource(@"
using System;
class C
{
void F<T>()
{
Func<T> x = <N:0>() => default(T)</N:0>;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
void F<T>()
{
Func<T> x = <N:0>() => default(T)</N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<>c__0}",
"C.<>c__0<T>: {<>9__0_0, <F>b__0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithStaticLocalFunctionGeneric1()
{
var source0 = MarkedSource(@"
using System;
class C
{
void F<T>()
{
<N:0>T x() => default(T);</N:0>
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
void F<T>()
{
<N:0>T x() => default(T);</N:0>
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<F>g__x|0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithThisOnlyClosure1()
{
var source0 = MarkedSource(@"
using System;
class C
{
int F(int a)
{
Func<int> x = <N:0>() => F(1)</N:0>;
return 1;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
int F(int a)
{
Func<int> x = <N:0>() => F(2)</N:0>;
return 2;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<F>b__0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithThisOnlyLocalFunctionClosure1()
{
var source0 = MarkedSource(@"
using System;
class C
{
int F(int a)
{
<N:0>int x() => F(1);</N:0>
return 1;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
int F(int a)
{
<N:0>int x() => F(2);</N:0>
return 2;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<F>g__x|0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithClosure1()
{
var source0 = MarkedSource(@"
using System;
class C
{
int F(int a)
<N:0>{</N:0>
Func<int> x = <N:1>() => F(a + 1)</N:1>;
return 1;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
int F(int a)
<N:0>{</N:0>
Func<int> x = <N:1>() => F(a + 2)</N:1>;
return 2;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass0_0: {<>4__this, a, <F>b__0}",
"C: {<>c__DisplayClass0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithNullable_AddingNullCheck()
{
var source0 = MarkedSource(@"
using System;
#nullable enable
class C
{
static T id<T>(T t) => t;
static T G<T>(Func<T> f) => f();
public void F(string? x)
<N:0>{</N:0>
var <N:1>y1</N:1> = new { A = id(x) };
var <N:2>y2</N:2> = G(<N:3>() => new { B = id(x) }</N:3>);
var <N:4>z</N:4> = G(<N:5>() => y1.A + y2.B</N:5>);
}
}", options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9));
var source1 = MarkedSource(@"
using System;
#nullable enable
class C
{
static T id<T>(T t) => t;
static T G<T>(Func<T> f) => f();
public void F(string? x)
<N:0>{</N:0>
if (x is null) throw new Exception();
var <N:1>y1</N:1> = new { A = id(x) };
var <N:2>y2</N:2> = G(<N:3>() => new { B = id(x) }</N:3>);
var <N:4>z</N:4> = G(<N:5>() => y1.A + y2.B</N:5>);
}
}", options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9));
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"Microsoft: {CodeAnalysis}",
"System.Runtime: {CompilerServices, CompilerServices}",
"<global namespace>: {Microsoft, System, System}",
"C: {<>c__DisplayClass2_0}",
"System: {Runtime, Runtime}",
"C.<>c__DisplayClass2_0: {x, y1, y2, <F>b__0, <F>b__1}",
"<>f__AnonymousType1<<B>j__TPar>: {Equals, GetHashCode, ToString}",
"System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.<>c__DisplayClass2_0.<F>b__1()", @"
{
// Code size 28 (0x1c)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""<anonymous type: string A> C.<>c__DisplayClass2_0.y1""
IL_0006: callvirt ""string <>f__AnonymousType0<string>.A.get""
IL_000b: ldarg.0
IL_000c: ldfld ""<anonymous type: string B> C.<>c__DisplayClass2_0.y2""
IL_0011: callvirt ""string <>f__AnonymousType1<string>.B.get""
IL_0016: call ""string string.Concat(string, string)""
IL_001b: ret
}");
diff1.VerifyIL("C.<>c__DisplayClass2_0.<F>b__0()", @"
{
// Code size 17 (0x11)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""string C.<>c__DisplayClass2_0.x""
IL_0006: call ""string C.id<string>(string)""
IL_000b: newobj ""<>f__AnonymousType1<string>..ctor(string)""
IL_0010: ret
}");
}
[Fact]
public void MethodWithLocalFunctionClosure1()
{
var source0 = MarkedSource(@"
using System;
class C
{
int F(int a)
<N:0>{</N:0>
<N:1>int x() => F(a + 1);</N:1>
return 1;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
int F(int a)
<N:0>{</N:0>
<N:1>int x() => F(a + 2);</N:1>
return 2;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<F>g__x|0_0, <>c__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {<>4__this, a}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void ConstructorWithClosure1()
{
var source0 = MarkedSource(@"
using System;
class D { public D(Func<int> f) { } }
class C : D
{
<N:0>public C(int a, int b)</N:0>
: base(<N:8>() => a</N:8>)
<N:1>{</N:1>
int c = 0;
Func<int> f1 = <N:2>() => a + 1</N:2>;
Func<int> f2 = <N:3>() => b + 2</N:3>;
Func<int> f3 = <N:4>() => c + 3</N:4>;
Func<int> f4 = <N:5>() => a + b + c</N:5>;
Func<int> f5 = <N:6>() => a + c</N:6>;
Func<int> f6 = <N:7>() => b + c</N:7>;
}
}");
var source1 = MarkedSource(@"
using System;
class D { public D(Func<int> f) { } }
class C : D
{
<N:0>public C(int a, int b)</N:0>
: base(<N:8>() => a * 10</N:8>)
<N:1>{</N:1>
int c = 0;
Func<int> f1 = <N:2>() => a * 10 + 1</N:2>;
Func<int> f2 = <N:3>() => b * 10 + 2</N:3>;
Func<int> f3 = <N:4>() => c * 10 + 3</N:4>;
Func<int> f4 = <N:5>() => a * 10 + b + c</N:5>;
Func<int> f5 = <N:6>() => a * 10 + c</N:6>;
Func<int> f6 = <N:7>() => b * 10 + c</N:7>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var ctor0 = compilation0.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single();
var ctor1 = compilation1.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single();
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0, <>c__DisplayClass0_1}",
"C.<>c__DisplayClass0_0: {a, b, <.ctor>b__0, <.ctor>b__1, <.ctor>b__2}",
"C.<>c__DisplayClass0_1: {c, CS$<>8__locals1, <.ctor>b__3, <.ctor>b__4, <.ctor>b__5, <.ctor>b__6}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void PartialClass()
{
var source0 = MarkedSource(@"
using System;
partial class C
{
Func<int> m1 = <N:0>() => 1</N:0>;
}
partial class C
{
Func<int> m2 = <N:1>() => 1</N:1>;
}
");
var source1 = MarkedSource(@"
using System;
partial class C
{
Func<int> m1 = <N:0>() => 10</N:0>;
}
partial class C
{
Func<int> m2 = <N:1>() => 10</N:1>;
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var ctor0 = compilation0.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single();
var ctor1 = compilation1.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single();
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__2_0, <>9__2_1, <.ctor>b__2_0, <.ctor>b__2_1}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default));
}
[Fact]
public void JoinAndGroupByClauses()
{
var source0 = MarkedSource(@"
using System.Linq;
class C
{
void F()
{
var result = <N:0>from a in new[] { 1, 2, 3 }</N:0>
<N:1>join b in new[] { 5 } on a + 1 equals b - 1</N:1>
<N:2>group</N:2> new { a, b = a + 5 } by new { c = a + 4 } into d
<N:3>select d.Key</N:3>;
}
}");
var source1 = MarkedSource(@"
using System.Linq;
class C
{
void F()
{
var result = <N:0>from a in new[] { 10, 20, 30 }</N:0>
<N:1>join b in new[] { 50 } on a + 10 equals b - 10</N:1>
<N:2>group</N:2> new { a, b = a + 50 } by new { c = a + 40 } into d
<N:3>select d.Key</N:3>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <>9__0_4, <>9__0_5, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3, <F>b__0_4, <F>b__0_5}",
"<>f__AnonymousType1<<c>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <b>j__TPar>: {Equals, GetHashCode, ToString}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates for lambdas:
CheckEncLogDefinitions(reader1,
Row(6, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(16, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(17, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(18, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(19, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(20, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(21, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.Param, EditAndContinueOperation.Default),
Row(7, TableIndex.Param, EditAndContinueOperation.Default),
Row(8, TableIndex.Param, EditAndContinueOperation.Default),
Row(9, TableIndex.Param, EditAndContinueOperation.Default),
Row(10, TableIndex.Param, EditAndContinueOperation.Default),
Row(11, TableIndex.Param, EditAndContinueOperation.Default),
Row(12, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void TransparentIdentifiers_FromClause()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var <N:10>result = <N:0>from a in new[] { 1 }</N:0>
<N:1>from b in <N:9>new[] { 1 }</N:9></N:1>
<N:2>where <N:7>Z(<N:5>() => a</N:5>) > 0</N:7></N:2>
<N:3>where <N:8>Z(<N:6>() => b</N:6>) > 0</N:8></N:3>
<N:4>select a</N:4></N:10>;
}
}");
var source1 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var <N:10>result = <N:0>from a in new[] { 1 }</N:0>
<N:1>from b in <N:9>new[] { 2 }</N:9></N:1>
<N:2>where <N:7>Z(<N:5>() => a</N:5>) > 1</N:7></N:2>
<N:3>where <N:8>Z(<N:6>() => b</N:6>) > 2</N:8></N:3>
<N:4>select a</N:4></N:10>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass1_1: {<>h__TransparentIdentifier0, <F>b__6}",
"C.<>c__DisplayClass1_0: {<>h__TransparentIdentifier0, <F>b__5}",
"C.<>c: {<>9__1_0, <>9__1_1, <>9__1_4, <F>b__1_0, <F>b__1_1, <F>b__1_4}",
"C: {<F>b__1_2, <F>b__1_3, <>c__DisplayClass1_0, <>c__DisplayClass1_1, <>c}",
"<>f__AnonymousType0<<a>j__TPar, <b>j__TPar>: {Equals, GetHashCode, ToString}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates for lambdas:
CheckEncLogDefinitions(reader1,
Row(7, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(8, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(9, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(15, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(18, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(19, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(20, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(6, TableIndex.Param, EditAndContinueOperation.Default),
Row(7, TableIndex.Param, EditAndContinueOperation.Default),
Row(8, TableIndex.Param, EditAndContinueOperation.Default),
Row(9, TableIndex.Param, EditAndContinueOperation.Default),
Row(10, TableIndex.Param, EditAndContinueOperation.Default),
Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void TransparentIdentifiers_LetClause()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var result = <N:0>from a in new[] { 1 }</N:0>
<N:1>let b = <N:2>Z(<N:3>() => a</N:3>)</N:2></N:1>
<N:4>select <N:5>a + b</N:5></N:4>;
}
}");
var source1 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var result = <N:0>from a in new[] { 1 }</N:0>
<N:1>let b = <N:2>Z(<N:3>() => a</N:3>) + 1</N:2></N:1>
<N:4>select <N:5>a + b</N:5></N:4>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C.<>c: {<>9__1_1, <F>b__1_1}",
"<>f__AnonymousType0<<a>j__TPar, <b>j__TPar>: {Equals, GetHashCode, ToString}",
"C.<>c__DisplayClass1_0: {a, <F>b__2}",
"C: {<F>b__1_0, <>c__DisplayClass1_0, <>c}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates for lambdas:
CheckEncLogDefinitions(reader1,
Row(6, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(7, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(15, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(6, TableIndex.Param, EditAndContinueOperation.Default),
Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void TransparentIdentifiers_JoinClause()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
public void F()
{
var result = <N:0>from a in <N:1>new[] { 1 }</N:1></N:0>
<N:2>join b in new[] { 3 } on
<N:3>Z(<N:4>() => <N:5>a + 1</N:5></N:4>)</N:3>
equals
<N:6>Z(<N:7>() => <N:8>b - 1</N:8></N:7>)</N:6></N:2>
<N:9>select <N:10>Z(<N:11>() => <N:12>a + b</N:12></N:11>)</N:10></N:9>;
}
}");
var source1 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
public void F()
{
var result = <N:0>from a in <N:1>new[] { 1 }</N:1></N:0>
<N:2>join b in new[] { 3 } on
<N:3>Z(<N:4>() => <N:5>a + 1</N:5></N:4>)</N:3>
equals
<N:6>Z(<N:7>() => <N:8>b - 1</N:8></N:7>)</N:6></N:2>
<N:9>select <N:10>Z(<N:11>() => <N:12>a - b</N:12></N:11>)</N:10></N:9>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass1_1: {b, <F>b__4}",
"C.<>c__DisplayClass1_2: {a, b, <F>b__5}",
"C.<>c__DisplayClass1_0: {a, <F>b__3}",
"C: {<F>b__1_0, <F>b__1_1, <F>b__1_2, <>c__DisplayClass1_0, <>c__DisplayClass1_1, <>c__DisplayClass1_2}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates for lambdas:
CheckEncLogDefinitions(reader1,
Row(6, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(7, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(8, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(9, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void TransparentIdentifiers_JoinIntoClause()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
public void F()
{
var result = <N:0>from a in <N:1>new[] { 1 }</N:1></N:0>
<N:2>join b in new[] { 3 } on
<N:3>a + 1</N:3> equals <N:4>b - 1</N:4>
into g</N:2>
<N:5>select <N:6>Z(<N:7>() => <N:8>g.First()</N:8></N:7>)</N:6></N:5>;
}
}");
var source1 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
public void F()
{
var result = <N:0>from a in <N:1>new[] { 1 }</N:1></N:0>
<N:2>join b in new[] { 3 } on
<N:3>a + 1</N:3> equals <N:4>b - 1</N:4>
into g</N:2>
<N:5>select <N:6>Z(<N:7>() => <N:8>g.Last()</N:8></N:7>)</N:6></N:5>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<F>b__1_2, <>c__DisplayClass1_0, <>c}",
"C.<>c: {<>9__1_0, <>9__1_1, <F>b__1_0, <F>b__1_1}",
"C.<>c__DisplayClass1_0: {g, <F>b__3}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates for lambdas:
CheckEncLogDefinitions(reader1,
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(5, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void TransparentIdentifiers_QueryContinuation()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
public void F()
{
var result = <N:0>from a in <N:1>new[] { 1 }</N:1></N:0>
<N:2>group a by <N:3>a + 1</N:3></N:2>
<N:4>into g
<N:5>select <N:6>Z(<N:7>() => <N:8>g.First()</N:8></N:7>)</N:6></N:5></N:4>;
}
}");
var source1 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
public void F()
{
var result = <N:0>from a in <N:1>new[] { 1 }</N:1></N:0>
<N:2>group a by <N:3>a + 1</N:3></N:2>
<N:4>into g
<N:5>select <N:6>Z(<N:7>() => <N:8>g.Last()</N:8></N:7>)</N:6></N:5></N:4>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<F>b__1_1, <>c__DisplayClass1_0, <>c}",
"C.<>c: {<>9__1_0, <F>b__1_0}",
"C.<>c__DisplayClass1_0: {g, <F>b__2}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates for lambdas:
CheckEncLogDefinitions(reader1,
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(5, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void Lambdas_UpdateAfterAdd()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(null);
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + 1</N:0>);
}
}");
var source2 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + 2</N:0>);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// new lambda "<F>b__0#1" has been added:
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0#1, <F>b__0#1}");
// added:
diff1.VerifyIL("C.<>c.<F>b__0#1", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0#1, <F>b__0#1}");
// updated:
diff2.VerifyIL("C.<>c.<F>b__0#1", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.2
IL_0002: add
IL_0003: ret
}
");
}
[Fact]
public void LocalFunctions_UpdateAfterAdd()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(null);
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
<N:0>int f(int a) => a + 1;</N:0>
return G(f);
}
}");
var source2 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
<N:0>int f(int a) => a + 2;</N:0>
return G(f);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// new lambda "<F>b__0#1" has been added:
diff1.VerifySynthesizedMembers(
"C: {<F>g__f|0#1}");
// added:
diff1.VerifyIL("C.<F>g__f|0#1(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<F>g__f|0#1}");
// updated:
diff2.VerifyIL("C.<F>g__f|0#1(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.2
IL_0002: add
IL_0003: ret
}
");
}
[Fact]
public void LocalFunctions_UpdateAfterAdd_NoDelegatePassing()
{
var source0 = MarkedSource(@"
using System;
class C
{
static object F()
{
return 0;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static object F()
{
<N:0>int f(int a) => a + 1;</N:0>
return 1;
}
}");
var source2 = MarkedSource(@"
using System;
class C
{
static object F()
{
<N:0>int f(int a) => a + 2;</N:0>
return 2;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// new lambda "<F>b__0#1" has been added:
diff1.VerifySynthesizedMembers(
"C: {<F>g__f|0#1}");
// added:
diff1.VerifyIL("C.<F>g__f|0#1(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<F>g__f|0#1}");
// updated:
diff2.VerifyIL("C.<F>g__f|0#1(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.2
IL_0002: add
IL_0003: ret
}
");
}
[Fact]
public void LambdasMultipleGenerations1()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + 1</N:0>);
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + 2</N:0>) + G(<N:1>b => b + 20</N:1>);
}
}");
var source2 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + 3</N:0>) + G(<N:1>b => b + 30</N:1>) + G(<N:2>c => c + 0x300</N:2>);
}
}");
var source3 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + 4</N:0>) + G(<N:1>b => b + 40</N:1>) + G(<N:2>c => c + 0x400</N:2>);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var compilation3 = compilation2.WithSource(source3.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var f3 = compilation3.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// new lambda "<F>b__1_1#1" has been added:
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__1_0, <>9__1_1#1, <F>b__1_0, <F>b__1_1#1}");
// updated:
diff1.VerifyIL("C.<>c.<F>b__1_0", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.2
IL_0002: add
IL_0003: ret
}
");
// added:
diff1.VerifyIL("C.<>c.<F>b__1_1#1", @"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.s 20
IL_0003: add
IL_0004: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
// new lambda "<F>b__1_2#2" has been added:
diff2.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__1_0, <>9__1_1#1, <>9__1_2#2, <F>b__1_0, <F>b__1_1#1, <F>b__1_2#2}");
// updated:
diff2.VerifyIL("C.<>c.<F>b__1_0", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.3
IL_0002: add
IL_0003: ret
}
");
// updated:
diff2.VerifyIL("C.<>c.<F>b__1_1#1", @"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.s 30
IL_0003: add
IL_0004: ret
}
");
// added:
diff2.VerifyIL("C.<>c.<F>b__1_2#2", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4 0x300
IL_0006: add
IL_0007: ret
}
");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f2, f3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables: true)));
diff3.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__1_0, <>9__1_1#1, <>9__1_2#2, <F>b__1_0, <F>b__1_1#1, <F>b__1_2#2}");
// updated:
diff3.VerifyIL("C.<>c.<F>b__1_0", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.4
IL_0002: add
IL_0003: ret
}
");
// updated:
diff3.VerifyIL("C.<>c.<F>b__1_1#1", @"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.s 40
IL_0003: add
IL_0004: ret
}
");
// updated:
diff3.VerifyIL("C.<>c.<F>b__1_2#2", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4 0x400
IL_0006: add
IL_0007: ret
}
");
}
[Fact]
public void LocalFunctionsMultipleGenerations1()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
<N:0>int f1(int a) => a + 1;</N:0>
return G(f1);
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
<N:0>int f1(int a) => a + 2;</N:0>
<N:1>int f2(int b) => b + 20;</N:1>
return G(f1) + G(f2);
}
}");
var source2 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
<N:0>int f1(int a) => a + 3;</N:0>
<N:1>int f2(int b) => b + 30;</N:1>
<N:2>int f3(int c) => c + 0x300;</N:2>
return G(f1) + G(f2) + G(f3);
}
}");
var source3 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
<N:0>int f1(int a) => a + 4;</N:0>
<N:1>int f2(int b) => b + 40;</N:1>
<N:2>int f3(int c) => c + 0x400;</N:2>
return G(f1) + G(f2) + G(f3);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var compilation3 = compilation2.WithSource(source3.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var f3 = compilation3.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C: {<F>g__f1|1_0, <F>g__f2|1_1#1}");
// updated:
diff1.VerifyIL("C.<F>g__f1|1_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.2
IL_0002: add
IL_0003: ret
}
");
// added:
diff1.VerifyIL("C.<F>g__f2|1_1#1(int)", @"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 20
IL_0003: add
IL_0004: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<F>g__f1|1_0, <F>g__f2|1_1#1, <F>g__f3|1_2#2}");
// updated:
diff2.VerifyIL("C.<F>g__f1|1_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.3
IL_0002: add
IL_0003: ret
}
");
// updated:
diff2.VerifyIL("C.<F>g__f2|1_1#1(int)", @"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 30
IL_0003: add
IL_0004: ret
}
");
// added:
diff2.VerifyIL("C.<F>g__f3|1_2#2(int)", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4 0x300
IL_0006: add
IL_0007: ret
}
");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f2, f3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables: true)));
diff3.VerifySynthesizedMembers(
"C: {<F>g__f1|1_0, <F>g__f2|1_1#1, <F>g__f3|1_2#2}");
// updated:
diff3.VerifyIL("C.<F>g__f1|1_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.4
IL_0002: add
IL_0003: ret
}
");
// updated:
diff3.VerifyIL("C.<F>g__f2|1_1#1(int)", @"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 40
IL_0003: add
IL_0004: ret
}
");
// updated:
diff3.VerifyIL("C.<F>g__f3|1_2#2(int)", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4 0x400
IL_0006: add
IL_0007: ret
}
");
}
[Fact, WorkItem(2284, "https://github.com/dotnet/roslyn/issues/2284")]
public void LambdasMultipleGenerations2()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
class C
{
private int[] _titles = new int[] { 1, 2 };
Action A;
private void F()
{
// edit 1
// var z = from title in _titles
// where title > 0
// select title;
A += <N:0>() =>
<N:1>{
Console.WriteLine(1);
// edit 2
// Console.WriteLine(2);
}</N:1></N:0>;
}
}");
var source1 = MarkedSource(@"
using System;
using System.Linq;
class C
{
private int[] _titles = new int[] { 1, 2 };
Action A;
private void F()
{
// edit 1
var <N:3>z = from title in _titles
<N:2>where title > 0</N:2>
select title</N:3>;
A += <N:0>() =>
<N:1>{
Console.WriteLine(1);
// edit 2
// Console.WriteLine(2);
}</N:1></N:0>;
}
}");
var source2 = MarkedSource(@"
using System;
using System.Linq;
class C
{
private int[] _titles = new int[] { 1, 2 };
Action A;
private void F()
{
// edit 1
var <N:3>z = from title in _titles
<N:2>where title > 0</N:2>
select title</N:3>;
A += <N:0>() =>
<N:1>{
Console.WriteLine(1);
// edit 2
Console.WriteLine(2);
}</N:1></N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// new lambda "<F>b__2_0#1" has been added:
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__2_0#1, <>9__2_0, <F>b__2_0#1, <F>b__2_0}");
// lambda body unchanged:
diff1.VerifyIL("C.<>c.<F>b__2_0", @"
{
// Code size 9 (0x9)
.maxstack 1
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: call ""void System.Console.WriteLine(int)""
IL_0007: nop
IL_0008: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
// no new members:
diff2.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__2_0#1, <>9__2_0, <F>b__2_0#1, <F>b__2_0}");
// lambda body updated:
diff2.VerifyIL("C.<>c.<F>b__2_0", @"
{
// Code size 16 (0x10)
.maxstack 1
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: call ""void System.Console.WriteLine(int)""
IL_0007: nop
IL_0008: ldc.i4.2
IL_0009: call ""void System.Console.WriteLine(int)""
IL_000e: nop
IL_000f: ret
}");
}
[Fact]
public void UniqueSynthesizedNames1()
{
var source0 = @"
using System;
public class C
{
public int F()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var source1 = @"
using System;
public class C
{
public int F(int x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
public int F()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var source2 = @"
using System;
public class C
{
public int F(int x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
public int F(byte x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
public int F()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A");
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var f_int1 = compilation1.GetMembers("C.F").Single(m => m.ToString() == "C.F(int)");
var f_byte2 = compilation2.GetMembers("C.F").Single(m => m.ToString() == "C.F(byte)");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>c__DisplayClass0_0", "<>c");
CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ".ctor", "<F>b__1", "<F>b__2", ".cctor", ".ctor", "<F>b__0_0");
CheckNames(reader0, reader0.GetFieldDefNames(), "<>4__this", "a", "<>9", "<>9__0_0");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f_int1)));
var reader1 = diff1.GetMetadata().Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>c__DisplayClass0#1_0#1");
CheckNames(new[] { reader0, reader1 }, reader1.GetMethodDefNames(), ".ctor", "F", ".ctor", "<F>b__1#1", "<F>b__2#1", "<F>b__0#1_0#1");
CheckNames(new[] { reader0, reader1 }, reader1.GetFieldDefNames(), "<>4__this", "a", "<>9__0#1_0#1");
diff1.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0#1_0#1, <>c}",
"C.<>c__DisplayClass0#1_0#1: {<>4__this, a, <F>b__1#1, <F>b__2#1}",
"C.<>c: {<>9__0#1_0#1, <F>b__0#1_0#1}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f_byte2)));
var reader2 = diff2.GetMetadata().Reader;
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>c__DisplayClass1#2_0#2");
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetMethodDefNames(), ".ctor", "F", ".ctor", "<F>b__1#2", "<F>b__2#2", "<F>b__1#2_0#2");
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetFieldDefNames(), "<>4__this", "a", "<>9__1#2_0#2");
}
[Fact]
public void UniqueSynthesizedNames1_Generic()
{
var source0 = @"
using System;
public class C
{
public int F<T>()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F<T>());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var source1 = @"
using System;
public class C
{
public int F<T>(int x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F<T>());
var f3 = new Func<int>(() => a);
return 2;
}
public int F<T>()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F<T>());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var source2 = @"
using System;
public class C
{
public int F<T>(int x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F<T>());
var f3 = new Func<int>(() => a);
return 2;
}
public int F<T>(byte x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F<T>());
var f3 = new Func<int>(() => a);
return 2;
}
public int F<T>()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F<T>());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A");
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var f_int1 = compilation1.GetMembers("C.F").Single(m => m.ToString() == "C.F<T>(int)");
var f_byte2 = compilation2.GetMembers("C.F").Single(m => m.ToString() == "C.F<T>(byte)");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>c__DisplayClass0_0`1", "<>c__0`1");
CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ".ctor", "<F>b__1", "<F>b__2", ".cctor", ".ctor", "<F>b__0_0");
CheckNames(reader0, reader0.GetFieldDefNames(), "<>4__this", "a", "<>9", "<>9__0_0");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f_int1)));
var reader1 = diff1.GetMetadata().Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>c__DisplayClass0#1_0#1`1", "<>c__0#1`1");
CheckNames(new[] { reader0, reader1 }, reader1.GetMethodDefNames(), "F", ".ctor", "<F>b__1#1", "<F>b__2#1", ".cctor", ".ctor", "<F>b__0#1_0#1");
CheckNames(new[] { reader0, reader1 }, reader1.GetFieldDefNames(), "<>4__this", "a", "<>9", "<>9__0#1_0#1");
diff1.VerifySynthesizedMembers(
"C.<>c__0#1<T>: {<>9__0#1_0#1, <F>b__0#1_0#1}",
"C: {<>c__DisplayClass0#1_0#1, <>c__0#1}",
"C.<>c__DisplayClass0#1_0#1<T>: {<>4__this, a, <F>b__1#1, <F>b__2#1}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f_byte2)));
var reader2 = diff2.GetMetadata().Reader;
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>c__DisplayClass1#2_0#2`1", "<>c__1#2`1");
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetMethodDefNames(), "F", ".ctor", "<F>b__1#2", "<F>b__2#2", ".cctor", ".ctor", "<F>b__1#2_0#2");
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetFieldDefNames(), "<>4__this", "a", "<>9", "<>9__1#2_0#2");
}
[Fact]
public void UniqueSynthesizedNames2()
{
var source0 = @"
using System;
public class C
{
public static void Main()
{
}
}";
var source1 = @"
using System;
public class C
{
public static void Main()
{
new C().F();
}
public int F()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var source2 = @"
using System;
public class C
{
public static void Main()
{
new C().F(1);
new C().F();
}
public int F(int x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
public int F()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var source3 = @"
using System;
public class C
{
public static void Main()
{
}
public int F(int x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
public int F()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A");
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var main0 = compilation0.GetMember<MethodSymbol>("C.Main");
var main1 = compilation1.GetMember<MethodSymbol>("C.Main");
var main2 = compilation2.GetMember<MethodSymbol>("C.Main");
var main3 = compilation3.GetMember<MethodSymbol>("C.Main");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f_int2 = compilation2.GetMembers("C.F").Single(m => m.ToString() == "C.F(int)");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f1),
SemanticEdit.Create(SemanticEditKind.Update, main0, main1, preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C.<>c: {<>9__1#1_0#1, <F>b__1#1_0#1}",
"C.<>c__DisplayClass1#1_0#1: {<>4__this, a, <F>b__1#1, <F>b__2#1}",
"C: {<>c__DisplayClass1#1_0#1, <>c}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f_int2),
SemanticEdit.Create(SemanticEditKind.Update, main1, main2, preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C.<>c__DisplayClass1#2_0#2: {<>4__this, a, <F>b__1#2, <F>b__2#2}",
"C: {<>c__DisplayClass1#2_0#2, <>c, <>c__DisplayClass1#1_0#1}",
"C.<>c: {<>9__1#2_0#2, <F>b__1#2_0#2, <>9__1#1_0#1, <F>b__1#1_0#1}",
"C.<>c__DisplayClass1#1_0#1: {<>4__this, a, <F>b__1#1, <F>b__2#1}");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, main2, main3, preserveLocalVariables: true)));
diff3.VerifySynthesizedMembers(
"C.<>c__DisplayClass1#1_0#1: {<>4__this, a, <F>b__1#1, <F>b__2#1}",
"C.<>c: {<>9__1#2_0#2, <F>b__1#2_0#2, <>9__1#1_0#1, <F>b__1#1_0#1}",
"C.<>c__DisplayClass1#2_0#2: {<>4__this, a, <F>b__1#2, <F>b__2#2}",
"C: {<>c__DisplayClass1#2_0#2, <>c, <>c__DisplayClass1#1_0#1}");
}
[Fact]
public void NestedLambdas()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + G(<N:1>b => 1</N:1>)</N:0>);
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + G(<N:1>b => 2</N:1>)</N:0>);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// 3 method updates:
// Note that even if the change is in the inner lambda such a change will usually impact sequence point
// spans in outer lambda and the method body. So although the IL doesn't change we usually need to update the outer methods.
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void LambdasInInitializers1()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
public int A = G(<N:0>a => a + 1</N:0>);
public C() : this(G(<N:1>a => a + 2</N:1>))
{
G(<N:2>a => a + 3</N:2>);
}
public C(int x)
{
G(<N:3>a => a + 4</N:3>);
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
public int A = G(<N:0>a => a - 1</N:0>);
public C() : this(G(<N:1>a => a - 2</N:1>))
{
G(<N:2>a => a - 3</N:2>);
}
public C(int x)
{
G(<N:3>a => a - 4</N:3>);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var ctor00 = compilation0.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor()");
var ctor10 = compilation0.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor(System.Int32 x)");
var ctor01 = compilation1.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor()");
var ctor11 = compilation1.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor(System.Int32 x)");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor00, ctor01, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true),
SemanticEdit.Create(SemanticEditKind.Update, ctor10, ctor11, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__2_0, <>9__2_1, <>9__3_0, <>9__3_1, <.ctor>b__2_0, <.ctor>b__2_1, <.ctor>b__3_0, <.ctor>b__3_1}");
diff1.VerifyIL("C.<>c.<.ctor>b__2_0", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.2
IL_0002: sub
IL_0003: ret
}");
diff1.VerifyIL("C.<>c.<.ctor>b__2_1", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.3
IL_0002: sub
IL_0003: ret
}");
diff1.VerifyIL("C.<>c.<.ctor>b__3_0", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.4
IL_0002: sub
IL_0003: ret
}");
diff1.VerifyIL("C.<>c.<.ctor>b__3_1", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: sub
IL_0003: ret
}");
}
[Fact]
public void LambdasInInitializers2()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
public int A = G(<N:0>a => { int <N:4>v1 = 1</N:4>; return 1; }</N:0>);
public C() : this(G(<N:1>a => { int <N:5>v2 = 1</N:5>; return 2; }</N:1>))
{
G(<N:2>a => { int <N:6>v3 = 1</N:6>; return 3; }</N:2>);
}
public C(int x)
{
G(<N:3>a => { int <N:7>v4 = 1</N:7>; return 4; }</N:3>);
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
public int A = G(<N:0>a => { int <N:4>v1 = 10</N:4>; return 1; }</N:0>);
public C() : this(G(<N:1>a => { int <N:5>v2 = 10</N:5>; return 2; }</N:1>))
{
G(<N:2>a => { int <N:6>v3 = 10</N:6>; return 3; }</N:2>);
}
public C(int x)
{
G(<N:3>a => { int <N:7>v4 = 10</N:7>; return 4; }</N:3>);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var ctor00 = compilation0.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor()");
var ctor10 = compilation0.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor(System.Int32 x)");
var ctor01 = compilation1.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor()");
var ctor11 = compilation1.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor(System.Int32 x)");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor00, ctor01, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true),
SemanticEdit.Create(SemanticEditKind.Update, ctor10, ctor11, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__2_0, <>9__2_1, <>9__3_0, <>9__3_1, <.ctor>b__2_0, <.ctor>b__2_1, <.ctor>b__3_0, <.ctor>b__3_1}");
diff1.VerifyIL("C.<>c.<.ctor>b__2_0", @"
{
// Code size 10 (0xa)
.maxstack 1
.locals init (int V_0, //v2
[int] V_1,
int V_2)
IL_0000: nop
IL_0001: ldc.i4.s 10
IL_0003: stloc.0
IL_0004: ldc.i4.2
IL_0005: stloc.2
IL_0006: br.s IL_0008
IL_0008: ldloc.2
IL_0009: ret
}");
diff1.VerifyIL("C.<>c.<.ctor>b__2_1", @"
{
// Code size 10 (0xa)
.maxstack 1
.locals init (int V_0, //v3
[int] V_1,
int V_2)
IL_0000: nop
IL_0001: ldc.i4.s 10
IL_0003: stloc.0
IL_0004: ldc.i4.3
IL_0005: stloc.2
IL_0006: br.s IL_0008
IL_0008: ldloc.2
IL_0009: ret
}");
diff1.VerifyIL("C.<>c.<.ctor>b__3_0", @"
{
// Code size 10 (0xa)
.maxstack 1
.locals init (int V_0, //v4
[int] V_1,
int V_2)
IL_0000: nop
IL_0001: ldc.i4.s 10
IL_0003: stloc.0
IL_0004: ldc.i4.4
IL_0005: stloc.2
IL_0006: br.s IL_0008
IL_0008: ldloc.2
IL_0009: ret
}");
diff1.VerifyIL("C.<>c.<.ctor>b__3_1", @"
{
// Code size 10 (0xa)
.maxstack 1
.locals init (int V_0, //v1
[int] V_1,
int V_2)
IL_0000: nop
IL_0001: ldc.i4.s 10
IL_0003: stloc.0
IL_0004: ldc.i4.1
IL_0005: stloc.2
IL_0006: br.s IL_0008
IL_0008: ldloc.2
IL_0009: ret
}");
}
[Fact]
public void UpdateParameterlessConstructorInPresenceOfFieldInitializersWithLambdas()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0>a => a + 1</N:0>);
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0>a => a + 1</N:0>);
int B = F(b => b + 1); // new field
public C() // new ctor
{
F(c => c + 1);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var b1 = compilation1.GetMember<FieldSymbol>("C.B");
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, b1),
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__2_0#1, <>9__2_0, <>9__2_2#1, <.ctor>b__2_0#1, <.ctor>b__2_0, <.ctor>b__2_2#1}");
diff1.VerifyIL("C..ctor", @"
{
// Code size 130 (0x82)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldsfld ""System.Func<int, int> C.<>c.<>9__2_0""
IL_0006: dup
IL_0007: brtrue.s IL_0020
IL_0009: pop
IL_000a: ldsfld ""C.<>c C.<>c.<>9""
IL_000f: ldftn ""int C.<>c.<.ctor>b__2_0(int)""
IL_0015: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_001a: dup
IL_001b: stsfld ""System.Func<int, int> C.<>c.<>9__2_0""
IL_0020: call ""int C.F(System.Func<int, int>)""
IL_0025: stfld ""int C.A""
IL_002a: ldarg.0
IL_002b: ldsfld ""System.Func<int, int> C.<>c.<>9__2_2#1""
IL_0030: dup
IL_0031: brtrue.s IL_004a
IL_0033: pop
IL_0034: ldsfld ""C.<>c C.<>c.<>9""
IL_0039: ldftn ""int C.<>c.<.ctor>b__2_2#1(int)""
IL_003f: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0044: dup
IL_0045: stsfld ""System.Func<int, int> C.<>c.<>9__2_2#1""
IL_004a: call ""int C.F(System.Func<int, int>)""
IL_004f: stfld ""int C.B""
IL_0054: ldarg.0
IL_0055: call ""object..ctor()""
IL_005a: nop
IL_005b: nop
IL_005c: ldsfld ""System.Func<int, int> C.<>c.<>9__2_0#1""
IL_0061: dup
IL_0062: brtrue.s IL_007b
IL_0064: pop
IL_0065: ldsfld ""C.<>c C.<>c.<>9""
IL_006a: ldftn ""int C.<>c.<.ctor>b__2_0#1(int)""
IL_0070: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0075: dup
IL_0076: stsfld ""System.Func<int, int> C.<>c.<>9__2_0#1""
IL_007b: call ""int C.F(System.Func<int, int>)""
IL_0080: pop
IL_0081: ret
}
");
}
[Fact(Skip = "2504"), WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")]
public void InsertConstructorInPresenceOfFieldInitializersWithLambdas()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0>a => a + 1</N:0>);
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0>a => a + 1</N:0>);
int B = F(b => b + 1); // new field
public C(int x) // new ctor
{
F(c => c + 1);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var b1 = compilation1.GetMember<FieldSymbol>("C.B");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, b1),
SemanticEdit.Create(SemanticEditKind.Insert, null, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C: {<> c}",
"C.<>c: {<>9__2_0#1, <>9__2_0, <>9__2_2#1, <.ctor>b__2_0#1, <.ctor>b__2_0, <.ctor>b__2_2#1}");
}
[Fact]
public void Queries_Select_Reduced1()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>where a > 0</N:1>
<N:2>select a</N:2></N:0>;
}
int[] array = null;
}
");
var source1 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>where a > 0</N:1>
<N:2>select a + 1</N:2></N:0>;
}
int[] array = null;
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// new lambda for Select(a => a + 1)
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1#1, <F>b__0_0, <F>b__0_1#1}");
diff1.VerifyIL("C.<>c.<F>b__0_1#1", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: ret
}
");
// old query:
v0.VerifyIL("C.F", @"
{
// Code size 45 (0x2d)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""bool C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_0026: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Where<int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_002b: stloc.0
IL_002c: ret
}
");
// new query:
diff1.VerifyIL("C.F", @"
{
// Code size 81 (0x51)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""bool C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_0026: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Where<int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_002b: ldsfld ""System.Func<int, int> C.<>c.<>9__0_1#1""
IL_0030: dup
IL_0031: brtrue.s IL_004a
IL_0033: pop
IL_0034: ldsfld ""C.<>c C.<>c.<>9""
IL_0039: ldftn ""int C.<>c.<F>b__0_1#1(int)""
IL_003f: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0044: dup
IL_0045: stsfld ""System.Func<int, int> C.<>c.<>9__0_1#1""
IL_004a: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_004f: stloc.0
IL_0050: ret
}
");
}
[Fact]
public void Queries_Select_Reduced2()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>where a > 0</N:1>
<N:2>select a + 1</N:2></N:0>;
}
int[] array = null;
}
");
var source1 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>where a > 0</N:1>
<N:2>select a</N:2></N:0>;
}
int[] array = null;
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// lambda for Select(a => a + 1) is gone
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <F>b__0_0}");
// old query:
v0.VerifyIL("C.F", @"
{
// Code size 81 (0x51)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""bool C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_0026: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Where<int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_002b: ldsfld ""System.Func<int, int> C.<>c.<>9__0_1""
IL_0030: dup
IL_0031: brtrue.s IL_004a
IL_0033: pop
IL_0034: ldsfld ""C.<>c C.<>c.<>9""
IL_0039: ldftn ""int C.<>c.<F>b__0_1(int)""
IL_003f: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0044: dup
IL_0045: stsfld ""System.Func<int, int> C.<>c.<>9__0_1""
IL_004a: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_004f: stloc.0
IL_0050: ret
}
");
// new query:
diff1.VerifyIL("C.F", @"
{
// Code size 45 (0x2d)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""bool C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_0026: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Where<int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_002b: stloc.0
IL_002c: ret
}
");
}
[Fact]
public void Queries_GroupBy_Reduced1()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>group a by a</N:1></N:0>;
}
int[] array = null;
}
");
var source1 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>group a + 1 by a</N:1></N:0>;
}
int[] array = null;
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// new lambda for GroupBy(..., a => a + 1)
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1#1, <F>b__0_0, <F>b__0_1#1}");
diff1.VerifyIL("C.<>c.<F>b__0_1#1", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: ret
}
");
// old query:
v0.VerifyIL("C.F", @"
{
// Code size 45 (0x2d)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""int C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_0026: call ""System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> System.Linq.Enumerable.GroupBy<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_002b: stloc.0
IL_002c: ret
}
");
// new query:
diff1.VerifyIL("C.F", @"
{
// Code size 76 (0x4c)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""int C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_0026: ldsfld ""System.Func<int, int> C.<>c.<>9__0_1#1""
IL_002b: dup
IL_002c: brtrue.s IL_0045
IL_002e: pop
IL_002f: ldsfld ""C.<>c C.<>c.<>9""
IL_0034: ldftn ""int C.<>c.<F>b__0_1#1(int)""
IL_003a: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_003f: dup
IL_0040: stsfld ""System.Func<int, int> C.<>c.<>9__0_1#1""
IL_0045: call ""System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> System.Linq.Enumerable.GroupBy<int, int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>, System.Func<int, int>)""
IL_004a: stloc.0
IL_004b: ret
}
");
}
[Fact]
public void Queries_GroupBy_Reduced2()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>group a + 1 by a</N:1></N:0>;
}
int[] array = null;
}
");
var source1 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>group a by a</N:1></N:0>;
}
int[] array = null;
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// lambda for GroupBy(..., a => a + 1) is gone
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <F>b__0_0}");
// old query:
v0.VerifyIL("C.F", @"
{
// Code size 76 (0x4c)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""int C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_0026: ldsfld ""System.Func<int, int> C.<>c.<>9__0_1""
IL_002b: dup
IL_002c: brtrue.s IL_0045
IL_002e: pop
IL_002f: ldsfld ""C.<>c C.<>c.<>9""
IL_0034: ldftn ""int C.<>c.<F>b__0_1(int)""
IL_003a: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_003f: dup
IL_0040: stsfld ""System.Func<int, int> C.<>c.<>9__0_1""
IL_0045: call ""System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> System.Linq.Enumerable.GroupBy<int, int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>, System.Func<int, int>)""
IL_004a: stloc.0
IL_004b: ret
}
");
// new query:
diff1.VerifyIL("C.F", @"
{
// Code size 45 (0x2d)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""int C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_0026: call ""System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> System.Linq.Enumerable.GroupBy<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_002b: stloc.0
IL_002c: ret
}
");
}
[Fact, WorkItem(1170899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1170899")]
public void CapturedAnonymousTypes1()
{
var source0 = MarkedSource(@"
using System;
class C
{
static void F()
<N:0>{
var <N:1>x = new { A = 1 }</N:1>;
var <N:2>y = new Func<int>(<N:3>() => x.A</N:3>)</N:2>;
Console.WriteLine(1);
}</N:0>
}
");
var source1 = MarkedSource(@"
using System;
class C
{
static void F()
<N:0>{
var <N:1>x = new { A = 1 }</N:1>;
var <N:2>y = new Func<int>(<N:3>() => x.A</N:3>)</N:2>;
Console.WriteLine(2);
}</N:0>
}
");
var source2 = MarkedSource(@"
using System;
class C
{
static void F()
<N:0>{
var <N:1>x = new { A = 1 }</N:1>;
var <N:2>y = new Func<int>(<N:3>() => x.A</N:3>)</N:2>;
Console.WriteLine(3);
}</N:0>
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
v0.VerifyIL("C.F", @"
{
// Code size 40 (0x28)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
System.Func<int> V_1) //y
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldc.i4.1
IL_0009: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_000e: stfld ""<anonymous type: int A> C.<>c__DisplayClass0_0.x""
IL_0013: ldloc.0
IL_0014: ldftn ""int C.<>c__DisplayClass0_0.<F>b__0()""
IL_001a: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001f: stloc.1
IL_0020: ldc.i4.1
IL_0021: call ""void System.Console.WriteLine(int)""
IL_0026: nop
IL_0027: ret
}");
var diff1 = compilation1.EmitDifference(generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {x, <F>b__0}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.F", @"
{
// Code size 40 (0x28)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
System.Func<int> V_1) //y
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldc.i4.1
IL_0009: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_000e: stfld ""<anonymous type: int A> C.<>c__DisplayClass0_0.x""
IL_0013: ldloc.0
IL_0014: ldftn ""int C.<>c__DisplayClass0_0.<F>b__0()""
IL_001a: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001f: stloc.1
IL_0020: ldc.i4.2
IL_0021: call ""void System.Console.WriteLine(int)""
IL_0026: nop
IL_0027: ret
}");
var diff2 = compilation2.EmitDifference(diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {x, <F>b__0}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", @"
{
// Code size 40 (0x28)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
System.Func<int> V_1) //y
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldc.i4.1
IL_0009: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_000e: stfld ""<anonymous type: int A> C.<>c__DisplayClass0_0.x""
IL_0013: ldloc.0
IL_0014: ldftn ""int C.<>c__DisplayClass0_0.<F>b__0()""
IL_001a: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001f: stloc.1
IL_0020: ldc.i4.3
IL_0021: call ""void System.Console.WriteLine(int)""
IL_0026: nop
IL_0027: ret
}");
}
[Fact, WorkItem(1170899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1170899")]
public void CapturedAnonymousTypes2()
{
var template = @"
using System;
class C
{
static void F()
<N:0>{
var x = new { X = <<VALUE>> };
Func<int> <N:2>y = <N:1>() => x.X</N:1></N:2>;
Console.WriteLine(y());
}</N:0>
}
";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
string expectedIL = @"
{
// Code size 45 (0x2d)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
System.Func<int> V_1) //y
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldc.i4.<<VALUE>>
IL_0009: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_000e: stfld ""<anonymous type: int X> C.<>c__DisplayClass0_0.x""
IL_0013: ldloc.0
IL_0014: ldftn ""int C.<>c__DisplayClass0_0.<F>b__0()""
IL_001a: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001f: stloc.1
IL_0020: ldloc.1
IL_0021: callvirt ""int System.Func<int>.Invoke()""
IL_0026: call ""void System.Console.WriteLine(int)""
IL_002b: nop
IL_002c: ret
}";
v0.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "0"));
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {x, <F>b__0}",
"<>f__AnonymousType0<<X>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "1"));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {x, <F>b__0}",
"<>f__AnonymousType0<<X>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2"));
}
[WorkItem(179990, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/179990")]
[Fact]
public void SynthesizedDelegates()
{
var template =
@"class C
{
static void F(dynamic d, out object x, object y)
<N:0>{
<<CALL>>;
}</N:0>
}";
var source0 = MarkedSource(template.Replace("<<CALL>>", "d.F(out x, new { })"));
var source1 = MarkedSource(template.Replace("<<CALL>>", "d.F(out x, new { y })"));
var source2 = MarkedSource(template.Replace("<<CALL>>", "d.F(new { y }, out x)"));
var compilation0 = CreateCompilationWithMscorlib40(new[] { source0.Tree }, references: new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
v0.VerifyIL("C.F",
@"{
// Code size 112 (0x70)
.maxstack 9
IL_0000: nop
IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>> C.<>o__0.<>p__0""
IL_0006: brfalse.s IL_000a
IL_0008: br.s IL_0053
IL_000a: ldc.i4 0x100
IL_000f: ldstr ""F""
IL_0014: ldnull
IL_0015: ldtoken ""C""
IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001f: ldc.i4.3
IL_0020: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_0025: dup
IL_0026: ldc.i4.0
IL_0027: ldc.i4.0
IL_0028: ldnull
IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_002e: stelem.ref
IL_002f: dup
IL_0030: ldc.i4.1
IL_0031: ldc.i4.s 17
IL_0033: ldnull
IL_0034: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0039: stelem.ref
IL_003a: dup
IL_003b: ldc.i4.2
IL_003c: ldc.i4.1
IL_003d: ldnull
IL_003e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0043: stelem.ref
IL_0044: 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_0049: call ""System.Runtime.CompilerServices.CallSite<<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>> System.Runtime.CompilerServices.CallSite<<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_004e: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>> C.<>o__0.<>p__0""
IL_0053: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>> C.<>o__0.<>p__0""
IL_0058: ldfld ""<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>> System.Runtime.CompilerServices.CallSite<<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>>.Target""
IL_005d: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>> C.<>o__0.<>p__0""
IL_0062: ldarg.0
IL_0063: ldarg.1
IL_0064: newobj ""<>f__AnonymousType0..ctor()""
IL_0069: callvirt ""void <>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic, ref object, <empty anonymous type>)""
IL_006e: nop
IL_006f: ret
}");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.F",
@"{
// Code size 113 (0x71)
.maxstack 9
IL_0000: nop
IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>> C.<>o__0#1.<>p__0""
IL_0006: brfalse.s IL_000a
IL_0008: br.s IL_0053
IL_000a: ldc.i4 0x100
IL_000f: ldstr ""F""
IL_0014: ldnull
IL_0015: ldtoken ""C""
IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001f: ldc.i4.3
IL_0020: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_0025: dup
IL_0026: ldc.i4.0
IL_0027: ldc.i4.0
IL_0028: ldnull
IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_002e: stelem.ref
IL_002f: dup
IL_0030: ldc.i4.1
IL_0031: ldc.i4.s 17
IL_0033: ldnull
IL_0034: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0039: stelem.ref
IL_003a: dup
IL_003b: ldc.i4.2
IL_003c: ldc.i4.1
IL_003d: ldnull
IL_003e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0043: stelem.ref
IL_0044: 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_0049: call ""System.Runtime.CompilerServices.CallSite<<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>> System.Runtime.CompilerServices.CallSite<<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_004e: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>> C.<>o__0#1.<>p__0""
IL_0053: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>> C.<>o__0#1.<>p__0""
IL_0058: ldfld ""<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>> System.Runtime.CompilerServices.CallSite<<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>>.Target""
IL_005d: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>> C.<>o__0#1.<>p__0""
IL_0062: ldarg.0
IL_0063: ldarg.1
IL_0064: ldarg.2
IL_0065: newobj ""<>f__AnonymousType1<object>..ctor(object)""
IL_006a: callvirt ""void <>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic, ref object, <anonymous type: object y>)""
IL_006f: nop
IL_0070: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifyIL("C.F",
@"{
// Code size 113 (0x71)
.maxstack 9
IL_0000: nop
IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>> C.<>o__0#2.<>p__0""
IL_0006: brfalse.s IL_000a
IL_0008: br.s IL_0053
IL_000a: ldc.i4 0x100
IL_000f: ldstr ""F""
IL_0014: ldnull
IL_0015: ldtoken ""C""
IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001f: ldc.i4.3
IL_0020: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_0025: dup
IL_0026: ldc.i4.0
IL_0027: ldc.i4.0
IL_0028: ldnull
IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_002e: stelem.ref
IL_002f: dup
IL_0030: ldc.i4.1
IL_0031: ldc.i4.1
IL_0032: ldnull
IL_0033: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0038: stelem.ref
IL_0039: dup
IL_003a: ldc.i4.2
IL_003b: ldc.i4.s 17
IL_003d: ldnull
IL_003e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0043: stelem.ref
IL_0044: 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_0049: call ""System.Runtime.CompilerServices.CallSite<<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>> System.Runtime.CompilerServices.CallSite<<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_004e: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>> C.<>o__0#2.<>p__0""
IL_0053: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>> C.<>o__0#2.<>p__0""
IL_0058: ldfld ""<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object> System.Runtime.CompilerServices.CallSite<<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>>.Target""
IL_005d: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>> C.<>o__0#2.<>p__0""
IL_0062: ldarg.0
IL_0063: ldarg.2
IL_0064: newobj ""<>f__AnonymousType1<object>..ctor(object)""
IL_0069: ldarg.1
IL_006a: callvirt ""void <>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, ref object)""
IL_006f: nop
IL_0070: ret
}");
}
[Fact]
public void TwoStructClosures()
{
var source0 = MarkedSource(@"
public class C
{
public void F()
<N:0>{</N:0>
int <N:1>x</N:1> = 0;
<N:2>{</N:2>
int <N:3>y</N:3> = 0;
// Captures two struct closures
<N:4>int L() => x + y;</N:4>
}
}
}");
var source1 = MarkedSource(@"
public class C
{
public void F()
<N:0>{</N:0>
int <N:1>x</N:1> = 0;
<N:2>{</N:2>
int <N:3>y</N:3> = 0;
// Captures two struct closures
<N:4>int L() => x + y + 1;</N:4>
}
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass0_0: {x}",
"C.<>c__DisplayClass0_1: {y}",
"C: {<F>g__L|0_0, <>c__DisplayClass0_0, <>c__DisplayClass0_1}");
v0.VerifyIL("C.<F>g__L|0_0(ref C.<>c__DisplayClass0_0, ref C.<>c__DisplayClass0_1)", @"
{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldarg.1
IL_0007: ldfld ""int C.<>c__DisplayClass0_1.y""
IL_000c: add
IL_000d: ret
}");
diff1.VerifyIL("C.<F>g__L|0_0(ref C.<>c__DisplayClass0_0, ref C.<>c__DisplayClass0_1)", @"
{
// Code size 16 (0x10)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldarg.1
IL_0007: ldfld ""int C.<>c__DisplayClass0_1.y""
IL_000c: add
IL_000d: ldc.i4.1
IL_000e: add
IL_000f: ret
}
");
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void ThisClosureAndStructClosure()
{
var source0 = MarkedSource(@"
public class C
{
int <N:0>x</N:0> = 0;
public void F()
<N:1>{</N:1>
int <N:2>y</N:2> = 0;
// This + struct closures
<N:3>int L() => x + y;</N:3>
L();
}
}");
var source1 = MarkedSource(@"
public class C
{
int <N:0>x</N:0> = 0;
public void F()
<N:1>{</N:1>
int <N:2>y</N:2> = 0;
// This + struct closures
<N:3>int L() => x + y + 1;</N:3>
L();
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass1_0: {<>4__this, y}",
"C: {<F>g__L|1_0, <>c__DisplayClass1_0}");
v0.VerifyIL("C.<F>g__L|1_0(ref C.<>c__DisplayClass1_0)", @"
{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.x""
IL_0006: ldarg.1
IL_0007: ldfld ""int C.<>c__DisplayClass1_0.y""
IL_000c: add
IL_000d: ret
}
");
diff1.VerifyIL("C.<F>g__L|1_0(ref C.<>c__DisplayClass1_0)", @"
{
// Code size 16 (0x10)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.x""
IL_0006: ldarg.1
IL_0007: ldfld ""int C.<>c__DisplayClass1_0.y""
IL_000c: add
IL_000d: ldc.i4.1
IL_000e: add
IL_000f: ret
}
");
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void ThisOnlyClosure()
{
var source0 = MarkedSource(@"
public class C
{
int <N:0>x</N:0> = 0;
public void F()
<N:1>{</N:1>
// This-only closure
<N:2>int L() => x;</N:2>
L();
}
}");
var source1 = MarkedSource(@"
public class C
{
int <N:0>x</N:0> = 0;
public void F()
<N:1>{</N:1>
// This-only closure
<N:2>int L() => x + 1;</N:2>
L();
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C: {<F>g__L|1_0}");
v0.VerifyIL("C.<F>g__L|1_0()", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""int C.x""
IL_0006: ret
}");
diff1.VerifyIL("C.<F>g__L|1_0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void LocatedInSameClosureEnvironment()
{
var source0 = MarkedSource(@"
using System;
public class C
{
public void F(int x)
<N:0>{</N:0>
Func<int> f = <N:1>() => x</N:1>;
// Located in same closure environment
<N:2>int L() => x;</N:2>
}
}");
var source1 = MarkedSource(@"
using System;
public class C
{
public void F(int x)
<N:0>{</N:0>
Func<int> f = <N:1>() => x</N:1>;
// Located in same closure environment
<N:2>int L() => x + 1;</N:2>
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass0_0: {x, <F>b__0, <F>g__L|1}",
"C: {<>c__DisplayClass0_0}");
v0.VerifyIL("C.<>c__DisplayClass0_0.<F>g__L|1()", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ret
}");
diff1.VerifyIL("C.<>c__DisplayClass0_0.<F>g__L|1()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void SameClassEnvironmentWithStruct()
{
var source0 = MarkedSource(@"
using System;
public class C
{
public void F(int x)
<N:0>{</N:0>
<N:1>{</N:1>
int <N:2>y</N:2> = 0;
Func<int> f = <N:3>() => x</N:3>;
// Same class environment, with struct env
<N:4>int L() => x + y;</N:4>
}
}
}");
var source1 = MarkedSource(@"
using System;
public class C
{
public void F(int x)
<N:0>{</N:0>
<N:1>{</N:1>
int <N:2>y</N:2> = 0;
Func<int> f = <N:3>() => x</N:3>;
// Same class environment, with struct env
<N:4>int L() => x + y + 1;</N:4>
}
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0, <>c__DisplayClass0_1}",
"C.<>c__DisplayClass0_0: {x, <F>b__0, <F>g__L|1}",
"C.<>c__DisplayClass0_1: {y}");
v0.VerifyIL("C.<>c__DisplayClass0_0.<F>g__L|1(ref C.<>c__DisplayClass0_1)", @"
{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldarg.1
IL_0007: ldfld ""int C.<>c__DisplayClass0_1.y""
IL_000c: add
IL_000d: ret
}");
diff1.VerifyIL("C.<>c__DisplayClass0_0.<F>g__L|1(ref C.<>c__DisplayClass0_1)", @"
{
// Code size 16 (0x10)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldarg.1
IL_0007: ldfld ""int C.<>c__DisplayClass0_1.y""
IL_000c: add
IL_000d: ldc.i4.1
IL_000e: add
IL_000f: ret
}
");
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void CaptureStructAndThroughClassEnvChain()
{
var source0 = MarkedSource(@"
using System;
public class C
{
public void F(int x)
<N:0>{</N:0>
<N:1>{</N:1>
int <N:2>y</N:2> = 0;
Func<int> f = <N:3>() => x</N:3>;
<N:4>{</N:4>
Func<int> f2 = <N:5>() => x + y</N:5>;
int <N:6>z</N:6> = 0;
// Capture struct and through class env chain
<N:7>int L() => x + y + z;</N:7>
}
}
}
}");
var source1 = MarkedSource(@"
using System;
public class C
{
public void F(int x)
<N:0>{</N:0>
<N:1>{</N:1>
int <N:2>y</N:2> = 0;
Func<int> f = <N:3>() => x</N:3>;
<N:4>{</N:4>
Func<int> f2 = <N:5>() => x + y</N:5>;
int <N:6>z</N:6> = 0;
// Capture struct and through class env chain
<N:7>int L() => x + y + z + 1;</N:7>
}
}
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass0_2: {z}",
"C.<>c__DisplayClass0_0: {x, <F>b__0}",
"C: {<>c__DisplayClass0_0, <>c__DisplayClass0_1, <>c__DisplayClass0_2}",
"C.<>c__DisplayClass0_1: {y, CS$<>8__locals1, <F>b__1, <F>g__L|2}");
v0.VerifyIL("C.<>c__DisplayClass0_1.<F>g__L|2(ref C.<>c__DisplayClass0_2)", @"
{
// Code size 26 (0x1a)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""C.<>c__DisplayClass0_0 C.<>c__DisplayClass0_1.CS$<>8__locals1""
IL_0006: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_000b: ldarg.0
IL_000c: ldfld ""int C.<>c__DisplayClass0_1.y""
IL_0011: add
IL_0012: ldarg.1
IL_0013: ldfld ""int C.<>c__DisplayClass0_2.z""
IL_0018: add
IL_0019: ret
}");
diff1.VerifyIL("C.<>c__DisplayClass0_1.<F>g__L|2(ref C.<>c__DisplayClass0_2)", @"
{
// Code size 28 (0x1c)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""C.<>c__DisplayClass0_0 C.<>c__DisplayClass0_1.CS$<>8__locals1""
IL_0006: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_000b: ldarg.0
IL_000c: ldfld ""int C.<>c__DisplayClass0_1.y""
IL_0011: add
IL_0012: ldarg.1
IL_0013: ldfld ""int C.<>c__DisplayClass0_2.z""
IL_0018: add
IL_0019: ldc.i4.1
IL_001a: add
IL_001b: ret
}
");
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void TopLevelStatement_Closure()
{
var source0 = MarkedSource(@"
<N:0>
using System;
Func<string> x = <N:1>() => args[0]</N:1>;
Console.WriteLine(x());
</N:0>
");
var source1 = MarkedSource(@"
<N:0>
using System;
Func<string> x = <N:1>() => args[1]</N:1>;
Console.WriteLine(x());
</N:0>
");
var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugExe);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("Program.<Main>$");
var f1 = compilation1.GetMember<MethodSymbol>("Program.<Main>$");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"Program.<>c__DisplayClass0_0: {args, <<Main>$>b__0}",
"Program: {<>c__DisplayClass0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
[WorkItem(55381, "https://github.com/dotnet/roslyn/issues/55381")]
public void HiddenMethodClosure()
{
var source0 = MarkedSource(@"
#line hidden
using System;
class C
{
public static void F(int arg)
<N:0>{</N:0>
Func<int> x = <N:1>() => arg</N:1>;
}
}
");
var source1 = MarkedSource(@"
#line hidden
using System;
class C
{
public static void F(int arg)
<N:0>{</N:0>
Func<int> x = <N:1>() => arg + 1</N:1>;
}
}
");
var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {arg, <F>b__0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
}
}
}
| 1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Compilers/CSharp/Test/Emit/PDB/PDBTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using System.Text;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.PdbUtilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB
{
public class PDBTests : CSharpPDBTestBase
{
private static readonly MetadataReference[] s_valueTupleRefs = new[] { SystemRuntimeFacadeRef, ValueTupleRef };
#region General
[Fact]
public void EmitDebugInfoForSourceTextWithoutEncoding1()
{
var tree1 = SyntaxFactory.ParseSyntaxTree("class A { }", encoding: null, path: "Foo.cs");
var tree2 = SyntaxFactory.ParseSyntaxTree("class B { }", encoding: null, path: "");
var tree3 = SyntaxFactory.ParseSyntaxTree(SourceText.From("class C { }", encoding: null), path: "Bar.cs");
var tree4 = SyntaxFactory.ParseSyntaxTree("class D { }", encoding: Encoding.UTF8, path: "Baz.cs");
var comp = CSharpCompilation.Create("Compilation", new[] { tree1, tree2, tree3, tree4 }, new[] { MscorlibRef }, options: TestOptions.ReleaseDll);
var result = comp.Emit(new MemoryStream(), pdbStream: new MemoryStream());
result.Diagnostics.Verify(
// Foo.cs(1,1): error CS8055: Cannot emit debug information for a source text without encoding.
Diagnostic(ErrorCode.ERR_EncodinglessSyntaxTree, "class A { }").WithLocation(1, 1),
// Bar.cs(1,1): error CS8055: Cannot emit debug information for a source text without encoding.
Diagnostic(ErrorCode.ERR_EncodinglessSyntaxTree, "class C { }").WithLocation(1, 1));
Assert.False(result.Success);
}
[Fact]
public void EmitDebugInfoForSourceTextWithoutEncoding2()
{
var tree1 = SyntaxFactory.ParseSyntaxTree("class A { public void F() { } }", encoding: Encoding.Unicode, path: "Foo.cs");
var tree2 = SyntaxFactory.ParseSyntaxTree("class B { public void F() { } }", encoding: null, path: "");
var tree3 = SyntaxFactory.ParseSyntaxTree("class C { public void F() { } }", encoding: new UTF8Encoding(true, false), path: "Bar.cs");
var tree4 = SyntaxFactory.ParseSyntaxTree(SourceText.From("class D { public void F() { } }", new UTF8Encoding(false, false)), path: "Baz.cs");
var comp = CSharpCompilation.Create("Compilation", new[] { tree1, tree2, tree3, tree4 }, new[] { MscorlibRef }, options: TestOptions.ReleaseDll);
var result = comp.Emit(new MemoryStream(), pdbStream: new MemoryStream());
result.Diagnostics.Verify();
Assert.True(result.Success);
var hash1 = CryptographicHashProvider.ComputeSha1(Encoding.Unicode.GetBytesWithPreamble(tree1.ToString())).ToArray();
var hash3 = CryptographicHashProvider.ComputeSha1(new UTF8Encoding(true, false).GetBytesWithPreamble(tree3.ToString())).ToArray();
var hash4 = CryptographicHashProvider.ComputeSha1(new UTF8Encoding(false, false).GetBytesWithPreamble(tree4.ToString())).ToArray();
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""Foo.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""" + BitConverter.ToString(hash1) + @""" />
<file id=""2"" name="""" language=""C#"" />
<file id=""3"" name=""Bar.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""" + BitConverter.ToString(hash3) + @""" />
<file id=""4"" name=""Baz.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""" + BitConverter.ToString(hash4) + @""" />
</files>
</symbols>", options: PdbValidationOptions.ExcludeMethods);
}
[WorkItem(846584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/846584")]
[ConditionalFact(typeof(WindowsOnly))]
public void RelativePathForExternalSource_Sha1_Windows()
{
var text1 = WithWindowsLineBreaks(@"
#pragma checksum ""..\Test2.cs"" ""{406ea660-64cf-4c82-b6f0-42d48172a799}"" ""BA8CBEA9C2EFABD90D53B616FB80A081""
public class C
{
public void InitializeComponent() {
#line 4 ""..\Test2.cs""
InitializeComponent();
#line default
}
}
");
var compilation = CreateCompilation(
new[] { Parse(text1, @"C:\Folder1\Folder2\Test1.cs") },
options: TestOptions.DebugDll.WithSourceReferenceResolver(SourceFileResolver.Default));
compilation.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""C:\Folder1\Folder2\Test1.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""40-A6-20-02-2E-60-7D-4F-2D-A8-F4-A6-ED-2E-0E-49-8D-9F-D7-EB"" />
<file id=""2"" name=""C:\Folder1\Test2.cs"" language=""C#"" checksumAlgorithm=""406ea660-64cf-4c82-b6f0-42d48172a799"" checksum=""BA-8C-BE-A9-C2-EF-AB-D9-0D-53-B6-16-FB-80-A0-81"" />
</files>
<methods>
<method containingType=""C"" name=""InitializeComponent"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""39"" endLine=""6"" endColumn=""40"" document=""1"" />
<entry offset=""0x1"" startLine=""4"" startColumn=""9"" endLine=""4"" endColumn=""31"" document=""2"" />
<entry offset=""0x8"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(846584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/846584")]
[ConditionalFact(typeof(UnixLikeOnly))]
public void RelativePathForExternalSource_Sha1_Unix()
{
var text1 = WithWindowsLineBreaks(@"
#pragma checksum ""../Test2.cs"" ""{406ea660-64cf-4c82-b6f0-42d48172a799}"" ""BA8CBEA9C2EFABD90D53B616FB80A081""
public class C
{
public void InitializeComponent() {
#line 4 ""../Test2.cs""
InitializeComponent();
#line default
}
}
");
var compilation = CreateCompilation(
new[] { Parse(text1, @"/Folder1/Folder2/Test1.cs") },
options: TestOptions.DebugDll.WithSourceReferenceResolver(SourceFileResolver.Default));
compilation.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""/Folder1/Folder2/Test1.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""82-08-07-BA-BA-52-02-D8-1D-1F-7C-E7-95-8A-6C-04-64-FF-50-31"" />
<file id=""2"" name=""/Folder1/Test2.cs"" language=""C#"" checksumAlgorithm=""406ea660-64cf-4c82-b6f0-42d48172a799"" checksum=""BA-8C-BE-A9-C2-EF-AB-D9-0D-53-B6-16-FB-80-A0-81"" />
</files>
<methods>
<method containingType=""C"" name=""InitializeComponent"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""39"" endLine=""6"" endColumn=""40"" document=""1"" />
<entry offset=""0x1"" startLine=""4"" startColumn=""9"" endLine=""4"" endColumn=""31"" document=""2"" />
<entry offset=""0x8"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SymWriterErrors()
{
var source0 =
@"class C
{
}";
var compilation = CreateCompilation(source0, options: TestOptions.DebugDll);
// Verify full metadata contains expected rows.
var result = compilation.Emit(
peStream: new MemoryStream(),
metadataPEStream: null,
pdbStream: new MemoryStream(),
xmlDocumentationStream: null,
cancellationToken: default,
win32Resources: null,
manifestResources: null,
options: null,
debugEntryPoint: null,
sourceLinkStream: null,
embeddedTexts: null,
rebuildData: null,
testData: new CompilationTestData() { SymWriterFactory = _ => new MockSymUnmanagedWriter() });
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'MockSymUnmanagedWriter error message'
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("MockSymUnmanagedWriter error message"));
Assert.False(result.Success);
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SymWriterErrors2()
{
var source0 =
@"class C
{
}";
var compilation = CreateCompilation(source0, options: TestOptions.DebugDll);
// Verify full metadata contains expected rows.
var result = compilation.Emit(
peStream: new MemoryStream(),
metadataPEStream: null,
pdbStream: new MemoryStream(),
xmlDocumentationStream: null,
cancellationToken: default,
win32Resources: null,
manifestResources: null,
options: null,
debugEntryPoint: null,
sourceLinkStream: null,
embeddedTexts: null,
rebuildData: null,
testData: new CompilationTestData() { SymWriterFactory = SymWriterTestUtilities.ThrowingFactory });
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'The version of Windows PDB writer is older than required: '<lib name>''
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments(string.Format(CodeAnalysisResources.SymWriterOlderVersionThanRequired, "<lib name>")));
Assert.False(result.Success);
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SymWriterErrors3()
{
var source0 =
@"class C
{
}";
var compilation = CreateCompilation(source0, options: TestOptions.DebugDll.WithDeterministic(true));
// Verify full metadata contains expected rows.
var result = compilation.Emit(
peStream: new MemoryStream(),
metadataPEStream: null,
pdbStream: new MemoryStream(),
xmlDocumentationStream: null,
cancellationToken: default,
win32Resources: null,
manifestResources: null,
options: null,
debugEntryPoint: null,
sourceLinkStream: null,
embeddedTexts: null,
rebuildData: null,
testData: new CompilationTestData() { SymWriterFactory = SymWriterTestUtilities.ThrowingFactory });
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'Windows PDB writer doesn't support deterministic compilation: '<lib name>''
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments(string.Format(CodeAnalysisResources.SymWriterNotDeterministic, "<lib name>")));
Assert.False(result.Success);
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SymWriterErrors4()
{
var source0 =
@"class C
{
}";
var compilation = CreateCompilation(source0);
// Verify full metadata contains expected rows.
var result = compilation.Emit(
peStream: new MemoryStream(),
metadataPEStream: null,
pdbStream: new MemoryStream(),
xmlDocumentationStream: null,
cancellationToken: default,
win32Resources: null,
manifestResources: null,
options: null,
debugEntryPoint: null,
sourceLinkStream: null,
embeddedTexts: null,
rebuildData: null,
testData: new CompilationTestData() { SymWriterFactory = _ => throw new DllNotFoundException("xxx") });
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'xxx'
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("xxx"));
Assert.False(result.Success);
}
[WorkItem(1067635, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067635")]
[Fact]
public void SuppressDynamicAndEncCDIForWinRT()
{
var source = @"
public class C
{
public static void F()
{
dynamic a = 1;
int b = 2;
foreach (var x in new[] { 1,2,3 })
{
System.Console.WriteLine(a * b);
}
}
}
";
var debug = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugWinMD);
debug.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""23"" document=""1"" />
<entry offset=""0x8"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""19"" document=""1"" />
<entry offset=""0xa"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""16"" document=""1"" />
<entry offset=""0xb"" startLine=""8"" startColumn=""27"" endLine=""8"" endColumn=""42"" document=""1"" />
<entry offset=""0x1f"" hidden=""true"" document=""1"" />
<entry offset=""0x24"" startLine=""8"" startColumn=""18"" endLine=""8"" endColumn=""23"" document=""1"" />
<entry offset=""0x29"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x2a"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""45"" document=""1"" />
<entry offset=""0xe6"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0xe7"" hidden=""true"" document=""1"" />
<entry offset=""0xeb"" startLine=""8"" startColumn=""24"" endLine=""8"" endColumn=""26"" document=""1"" />
<entry offset=""0xf4"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xf5"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0xf5"" attributes=""0"" />
<local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0xf5"" attributes=""0"" />
<scope startOffset=""0x24"" endOffset=""0xe7"">
<local name=""x"" il_index=""4"" il_start=""0x24"" il_end=""0xe7"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>", format: DebugInformationFormat.Pdb, options: PdbValidationOptions.SkipConversionValidation);
var release = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.ReleaseWinMD);
release.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""23"" document=""1"" />
<entry offset=""0x7"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""19"" document=""1"" />
<entry offset=""0x9"" startLine=""8"" startColumn=""27"" endLine=""8"" endColumn=""42"" document=""1"" />
<entry offset=""0x1d"" hidden=""true"" document=""1"" />
<entry offset=""0x22"" startLine=""8"" startColumn=""18"" endLine=""8"" endColumn=""23"" document=""1"" />
<entry offset=""0x26"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""45"" document=""1"" />
<entry offset=""0xdd"" hidden=""true"" document=""1"" />
<entry offset=""0xe1"" startLine=""8"" startColumn=""24"" endLine=""8"" endColumn=""26"" document=""1"" />
<entry offset=""0xea"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xeb"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0xeb"" attributes=""0"" />
<local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0xeb"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>", format: DebugInformationFormat.Pdb, options: PdbValidationOptions.SkipConversionValidation);
}
[WorkItem(1067635, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067635")]
[Fact]
public void SuppressTupleElementNamesCDIForWinRT()
{
var source =
@"class C
{
static void F()
{
(int A, int B) o = (1, 2);
}
}";
var debug = CreateCompilation(source, options: TestOptions.DebugWinMD);
debug.VerifyPdb(
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""35"" document=""1"" />
<entry offset=""0x9"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xa"">
<local name=""o"" il_index=""0"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>", format: DebugInformationFormat.Pdb, options: PdbValidationOptions.SkipConversionValidation);
var release = CreateCompilation(source, options: TestOptions.ReleaseWinMD);
release.VerifyPdb(
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>", format: DebugInformationFormat.Pdb, options: PdbValidationOptions.SkipConversionValidation);
}
[Fact]
public void DuplicateDocuments()
{
var source1 = @"class C { static void F() { } }";
var source2 = @"class D { static void F() { } }";
var tree1 = Parse(source1, @"foo.cs");
var tree2 = Parse(source2, @"foo.cs");
var comp = CreateCompilation(new[] { tree1, tree2 });
// the first file wins (checksum CB 22 ...)
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""foo.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""CB-22-D8-03-D3-27-32-64-2C-BC-7D-67-5D-E3-CB-AC-D1-64-25-83"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""29"" endLine=""1"" endColumn=""30"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""D"" name=""F"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""29"" endLine=""1"" endColumn=""30"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
public void CustomDebugEntryPoint_DLL()
{
var source = @"class C { static void F() { } }";
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var f = c.GetMember<MethodSymbol>("C.F");
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""F"" />
<methods/>
</symbols>", debugEntryPoint: f.GetPublicSymbol(), options: PdbValidationOptions.ExcludeScopes | PdbValidationOptions.ExcludeSequencePoints | PdbValidationOptions.ExcludeCustomDebugInformation);
var peReader = new PEReader(c.EmitToArray(debugEntryPoint: f.GetPublicSymbol()));
int peEntryPointToken = peReader.PEHeaders.CorHeader.EntryPointTokenOrRelativeVirtualAddress;
Assert.Equal(0, peEntryPointToken);
}
[Fact]
public void CustomDebugEntryPoint_EXE()
{
var source = @"class M { static void Main() { } } class C { static void F<S>() { } }";
var c = CreateCompilation(source, options: TestOptions.DebugExe);
var f = c.GetMember<MethodSymbol>("C.F");
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""F"" />
<methods/>
</symbols>", debugEntryPoint: f.GetPublicSymbol(), options: PdbValidationOptions.ExcludeScopes | PdbValidationOptions.ExcludeSequencePoints | PdbValidationOptions.ExcludeCustomDebugInformation);
var peReader = new PEReader(c.EmitToArray(debugEntryPoint: f.GetPublicSymbol()));
int peEntryPointToken = peReader.PEHeaders.CorHeader.EntryPointTokenOrRelativeVirtualAddress;
var mdReader = peReader.GetMetadataReader();
var methodDef = mdReader.GetMethodDefinition((MethodDefinitionHandle)MetadataTokens.Handle(peEntryPointToken));
Assert.Equal("Main", mdReader.GetString(methodDef.Name));
}
[Fact]
public void CustomDebugEntryPoint_Errors()
{
var source1 = @"class C { static void F() { } } class D<T> { static void G<S>() {} }";
var source2 = @"class C { static void F() { } }";
var c1 = CreateCompilation(source1, options: TestOptions.DebugDll);
var c2 = CreateCompilation(source2, options: TestOptions.DebugDll);
var f1 = c1.GetMember<MethodSymbol>("C.F");
var f2 = c2.GetMember<MethodSymbol>("C.F");
var g = c1.GetMember<MethodSymbol>("D.G");
var d = c1.GetMember<NamedTypeSymbol>("D");
Assert.NotNull(f1);
Assert.NotNull(f2);
Assert.NotNull(g);
Assert.NotNull(d);
var stInt = c1.GetSpecialType(SpecialType.System_Int32);
var d_t_g_int = g.Construct(stInt);
var d_int = d.Construct(stInt);
var d_int_g = d_int.GetMember<MethodSymbol>("G");
var d_int_g_int = d_int_g.Construct(stInt);
var result = c1.Emit(new MemoryStream(), new MemoryStream(), debugEntryPoint: f2.GetPublicSymbol());
result.Diagnostics.Verify(
// error CS8096: Debug entry point must be a definition of a source method in the current compilation.
Diagnostic(ErrorCode.ERR_DebugEntryPointNotSourceMethodDefinition));
result = c1.Emit(new MemoryStream(), new MemoryStream(), debugEntryPoint: d_t_g_int.GetPublicSymbol());
result.Diagnostics.Verify(
// error CS8096: Debug entry point must be a definition of a source method in the current compilation.
Diagnostic(ErrorCode.ERR_DebugEntryPointNotSourceMethodDefinition));
result = c1.Emit(new MemoryStream(), new MemoryStream(), debugEntryPoint: d_int_g.GetPublicSymbol());
result.Diagnostics.Verify(
// error CS8096: Debug entry point must be a definition of a source method in the current compilation.
Diagnostic(ErrorCode.ERR_DebugEntryPointNotSourceMethodDefinition));
result = c1.Emit(new MemoryStream(), new MemoryStream(), debugEntryPoint: d_int_g_int.GetPublicSymbol());
result.Diagnostics.Verify(
// error CS8096: Debug entry point must be a definition of a source method in the current compilation.
Diagnostic(ErrorCode.ERR_DebugEntryPointNotSourceMethodDefinition));
}
[Fact]
[WorkItem(768862, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/768862")]
public void TestLargeLineDelta()
{
var verbatim = string.Join("\r\n", Enumerable.Repeat("x", 1000));
var source = $@"
class C {{ public static void Main() => System.Console.WriteLine(@""{verbatim}""); }}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""2"" startColumn=""40"" endLine=""1001"" endColumn=""4"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
", format: DebugInformationFormat.PortablePdb);
// Native PDBs only support spans with line delta <= 127 (7 bit)
// https://github.com/Microsoft/microsoft-pdb/blob/main/include/cvinfo.h#L4621
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""2"" startColumn=""40"" endLine=""129"" endColumn=""4"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
", format: DebugInformationFormat.Pdb);
}
[Fact]
[WorkItem(20118, "https://github.com/dotnet/roslyn/issues/20118")]
public void TestLargeStartAndEndColumn_SameLine()
{
var spaces = new string(' ', 0x10000);
var source = $@"
class C
{{
public static void Main() =>
{spaces}System.Console.WriteLine(""{spaces}"");
}}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""65533"" endLine=""5"" endColumn=""65534"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
[WorkItem(20118, "https://github.com/dotnet/roslyn/issues/20118")]
public void TestLargeStartAndEndColumn_DifferentLine()
{
var spaces = new string(' ', 0x10000);
var source = $@"
class C
{{
public static void Main() =>
{spaces}System.Console.WriteLine(
""{spaces}"");
}}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""65534"" endLine=""6"" endColumn=""65534"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
#endregion
#region Method Bodies
[Fact]
public void TestBasic()
{
var source = WithWindowsLineBreaks(@"
class Program
{
Program() { }
static void Main(string[] args)
{
Program p = new Program();
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("Program.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<forward declaringType=""Program"" methodName="".ctor"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""19"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""35"" document=""1"" />
<entry offset=""0x7"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x8"">
<local name=""p"" il_index=""0"" il_start=""0x0"" il_end=""0x8"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void TestSimpleLocals()
{
var source = WithWindowsLineBreaks(@"
class C
{
void Method()
{ //local at method scope
object version = 6;
System.Console.WriteLine(""version {0}"", version);
{
//a scope that defines no locals
{
//a nested local
object foob = 1;
System.Console.WriteLine(""foob {0}"", foob);
}
{
//a nested local
int foob1 = 1;
System.Console.WriteLine(""foob1 {0}"", foob1);
}
System.Console.WriteLine(""Eva"");
}
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.Method", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Method"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""44"" />
<slot kind=""0"" offset=""246"" />
<slot kind=""0"" offset=""402"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""28"" document=""1"" />
<entry offset=""0x8"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""58"" document=""1"" />
<entry offset=""0x14"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" />
<entry offset=""0x15"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""14"" document=""1"" />
<entry offset=""0x16"" startLine=""12"" startColumn=""17"" endLine=""12"" endColumn=""33"" document=""1"" />
<entry offset=""0x1d"" startLine=""13"" startColumn=""17"" endLine=""13"" endColumn=""60"" document=""1"" />
<entry offset=""0x29"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""14"" document=""1"" />
<entry offset=""0x2a"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""14"" document=""1"" />
<entry offset=""0x2b"" startLine=""17"" startColumn=""17"" endLine=""17"" endColumn=""31"" document=""1"" />
<entry offset=""0x2d"" startLine=""18"" startColumn=""17"" endLine=""18"" endColumn=""62"" document=""1"" />
<entry offset=""0x3e"" startLine=""19"" startColumn=""13"" endLine=""19"" endColumn=""14"" document=""1"" />
<entry offset=""0x3f"" startLine=""20"" startColumn=""13"" endLine=""20"" endColumn=""45"" document=""1"" />
<entry offset=""0x4a"" startLine=""21"" startColumn=""9"" endLine=""21"" endColumn=""10"" document=""1"" />
<entry offset=""0x4b"" startLine=""22"" startColumn=""5"" endLine=""22"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x4c"">
<local name=""version"" il_index=""0"" il_start=""0x0"" il_end=""0x4c"" attributes=""0"" />
<scope startOffset=""0x15"" endOffset=""0x2a"">
<local name=""foob"" il_index=""1"" il_start=""0x15"" il_end=""0x2a"" attributes=""0"" />
</scope>
<scope startOffset=""0x2a"" endOffset=""0x3f"">
<local name=""foob1"" il_index=""2"" il_start=""0x2a"" il_end=""0x3f"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
[WorkItem(7244, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/7244")]
public void ConstructorsWithoutInitializers()
{
var source = WithWindowsLineBreaks(
@"class C
{
C()
{
object o;
}
C(object x)
{
object y = x;
}
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""18"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""3"" startColumn=""5"" endLine=""3"" endColumn=""8"" document=""1"" />
<entry offset=""0x7"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" />
<entry offset=""0x8"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x9"">
<scope startOffset=""0x7"" endOffset=""0x9"">
<local name=""o"" il_index=""0"" il_start=""0x7"" il_end=""0x9"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""C"" name="".ctor"" parameterNames=""x"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""18"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""16"" document=""1"" />
<entry offset=""0x7"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
<entry offset=""0x8"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""22"" document=""1"" />
<entry offset=""0xa"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xb"">
<scope startOffset=""0x7"" endOffset=""0xb"">
<local name=""y"" il_index=""0"" il_start=""0x7"" il_end=""0xb"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(7244, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/7244")]
[Fact]
public void ConstructorsWithInitializers()
{
var source = WithWindowsLineBreaks(
@"class C
{
static object G = 1;
object F = G;
C()
{
object o;
}
C(object x)
{
object y = x;
}
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""18"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""18"" document=""1"" />
<entry offset=""0xb"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""8"" document=""1"" />
<entry offset=""0x12"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
<entry offset=""0x13"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x14"">
<scope startOffset=""0x12"" endOffset=""0x14"">
<local name=""o"" il_index=""0"" il_start=""0x12"" il_end=""0x14"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""C"" name="".ctor"" parameterNames=""x"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""18"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""18"" document=""1"" />
<entry offset=""0xb"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""16"" document=""1"" />
<entry offset=""0x12"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
<entry offset=""0x13"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""22"" document=""1"" />
<entry offset=""0x15"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x16"">
<scope startOffset=""0x12"" endOffset=""0x16"">
<local name=""y"" il_index=""0"" il_start=""0x12"" il_end=""0x16"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
/// <summary>
/// Although the debugging info attached to DebuggerHidden method is not used by the debugger
/// (the debugger doesn't ever stop in the method) Dev11 emits the info and so do we.
///
/// StepThrough method needs the information if JustMyCode is disabled and a breakpoint is set within the method.
/// NonUserCode method needs the information if JustMyCode is disabled.
///
/// It's up to the tool that consumes the debugging information, not the compiler to decide whether to ignore the info or not.
/// BTW, the information can actually be retrieved at runtime from the PDB file via Reflection StackTrace.
/// </summary>
[Fact]
public void MethodsWithDebuggerAttributes()
{
var source = WithWindowsLineBreaks(@"
using System;
using System.Diagnostics;
class Program
{
[DebuggerHidden]
static void Hidden()
{
int x = 1;
Console.WriteLine(x);
}
[DebuggerStepThrough]
static void StepThrough()
{
int y = 1;
Console.WriteLine(y);
}
[DebuggerNonUserCode]
static void NonUserCode()
{
int z = 1;
Console.WriteLine(z);
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Hidden"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""19"" document=""1"" />
<entry offset=""0x3"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""30"" document=""1"" />
<entry offset=""0xa"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xb"">
<namespace name=""System"" />
<namespace name=""System.Diagnostics"" />
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0xb"" attributes=""0"" />
</scope>
</method>
<method containingType=""Program"" name=""StepThrough"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""Hidden"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""19"" document=""1"" />
<entry offset=""0x3"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""30"" document=""1"" />
<entry offset=""0xa"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xb"">
<local name=""y"" il_index=""0"" il_start=""0x0"" il_end=""0xb"" attributes=""0"" />
</scope>
</method>
<method containingType=""Program"" name=""NonUserCode"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""Hidden"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""19"" document=""1"" />
<entry offset=""0x3"" startLine=""25"" startColumn=""9"" endLine=""25"" endColumn=""30"" document=""1"" />
<entry offset=""0xa"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xb"">
<local name=""z"" il_index=""0"" il_start=""0x0"" il_end=""0xb"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
/// <summary>
/// If a synthesized method contains any user code,
/// the method must have a sequence point at
/// offset 0 for correct stepping behavior.
/// </summary>
[WorkItem(804681, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/804681")]
[Fact]
public void SequencePointAtOffset0()
{
string source = WithWindowsLineBreaks(
@"using System;
class C
{
static Func<object, int> F = x =>
{
Func<object, int> f = o => 1;
Func<Func<object, int>, Func<object, int>> g = h => y => h(y);
return g(f)(null);
};
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".cctor"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLambdaMap>
<methodOrdinal>2</methodOrdinal>
<closure offset=""-45"" />
<lambda offset=""-147"" />
<lambda offset=""-109"" />
<lambda offset=""-45"" />
<lambda offset=""-40"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""9"" endColumn=""7"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x16"">
<namespace name=""System"" />
</scope>
</method>
<method containingType=""C+<>c__DisplayClass2_0"" name=""<.cctor>b__3"" parameterNames=""y"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".cctor"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""66"" endLine=""7"" endColumn=""70"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C+<>c"" name=""<.cctor>b__2_0"" parameterNames=""x"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".cctor"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""-118"" />
<slot kind=""0"" offset=""-54"" />
<slot kind=""21"" offset=""-147"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""38"" document=""1"" />
<entry offset=""0x21"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""71"" document=""1"" />
<entry offset=""0x41"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""27"" document=""1"" />
<entry offset=""0x51"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x53"">
<local name=""f"" il_index=""0"" il_start=""0x0"" il_end=""0x53"" attributes=""0"" />
<local name=""g"" il_index=""1"" il_start=""0x0"" il_end=""0x53"" attributes=""0"" />
</scope>
</method>
<method containingType=""C+<>c"" name=""<.cctor>b__2_1"" parameterNames=""o"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".cctor"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""36"" endLine=""6"" endColumn=""37"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C+<>c"" name=""<.cctor>b__2_2"" parameterNames=""h"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".cctor"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""-45"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""7"" startColumn=""61"" endLine=""7"" endColumn=""70"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1a"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x1a"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
/// <summary>
/// Leading trivia is not included in the syntax offset.
/// </summary>
[Fact]
public void SyntaxOffsetInPresenceOfTrivia_Methods()
{
string source = @"
class C
{
public static void Main1() /*Comment1*/{/*Comment2*/int a = 1;/*Comment3*/}/*Comment4*/
public static void Main2() {/*Comment2*/int a = 2;/*Comment3*/}/*Comment4*/
}";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
// verify that both syntax offsets are the same
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main1"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""17"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""44"" endLine=""4"" endColumn=""45"" document=""1"" />
<entry offset=""0x1"" startLine=""4"" startColumn=""57"" endLine=""4"" endColumn=""67"" document=""1"" />
<entry offset=""0x3"" startLine=""4"" startColumn=""79"" endLine=""4"" endColumn=""80"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x4"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" />
</scope>
</method>
<method containingType=""C"" name=""Main2"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Main1"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""17"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""32"" endLine=""5"" endColumn=""33"" document=""1"" />
<entry offset=""0x1"" startLine=""5"" startColumn=""45"" endLine=""5"" endColumn=""55"" document=""1"" />
<entry offset=""0x3"" startLine=""5"" startColumn=""67"" endLine=""5"" endColumn=""68"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x4"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
/// <summary>
/// Leading and trailing trivia are not included in the syntax offset.
/// </summary>
[Fact]
public void SyntaxOffsetInPresenceOfTrivia_Initializers()
{
string source = @"
using System;
class C1
{
public static Func<int> e=() => 0;
public static Func<int> f/*Comment0*/=/*Comment1*/() => 1;/*Comment2*/
public static Func<int> g=() => 2;
}
class C2
{
public static Func<int> e=() => 0;
public static Func<int> f=/*Comment1*/() => 1;
public static Func<int> g=() => 2;
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
// verify that syntax offsets of both .cctor's are the same
c.VerifyPdb("C1..cctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C1"" name="".cctor"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLambdaMap>
<methodOrdinal>4</methodOrdinal>
<lambda offset=""-29"" />
<lambda offset=""-9"" />
<lambda offset=""-1"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""39"" document=""1"" />
<entry offset=""0x15"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""63"" document=""1"" />
<entry offset=""0x2a"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""39"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x40"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
c.VerifyPdb("C2..cctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C2"" name="".cctor"">
<customDebugInfo>
<forward declaringType=""C1"" methodName="".cctor"" />
<encLambdaMap>
<methodOrdinal>4</methodOrdinal>
<lambda offset=""-29"" />
<lambda offset=""-9"" />
<lambda offset=""-1"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""39"" document=""1"" />
<entry offset=""0x15"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""51"" document=""1"" />
<entry offset=""0x2a"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""39"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
#endregion
#region ReturnStatement
[Fact]
public void Return_Method1()
{
var source = WithWindowsLineBreaks(@"
class Program
{
static int Main()
{
return 1;
}
}
");
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
// In order to place a breakpoint on the closing brace we need to save the return expression value to
// a local and then load it again (since sequence point needs an empty stack). This variable has to be marked as long-lived.
v.VerifyIL("Program.Main", @"
{
// Code size 7 (0x7)
.maxstack 1
.locals init (int V_0)
-IL_0000: nop
-IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: br.s IL_0005
-IL_0005: ldloc.0
IL_0006: ret
}", sequencePoints: "Program.Main");
v.VerifyPdb("Program.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""18"" document=""1"" />
<entry offset=""0x5"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void Return_Property1()
{
var source = WithWindowsLineBreaks(@"
class C
{
static int P
{
get { return 1; }
}
}
");
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
// In order to place a breakpoint on the closing brace we need to save the return expression value to
// a local and then load it again (since sequence point needs an empty stack). This variable has to be marked as long-lived.
v.VerifyIL("C.P.get", @"
{
// Code size 7 (0x7)
.maxstack 1
.locals init (int V_0)
-IL_0000: nop
-IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: br.s IL_0005
-IL_0005: ldloc.0
IL_0006: ret
}", sequencePoints: "C.get_P");
v.VerifyPdb("C.get_P", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""get_P"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""13"" endLine=""6"" endColumn=""14"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""15"" endLine=""6"" endColumn=""24"" document=""1"" />
<entry offset=""0x5"" startLine=""6"" startColumn=""25"" endLine=""6"" endColumn=""26"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void Return_Void1()
{
var source = @"
class Program
{
static void Main()
{
return;
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.Main", @"
{
// Code size 4 (0x4)
.maxstack 0
-IL_0000: nop
-IL_0001: br.s IL_0003
-IL_0003: ret
}", sequencePoints: "Program.Main");
}
[Fact]
public void Return_ExpressionBodied1()
{
var source = @"
class Program
{
static int Main() => 1;
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.Main", @"
{
// Code size 2 (0x2)
.maxstack 1
-IL_0000: ldc.i4.1
IL_0001: ret
}", sequencePoints: "Program.Main");
}
[Fact]
public void Return_FromExceptionHandler1()
{
var source = WithWindowsLineBreaks(@"
using System;
class Program
{
static int Main()
{
try
{
Console.WriteLine();
return 1;
}
catch (Exception)
{
return 2;
}
}
}
");
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.Main", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (int V_0)
-IL_0000: nop
.try
{
-IL_0001: nop
-IL_0002: call ""void System.Console.WriteLine()""
IL_0007: nop
-IL_0008: ldc.i4.1
IL_0009: stloc.0
IL_000a: leave.s IL_0012
}
catch System.Exception
{
-IL_000c: pop
-IL_000d: nop
-IL_000e: ldc.i4.2
IL_000f: stloc.0
IL_0010: leave.s IL_0012
}
-IL_0012: ldloc.0
IL_0013: ret
}", sequencePoints: "Program.Main");
v.VerifyPdb("Program.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x2"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""33"" document=""1"" />
<entry offset=""0x8"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""22"" document=""1"" />
<entry offset=""0xc"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""26"" document=""1"" />
<entry offset=""0xd"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" />
<entry offset=""0xe"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""22"" document=""1"" />
<entry offset=""0x12"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x14"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region IfStatement
[Fact]
public void IfStatement()
{
var source = WithWindowsLineBreaks(@"
class C
{
void Method()
{
bool b = true;
if (b)
{
string s = ""true"";
System.Console.WriteLine(s);
}
else
{
string s = ""false"";
int i = 1;
while (i < 100)
{
int j = i, k = 1;
System.Console.WriteLine(j);
i = j + k;
}
i = i + 1;
}
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.Method", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Method"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""19"" />
<slot kind=""1"" offset=""38"" />
<slot kind=""0"" offset=""76"" />
<slot kind=""0"" offset=""188"" />
<slot kind=""0"" offset=""218"" />
<slot kind=""0"" offset=""292"" />
<slot kind=""0"" offset=""299"" />
<slot kind=""1"" offset=""240"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""23"" document=""1"" />
<entry offset=""0x3"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""15"" document=""1"" />
<entry offset=""0x5"" hidden=""true"" document=""1"" />
<entry offset=""0x8"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" />
<entry offset=""0x9"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""31"" document=""1"" />
<entry offset=""0xf"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""41"" document=""1"" />
<entry offset=""0x16"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0x17"" hidden=""true"" document=""1"" />
<entry offset=""0x19"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x1a"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""32"" document=""1"" />
<entry offset=""0x20"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""23"" document=""1"" />
<entry offset=""0x23"" hidden=""true"" document=""1"" />
<entry offset=""0x25"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""14"" document=""1"" />
<entry offset=""0x26"" startLine=""19"" startColumn=""17"" endLine=""19"" endColumn=""26"" document=""1"" />
<entry offset=""0x2a"" startLine=""19"" startColumn=""28"" endLine=""19"" endColumn=""33"" document=""1"" />
<entry offset=""0x2d"" startLine=""20"" startColumn=""17"" endLine=""20"" endColumn=""45"" document=""1"" />
<entry offset=""0x35"" startLine=""21"" startColumn=""17"" endLine=""21"" endColumn=""27"" document=""1"" />
<entry offset=""0x3c"" startLine=""22"" startColumn=""13"" endLine=""22"" endColumn=""14"" document=""1"" />
<entry offset=""0x3d"" startLine=""17"" startColumn=""13"" endLine=""17"" endColumn=""28"" document=""1"" />
<entry offset=""0x45"" hidden=""true"" document=""1"" />
<entry offset=""0x49"" startLine=""24"" startColumn=""13"" endLine=""24"" endColumn=""23"" document=""1"" />
<entry offset=""0x4f"" startLine=""25"" startColumn=""9"" endLine=""25"" endColumn=""10"" document=""1"" />
<entry offset=""0x50"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x51"">
<local name=""b"" il_index=""0"" il_start=""0x0"" il_end=""0x51"" attributes=""0"" />
<scope startOffset=""0x8"" endOffset=""0x17"">
<local name=""s"" il_index=""2"" il_start=""0x8"" il_end=""0x17"" attributes=""0"" />
</scope>
<scope startOffset=""0x19"" endOffset=""0x50"">
<local name=""s"" il_index=""3"" il_start=""0x19"" il_end=""0x50"" attributes=""0"" />
<local name=""i"" il_index=""4"" il_start=""0x19"" il_end=""0x50"" attributes=""0"" />
<scope startOffset=""0x25"" endOffset=""0x3d"">
<local name=""j"" il_index=""5"" il_start=""0x25"" il_end=""0x3d"" attributes=""0"" />
<local name=""k"" il_index=""6"" il_start=""0x25"" il_end=""0x3d"" attributes=""0"" />
</scope>
</scope>
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region WhileStatement
[WorkItem(538299, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538299")]
[Fact]
public void WhileStatement()
{
var source = @"using System;
public class SeqPointForWhile
{
public static void Main()
{
SeqPointForWhile obj = new SeqPointForWhile();
obj.While(234);
}
int field;
public void While(int p)
{
while (p > 0) // SeqPt should be generated at the end of loop
{
p = (int)(p / 2);
if (p > 100)
{
continue;
}
else if (p > 10)
{
int x = p;
field = x;
}
else
{
int x = p;
Console.WriteLine(x);
break;
}
}
field = -1;
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe);
// Offset 0x01 should be:
// <entry offset=""0x1"" hidden=""true"" document=""1"" />
// Move original offset 0x01 to 0x33
// <entry offset=""0x33"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""22"" document=""1"" />
//
// Note: 16707566 == 0x00FEEFEE
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""SeqPointForWhile"" methodName=""Main"" />
<methods>
<method containingType=""SeqPointForWhile"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""55"" document=""1"" />
<entry offset=""0x5"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""24"" document=""1"" />
<entry offset=""0xf"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x10"">
<namespace name=""System"" />
</scope>
</method>
<method containingType=""SeqPointForWhile"" name=""While"" parameterNames=""p"">
<customDebugInfo>
<forward declaringType=""SeqPointForWhile"" methodName=""Main"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x2"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""30"" document=""1"" />
<entry offset=""0x7"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""25"" document=""1"" />
<entry offset=""0xc"" startLine=""22"" startColumn=""18"" endLine=""22"" endColumn=""29"" document=""1"" />
<entry offset=""0x11"" startLine=""24"" startColumn=""17"" endLine=""24"" endColumn=""27"" document=""1"" />
<entry offset=""0x13"" startLine=""25"" startColumn=""17"" endLine=""25"" endColumn=""27"" document=""1"" />
<entry offset=""0x1a"" hidden=""true"" document=""1"" />
<entry offset=""0x1c"" startLine=""29"" startColumn=""17"" endLine=""29"" endColumn=""27"" document=""1"" />
<entry offset=""0x1d"" startLine=""30"" startColumn=""17"" endLine=""30"" endColumn=""38"" document=""1"" />
<entry offset=""0x22"" startLine=""31"" startColumn=""17"" endLine=""31"" endColumn=""23"" document=""1"" />
<entry offset=""0x24"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""22"" document=""1"" />
<entry offset=""0x28"" startLine=""34"" startColumn=""9"" endLine=""34"" endColumn=""20"" document=""1"" />
<entry offset=""0x2f"" startLine=""35"" startColumn=""5"" endLine=""35"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x30"">
<scope startOffset=""0x11"" endOffset=""0x1a"">
<local name=""x"" il_index=""0"" il_start=""0x11"" il_end=""0x1a"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region ForStatement
[Fact]
public void ForStatement1()
{
var source = WithWindowsLineBreaks(@"
class C
{
static bool F(int i) { return true; }
static void G(int i) { }
static void M()
{
for (int i = 1; F(i); G(i))
{
System.Console.WriteLine(1);
}
}
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.M", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" parameterNames=""i"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""20"" />
<slot kind=""1"" offset=""11"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""14"" endLine=""9"" endColumn=""23"" document=""1"" />
<entry offset=""0x3"" hidden=""true"" document=""1"" />
<entry offset=""0x5"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" />
<entry offset=""0x6"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""41"" document=""1"" />
<entry offset=""0xd"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" />
<entry offset=""0xe"" startLine=""9"" startColumn=""31"" endLine=""9"" endColumn=""35"" document=""1"" />
<entry offset=""0x15"" startLine=""9"" startColumn=""25"" endLine=""9"" endColumn=""29"" document=""1"" />
<entry offset=""0x1c"" hidden=""true"" document=""1"" />
<entry offset=""0x1f"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x20"">
<scope startOffset=""0x1"" endOffset=""0x1f"">
<local name=""i"" il_index=""0"" il_start=""0x1"" il_end=""0x1f"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void ForStatement2()
{
var source = @"
class C
{
static void M()
{
for (;;)
{
System.Console.WriteLine(1);
}
}
}";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.M", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" hidden=""true"" document=""1"" />
<entry offset=""0x3"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" />
<entry offset=""0x4"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""41"" document=""1"" />
<entry offset=""0xb"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0xc"" hidden=""true"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
public void ForStatement3()
{
var source = WithWindowsLineBreaks(@"
class C
{
static void M()
{
int i = 0;
for (;;i++)
{
System.Console.WriteLine(i);
}
}
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.M", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""19"" document=""1"" />
<entry offset=""0x3"" hidden=""true"" document=""1"" />
<entry offset=""0x5"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" />
<entry offset=""0x6"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""41"" document=""1"" />
<entry offset=""0xd"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" />
<entry offset=""0xe"" startLine=""7"" startColumn=""16"" endLine=""7"" endColumn=""19"" document=""1"" />
<entry offset=""0x12"" hidden=""true"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x14"">
<local name=""i"" il_index=""0"" il_start=""0x0"" il_end=""0x14"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region ForEachStatement
[Fact]
public void ForEachStatement_String()
{
var source = @"
public class C
{
public static void Main()
{
foreach (var c in ""hello"")
{
System.Console.WriteLine(c);
}
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe);
// Sequence points:
// 1) Open brace at start of method
// 2) 'foreach'
// 3) '"hello"'
// 4) Hidden initial jump (of for loop)
// 5) 'var c'
// 6) Open brace of loop
// 7) Loop body
// 8) Close brace of loop
// 9) Hidden index increment.
// 10) 'in'
// 11) Close brace at end of method
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""27"" endLine=""6"" endColumn=""34"" document=""1"" />
<entry offset=""0x8"" hidden=""true"" document=""1"" />
<entry offset=""0xa"" startLine=""6"" startColumn=""18"" endLine=""6"" endColumn=""23"" document=""1"" />
<entry offset=""0x11"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""41"" document=""1"" />
<entry offset=""0x16"" hidden=""true"" document=""1"" />
<entry offset=""0x1a"" startLine=""6"" startColumn=""24"" endLine=""6"" endColumn=""26"" document=""1"" />
<entry offset=""0x23"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void ForEachStatement_Array()
{
var source = WithWindowsLineBreaks(@"
public class C
{
public static void Main()
{
foreach (var x in new int[2])
{
System.Console.WriteLine(x);
}
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
// Sequence points:
// 1) Open brace at start of method
// 2) 'foreach'
// 3) 'new int[2]'
// 4) Hidden initial jump (of for loop)
// 5) 'var c'
// 6) Open brace of loop
// 7) Loop body
// 8) Close brace of loop
// 9) Hidden index increment.
// 10) 'in'
// 11) Close brace at end of method
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""6"" offset=""11"" />
<slot kind=""8"" offset=""11"" />
<slot kind=""0"" offset=""11"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""16"" document=""1"" />
<entry offset=""0x2"" startLine=""6"" startColumn=""27"" endLine=""6"" endColumn=""37"" document=""1"" />
<entry offset=""0xb"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""6"" startColumn=""18"" endLine=""6"" endColumn=""23"" document=""1"" />
<entry offset=""0x11"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" />
<entry offset=""0x12"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""41"" document=""1"" />
<entry offset=""0x19"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x1a"" hidden=""true"" document=""1"" />
<entry offset=""0x1e"" startLine=""6"" startColumn=""24"" endLine=""6"" endColumn=""26"" document=""1"" />
<entry offset=""0x24"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x25"">
<scope startOffset=""0xd"" endOffset=""0x1a"">
<local name=""x"" il_index=""2"" il_start=""0xd"" il_end=""0x1a"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(544937, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544937")]
[Fact]
public void ForEachStatement_MultiDimensionalArray()
{
var source = @"
public class C
{
public static void Main()
{
foreach (var x in new int[2, 3])
{
System.Console.WriteLine(x);
}
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
// Sequence points:
// 1) Open brace at start of method
// 2) 'foreach'
// 3) 'new int[2, 3]'
// 4) Hidden initial jump (of for loop)
// 5) 'var c'
// 6) Open brace of loop
// 7) Loop body
// 8) Close brace of loop
// 9) 'in'
// 10) Close brace at end of method
v.VerifyIL("C.Main", @"
{
// Code size 88 (0x58)
.maxstack 3
.locals init (int[,] V_0,
int V_1,
int V_2,
int V_3,
int V_4,
int V_5) //x
-IL_0000: nop
-IL_0001: nop
-IL_0002: ldc.i4.2
IL_0003: ldc.i4.3
IL_0004: newobj ""int[*,*]..ctor""
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: ldc.i4.0
IL_000c: callvirt ""int System.Array.GetUpperBound(int)""
IL_0011: stloc.1
IL_0012: ldloc.0
IL_0013: ldc.i4.1
IL_0014: callvirt ""int System.Array.GetUpperBound(int)""
IL_0019: stloc.2
IL_001a: ldloc.0
IL_001b: ldc.i4.0
IL_001c: callvirt ""int System.Array.GetLowerBound(int)""
IL_0021: stloc.3
~IL_0022: br.s IL_0053
IL_0024: ldloc.0
IL_0025: ldc.i4.1
IL_0026: callvirt ""int System.Array.GetLowerBound(int)""
IL_002b: stloc.s V_4
~IL_002d: br.s IL_004a
-IL_002f: ldloc.0
IL_0030: ldloc.3
IL_0031: ldloc.s V_4
IL_0033: call ""int[*,*].Get""
IL_0038: stloc.s V_5
-IL_003a: nop
-IL_003b: ldloc.s V_5
IL_003d: call ""void System.Console.WriteLine(int)""
IL_0042: nop
-IL_0043: nop
~IL_0044: ldloc.s V_4
IL_0046: ldc.i4.1
IL_0047: add
IL_0048: stloc.s V_4
-IL_004a: ldloc.s V_4
IL_004c: ldloc.2
IL_004d: ble.s IL_002f
~IL_004f: ldloc.3
IL_0050: ldc.i4.1
IL_0051: add
IL_0052: stloc.3
-IL_0053: ldloc.3
IL_0054: ldloc.1
IL_0055: ble.s IL_0024
-IL_0057: ret
}
", sequencePoints: "C.Main");
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ConditionalInAsyncMethod()
{
var source = WithWindowsLineBreaks(@"
using System;
class Program
{
public static async void Test()
{
int i = 0;
if (i != 0)
Console
.WriteLine();
}
}
");
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 81 (0x51)
.maxstack 2
.locals init (int V_0,
bool V_1,
System.Exception V_2)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Test>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: int i = 0;
IL_0008: ldarg.0
IL_0009: ldc.i4.0
IL_000a: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: if (i != 0)
IL_000f: ldarg.0
IL_0010: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_0015: ldc.i4.0
IL_0016: cgt.un
IL_0018: stloc.1
// sequence point: <hidden>
IL_0019: ldloc.1
IL_001a: brfalse.s IL_0022
// sequence point: Console ... .WriteLine()
IL_001c: call ""void System.Console.WriteLine()""
IL_0021: nop
// sequence point: <hidden>
IL_0022: leave.s IL_003c
}
catch System.Exception
{
// async: catch handler, sequence point: <hidden>
IL_0024: stloc.2
IL_0025: ldarg.0
IL_0026: ldc.i4.s -2
IL_0028: stfld ""int Program.<Test>d__0.<>1__state""
IL_002d: ldarg.0
IL_002e: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_0033: ldloc.2
IL_0034: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)""
IL_0039: nop
IL_003a: leave.s IL_0050
}
// sequence point: }
IL_003c: ldarg.0
IL_003d: ldc.i4.s -2
IL_003f: stfld ""int Program.<Test>d__0.<>1__state""
// sequence point: <hidden>
IL_0044: ldarg.0
IL_0045: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_004a: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()""
IL_004f: nop
IL_0050: ret
}
", sequencePoints: "Program+<Test>d__0.MoveNext", source: source);
v.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Test"">
<customDebugInfo>
<forwardIterator name=""<Test>d__0"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
<method containingType=""Program+<Test>d__0"" name=""MoveNext"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0x51"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""1"" offset=""33"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x8"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""19"" document=""1"" />
<entry offset=""0xf"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""20"" document=""1"" />
<entry offset=""0x19"" hidden=""true"" document=""1"" />
<entry offset=""0x1c"" startLine=""11"" startColumn=""13"" endLine=""12"" endColumn=""30"" document=""1"" />
<entry offset=""0x22"" hidden=""true"" document=""1"" />
<entry offset=""0x24"" hidden=""true"" document=""1"" />
<entry offset=""0x3c"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
<entry offset=""0x44"" hidden=""true"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x51"">
<namespace name=""System"" />
</scope>
<asyncInfo>
<catchHandler offset=""0x24"" />
<kickoffMethod declaringType=""Program"" methodName=""Test"" />
</asyncInfo>
</method>
</methods>
</symbols>");
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ConditionalBeforeLocalFunction()
{
var source = @"
class C
{
void M()
{
int i = 0;
if (i != 0)
{
return;
}
string local()
{
throw null;
}
System.Console.Write(1);
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("C.M", @"
{
// Code size 23 (0x17)
.maxstack 2
.locals init (int V_0, //i
bool V_1)
// sequence point: {
IL_0000: nop
// sequence point: int i = 0;
IL_0001: ldc.i4.0
IL_0002: stloc.0
// sequence point: if (i != 0)
IL_0003: ldloc.0
IL_0004: ldc.i4.0
IL_0005: cgt.un
IL_0007: stloc.1
// sequence point: <hidden>
IL_0008: ldloc.1
IL_0009: brfalse.s IL_000e
// sequence point: {
IL_000b: nop
// sequence point: return;
IL_000c: br.s IL_0016
// sequence point: <hidden>
IL_000e: nop
// sequence point: System.Console.Write(1);
IL_000f: ldc.i4.1
IL_0010: call ""void System.Console.Write(int)""
IL_0015: nop
// sequence point: }
IL_0016: ret
}
", sequencePoints: "C.M", source: source);
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ConditionalInAsyncMethodWithExplicitReturn()
{
var source = @"
using System;
class Program
{
public static async void Test()
{
int i = 0;
if (i != 0)
Console
.WriteLine();
return;
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 81 (0x51)
.maxstack 2
.locals init (int V_0,
bool V_1,
System.Exception V_2)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Test>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: int i = 0;
IL_0008: ldarg.0
IL_0009: ldc.i4.0
IL_000a: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: if (i != 0)
IL_000f: ldarg.0
IL_0010: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_0015: ldc.i4.0
IL_0016: cgt.un
IL_0018: stloc.1
// sequence point: <hidden>
IL_0019: ldloc.1
IL_001a: brfalse.s IL_0022
// sequence point: Console ... .WriteLine()
IL_001c: call ""void System.Console.WriteLine()""
IL_0021: nop
// sequence point: return;
IL_0022: leave.s IL_003c
}
catch System.Exception
{
// async: catch handler, sequence point: <hidden>
IL_0024: stloc.2
IL_0025: ldarg.0
IL_0026: ldc.i4.s -2
IL_0028: stfld ""int Program.<Test>d__0.<>1__state""
IL_002d: ldarg.0
IL_002e: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_0033: ldloc.2
IL_0034: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)""
IL_0039: nop
IL_003a: leave.s IL_0050
}
// sequence point: }
IL_003c: ldarg.0
IL_003d: ldc.i4.s -2
IL_003f: stfld ""int Program.<Test>d__0.<>1__state""
// sequence point: <hidden>
IL_0044: ldarg.0
IL_0045: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_004a: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()""
IL_004f: nop
IL_0050: ret
}
", sequencePoints: "Program+<Test>d__0.MoveNext", source: source);
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ConditionalInSimpleMethod()
{
var source = @"
using System;
class Program
{
public static void Test()
{
int i = 0;
if (i != 0)
Console.WriteLine();
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.Test()", @"
{
// Code size 18 (0x12)
.maxstack 2
.locals init (int V_0, //i
bool V_1)
// sequence point: {
IL_0000: nop
// sequence point: int i = 0;
IL_0001: ldc.i4.0
IL_0002: stloc.0
// sequence point: if (i != 0)
IL_0003: ldloc.0
IL_0004: ldc.i4.0
IL_0005: cgt.un
IL_0007: stloc.1
// sequence point: <hidden>
IL_0008: ldloc.1
IL_0009: brfalse.s IL_0011
// sequence point: Console.WriteLine();
IL_000b: call ""void System.Console.WriteLine()""
IL_0010: nop
// sequence point: }
IL_0011: ret
}
", sequencePoints: "Program.Test", source: source);
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ElseConditionalInAsyncMethod()
{
var source = WithWindowsLineBreaks(@"
using System;
class Program
{
public static async void Test()
{
int i = 0;
if (i != 0)
Console.WriteLine(""one"");
else
Console.WriteLine(""other"");
}
}
");
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 99 (0x63)
.maxstack 2
.locals init (int V_0,
bool V_1,
System.Exception V_2)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Test>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: int i = 0;
IL_0008: ldarg.0
IL_0009: ldc.i4.0
IL_000a: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: if (i != 0)
IL_000f: ldarg.0
IL_0010: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_0015: ldc.i4.0
IL_0016: cgt.un
IL_0018: stloc.1
// sequence point: <hidden>
IL_0019: ldloc.1
IL_001a: brfalse.s IL_0029
// sequence point: Console.WriteLine(""one"");
IL_001c: ldstr ""one""
IL_0021: call ""void System.Console.WriteLine(string)""
IL_0026: nop
// sequence point: <hidden>
IL_0027: br.s IL_0034
// sequence point: Console.WriteLine(""other"");
IL_0029: ldstr ""other""
IL_002e: call ""void System.Console.WriteLine(string)""
IL_0033: nop
// sequence point: <hidden>
IL_0034: leave.s IL_004e
}
catch System.Exception
{
// async: catch handler, sequence point: <hidden>
IL_0036: stloc.2
IL_0037: ldarg.0
IL_0038: ldc.i4.s -2
IL_003a: stfld ""int Program.<Test>d__0.<>1__state""
IL_003f: ldarg.0
IL_0040: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_0045: ldloc.2
IL_0046: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)""
IL_004b: nop
IL_004c: leave.s IL_0062
}
// sequence point: }
IL_004e: ldarg.0
IL_004f: ldc.i4.s -2
IL_0051: stfld ""int Program.<Test>d__0.<>1__state""
// sequence point: <hidden>
IL_0056: ldarg.0
IL_0057: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_005c: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()""
IL_0061: nop
IL_0062: ret
}
", sequencePoints: "Program+<Test>d__0.MoveNext", source: source);
v.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Test"">
<customDebugInfo>
<forwardIterator name=""<Test>d__0"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
<method containingType=""Program+<Test>d__0"" name=""MoveNext"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0x63"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""1"" offset=""33"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x8"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""19"" document=""1"" />
<entry offset=""0xf"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""20"" document=""1"" />
<entry offset=""0x19"" hidden=""true"" document=""1"" />
<entry offset=""0x1c"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""38"" document=""1"" />
<entry offset=""0x27"" hidden=""true"" document=""1"" />
<entry offset=""0x29"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""40"" document=""1"" />
<entry offset=""0x34"" hidden=""true"" document=""1"" />
<entry offset=""0x36"" hidden=""true"" document=""1"" />
<entry offset=""0x4e"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" />
<entry offset=""0x56"" hidden=""true"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x63"">
<namespace name=""System"" />
</scope>
<asyncInfo>
<catchHandler offset=""0x36"" />
<kickoffMethod declaringType=""Program"" methodName=""Test"" />
</asyncInfo>
</method>
</methods>
</symbols>");
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ConditionalInTry()
{
var source = WithWindowsLineBreaks(@"
using System;
class Program
{
public static void Test()
{
try
{
int i = 0;
if (i != 0)
Console.WriteLine();
}
catch { }
}
}
");
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.Test", @"
{
// Code size 27 (0x1b)
.maxstack 2
.locals init (int V_0, //i
bool V_1)
// sequence point: {
IL_0000: nop
.try
{
// sequence point: {
IL_0001: nop
// sequence point: int i = 0;
IL_0002: ldc.i4.0
IL_0003: stloc.0
// sequence point: if (i != 0)
IL_0004: ldloc.0
IL_0005: ldc.i4.0
IL_0006: cgt.un
IL_0008: stloc.1
// sequence point: <hidden>
IL_0009: ldloc.1
IL_000a: brfalse.s IL_0012
// sequence point: Console.WriteLine();
IL_000c: call ""void System.Console.WriteLine()""
IL_0011: nop
// sequence point: }
IL_0012: nop
IL_0013: leave.s IL_001a
}
catch object
{
// sequence point: catch
IL_0015: pop
// sequence point: {
IL_0016: nop
// sequence point: }
IL_0017: nop
IL_0018: leave.s IL_001a
}
// sequence point: }
IL_001a: ret
}
", sequencePoints: "Program.Test", source: source);
v.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Test"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""43"" />
<slot kind=""1"" offset=""65"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x2"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""23"" document=""1"" />
<entry offset=""0x4"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""24"" document=""1"" />
<entry offset=""0x9"" hidden=""true"" document=""1"" />
<entry offset=""0xc"" startLine=""13"" startColumn=""17"" endLine=""13"" endColumn=""37"" document=""1"" />
<entry offset=""0x12"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" />
<entry offset=""0x15"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""14"" document=""1"" />
<entry offset=""0x16"" startLine=""15"" startColumn=""15"" endLine=""15"" endColumn=""16"" document=""1"" />
<entry offset=""0x17"" startLine=""15"" startColumn=""17"" endLine=""15"" endColumn=""18"" document=""1"" />
<entry offset=""0x1a"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1b"">
<namespace name=""System"" />
<scope startOffset=""0x1"" endOffset=""0x13"">
<local name=""i"" il_index=""0"" il_start=""0x1"" il_end=""0x13"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(544937, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544937")]
[Fact]
public void ForEachStatement_MultiDimensionalArrayBreakAndContinue()
{
var source = @"
using System;
class C
{
static void Main()
{
int[, ,] array = new[,,]
{
{ {1, 2}, {3, 4} },
{ {5, 6}, {7, 8} },
};
foreach (int i in array)
{
if (i % 2 == 1) continue;
if (i > 4) break;
Console.WriteLine(i);
}
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll.WithModuleName("MODULE"));
// Stepping:
// After "continue", step to "in".
// After "break", step to first sequence point following loop body (in this case, method close brace).
v.VerifyIL("C.Main", @"
{
// Code size 169 (0xa9)
.maxstack 4
.locals init (int[,,] V_0, //array
int[,,] V_1,
int V_2,
int V_3,
int V_4,
int V_5,
int V_6,
int V_7,
int V_8, //i
bool V_9,
bool V_10)
-IL_0000: nop
-IL_0001: ldc.i4.2
IL_0002: ldc.i4.2
IL_0003: ldc.i4.2
IL_0004: newobj ""int[*,*,*]..ctor""
IL_0009: dup
IL_000a: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=32 <PrivateImplementationDetails>.8B4B2444E57AED8C2D05A1293255DA1B048C63224317D4666230760935FA4A18""
IL_000f: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_0014: stloc.0
-IL_0015: nop
-IL_0016: ldloc.0
IL_0017: stloc.1
IL_0018: ldloc.1
IL_0019: ldc.i4.0
IL_001a: callvirt ""int System.Array.GetUpperBound(int)""
IL_001f: stloc.2
IL_0020: ldloc.1
IL_0021: ldc.i4.1
IL_0022: callvirt ""int System.Array.GetUpperBound(int)""
IL_0027: stloc.3
IL_0028: ldloc.1
IL_0029: ldc.i4.2
IL_002a: callvirt ""int System.Array.GetUpperBound(int)""
IL_002f: stloc.s V_4
IL_0031: ldloc.1
IL_0032: ldc.i4.0
IL_0033: callvirt ""int System.Array.GetLowerBound(int)""
IL_0038: stloc.s V_5
~IL_003a: br.s IL_00a3
IL_003c: ldloc.1
IL_003d: ldc.i4.1
IL_003e: callvirt ""int System.Array.GetLowerBound(int)""
IL_0043: stloc.s V_6
~IL_0045: br.s IL_0098
IL_0047: ldloc.1
IL_0048: ldc.i4.2
IL_0049: callvirt ""int System.Array.GetLowerBound(int)""
IL_004e: stloc.s V_7
~IL_0050: br.s IL_008c
-IL_0052: ldloc.1
IL_0053: ldloc.s V_5
IL_0055: ldloc.s V_6
IL_0057: ldloc.s V_7
IL_0059: call ""int[*,*,*].Get""
IL_005e: stloc.s V_8
-IL_0060: nop
-IL_0061: ldloc.s V_8
IL_0063: ldc.i4.2
IL_0064: rem
IL_0065: ldc.i4.1
IL_0066: ceq
IL_0068: stloc.s V_9
~IL_006a: ldloc.s V_9
IL_006c: brfalse.s IL_0070
-IL_006e: br.s IL_0086
-IL_0070: ldloc.s V_8
IL_0072: ldc.i4.4
IL_0073: cgt
IL_0075: stloc.s V_10
~IL_0077: ldloc.s V_10
IL_0079: brfalse.s IL_007d
-IL_007b: br.s IL_00a8
-IL_007d: ldloc.s V_8
IL_007f: call ""void System.Console.WriteLine(int)""
IL_0084: nop
-IL_0085: nop
~IL_0086: ldloc.s V_7
IL_0088: ldc.i4.1
IL_0089: add
IL_008a: stloc.s V_7
-IL_008c: ldloc.s V_7
IL_008e: ldloc.s V_4
IL_0090: ble.s IL_0052
~IL_0092: ldloc.s V_6
IL_0094: ldc.i4.1
IL_0095: add
IL_0096: stloc.s V_6
-IL_0098: ldloc.s V_6
IL_009a: ldloc.3
IL_009b: ble.s IL_0047
~IL_009d: ldloc.s V_5
IL_009f: ldc.i4.1
IL_00a0: add
IL_00a1: stloc.s V_5
-IL_00a3: ldloc.s V_5
IL_00a5: ldloc.2
IL_00a6: ble.s IL_003c
-IL_00a8: ret
}
", sequencePoints: "C.Main");
}
[Fact]
public void ForEachStatement_Enumerator()
{
var source = @"
public class C
{
public static void Main()
{
foreach (var x in new System.Collections.Generic.List<int>())
{
System.Console.WriteLine(x);
}
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
// Sequence points:
// 1) Open brace at start of method
// 2) 'foreach'
// 3) 'new System.Collections.Generic.List<int>()'
// 4) Hidden initial jump (of while loop)
// 5) 'var c'
// 6) Open brace of loop
// 7) Loop body
// 8) Close brace of loop
// 9) 'in'
// 10) hidden point in Finally
// 11) Close brace at end of method
v.VerifyIL("C.Main", @"
{
// Code size 59 (0x3b)
.maxstack 1
.locals init (System.Collections.Generic.List<int>.Enumerator V_0,
int V_1) //x
-IL_0000: nop
-IL_0001: nop
-IL_0002: newobj ""System.Collections.Generic.List<int>..ctor()""
IL_0007: call ""System.Collections.Generic.List<int>.Enumerator System.Collections.Generic.List<int>.GetEnumerator()""
IL_000c: stloc.0
.try
{
~IL_000d: br.s IL_0020
-IL_000f: ldloca.s V_0
IL_0011: call ""int System.Collections.Generic.List<int>.Enumerator.Current.get""
IL_0016: stloc.1
-IL_0017: nop
-IL_0018: ldloc.1
IL_0019: call ""void System.Console.WriteLine(int)""
IL_001e: nop
-IL_001f: nop
-IL_0020: ldloca.s V_0
IL_0022: call ""bool System.Collections.Generic.List<int>.Enumerator.MoveNext()""
IL_0027: brtrue.s IL_000f
IL_0029: leave.s IL_003a
}
finally
{
~IL_002b: ldloca.s V_0
IL_002d: constrained. ""System.Collections.Generic.List<int>.Enumerator""
IL_0033: callvirt ""void System.IDisposable.Dispose()""
IL_0038: nop
IL_0039: endfinally
}
-IL_003a: ret
}
", sequencePoints: "C.Main");
}
[WorkItem(718501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/718501")]
[Fact]
public void ForEachNops()
{
string source = WithWindowsLineBreaks(@"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
private static List<List<int>> l = new List<List<int>>();
static void Main(string[] args)
{
foreach (var i in l.AsEnumerable())
{
switch (i.Count)
{
case 1:
break;
default:
if (i.Count != 0)
{
}
break;
}
}
}
}
");
// we just want this to compile without crashing/asserting
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("Program.Main", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""3"" />
</using>
<encLocalSlotMap>
<slot kind=""5"" offset=""15"" />
<slot kind=""0"" offset=""15"" />
<slot kind=""35"" offset=""83"" />
<slot kind=""1"" offset=""83"" />
<slot kind=""1"" offset=""237"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0x1"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""20"" document=""1"" />
<entry offset=""0x2"" startLine=""12"" startColumn=""31"" endLine=""12"" endColumn=""47"" document=""1"" />
<entry offset=""0x12"" hidden=""true"" document=""1"" />
<entry offset=""0x14"" startLine=""12"" startColumn=""22"" endLine=""12"" endColumn=""27"" document=""1"" />
<entry offset=""0x1b"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""14"" document=""1"" />
<entry offset=""0x1c"" startLine=""14"" startColumn=""17"" endLine=""14"" endColumn=""33"" document=""1"" />
<entry offset=""0x23"" hidden=""true"" document=""1"" />
<entry offset=""0x25"" hidden=""true"" document=""1"" />
<entry offset=""0x2b"" startLine=""17"" startColumn=""25"" endLine=""17"" endColumn=""31"" document=""1"" />
<entry offset=""0x2d"" startLine=""20"" startColumn=""25"" endLine=""20"" endColumn=""42"" document=""1"" />
<entry offset=""0x38"" hidden=""true"" document=""1"" />
<entry offset=""0x3c"" startLine=""21"" startColumn=""25"" endLine=""21"" endColumn=""26"" document=""1"" />
<entry offset=""0x3d"" startLine=""22"" startColumn=""25"" endLine=""22"" endColumn=""26"" document=""1"" />
<entry offset=""0x3e"" startLine=""24"" startColumn=""25"" endLine=""24"" endColumn=""31"" document=""1"" />
<entry offset=""0x40"" startLine=""26"" startColumn=""13"" endLine=""26"" endColumn=""14"" document=""1"" />
<entry offset=""0x41"" startLine=""12"" startColumn=""28"" endLine=""12"" endColumn=""30"" document=""1"" />
<entry offset=""0x4b"" hidden=""true"" document=""1"" />
<entry offset=""0x55"" hidden=""true"" document=""1"" />
<entry offset=""0x56"" startLine=""27"" startColumn=""9"" endLine=""27"" endColumn=""10"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x57"">
<namespace name=""System"" />
<namespace name=""System.Collections.Generic"" />
<namespace name=""System.Linq"" />
<scope startOffset=""0x14"" endOffset=""0x41"">
<local name=""i"" il_index=""1"" il_start=""0x14"" il_end=""0x41"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>"
);
}
[Fact]
public void ForEachStatement_Deconstruction()
{
var source = WithWindowsLineBreaks(@"
public class C
{
public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) };
public static void Main()
{
foreach (var (c, (d, e)) in F())
{
System.Console.WriteLine(c);
}
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.Main", @"
{
// Code size 70 (0x46)
.maxstack 2
.locals init (System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_0,
int V_1,
int V_2, //c
bool V_3, //d
double V_4, //e
System.ValueTuple<bool, double> V_5)
// sequence point: {
IL_0000: nop
// sequence point: foreach
IL_0001: nop
// sequence point: F()
IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()""
IL_0007: stloc.0
IL_0008: ldc.i4.0
IL_0009: stloc.1
// sequence point: <hidden>
IL_000a: br.s IL_003f
// sequence point: var (c, (d, e))
IL_000c: ldloc.0
IL_000d: ldloc.1
IL_000e: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>""
IL_0013: dup
IL_0014: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2""
IL_0019: stloc.s V_5
IL_001b: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1""
IL_0020: stloc.2
IL_0021: ldloc.s V_5
IL_0023: ldfld ""bool System.ValueTuple<bool, double>.Item1""
IL_0028: stloc.3
IL_0029: ldloc.s V_5
IL_002b: ldfld ""double System.ValueTuple<bool, double>.Item2""
IL_0030: stloc.s V_4
// sequence point: {
IL_0032: nop
// sequence point: System.Console.WriteLine(c);
IL_0033: ldloc.2
IL_0034: call ""void System.Console.WriteLine(int)""
IL_0039: nop
// sequence point: }
IL_003a: nop
// sequence point: <hidden>
IL_003b: ldloc.1
IL_003c: ldc.i4.1
IL_003d: add
IL_003e: stloc.1
// sequence point: in
IL_003f: ldloc.1
IL_0040: ldloc.0
IL_0041: ldlen
IL_0042: conv.i4
IL_0043: blt.s IL_000c
// sequence point: }
IL_0045: ret
}
", sequencePoints: "C.Main", source: source);
v.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""50"" endLine=""4"" endColumn=""76"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
<encLocalSlotMap>
<slot kind=""6"" offset=""11"" />
<slot kind=""8"" offset=""11"" />
<slot kind=""0"" offset=""25"" />
<slot kind=""0"" offset=""29"" />
<slot kind=""0"" offset=""32"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""16"" document=""1"" />
<entry offset=""0x2"" startLine=""8"" startColumn=""37"" endLine=""8"" endColumn=""40"" document=""1"" />
<entry offset=""0xa"" hidden=""true"" document=""1"" />
<entry offset=""0xc"" startLine=""8"" startColumn=""18"" endLine=""8"" endColumn=""33"" document=""1"" />
<entry offset=""0x32"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x33"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""41"" document=""1"" />
<entry offset=""0x3a"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0x3b"" hidden=""true"" document=""1"" />
<entry offset=""0x3f"" startLine=""8"" startColumn=""34"" endLine=""8"" endColumn=""36"" document=""1"" />
<entry offset=""0x45"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x46"">
<scope startOffset=""0xc"" endOffset=""0x3b"">
<local name=""c"" il_index=""2"" il_start=""0xc"" il_end=""0x3b"" attributes=""0"" />
<local name=""d"" il_index=""3"" il_start=""0xc"" il_end=""0x3b"" attributes=""0"" />
<local name=""e"" il_index=""4"" il_start=""0xc"" il_end=""0x3b"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region Switch
[Fact]
public void SwitchWithPattern_01()
{
string source = WithWindowsLineBreaks(@"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
private static List<List<int>> l = new List<List<int>>();
static void Main(string[] args)
{
Student s = new Student();
s.Name = ""Bozo"";
s.GPA = 2.3;
Operate(s);
}
static string Operate(Person p)
{
switch (p)
{
case Student s when s.GPA > 3.5:
return $""Student {s.Name} ({s.GPA:N1})"";
case Student s:
return $""Student {s.Name} ({s.GPA:N1})"";
case Teacher t:
return $""Teacher {t.Name} of {t.Subject}"";
default:
return $""Person {p.Name}"";
}
}
}
class Person { public string Name; }
class Teacher : Person { public string Subject; }
class Student : Person { public double GPA; }
");
// we just want this to compile without crashing/asserting
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("Program.Operate",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Operate"" parameterNames=""p"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""59"" />
<slot kind=""0"" offset=""163"" />
<slot kind=""0"" offset=""250"" />
<slot kind=""35"" offset=""11"" />
<slot kind=""1"" offset=""11"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""19"" document=""1"" />
<entry offset=""0x4"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" hidden=""true"" document=""1"" />
<entry offset=""0x1d"" startLine=""22"" startColumn=""28"" endLine=""22"" endColumn=""44"" document=""1"" />
<entry offset=""0x2e"" hidden=""true"" document=""1"" />
<entry offset=""0x30"" startLine=""23"" startColumn=""17"" endLine=""23"" endColumn=""57"" document=""1"" />
<entry offset=""0x4f"" hidden=""true"" document=""1"" />
<entry offset=""0x53"" startLine=""25"" startColumn=""17"" endLine=""25"" endColumn=""57"" document=""1"" />
<entry offset=""0x72"" hidden=""true"" document=""1"" />
<entry offset=""0x74"" startLine=""27"" startColumn=""17"" endLine=""27"" endColumn=""59"" document=""1"" />
<entry offset=""0x93"" startLine=""29"" startColumn=""17"" endLine=""29"" endColumn=""43"" document=""1"" />
<entry offset=""0xa7"" startLine=""31"" startColumn=""5"" endLine=""31"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xaa"">
<scope startOffset=""0x1d"" endOffset=""0x4f"">
<local name=""s"" il_index=""0"" il_start=""0x1d"" il_end=""0x4f"" attributes=""0"" />
</scope>
<scope startOffset=""0x4f"" endOffset=""0x72"">
<local name=""s"" il_index=""1"" il_start=""0x4f"" il_end=""0x72"" attributes=""0"" />
</scope>
<scope startOffset=""0x72"" endOffset=""0x93"">
<local name=""t"" il_index=""2"" il_start=""0x72"" il_end=""0x93"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void SwitchWithPattern_02()
{
string source = WithWindowsLineBreaks(@"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
private static List<List<int>> l = new List<List<int>>();
static void Main(string[] args)
{
Student s = new Student();
s.Name = ""Bozo"";
s.GPA = 2.3;
Operate(s);
}
static System.Func<string> Operate(Person p)
{
switch (p)
{
case Student s when s.GPA > 3.5:
return () => $""Student {s.Name} ({s.GPA:N1})"";
case Student s:
return () => $""Student {s.Name} ({s.GPA:N1})"";
case Teacher t:
return () => $""Teacher {t.Name} of {t.Subject}"";
default:
return () => $""Person {p.Name}"";
}
}
}
class Person { public string Name; }
class Teacher : Person { public string Subject; }
class Student : Person { public double GPA; }
");
// we just want this to compile without crashing/asserting
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("Program.Operate",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Operate"" parameterNames=""p"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""0"" />
<slot kind=""30"" offset=""11"" />
<slot kind=""35"" offset=""11"" />
<slot kind=""1"" offset=""11"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>2</methodOrdinal>
<closure offset=""0"" />
<closure offset=""11"" />
<lambda offset=""109"" closure=""1"" />
<lambda offset=""202"" closure=""1"" />
<lambda offset=""295"" closure=""1"" />
<lambda offset=""383"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" />
<entry offset=""0xe"" hidden=""true"" document=""1"" />
<entry offset=""0x1b"" hidden=""true"" document=""1"" />
<entry offset=""0x1d"" hidden=""true"" document=""1"" />
<entry offset=""0x47"" startLine=""22"" startColumn=""28"" endLine=""22"" endColumn=""44"" document=""1"" />
<entry offset=""0x5d"" hidden=""true"" document=""1"" />
<entry offset=""0x5f"" startLine=""23"" startColumn=""17"" endLine=""23"" endColumn=""63"" document=""1"" />
<entry offset=""0x6f"" hidden=""true"" document=""1"" />
<entry offset=""0x7d"" startLine=""25"" startColumn=""17"" endLine=""25"" endColumn=""63"" document=""1"" />
<entry offset=""0x8d"" hidden=""true"" document=""1"" />
<entry offset=""0x8f"" startLine=""27"" startColumn=""17"" endLine=""27"" endColumn=""65"" document=""1"" />
<entry offset=""0x9f"" startLine=""29"" startColumn=""17"" endLine=""29"" endColumn=""49"" document=""1"" />
<entry offset=""0xaf"" startLine=""31"" startColumn=""5"" endLine=""31"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xb2"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0xb2"" attributes=""0"" />
<scope startOffset=""0xe"" endOffset=""0xaf"">
<local name=""CS$<>8__locals1"" il_index=""1"" il_start=""0xe"" il_end=""0xaf"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void SwitchWithPatternAndLocalFunctions()
{
string source = WithWindowsLineBreaks(@"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
private static List<List<int>> l = new List<List<int>>();
static void Main(string[] args)
{
Student s = new Student();
s.Name = ""Bozo"";
s.GPA = 2.3;
Operate(s);
}
static System.Func<string> Operate(Person p)
{
switch (p)
{
case Student s when s.GPA > 3.5:
string f1() => $""Student {s.Name} ({s.GPA:N1})"";
return f1;
case Student s:
string f2() => $""Student {s.Name} ({s.GPA:N1})"";
return f2;
case Teacher t:
string f3() => $""Teacher {t.Name} of {t.Subject}"";
return f3;
default:
string f4() => $""Person {p.Name}"";
return f4;
}
}
}
class Person { public string Name; }
class Teacher : Person { public string Subject; }
class Student : Person { public double GPA; }
");
// we just want this to compile without crashing/asserting
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("Program.Operate", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Operate"" parameterNames=""p"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""0"" />
<slot kind=""30"" offset=""11"" />
<slot kind=""35"" offset=""11"" />
<slot kind=""1"" offset=""11"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>2</methodOrdinal>
<closure offset=""0"" />
<closure offset=""11"" />
<lambda offset=""111"" closure=""1"" />
<lambda offset=""234"" closure=""1"" />
<lambda offset=""357"" closure=""1"" />
<lambda offset=""475"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" />
<entry offset=""0xe"" hidden=""true"" document=""1"" />
<entry offset=""0x1b"" hidden=""true"" document=""1"" />
<entry offset=""0x1d"" hidden=""true"" document=""1"" />
<entry offset=""0x47"" startLine=""22"" startColumn=""28"" endLine=""22"" endColumn=""44"" document=""1"" />
<entry offset=""0x5d"" hidden=""true"" document=""1"" />
<entry offset=""0x60"" startLine=""24"" startColumn=""17"" endLine=""24"" endColumn=""27"" document=""1"" />
<entry offset=""0x70"" hidden=""true"" document=""1"" />
<entry offset=""0x7f"" startLine=""27"" startColumn=""17"" endLine=""27"" endColumn=""27"" document=""1"" />
<entry offset=""0x8f"" hidden=""true"" document=""1"" />
<entry offset=""0x92"" startLine=""30"" startColumn=""17"" endLine=""30"" endColumn=""27"" document=""1"" />
<entry offset=""0xa2"" hidden=""true"" document=""1"" />
<entry offset=""0xa3"" startLine=""33"" startColumn=""17"" endLine=""33"" endColumn=""27"" document=""1"" />
<entry offset=""0xb3"" startLine=""35"" startColumn=""5"" endLine=""35"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xb6"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0xb6"" attributes=""0"" />
<scope startOffset=""0xe"" endOffset=""0xb3"">
<local name=""CS$<>8__locals1"" il_index=""1"" il_start=""0xe"" il_end=""0xb3"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(17090, "https://github.com/dotnet/roslyn/issues/17090"), WorkItem(19731, "https://github.com/dotnet/roslyn/issues/19731")]
[Fact]
public void SwitchWithConstantPattern()
{
string source = @"
using System;
class Program
{
static void Main(string[] args)
{
M1();
M2();
}
static void M1()
{
switch
(1)
{
case 0 when true:
;
case 1:
Console.Write(1);
break;
case 2:
;
}
}
static void M2()
{
switch
(nameof(M2))
{
case nameof(M1) when true:
;
case nameof(M2):
Console.Write(nameof(M2));
break;
case nameof(Main):
;
}
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugExe);
c.VerifyDiagnostics();
var verifier = CompileAndVerify(c, expectedOutput: "1M2");
verifier.VerifyIL(qualifiedMethodName: "Program.M1", sequencePoints: "Program.M1", source: source,
expectedIL: @"{
// Code size 17 (0x11)
.maxstack 1
.locals init (int V_0,
int V_1)
// sequence point: {
IL_0000: nop
// sequence point: switch ... (1
IL_0001: ldc.i4.1
IL_0002: stloc.1
IL_0003: ldc.i4.1
IL_0004: stloc.0
// sequence point: <hidden>
IL_0005: br.s IL_0007
// sequence point: Console.Write(1);
IL_0007: ldc.i4.1
IL_0008: call ""void System.Console.Write(int)""
IL_000d: nop
// sequence point: break;
IL_000e: br.s IL_0010
// sequence point: }
IL_0010: ret
}");
verifier.VerifyIL(qualifiedMethodName: "Program.M2", sequencePoints: "Program.M2", source: source,
expectedIL: @"{
// Code size 29 (0x1d)
.maxstack 1
.locals init (string V_0,
string V_1)
// sequence point: {
IL_0000: nop
// sequence point: switch ... (nameof(M2)
IL_0001: ldstr ""M2""
IL_0006: stloc.1
IL_0007: ldstr ""M2""
IL_000c: stloc.0
// sequence point: <hidden>
IL_000d: br.s IL_000f
// sequence point: Console.Write(nameof(M2));
IL_000f: ldstr ""M2""
IL_0014: call ""void System.Console.Write(string)""
IL_0019: nop
// sequence point: break;
IL_001a: br.s IL_001c
// sequence point: }
IL_001c: ret
}");
// Check the release code generation too.
c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe);
c.VerifyDiagnostics();
verifier = CompileAndVerify(c, expectedOutput: "1M2");
verifier.VerifyIL("Program.M1",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: call ""void System.Console.Write(int)""
IL_0006: ret
}");
verifier.VerifyIL("Program.M2",
@"{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldstr ""M2""
IL_0005: call ""void System.Console.Write(string)""
IL_000a: ret
}");
}
[WorkItem(19734, "https://github.com/dotnet/roslyn/issues/19734")]
[Fact]
public void SwitchWithConstantGenericPattern_01()
{
string source = @"
using System;
class Program
{
static void Main(string[] args)
{
M1<int>(); // 1
M1<long>(); // 2
M2<string>(); // 3
M2<int>(); // 4
}
static void M1<T>()
{
switch (1)
{
case T t:
Console.Write(1);
break;
case int i:
Console.Write(2);
break;
}
}
static void M2<T>()
{
switch (nameof(M2))
{
case T t:
Console.Write(3);
break;
case string s:
Console.Write(4);
break;
case null:
;
}
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_1);
c.VerifyDiagnostics();
var verifier = CompileAndVerify(c, expectedOutput: "1234");
verifier.VerifyIL(qualifiedMethodName: "Program.M1<T>", sequencePoints: "Program.M1", source: source,
expectedIL: @"{
// Code size 60 (0x3c)
.maxstack 1
.locals init (T V_0, //t
int V_1, //i
int V_2)
// sequence point: {
IL_0000: nop
// sequence point: switch (1)
IL_0001: ldc.i4.1
IL_0002: stloc.2
IL_0003: ldc.i4.1
IL_0004: stloc.1
// sequence point: <hidden>
IL_0005: ldloc.1
IL_0006: box ""int""
IL_000b: isinst ""T""
IL_0010: brfalse.s IL_0030
IL_0012: ldloc.1
IL_0013: box ""int""
IL_0018: isinst ""T""
IL_001d: unbox.any ""T""
IL_0022: stloc.0
// sequence point: <hidden>
IL_0023: br.s IL_0025
// sequence point: <hidden>
IL_0025: br.s IL_0027
// sequence point: Console.Write(1);
IL_0027: ldc.i4.1
IL_0028: call ""void System.Console.Write(int)""
IL_002d: nop
// sequence point: break;
IL_002e: br.s IL_003b
// sequence point: <hidden>
IL_0030: br.s IL_0032
// sequence point: Console.Write(2);
IL_0032: ldc.i4.2
IL_0033: call ""void System.Console.Write(int)""
IL_0038: nop
// sequence point: break;
IL_0039: br.s IL_003b
// sequence point: }
IL_003b: ret
}");
verifier.VerifyIL(qualifiedMethodName: "Program.M2<T>", sequencePoints: "Program.M2", source: source,
expectedIL: @"{
// Code size 58 (0x3a)
.maxstack 1
.locals init (T V_0, //t
string V_1, //s
string V_2)
// sequence point: {
IL_0000: nop
// sequence point: switch (nameof(M2))
IL_0001: ldstr ""M2""
IL_0006: stloc.2
IL_0007: ldstr ""M2""
IL_000c: stloc.1
// sequence point: <hidden>
IL_000d: ldloc.1
IL_000e: isinst ""T""
IL_0013: brfalse.s IL_002e
IL_0015: ldloc.1
IL_0016: isinst ""T""
IL_001b: unbox.any ""T""
IL_0020: stloc.0
// sequence point: <hidden>
IL_0021: br.s IL_0023
// sequence point: <hidden>
IL_0023: br.s IL_0025
// sequence point: Console.Write(3);
IL_0025: ldc.i4.3
IL_0026: call ""void System.Console.Write(int)""
IL_002b: nop
// sequence point: break;
IL_002c: br.s IL_0039
// sequence point: <hidden>
IL_002e: br.s IL_0030
// sequence point: Console.Write(4);
IL_0030: ldc.i4.4
IL_0031: call ""void System.Console.Write(int)""
IL_0036: nop
// sequence point: break;
IL_0037: br.s IL_0039
// sequence point: }
IL_0039: ret
}");
// Check the release code generation too.
c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_1);
c.VerifyDiagnostics();
verifier = CompileAndVerify(c, expectedOutput: "1234");
verifier.VerifyIL("Program.M1<T>",
@"{
// Code size 29 (0x1d)
.maxstack 1
.locals init (int V_0) //i
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: box ""int""
IL_0008: isinst ""T""
IL_000d: brfalse.s IL_0016
IL_000f: ldc.i4.1
IL_0010: call ""void System.Console.Write(int)""
IL_0015: ret
IL_0016: ldc.i4.2
IL_0017: call ""void System.Console.Write(int)""
IL_001c: ret
}");
verifier.VerifyIL("Program.M2<T>",
@"{
// Code size 28 (0x1c)
.maxstack 1
.locals init (string V_0) //s
IL_0000: ldstr ""M2""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: isinst ""T""
IL_000c: brfalse.s IL_0015
IL_000e: ldc.i4.3
IL_000f: call ""void System.Console.Write(int)""
IL_0014: ret
IL_0015: ldc.i4.4
IL_0016: call ""void System.Console.Write(int)""
IL_001b: ret
}");
}
[WorkItem(19734, "https://github.com/dotnet/roslyn/issues/19734")]
[Fact]
public void SwitchWithConstantGenericPattern_02()
{
string source = @"
using System;
class Program
{
static void Main(string[] args)
{
M2<string>(); // 6
M2<int>(); // 6
}
static void M2<T>()
{
const string x = null;
switch (x)
{
case T t:
;
case string s:
;
case null:
Console.Write(6);
break;
}
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_1);
c.VerifyDiagnostics();
var verifier = CompileAndVerify(c, expectedOutput: "66");
verifier.VerifyIL(qualifiedMethodName: "Program.M2<T>", sequencePoints: "Program.M2", source: source,
expectedIL: @"{
// Code size 17 (0x11)
.maxstack 1
.locals init (T V_0, //t
string V_1, //s
string V_2,
string V_3)
// sequence point: {
IL_0000: nop
// sequence point: switch (x)
IL_0001: ldnull
IL_0002: stloc.3
IL_0003: ldnull
IL_0004: stloc.2
// sequence point: <hidden>
IL_0005: br.s IL_0007
// sequence point: Console.Write(6);
IL_0007: ldc.i4.6
IL_0008: call ""void System.Console.Write(int)""
IL_000d: nop
// sequence point: break;
IL_000e: br.s IL_0010
// sequence point: }
IL_0010: ret
}");
// Check the release code generation too.
c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_1);
c.VerifyDiagnostics();
verifier = CompileAndVerify(c, expectedOutput: "66");
verifier.VerifyIL("Program.M2<T>",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldc.i4.6
IL_0001: call ""void System.Console.Write(int)""
IL_0006: ret
}");
}
[Fact]
[WorkItem(31665, "https://github.com/dotnet/roslyn/issues/31665")]
public void TestSequencePoints_31665()
{
var source = @"
using System;
internal class Program
{
private static void Main(string[] args)
{
var s = ""1"";
if (true)
switch (s)
{
case ""1"":
Console.Out.WriteLine(""Input was 1"");
break;
default:
throw new Exception(""Default case"");
}
else
Console.Out.WriteLine(""Too many inputs"");
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.Main(string[])", @"
{
// Code size 60 (0x3c)
.maxstack 2
.locals init (string V_0, //s
bool V_1,
string V_2,
string V_3)
// sequence point: {
IL_0000: nop
// sequence point: var s = ""1"";
IL_0001: ldstr ""1""
IL_0006: stloc.0
// sequence point: if (true)
IL_0007: ldc.i4.1
IL_0008: stloc.1
// sequence point: switch (s)
IL_0009: ldloc.0
IL_000a: stloc.3
// sequence point: <hidden>
IL_000b: ldloc.3
IL_000c: stloc.2
// sequence point: <hidden>
IL_000d: ldloc.2
IL_000e: ldstr ""1""
IL_0013: call ""bool string.op_Equality(string, string)""
IL_0018: brtrue.s IL_001c
IL_001a: br.s IL_002e
// sequence point: Console.Out.WriteLine(""Input was 1"");
IL_001c: call ""System.IO.TextWriter System.Console.Out.get""
IL_0021: ldstr ""Input was 1""
IL_0026: callvirt ""void System.IO.TextWriter.WriteLine(string)""
IL_002b: nop
// sequence point: break;
IL_002c: br.s IL_0039
// sequence point: throw new Exception(""Default case"");
IL_002e: ldstr ""Default case""
IL_0033: newobj ""System.Exception..ctor(string)""
IL_0038: throw
// sequence point: <hidden>
IL_0039: br.s IL_003b
// sequence point: }
IL_003b: ret
}
", sequencePoints: "Program.Main", source: source);
}
[Fact]
[WorkItem(17076, "https://github.com/dotnet/roslyn/issues/17076")]
public void TestSequencePoints_17076()
{
var source = @"
using System.Threading.Tasks;
internal class Program
{
private static void Main(string[] args)
{
M(new Node()).GetAwaiter().GetResult();
}
static async Task M(Node node)
{
while (node != null)
{
if (node is A a)
{
await Task.Yield();
return;
}
else if (node is B b)
{
await Task.Yield();
return;
}
node = node.Parent;
}
}
}
class Node
{
public Node Parent = null;
}
class A : Node { }
class B : Node { }
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<M>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 403 (0x193)
.maxstack 3
.locals init (int V_0,
bool V_1,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_2,
System.Runtime.CompilerServices.YieldAwaitable V_3,
Program.<M>d__1 V_4,
bool V_5,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_6,
bool V_7,
System.Exception V_8)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<M>d__1.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: <hidden>
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0012
IL_000a: br.s IL_000c
IL_000c: ldloc.0
IL_000d: ldc.i4.1
IL_000e: beq.s IL_0014
IL_0010: br.s IL_0019
IL_0012: br.s IL_007e
IL_0014: br IL_0109
// sequence point: {
IL_0019: nop
// sequence point: <hidden>
IL_001a: br IL_0150
// sequence point: {
IL_001f: nop
// sequence point: if (node is A a)
IL_0020: ldarg.0
IL_0021: ldarg.0
IL_0022: ldfld ""Node Program.<M>d__1.node""
IL_0027: isinst ""A""
IL_002c: stfld ""A Program.<M>d__1.<a>5__1""
IL_0031: ldarg.0
IL_0032: ldfld ""A Program.<M>d__1.<a>5__1""
IL_0037: ldnull
IL_0038: cgt.un
IL_003a: stloc.1
// sequence point: <hidden>
IL_003b: ldloc.1
IL_003c: brfalse.s IL_00a7
// sequence point: {
IL_003e: nop
// sequence point: await Task.Yield();
IL_003f: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_0044: stloc.3
IL_0045: ldloca.s V_3
IL_0047: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_004c: stloc.2
// sequence point: <hidden>
IL_004d: ldloca.s V_2
IL_004f: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_0054: brtrue.s IL_009a
IL_0056: ldarg.0
IL_0057: ldc.i4.0
IL_0058: dup
IL_0059: stloc.0
IL_005a: stfld ""int Program.<M>d__1.<>1__state""
// async: yield
IL_005f: ldarg.0
IL_0060: ldloc.2
IL_0061: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1""
IL_0066: ldarg.0
IL_0067: stloc.s V_4
IL_0069: ldarg.0
IL_006a: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<M>d__1.<>t__builder""
IL_006f: ldloca.s V_2
IL_0071: ldloca.s V_4
IL_0073: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Program.<M>d__1>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Program.<M>d__1)""
IL_0078: nop
IL_0079: leave IL_0192
// async: resume
IL_007e: ldarg.0
IL_007f: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1""
IL_0084: stloc.2
IL_0085: ldarg.0
IL_0086: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1""
IL_008b: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_0091: ldarg.0
IL_0092: ldc.i4.m1
IL_0093: dup
IL_0094: stloc.0
IL_0095: stfld ""int Program.<M>d__1.<>1__state""
IL_009a: ldloca.s V_2
IL_009c: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_00a1: nop
// sequence point: return;
IL_00a2: leave IL_017e
// sequence point: if (node is B b)
IL_00a7: ldarg.0
IL_00a8: ldarg.0
IL_00a9: ldfld ""Node Program.<M>d__1.node""
IL_00ae: isinst ""B""
IL_00b3: stfld ""B Program.<M>d__1.<b>5__2""
IL_00b8: ldarg.0
IL_00b9: ldfld ""B Program.<M>d__1.<b>5__2""
IL_00be: ldnull
IL_00bf: cgt.un
IL_00c1: stloc.s V_5
// sequence point: <hidden>
IL_00c3: ldloc.s V_5
IL_00c5: brfalse.s IL_0130
// sequence point: {
IL_00c7: nop
// sequence point: await Task.Yield();
IL_00c8: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_00cd: stloc.3
IL_00ce: ldloca.s V_3
IL_00d0: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_00d5: stloc.s V_6
// sequence point: <hidden>
IL_00d7: ldloca.s V_6
IL_00d9: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_00de: brtrue.s IL_0126
IL_00e0: ldarg.0
IL_00e1: ldc.i4.1
IL_00e2: dup
IL_00e3: stloc.0
IL_00e4: stfld ""int Program.<M>d__1.<>1__state""
// async: yield
IL_00e9: ldarg.0
IL_00ea: ldloc.s V_6
IL_00ec: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1""
IL_00f1: ldarg.0
IL_00f2: stloc.s V_4
IL_00f4: ldarg.0
IL_00f5: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<M>d__1.<>t__builder""
IL_00fa: ldloca.s V_6
IL_00fc: ldloca.s V_4
IL_00fe: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Program.<M>d__1>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Program.<M>d__1)""
IL_0103: nop
IL_0104: leave IL_0192
// async: resume
IL_0109: ldarg.0
IL_010a: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1""
IL_010f: stloc.s V_6
IL_0111: ldarg.0
IL_0112: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1""
IL_0117: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_011d: ldarg.0
IL_011e: ldc.i4.m1
IL_011f: dup
IL_0120: stloc.0
IL_0121: stfld ""int Program.<M>d__1.<>1__state""
IL_0126: ldloca.s V_6
IL_0128: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_012d: nop
// sequence point: return;
IL_012e: leave.s IL_017e
// sequence point: <hidden>
IL_0130: ldarg.0
IL_0131: ldnull
IL_0132: stfld ""B Program.<M>d__1.<b>5__2""
// sequence point: node = node.Parent;
IL_0137: ldarg.0
IL_0138: ldarg.0
IL_0139: ldfld ""Node Program.<M>d__1.node""
IL_013e: ldfld ""Node Node.Parent""
IL_0143: stfld ""Node Program.<M>d__1.node""
// sequence point: }
IL_0148: nop
IL_0149: ldarg.0
IL_014a: ldnull
IL_014b: stfld ""A Program.<M>d__1.<a>5__1""
// sequence point: while (node != null)
IL_0150: ldarg.0
IL_0151: ldfld ""Node Program.<M>d__1.node""
IL_0156: ldnull
IL_0157: cgt.un
IL_0159: stloc.s V_7
// sequence point: <hidden>
IL_015b: ldloc.s V_7
IL_015d: brtrue IL_001f
IL_0162: leave.s IL_017e
}
catch System.Exception
{
// sequence point: <hidden>
IL_0164: stloc.s V_8
IL_0166: ldarg.0
IL_0167: ldc.i4.s -2
IL_0169: stfld ""int Program.<M>d__1.<>1__state""
IL_016e: ldarg.0
IL_016f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<M>d__1.<>t__builder""
IL_0174: ldloc.s V_8
IL_0176: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_017b: nop
IL_017c: leave.s IL_0192
}
// sequence point: }
IL_017e: ldarg.0
IL_017f: ldc.i4.s -2
IL_0181: stfld ""int Program.<M>d__1.<>1__state""
// sequence point: <hidden>
IL_0186: ldarg.0
IL_0187: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<M>d__1.<>t__builder""
IL_018c: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_0191: nop
IL_0192: ret
}
", sequencePoints: "Program+<M>d__1.MoveNext", source: source);
}
[Fact]
[WorkItem(28288, "https://github.com/dotnet/roslyn/issues/28288")]
public void TestSequencePoints_28288()
{
var source = @"
using System.Threading.Tasks;
public class C
{
public static async Task Main()
{
object o = new C();
switch (o)
{
case C c:
System.Console.Write(1);
break;
default:
return;
}
if (M() != null)
{
}
}
private static object M()
{
return new C();
}
}";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("C.<Main>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 162 (0xa2)
.maxstack 2
.locals init (int V_0,
object V_1,
bool V_2,
System.Exception V_3)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<Main>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: object o = new C();
IL_0008: ldarg.0
IL_0009: newobj ""C..ctor()""
IL_000e: stfld ""object C.<Main>d__0.<o>5__1""
// sequence point: switch (o)
IL_0013: ldarg.0
IL_0014: ldarg.0
IL_0015: ldfld ""object C.<Main>d__0.<o>5__1""
IL_001a: stloc.1
// sequence point: <hidden>
IL_001b: ldloc.1
IL_001c: stfld ""object C.<Main>d__0.<>s__3""
// sequence point: <hidden>
IL_0021: ldarg.0
IL_0022: ldarg.0
IL_0023: ldfld ""object C.<Main>d__0.<>s__3""
IL_0028: isinst ""C""
IL_002d: stfld ""C C.<Main>d__0.<c>5__2""
IL_0032: ldarg.0
IL_0033: ldfld ""C C.<Main>d__0.<c>5__2""
IL_0038: brtrue.s IL_003c
IL_003a: br.s IL_0047
// sequence point: <hidden>
IL_003c: br.s IL_003e
// sequence point: System.Console.Write(1);
IL_003e: ldc.i4.1
IL_003f: call ""void System.Console.Write(int)""
IL_0044: nop
// sequence point: break;
IL_0045: br.s IL_0049
// sequence point: return;
IL_0047: leave.s IL_0086
// sequence point: <hidden>
IL_0049: ldarg.0
IL_004a: ldnull
IL_004b: stfld ""C C.<Main>d__0.<c>5__2""
IL_0050: ldarg.0
IL_0051: ldnull
IL_0052: stfld ""object C.<Main>d__0.<>s__3""
// sequence point: if (M() != null)
IL_0057: call ""object C.M()""
IL_005c: ldnull
IL_005d: cgt.un
IL_005f: stloc.2
// sequence point: <hidden>
IL_0060: ldloc.2
IL_0061: brfalse.s IL_0065
// sequence point: {
IL_0063: nop
// sequence point: }
IL_0064: nop
// sequence point: <hidden>
IL_0065: leave.s IL_0086
}
catch System.Exception
{
// sequence point: <hidden>
IL_0067: stloc.3
IL_0068: ldarg.0
IL_0069: ldc.i4.s -2
IL_006b: stfld ""int C.<Main>d__0.<>1__state""
IL_0070: ldarg.0
IL_0071: ldnull
IL_0072: stfld ""object C.<Main>d__0.<o>5__1""
IL_0077: ldarg.0
IL_0078: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder""
IL_007d: ldloc.3
IL_007e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_0083: nop
IL_0084: leave.s IL_00a1
}
// sequence point: }
IL_0086: ldarg.0
IL_0087: ldc.i4.s -2
IL_0089: stfld ""int C.<Main>d__0.<>1__state""
// sequence point: <hidden>
IL_008e: ldarg.0
IL_008f: ldnull
IL_0090: stfld ""object C.<Main>d__0.<o>5__1""
IL_0095: ldarg.0
IL_0096: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder""
IL_009b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_00a0: nop
IL_00a1: ret
}
", sequencePoints: "C+<Main>d__0.MoveNext", source: source);
}
[Fact]
public void SwitchExpressionWithPattern()
{
string source = WithWindowsLineBreaks(@"
class C
{
static string M(object o)
{
return o switch
{
int i => $""Number: {i}"",
_ => ""Don't know""
};
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.M",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"" parameterNames=""o"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""55"" />
<slot kind=""temp"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""10"" endColumn=""11"" document=""1"" />
<entry offset=""0x4"" startLine=""6"" startColumn=""18"" endLine=""10"" endColumn=""10"" document=""1"" />
<entry offset=""0x5"" hidden=""true"" document=""1"" />
<entry offset=""0x14"" hidden=""true"" document=""1"" />
<entry offset=""0x16"" hidden=""true"" document=""1"" />
<entry offset=""0x18"" startLine=""8"" startColumn=""22"" endLine=""8"" endColumn=""36"" document=""1"" />
<entry offset=""0x2b"" startLine=""9"" startColumn=""18"" endLine=""9"" endColumn=""30"" document=""1"" />
<entry offset=""0x33"" hidden=""true"" document=""1"" />
<entry offset=""0x36"" startLine=""6"" startColumn=""9"" endLine=""10"" endColumn=""11"" document=""1"" />
<entry offset=""0x37"" hidden=""true"" document=""1"" />
<entry offset=""0x3b"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x3d"">
<scope startOffset=""0x16"" endOffset=""0x2b"">
<local name=""i"" il_index=""0"" il_start=""0x16"" il_end=""0x2b"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region DoStatement
[Fact]
public void DoStatement()
{
var source = WithWindowsLineBreaks(
@"using System;
public class SeqPointForWhile
{
public static void Main()
{
SeqPointForWhile obj = new SeqPointForWhile();
obj.While(234);
}
int field;
public void While(int p)
{
do
{
p = (int)(p / 2);
if (p > 100)
{
continue;
}
else if (p > 10)
{
field = 1;
}
else
{
break;
}
} while (p > 0); // SeqPt should be generated for [while (p > 0);]
field = -1;
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""SeqPointForWhile"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""28"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""55"" document=""1"" />
<entry offset=""0x7"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""24"" document=""1"" />
<entry offset=""0x13"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x14"">
<namespace name=""System"" />
<local name=""obj"" il_index=""0"" il_start=""0x0"" il_end=""0x14"" attributes=""0"" />
</scope>
</method>
<method containingType=""SeqPointForWhile"" name=""While"" parameterNames=""p"">
<customDebugInfo>
<forward declaringType=""SeqPointForWhile"" methodName=""Main"" />
<encLocalSlotMap>
<slot kind=""1"" offset=""71"" />
<slot kind=""1"" offset=""159"" />
<slot kind=""1"" offset=""11"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" />
<entry offset=""0x2"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""30"" document=""1"" />
<entry offset=""0x7"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""25"" document=""1"" />
<entry offset=""0xd"" hidden=""true"" document=""1"" />
<entry offset=""0x10"" startLine=""19"" startColumn=""13"" endLine=""19"" endColumn=""14"" document=""1"" />
<entry offset=""0x11"" startLine=""20"" startColumn=""17"" endLine=""20"" endColumn=""26"" document=""1"" />
<entry offset=""0x13"" startLine=""22"" startColumn=""18"" endLine=""22"" endColumn=""29"" document=""1"" />
<entry offset=""0x19"" hidden=""true"" document=""1"" />
<entry offset=""0x1c"" startLine=""23"" startColumn=""13"" endLine=""23"" endColumn=""14"" document=""1"" />
<entry offset=""0x1d"" startLine=""24"" startColumn=""17"" endLine=""24"" endColumn=""27"" document=""1"" />
<entry offset=""0x24"" startLine=""25"" startColumn=""13"" endLine=""25"" endColumn=""14"" document=""1"" />
<entry offset=""0x25"" hidden=""true"" document=""1"" />
<entry offset=""0x27"" startLine=""27"" startColumn=""13"" endLine=""27"" endColumn=""14"" document=""1"" />
<entry offset=""0x28"" startLine=""28"" startColumn=""17"" endLine=""28"" endColumn=""23"" document=""1"" />
<entry offset=""0x2a"" startLine=""30"" startColumn=""9"" endLine=""30"" endColumn=""10"" document=""1"" />
<entry offset=""0x2b"" startLine=""30"" startColumn=""11"" endLine=""30"" endColumn=""25"" document=""1"" />
<entry offset=""0x30"" hidden=""true"" document=""1"" />
<entry offset=""0x33"" startLine=""32"" startColumn=""9"" endLine=""32"" endColumn=""20"" document=""1"" />
<entry offset=""0x3a"" startLine=""33"" startColumn=""5"" endLine=""33"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
#endregion
#region Constructor
[WorkItem(538317, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538317")]
[Fact]
public void ConstructorSequencePoints1()
{
var source = WithWindowsLineBreaks(
@"namespace NS
{
public class MyClass
{
int intTest;
public MyClass()
{
intTest = 123;
}
public MyClass(params int[] values)
{
intTest = values[0] + values[1] + values[2];
}
public static int Main()
{
int intI = 1, intJ = 8;
int intK = 3;
// Can't step into Ctor
MyClass mc = new MyClass();
// Can't step into Ctor
mc = new MyClass(intI, intJ, intK);
return mc.intTest - 12;
}
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
// Dev10 vs. Roslyn
//
// Default Ctor (no param)
// Dev10 Roslyn
// ======================================================================================
// Code size 18 (0x12) // Code size 16 (0x10)
// .maxstack 8 .maxstack 8
//* IL_0000: ldarg.0 *IL_0000: ldarg.0
// IL_0001: call IL_0001: callvirt
// instance void [mscorlib]System.Object::.ctor() instance void [mscorlib]System.Object::.ctor()
// IL_0006: nop *IL_0006: nop
//* IL_0007: nop
//* IL_0008: ldarg.0 *IL_0007: ldarg.0
// IL_0009: ldc.i4.s 123 IL_0008: ldc.i4.s 123
// IL_000b: stfld int32 NS.MyClass::intTest IL_000a: stfld int32 NS.MyClass::intTest
// IL_0010: nop
//* IL_0011: ret *IL_000f: ret
// -----------------------------------------------------------------------------------------
// SeqPoint: 0, 7 ,8, 0x10 0, 6, 7, 0xf
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""NS.MyClass"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""25"" document=""1"" />
<entry offset=""0x7"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" />
<entry offset=""0x8"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""27"" document=""1"" />
<entry offset=""0x10"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""NS.MyClass"" name="".ctor"" parameterNames=""values"">
<customDebugInfo>
<forward declaringType=""NS.MyClass"" methodName="".ctor"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""44"" document=""1"" />
<entry offset=""0x7"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" />
<entry offset=""0x8"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""57"" document=""1"" />
<entry offset=""0x19"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""NS.MyClass"" name=""Main"">
<customDebugInfo>
<forward declaringType=""NS.MyClass"" methodName="".ctor"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""19"" />
<slot kind=""0"" offset=""29"" />
<slot kind=""0"" offset=""56"" />
<slot kind=""0"" offset=""126"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" />
<entry offset=""0x1"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""25"" document=""1"" />
<entry offset=""0x3"" startLine=""18"" startColumn=""27"" endLine=""18"" endColumn=""35"" document=""1"" />
<entry offset=""0x5"" startLine=""19"" startColumn=""13"" endLine=""19"" endColumn=""26"" document=""1"" />
<entry offset=""0x7"" startLine=""22"" startColumn=""13"" endLine=""22"" endColumn=""40"" document=""1"" />
<entry offset=""0xd"" startLine=""25"" startColumn=""13"" endLine=""25"" endColumn=""48"" document=""1"" />
<entry offset=""0x25"" startLine=""27"" startColumn=""13"" endLine=""27"" endColumn=""36"" document=""1"" />
<entry offset=""0x32"" startLine=""28"" startColumn=""9"" endLine=""28"" endColumn=""10"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x35"">
<local name=""intI"" il_index=""0"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" />
<local name=""intJ"" il_index=""1"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" />
<local name=""intK"" il_index=""2"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" />
<local name=""mc"" il_index=""3"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void ConstructorSequencePoints2()
{
TestSequencePoints(
@"using System;
class D
{
public D() : [|base()|]
{
}
}", TestOptions.DebugDll);
TestSequencePoints(
@"using System;
class D
{
static D()
[|{|]
}
}", TestOptions.DebugDll);
TestSequencePoints(
@"using System;
class A : Attribute {}
class D
{
[A]
public D() : [|base()|]
{
}
}", TestOptions.DebugDll);
TestSequencePoints(
@"using System;
class A : Attribute {}
class D
{
[A]
public D()
: [|base()|]
{
}
}", TestOptions.DebugDll);
TestSequencePoints(
@"using System;
class A : Attribute {}
class C { }
class D
{
[A]
[|public D()|]
{
}
}", TestOptions.DebugDll);
}
#endregion
#region Destructor
[Fact]
public void Destructors()
{
var source = @"
using System;
public class Base
{
~Base()
{
Console.WriteLine();
}
}
public class Derived : Base
{
~Derived()
{
Console.WriteLine();
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Base"" name=""Finalize"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x2"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""29"" document=""1"" />
<entry offset=""0xa"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x12"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x13"">
<namespace name=""System"" />
</scope>
</method>
<method containingType=""Derived"" name=""Finalize"">
<customDebugInfo>
<forward declaringType=""Base"" methodName=""Finalize"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
<entry offset=""0x2"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""29"" document=""1"" />
<entry offset=""0xa"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" />
<entry offset=""0x12"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
#endregion
#region Field and Property Initializers
[Fact]
[WorkItem(50611, "https://github.com/dotnet/roslyn/issues/50611")]
public void TestPartialClassFieldInitializers()
{
var text1 = WithWindowsLineBreaks(@"
public partial class C
{
int x = 1;
}
");
var text2 = WithWindowsLineBreaks(@"
public partial class C
{
int y = 1;
static void Main()
{
C c = new C();
}
}
");
// Having a unique name here may be important. The infrastructure of the pdb to xml conversion
// loads the assembly into the ReflectionOnlyLoadFrom context.
// So it's probably a good idea to have a new name for each assembly.
var compilation = CreateCompilation(new SyntaxTree[] { Parse(text1, "a.cs"), Parse(text2, "b.cs") });
compilation.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name=""b.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""BB-7A-A6-D2-B2-32-59-43-8C-98-7F-E1-98-8D-F0-94-68-E9-EB-80"" />
<file id=""2"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""B4-EA-18-73-D2-0E-7F-15-51-4C-68-86-40-DF-E3-C3-97-9D-F6-B7"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Main"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""15"" document=""2"" />
<entry offset=""0x7"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""15"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>", format: DebugInformationFormat.Pdb);
compilation.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""B4-EA-18-73-D2-0E-7F-15-51-4C-68-86-40-DF-E3-C3-97-9D-F6-B7"" />
<file id=""2"" name=""b.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""BB-7A-A6-D2-B2-32-59-43-8C-98-7F-E1-98-8D-F0-94-68-E9-EB-80"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""15"" document=""1"" />
<entry offset=""0x7"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""15"" document=""2"" />
</sequencePoints>
</method>
</methods>
</symbols>", format: DebugInformationFormat.PortablePdb);
}
[Fact]
[WorkItem(50611, "https://github.com/dotnet/roslyn/issues/50611")]
public void TestPartialClassFieldInitializersWithLineDirectives()
{
var text1 = WithWindowsLineBreaks(@"
using System;
public partial class C
{
int x = 1;
#line 12 ""foo.cs""
int z = Math.Abs(-3);
int w = Math.Abs(4);
#line 17 ""bar.cs""
double zed = Math.Sin(5);
}
#pragma checksum ""mah.cs"" ""{406EA660-64CF-4C82-B6F0-42D48172A799}"" ""ab007f1d23d9""
");
var text2 = WithWindowsLineBreaks(@"
using System;
public partial class C
{
int y = 1;
int x2 = 1;
#line 12 ""foo2.cs""
int z2 = Math.Abs(-3);
int w2 = Math.Abs(4);
}
");
var text3 = WithWindowsLineBreaks(@"
using System;
public partial class C
{
#line 112 ""mah.cs""
int y3 = 1;
int x3 = 1;
int z3 = Math.Abs(-3);
#line default
int w3 = Math.Abs(4);
double zed3 = Math.Sin(5);
C() {
Console.WriteLine(""hi"");
}
static void Main()
{
C c = new C();
}
}
");
//Having a unique name here may be important. The infrastructure of the pdb to xml conversion
//loads the assembly into the ReflectionOnlyLoadFrom context.
//So it's probably a good idea to have a new name for each assembly.
var compilation = CreateCompilation(new[] { Parse(text1, "a.cs"), Parse(text2, "b.cs"), Parse(text3, "a.cs") }, options: TestOptions.DebugDll);
compilation.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""E2-3B-47-02-DC-E4-8D-B4-FF-00-67-90-31-68-74-C0-06-D7-39-0E"" />
<file id=""2"" name=""b.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""DB-CE-E5-E9-CB-53-E5-EF-C1-7F-2C-53-EC-02-FE-5C-34-2C-EF-94"" />
<file id=""3"" name=""foo.cs"" language=""C#"" />
<file id=""4"" name=""bar.cs"" language=""C#"" />
<file id=""5"" name=""foo2.cs"" language=""C#"" />
<file id=""6"" name=""mah.cs"" language=""C#"" checksumAlgorithm=""406ea660-64cf-4c82-b6f0-42d48172a799"" checksum=""AB-00-7F-1D-23-D9"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""15"" document=""1"" />
<entry offset=""0x7"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""26"" document=""3"" />
<entry offset=""0x14"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""25"" document=""3"" />
<entry offset=""0x20"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""30"" document=""4"" />
<entry offset=""0x34"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""15"" document=""2"" />
<entry offset=""0x3b"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""16"" document=""2"" />
<entry offset=""0x42"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""27"" document=""5"" />
<entry offset=""0x4f"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""26"" document=""5"" />
<entry offset=""0x5b"" startLine=""112"" startColumn=""5"" endLine=""112"" endColumn=""16"" document=""6"" />
<entry offset=""0x62"" startLine=""113"" startColumn=""5"" endLine=""113"" endColumn=""16"" document=""6"" />
<entry offset=""0x69"" startLine=""114"" startColumn=""5"" endLine=""114"" endColumn=""27"" document=""6"" />
<entry offset=""0x76"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""26"" document=""1"" />
<entry offset=""0x82"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""31"" document=""1"" />
<entry offset=""0x96"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""8"" document=""1"" />
<entry offset=""0x9d"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x9e"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""33"" document=""1"" />
<entry offset=""0xa9"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>", format: DebugInformationFormat.PortablePdb);
}
[WorkItem(543313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543313")]
[Fact]
public void TestFieldInitializerExpressionLambda()
{
var source = @"
class C
{
int x = ((System.Func<int, int>)(z => z))(1);
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLambdaMap>
<methodOrdinal>1</methodOrdinal>
<lambda offset=""-6"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""50"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C+<>c"" name=""<.ctor>b__1_0"" parameterNames=""z"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""43"" endLine=""4"" endColumn=""44"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void FieldInitializerSequencePointSpans()
{
var source = @"
class C
{
int x = 1, y = 2;
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""14"" document=""1"" />
<entry offset=""0x7"" startLine=""4"" startColumn=""16"" endLine=""4"" endColumn=""21"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
#endregion
#region Auto-Property
[WorkItem(820806, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/820806")]
[Fact]
public void BreakpointForAutoImplementedProperty()
{
var source = @"
public class C
{
public static int AutoProp1 { get; private set; }
internal string AutoProp2 { get; set; }
internal protected C AutoProp3 { internal get; set; }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugDll);
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""get_AutoProp1"">
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""35"" endLine=""4"" endColumn=""39"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""set_AutoProp1"" parameterNames=""value"">
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""40"" endLine=""4"" endColumn=""52"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""get_AutoProp2"">
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""33"" endLine=""5"" endColumn=""37"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""set_AutoProp2"" parameterNames=""value"">
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""38"" endLine=""5"" endColumn=""42"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""get_AutoProp3"">
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""38"" endLine=""6"" endColumn=""51"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""set_AutoProp3"" parameterNames=""value"">
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""52"" endLine=""6"" endColumn=""56"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void PropertyDeclaration()
{
TestSequencePoints(
@"using System;
public class C
{
int P { [|get;|] set; }
}", TestOptions.DebugDll);
TestSequencePoints(
@"using System;
public class C
{
int P { get; [|set;|] }
}", TestOptions.DebugDll);
TestSequencePoints(
@"using System;
public class C
{
int P { get [|{|] return 0; } }
}", TestOptions.DebugDll);
TestSequencePoints(
@"using System;
public class C
{
int P { get; } = [|int.Parse(""42"")|];
}", TestOptions.DebugDll, TestOptions.Regular);
}
#endregion
#region ReturnStatement
[Fact]
public void Return_Implicit()
{
var source = @"class C
{
static void Main()
{
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void Return_Explicit()
{
var source = @"class C
{
static void Main()
{
return;
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""16"" document=""1"" />
<entry offset=""0x3"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(538298, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538298")]
[Fact]
public void RegressSeqPtEndOfMethodAfterReturn()
{
var source = WithWindowsLineBreaks(
@"using System;
public class SeqPointAfterReturn
{
public static int Main()
{
int ret = 0;
ReturnVoid(100);
if (field != ""Even"")
ret = 1;
ReturnVoid(99);
if (field != ""Odd"")
ret = ret + 1;
string rets = ReturnValue(101);
if (rets != ""Odd"")
ret = ret + 1;
rets = ReturnValue(102);
if (rets != ""Even"")
ret = ret + 1;
return ret;
}
static string field;
public static void ReturnVoid(int p)
{
int x = (int)(p % 2);
if (x == 0)
{
field = ""Even"";
}
else
{
field = ""Odd"";
}
}
public static string ReturnValue(int p)
{
int x = (int)(p % 2);
if (x == 0)
{
return ""Even"";
}
else
{
return ""Odd"";
}
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
// Expected are current actual output plus Two extra expected SeqPt:
// <entry offset=""0x73"" startLine=""25"" startColumn=""5"" endLine=""25"" endColumn=""6"" document=""1"" />
// <entry offset=""0x22"" startLine=""52"" startColumn=""5"" endLine=""52"" endColumn=""6"" document=""1"" />
//
// Note: NOT include other differences between Roslyn and Dev10, as they are filed in separated bugs
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""SeqPointAfterReturn"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""0"" offset=""204"" />
<slot kind=""1"" offset=""59"" />
<slot kind=""1"" offset=""138"" />
<slot kind=""1"" offset=""238"" />
<slot kind=""1"" offset=""330"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""21"" document=""1"" />
<entry offset=""0x3"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""25"" document=""1"" />
<entry offset=""0xb"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""29"" document=""1"" />
<entry offset=""0x1b"" hidden=""true"" document=""1"" />
<entry offset=""0x1e"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""21"" document=""1"" />
<entry offset=""0x20"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""24"" document=""1"" />
<entry offset=""0x28"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""28"" document=""1"" />
<entry offset=""0x38"" hidden=""true"" document=""1"" />
<entry offset=""0x3b"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""27"" document=""1"" />
<entry offset=""0x3f"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""40"" document=""1"" />
<entry offset=""0x47"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""27"" document=""1"" />
<entry offset=""0x54"" hidden=""true"" document=""1"" />
<entry offset=""0x58"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""27"" document=""1"" />
<entry offset=""0x5c"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""33"" document=""1"" />
<entry offset=""0x64"" startLine=""21"" startColumn=""9"" endLine=""21"" endColumn=""28"" document=""1"" />
<entry offset=""0x71"" hidden=""true"" document=""1"" />
<entry offset=""0x75"" startLine=""22"" startColumn=""13"" endLine=""22"" endColumn=""27"" document=""1"" />
<entry offset=""0x79"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""20"" document=""1"" />
<entry offset=""0x7e"" startLine=""25"" startColumn=""5"" endLine=""25"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x81"">
<namespace name=""System"" />
<local name=""ret"" il_index=""0"" il_start=""0x0"" il_end=""0x81"" attributes=""0"" />
<local name=""rets"" il_index=""1"" il_start=""0x0"" il_end=""0x81"" attributes=""0"" />
</scope>
</method>
<method containingType=""SeqPointAfterReturn"" name=""ReturnVoid"" parameterNames=""p"">
<customDebugInfo>
<forward declaringType=""SeqPointAfterReturn"" methodName=""Main"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""1"" offset=""42"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""29"" startColumn=""5"" endLine=""29"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""30"" startColumn=""9"" endLine=""30"" endColumn=""30"" document=""1"" />
<entry offset=""0x5"" startLine=""31"" startColumn=""9"" endLine=""31"" endColumn=""20"" document=""1"" />
<entry offset=""0xa"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""32"" startColumn=""9"" endLine=""32"" endColumn=""10"" document=""1"" />
<entry offset=""0xe"" startLine=""33"" startColumn=""13"" endLine=""33"" endColumn=""28"" document=""1"" />
<entry offset=""0x18"" startLine=""34"" startColumn=""9"" endLine=""34"" endColumn=""10"" document=""1"" />
<entry offset=""0x19"" hidden=""true"" document=""1"" />
<entry offset=""0x1b"" startLine=""36"" startColumn=""9"" endLine=""36"" endColumn=""10"" document=""1"" />
<entry offset=""0x1c"" startLine=""37"" startColumn=""13"" endLine=""37"" endColumn=""27"" document=""1"" />
<entry offset=""0x26"" startLine=""38"" startColumn=""9"" endLine=""38"" endColumn=""10"" document=""1"" />
<entry offset=""0x27"" startLine=""39"" startColumn=""5"" endLine=""39"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x28"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x28"" attributes=""0"" />
</scope>
</method>
<method containingType=""SeqPointAfterReturn"" name=""ReturnValue"" parameterNames=""p"">
<customDebugInfo>
<forward declaringType=""SeqPointAfterReturn"" methodName=""Main"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""1"" offset=""42"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""42"" startColumn=""5"" endLine=""42"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""43"" startColumn=""9"" endLine=""43"" endColumn=""30"" document=""1"" />
<entry offset=""0x5"" startLine=""44"" startColumn=""9"" endLine=""44"" endColumn=""20"" document=""1"" />
<entry offset=""0xa"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""45"" startColumn=""9"" endLine=""45"" endColumn=""10"" document=""1"" />
<entry offset=""0xe"" startLine=""46"" startColumn=""13"" endLine=""46"" endColumn=""27"" document=""1"" />
<entry offset=""0x16"" startLine=""49"" startColumn=""9"" endLine=""49"" endColumn=""10"" document=""1"" />
<entry offset=""0x17"" startLine=""50"" startColumn=""13"" endLine=""50"" endColumn=""26"" document=""1"" />
<entry offset=""0x1f"" startLine=""52"" startColumn=""5"" endLine=""52"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x21"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region Exception Handling
[WorkItem(542064, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542064")]
[Fact]
public void ExceptionHandling()
{
var source = WithWindowsLineBreaks(@"
class Test
{
static int Main()
{
int ret = 0; // stop 1
try
{ // stop 2
throw new System.Exception(); // stop 3
}
catch (System.Exception e) // stop 4
{ // stop 5
ret = 1; // stop 6
}
try
{ // stop 7
throw new System.Exception(); // stop 8
}
catch // stop 9
{ // stop 10
return ret; // stop 11
}
}
}
");
// Dev12 inserts an additional sequence point on catch clause, just before
// the exception object is assigned to the variable. We don't place that sequence point.
// Also the scope of he exception variable is different.
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("Test.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Test"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""0"" offset=""147"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""21"" document=""1"" />
<entry offset=""0x3"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" />
<entry offset=""0x4"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""42"" document=""1"" />
<entry offset=""0xa"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""35"" document=""1"" />
<entry offset=""0xb"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" />
<entry offset=""0xc"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""21"" document=""1"" />
<entry offset=""0xe"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" />
<entry offset=""0x11"" hidden=""true"" document=""1"" />
<entry offset=""0x12"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" />
<entry offset=""0x13"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""42"" document=""1"" />
<entry offset=""0x19"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""14"" document=""1"" />
<entry offset=""0x1a"" startLine=""21"" startColumn=""9"" endLine=""21"" endColumn=""10"" document=""1"" />
<entry offset=""0x1b"" startLine=""22"" startColumn=""13"" endLine=""22"" endColumn=""24"" document=""1"" />
<entry offset=""0x1f"" startLine=""25"" startColumn=""5"" endLine=""25"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x21"">
<local name=""ret"" il_index=""0"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" />
<scope startOffset=""0xa"" endOffset=""0x11"">
<local name=""e"" il_index=""1"" il_start=""0xa"" il_end=""0x11"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(2911, "https://github.com/dotnet/roslyn/issues/2911")]
[Fact]
public void ExceptionHandling_Filter_Debug1()
{
var source = WithWindowsLineBreaks(@"
using System;
using System.IO;
class Test
{
static string filter(Exception e)
{
return null;
}
static void Main()
{
try
{
throw new InvalidOperationException();
}
catch (IOException e) when (filter(e) != null)
{
Console.WriteLine();
}
catch (Exception e) when (filter(e) != null)
{
Console.WriteLine();
}
}
}
");
var v = CompileAndVerify(CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll));
v.VerifyIL("Test.Main", @"
{
// Code size 89 (0x59)
.maxstack 2
.locals init (System.IO.IOException V_0, //e
bool V_1,
System.Exception V_2, //e
bool V_3)
-IL_0000: nop
.try
{
-IL_0001: nop
-IL_0002: newobj ""System.InvalidOperationException..ctor()""
IL_0007: throw
}
filter
{
~IL_0008: isinst ""System.IO.IOException""
IL_000d: dup
IL_000e: brtrue.s IL_0014
IL_0010: pop
IL_0011: ldc.i4.0
IL_0012: br.s IL_0023
IL_0014: stloc.0
-IL_0015: ldloc.0
IL_0016: call ""string Test.filter(System.Exception)""
IL_001b: ldnull
IL_001c: cgt.un
IL_001e: stloc.1
~IL_001f: ldloc.1
IL_0020: ldc.i4.0
IL_0021: cgt.un
IL_0023: endfilter
} // end filter
{ // handler
~IL_0025: pop
-IL_0026: nop
-IL_0027: call ""void System.Console.WriteLine()""
IL_002c: nop
-IL_002d: nop
IL_002e: leave.s IL_0058
}
filter
{
~IL_0030: isinst ""System.Exception""
IL_0035: dup
IL_0036: brtrue.s IL_003c
IL_0038: pop
IL_0039: ldc.i4.0
IL_003a: br.s IL_004b
IL_003c: stloc.2
-IL_003d: ldloc.2
IL_003e: call ""string Test.filter(System.Exception)""
IL_0043: ldnull
IL_0044: cgt.un
IL_0046: stloc.3
~IL_0047: ldloc.3
IL_0048: ldc.i4.0
IL_0049: cgt.un
IL_004b: endfilter
} // end filter
{ // handler
~IL_004d: pop
-IL_004e: nop
-IL_004f: call ""void System.Console.WriteLine()""
IL_0054: nop
-IL_0055: nop
IL_0056: leave.s IL_0058
}
-IL_0058: ret
}
", sequencePoints: "Test.Main");
v.VerifyPdb("Test.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Test"" name=""Main"">
<customDebugInfo>
<forward declaringType=""Test"" methodName=""filter"" parameterNames=""e"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""104"" />
<slot kind=""1"" offset=""120"" />
<slot kind=""0"" offset=""216"" />
<slot kind=""1"" offset=""230"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" />
<entry offset=""0x2"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""51"" document=""1"" />
<entry offset=""0x8"" hidden=""true"" document=""1"" />
<entry offset=""0x15"" startLine=""18"" startColumn=""31"" endLine=""18"" endColumn=""55"" document=""1"" />
<entry offset=""0x1f"" hidden=""true"" document=""1"" />
<entry offset=""0x25"" hidden=""true"" document=""1"" />
<entry offset=""0x26"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""1"" />
<entry offset=""0x27"" startLine=""20"" startColumn=""13"" endLine=""20"" endColumn=""33"" document=""1"" />
<entry offset=""0x2d"" startLine=""21"" startColumn=""9"" endLine=""21"" endColumn=""10"" document=""1"" />
<entry offset=""0x30"" hidden=""true"" document=""1"" />
<entry offset=""0x3d"" startLine=""22"" startColumn=""29"" endLine=""22"" endColumn=""53"" document=""1"" />
<entry offset=""0x47"" hidden=""true"" document=""1"" />
<entry offset=""0x4d"" hidden=""true"" document=""1"" />
<entry offset=""0x4e"" startLine=""23"" startColumn=""9"" endLine=""23"" endColumn=""10"" document=""1"" />
<entry offset=""0x4f"" startLine=""24"" startColumn=""13"" endLine=""24"" endColumn=""33"" document=""1"" />
<entry offset=""0x55"" startLine=""25"" startColumn=""9"" endLine=""25"" endColumn=""10"" document=""1"" />
<entry offset=""0x58"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x59"">
<scope startOffset=""0x8"" endOffset=""0x30"">
<local name=""e"" il_index=""0"" il_start=""0x8"" il_end=""0x30"" attributes=""0"" />
</scope>
<scope startOffset=""0x30"" endOffset=""0x58"">
<local name=""e"" il_index=""2"" il_start=""0x30"" il_end=""0x58"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(2911, "https://github.com/dotnet/roslyn/issues/2911")]
[Fact]
public void ExceptionHandling_Filter_Debug2()
{
var source = WithWindowsLineBreaks(@"
class Test
{
static void Main()
{
try
{
throw new System.Exception();
}
catch when (F())
{
System.Console.WriteLine();
}
}
private static bool F()
{
return true;
}
}
");
var v = CompileAndVerify(CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll));
v.VerifyIL("Test.Main", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (bool V_0)
-IL_0000: nop
.try
{
-IL_0001: nop
-IL_0002: newobj ""System.Exception..ctor()""
IL_0007: throw
}
filter
{
~IL_0008: pop
-IL_0009: call ""bool Test.F()""
IL_000e: stloc.0
~IL_000f: ldloc.0
IL_0010: ldc.i4.0
IL_0011: cgt.un
IL_0013: endfilter
} // end filter
{ // handler
~IL_0015: pop
-IL_0016: nop
-IL_0017: call ""void System.Console.WriteLine()""
IL_001c: nop
-IL_001d: nop
IL_001e: leave.s IL_0020
}
-IL_0020: ret
}
", sequencePoints: "Test.Main");
v.VerifyPdb("Test.Main", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Test"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""1"" offset=""95"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" />
<entry offset=""0x2"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""42"" document=""1"" />
<entry offset=""0x8"" hidden=""true"" document=""1"" />
<entry offset=""0x9"" startLine=""10"" startColumn=""15"" endLine=""10"" endColumn=""25"" document=""1"" />
<entry offset=""0xf"" hidden=""true"" document=""1"" />
<entry offset=""0x15"" hidden=""true"" document=""1"" />
<entry offset=""0x16"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0x17"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""40"" document=""1"" />
<entry offset=""0x1d"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x20"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(2911, "https://github.com/dotnet/roslyn/issues/2911")]
[Fact]
public void ExceptionHandling_Filter_Debug3()
{
var source = WithWindowsLineBreaks(@"
class Test
{
static bool a = true;
static void Main()
{
try
{
throw new System.Exception();
}
catch when (a)
{
System.Console.WriteLine();
}
}
}
");
var v = CompileAndVerify(CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll));
v.VerifyIL("Test.Main", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (bool V_0)
-IL_0000: nop
.try
{
-IL_0001: nop
-IL_0002: newobj ""System.Exception..ctor()""
IL_0007: throw
}
filter
{
~IL_0008: pop
-IL_0009: ldsfld ""bool Test.a""
IL_000e: stloc.0
~IL_000f: ldloc.0
IL_0010: ldc.i4.0
IL_0011: cgt.un
IL_0013: endfilter
} // end filter
{ // handler
~IL_0015: pop
-IL_0016: nop
-IL_0017: call ""void System.Console.WriteLine()""
IL_001c: nop
-IL_001d: nop
IL_001e: leave.s IL_0020
}
-IL_0020: ret
}
", sequencePoints: "Test.Main");
v.VerifyPdb("Test.Main", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Test"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""1"" offset=""95"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x2"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""42"" document=""1"" />
<entry offset=""0x8"" hidden=""true"" document=""1"" />
<entry offset=""0x9"" startLine=""12"" startColumn=""15"" endLine=""12"" endColumn=""23"" document=""1"" />
<entry offset=""0xf"" hidden=""true"" document=""1"" />
<entry offset=""0x15"" hidden=""true"" document=""1"" />
<entry offset=""0x16"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x17"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""40"" document=""1"" />
<entry offset=""0x1d"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" />
<entry offset=""0x20"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(2911, "https://github.com/dotnet/roslyn/issues/2911")]
[Fact]
public void ExceptionHandling_Filter_Release3()
{
var source = @"
class Test
{
static bool a = true;
static void Main()
{
try
{
throw new System.Exception();
}
catch when (a)
{
System.Console.WriteLine();
}
}
}
";
var v = CompileAndVerify(CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseDll));
v.VerifyIL("Test.Main", @"
{
// Code size 26 (0x1a)
.maxstack 2
.try
{
-IL_0000: newobj ""System.Exception..ctor()""
IL_0005: throw
}
filter
{
~IL_0006: pop
-IL_0007: ldsfld ""bool Test.a""
IL_000c: ldc.i4.0
IL_000d: cgt.un
IL_000f: endfilter
} // end filter
{ // handler
~IL_0011: pop
-IL_0012: call ""void System.Console.WriteLine()""
-IL_0017: leave.s IL_0019
}
-IL_0019: ret
}
", sequencePoints: "Test.Main");
v.VerifyPdb("Test.Main", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Test"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""42"" document=""1"" />
<entry offset=""0x6"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" startLine=""12"" startColumn=""15"" endLine=""12"" endColumn=""23"" document=""1"" />
<entry offset=""0x11"" hidden=""true"" document=""1"" />
<entry offset=""0x12"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""40"" document=""1"" />
<entry offset=""0x17"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" />
<entry offset=""0x19"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(778655, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/778655")]
[Fact]
public void BranchToStartOfTry()
{
string source = WithWindowsLineBreaks(@"
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
string str = null;
bool isEmpty = string.IsNullOrEmpty(str);
// isEmpty is always true here, so it should never go thru this if statement.
if (!isEmpty)
{
throw new Exception();
}
try
{
Console.WriteLine();
}
catch
{
}
}
}
");
// Note the hidden sequence point @IL_0019.
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""18"" />
<slot kind=""0"" offset=""44"" />
<slot kind=""1"" offset=""177"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""27"" document=""1"" />
<entry offset=""0x3"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""50"" document=""1"" />
<entry offset=""0xa"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""22"" document=""1"" />
<entry offset=""0xf"" hidden=""true"" document=""1"" />
<entry offset=""0x12"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x13"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""35"" document=""1"" />
<entry offset=""0x19"" hidden=""true"" document=""1"" />
<entry offset=""0x1a"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" />
<entry offset=""0x1b"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""33"" document=""1"" />
<entry offset=""0x21"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""1"" />
<entry offset=""0x24"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""14"" document=""1"" />
<entry offset=""0x25"" startLine=""21"" startColumn=""9"" endLine=""21"" endColumn=""10"" document=""1"" />
<entry offset=""0x26"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" />
<entry offset=""0x29"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2a"">
<namespace name=""System"" />
<namespace name=""System.Collections.Generic"" />
<local name=""str"" il_index=""0"" il_start=""0x0"" il_end=""0x2a"" attributes=""0"" />
<local name=""isEmpty"" il_index=""1"" il_start=""0x0"" il_end=""0x2a"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region UsingStatement
[Fact]
public void UsingStatement_EmbeddedStatement()
{
var source = WithWindowsLineBreaks(@"
public class DisposableClass : System.IDisposable
{
public DisposableClass(int a) { }
public void Dispose() { }
}
class C
{
static void Main()
{
using (DisposableClass a = new DisposableClass(1), b = new DisposableClass(2))
System.Console.WriteLine(""First"");
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.Main", sequencePoints: "C.Main", source: source, expectedIL: @"
{
// Code size 53 (0x35)
.maxstack 1
.locals init (DisposableClass V_0, //a
DisposableClass V_1) //b
// sequence point: {
IL_0000: nop
// sequence point: DisposableClass a = new DisposableClass(1)
IL_0001: ldc.i4.1
IL_0002: newobj ""DisposableClass..ctor(int)""
IL_0007: stloc.0
.try
{
// sequence point: b = new DisposableClass(2)
IL_0008: ldc.i4.2
IL_0009: newobj ""DisposableClass..ctor(int)""
IL_000e: stloc.1
.try
{
// sequence point: System.Console.WriteLine(""First"");
IL_000f: ldstr ""First""
IL_0014: call ""void System.Console.WriteLine(string)""
IL_0019: nop
IL_001a: leave.s IL_0027
}
finally
{
// sequence point: <hidden>
IL_001c: ldloc.1
IL_001d: brfalse.s IL_0026
IL_001f: ldloc.1
IL_0020: callvirt ""void System.IDisposable.Dispose()""
IL_0025: nop
// sequence point: <hidden>
IL_0026: endfinally
}
// sequence point: <hidden>
IL_0027: leave.s IL_0034
}
finally
{
// sequence point: <hidden>
IL_0029: ldloc.0
IL_002a: brfalse.s IL_0033
IL_002c: ldloc.0
IL_002d: callvirt ""void System.IDisposable.Dispose()""
IL_0032: nop
// sequence point: <hidden>
IL_0033: endfinally
}
// sequence point: }
IL_0034: ret
}
");
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<forward declaringType=""DisposableClass"" methodName="".ctor"" parameterNames=""a"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""34"" />
<slot kind=""0"" offset=""62"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""58"" document=""1"" />
<entry offset=""0x8"" startLine=""12"" startColumn=""60"" endLine=""12"" endColumn=""86"" document=""1"" />
<entry offset=""0xf"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""47"" document=""1"" />
<entry offset=""0x1c"" hidden=""true"" document=""1"" />
<entry offset=""0x26"" hidden=""true"" document=""1"" />
<entry offset=""0x27"" hidden=""true"" document=""1"" />
<entry offset=""0x29"" hidden=""true"" document=""1"" />
<entry offset=""0x33"" hidden=""true"" document=""1"" />
<entry offset=""0x34"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x35"">
<scope startOffset=""0x1"" endOffset=""0x34"">
<local name=""a"" il_index=""0"" il_start=""0x1"" il_end=""0x34"" attributes=""0"" />
<local name=""b"" il_index=""1"" il_start=""0x1"" il_end=""0x34"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void UsingStatement_Block()
{
var source = WithWindowsLineBreaks(@"
public class DisposableClass : System.IDisposable
{
public DisposableClass(int a) { }
public void Dispose() { }
}
class C
{
static void Main()
{
using (DisposableClass c = new DisposableClass(3), d = new DisposableClass(4))
{
System.Console.WriteLine(""Second"");
}
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.Main", sequencePoints: "C.Main", source: source, expectedIL: @"
{
// Code size 55 (0x37)
.maxstack 1
.locals init (DisposableClass V_0, //c
DisposableClass V_1) //d
// sequence point: {
IL_0000: nop
// sequence point: DisposableClass c = new DisposableClass(3)
IL_0001: ldc.i4.3
IL_0002: newobj ""DisposableClass..ctor(int)""
IL_0007: stloc.0
.try
{
// sequence point: d = new DisposableClass(4)
IL_0008: ldc.i4.4
IL_0009: newobj ""DisposableClass..ctor(int)""
IL_000e: stloc.1
.try
{
// sequence point: {
IL_000f: nop
// sequence point: System.Console.WriteLine(""Second"");
IL_0010: ldstr ""Second""
IL_0015: call ""void System.Console.WriteLine(string)""
IL_001a: nop
// sequence point: }
IL_001b: nop
IL_001c: leave.s IL_0029
}
finally
{
// sequence point: <hidden>
IL_001e: ldloc.1
IL_001f: brfalse.s IL_0028
IL_0021: ldloc.1
IL_0022: callvirt ""void System.IDisposable.Dispose()""
IL_0027: nop
// sequence point: <hidden>
IL_0028: endfinally
}
// sequence point: <hidden>
IL_0029: leave.s IL_0036
}
finally
{
// sequence point: <hidden>
IL_002b: ldloc.0
IL_002c: brfalse.s IL_0035
IL_002e: ldloc.0
IL_002f: callvirt ""void System.IDisposable.Dispose()""
IL_0034: nop
// sequence point: <hidden>
IL_0035: endfinally
}
// sequence point: }
IL_0036: ret
}
"
);
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<forward declaringType=""DisposableClass"" methodName="".ctor"" parameterNames=""a"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""34"" />
<slot kind=""0"" offset=""62"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""58"" document=""1"" />
<entry offset=""0x8"" startLine=""12"" startColumn=""60"" endLine=""12"" endColumn=""86"" document=""1"" />
<entry offset=""0xf"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x10"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""48"" document=""1"" />
<entry offset=""0x1b"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" />
<entry offset=""0x1e"" hidden=""true"" document=""1"" />
<entry offset=""0x28"" hidden=""true"" document=""1"" />
<entry offset=""0x29"" hidden=""true"" document=""1"" />
<entry offset=""0x2b"" hidden=""true"" document=""1"" />
<entry offset=""0x35"" hidden=""true"" document=""1"" />
<entry offset=""0x36"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x37"">
<scope startOffset=""0x1"" endOffset=""0x36"">
<local name=""c"" il_index=""0"" il_start=""0x1"" il_end=""0x36"" attributes=""0"" />
<local name=""d"" il_index=""1"" il_start=""0x1"" il_end=""0x36"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(18844, "https://github.com/dotnet/roslyn/issues/18844")]
[Fact]
public void UsingStatement_EmbeddedConditional()
{
var source = @"
class C
{
bool F()
{
bool x = true;
bool value = false;
using (var stream = new System.IO.MemoryStream())
if (x)
{
value = true;
}
else
value = false;
return value;
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.F", @"
{
// Code size 45 (0x2d)
.maxstack 1
.locals init (bool V_0, //x
bool V_1, //value
System.IO.MemoryStream V_2, //stream
bool V_3,
bool V_4)
// sequence point: {
IL_0000: nop
// sequence point: bool x = true;
IL_0001: ldc.i4.1
IL_0002: stloc.0
// sequence point: bool value = false;
IL_0003: ldc.i4.0
IL_0004: stloc.1
// sequence point: var stream = new System.IO.MemoryStream()
IL_0005: newobj ""System.IO.MemoryStream..ctor()""
IL_000a: stloc.2
.try
{
// sequence point: if (x)
IL_000b: ldloc.0
IL_000c: stloc.3
// sequence point: <hidden>
IL_000d: ldloc.3
IL_000e: brfalse.s IL_0016
// sequence point: {
IL_0010: nop
// sequence point: value = true;
IL_0011: ldc.i4.1
IL_0012: stloc.1
// sequence point: }
IL_0013: nop
// sequence point: <hidden>
IL_0014: br.s IL_0018
// sequence point: value = false;
IL_0016: ldc.i4.0
IL_0017: stloc.1
// sequence point: <hidden>
IL_0018: leave.s IL_0025
}
finally
{
// sequence point: <hidden>
IL_001a: ldloc.2
IL_001b: brfalse.s IL_0024
IL_001d: ldloc.2
IL_001e: callvirt ""void System.IDisposable.Dispose()""
IL_0023: nop
// sequence point: <hidden>
IL_0024: endfinally
}
// sequence point: return value;
IL_0025: ldloc.1
IL_0026: stloc.s V_4
IL_0028: br.s IL_002a
// sequence point: }
IL_002a: ldloc.s V_4
IL_002c: ret
}
", sequencePoints: "C.F", source: source);
}
[WorkItem(18844, "https://github.com/dotnet/roslyn/issues/18844")]
[Fact]
public void UsingStatement_EmbeddedConditional2()
{
var source = @"
class C
{
bool F()
{
bool x = true;
bool value = false;
using (var stream = new System.IO.MemoryStream())
if (x)
{
value = true;
}
else
{
value = false;
}
return value;
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.F", @"
{
// Code size 47 (0x2f)
.maxstack 1
.locals init (bool V_0, //x
bool V_1, //value
System.IO.MemoryStream V_2, //stream
bool V_3,
bool V_4)
// sequence point: {
IL_0000: nop
// sequence point: bool x = true;
IL_0001: ldc.i4.1
IL_0002: stloc.0
// sequence point: bool value = false;
IL_0003: ldc.i4.0
IL_0004: stloc.1
// sequence point: var stream = new System.IO.MemoryStream()
IL_0005: newobj ""System.IO.MemoryStream..ctor()""
IL_000a: stloc.2
.try
{
// sequence point: if (x)
IL_000b: ldloc.0
IL_000c: stloc.3
// sequence point: <hidden>
IL_000d: ldloc.3
IL_000e: brfalse.s IL_0016
// sequence point: {
IL_0010: nop
// sequence point: value = true;
IL_0011: ldc.i4.1
IL_0012: stloc.1
// sequence point: }
IL_0013: nop
// sequence point: <hidden>
IL_0014: br.s IL_001a
// sequence point: {
IL_0016: nop
// sequence point: value = false;
IL_0017: ldc.i4.0
IL_0018: stloc.1
// sequence point: }
IL_0019: nop
// sequence point: <hidden>
IL_001a: leave.s IL_0027
}
finally
{
// sequence point: <hidden>
IL_001c: ldloc.2
IL_001d: brfalse.s IL_0026
IL_001f: ldloc.2
IL_0020: callvirt ""void System.IDisposable.Dispose()""
IL_0025: nop
// sequence point: <hidden>
IL_0026: endfinally
}
// sequence point: return value;
IL_0027: ldloc.1
IL_0028: stloc.s V_4
IL_002a: br.s IL_002c
// sequence point: }
IL_002c: ldloc.s V_4
IL_002e: ret
}
", sequencePoints: "C.F", source: source);
}
[WorkItem(18844, "https://github.com/dotnet/roslyn/issues/18844")]
[Fact]
public void UsingStatement_EmbeddedWhile()
{
var source = @"
class C
{
void F(bool x)
{
using (var stream = new System.IO.MemoryStream())
while (x)
x = false;
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.F", @"
{
// Code size 31 (0x1f)
.maxstack 1
.locals init (System.IO.MemoryStream V_0, //stream
bool V_1)
// sequence point: {
IL_0000: nop
// sequence point: var stream = new System.IO.MemoryStream()
IL_0001: newobj ""System.IO.MemoryStream..ctor()""
IL_0006: stloc.0
.try
{
// sequence point: <hidden>
IL_0007: br.s IL_000c
// sequence point: x = false;
IL_0009: ldc.i4.0
IL_000a: starg.s V_1
// sequence point: while (x)
IL_000c: ldarg.1
IL_000d: stloc.1
// sequence point: <hidden>
IL_000e: ldloc.1
IL_000f: brtrue.s IL_0009
IL_0011: leave.s IL_001e
}
finally
{
// sequence point: <hidden>
IL_0013: ldloc.0
IL_0014: brfalse.s IL_001d
IL_0016: ldloc.0
IL_0017: callvirt ""void System.IDisposable.Dispose()""
IL_001c: nop
// sequence point: <hidden>
IL_001d: endfinally
}
// sequence point: }
IL_001e: ret
}
", sequencePoints: "C.F", source: source);
}
[WorkItem(18844, "https://github.com/dotnet/roslyn/issues/18844")]
[Fact]
public void UsingStatement_EmbeddedFor()
{
var source = @"
class C
{
void F(bool x)
{
using (var stream = new System.IO.MemoryStream())
for ( ; x == true; )
x = false;
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.F", @"
{
// Code size 31 (0x1f)
.maxstack 1
.locals init (System.IO.MemoryStream V_0, //stream
bool V_1)
// sequence point: {
IL_0000: nop
// sequence point: var stream = new System.IO.MemoryStream()
IL_0001: newobj ""System.IO.MemoryStream..ctor()""
IL_0006: stloc.0
.try
{
// sequence point: <hidden>
IL_0007: br.s IL_000c
// sequence point: x = false;
IL_0009: ldc.i4.0
IL_000a: starg.s V_1
// sequence point: x == true
IL_000c: ldarg.1
IL_000d: stloc.1
// sequence point: <hidden>
IL_000e: ldloc.1
IL_000f: brtrue.s IL_0009
IL_0011: leave.s IL_001e
}
finally
{
// sequence point: <hidden>
IL_0013: ldloc.0
IL_0014: brfalse.s IL_001d
IL_0016: ldloc.0
IL_0017: callvirt ""void System.IDisposable.Dispose()""
IL_001c: nop
// sequence point: <hidden>
IL_001d: endfinally
}
// sequence point: }
IL_001e: ret
}
", sequencePoints: "C.F", source: source);
}
[WorkItem(18844, "https://github.com/dotnet/roslyn/issues/18844")]
[Fact]
public void LockStatement_EmbeddedIf()
{
var source = @"
class C
{
void F(bool x)
{
string y = """";
lock (y)
if (!x)
System.Console.Write(1);
else
System.Console.Write(2);
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.F", @"
{
// Code size 58 (0x3a)
.maxstack 2
.locals init (string V_0, //y
string V_1,
bool V_2,
bool V_3)
// sequence point: {
IL_0000: nop
// sequence point: string y = """";
IL_0001: ldstr """"
IL_0006: stloc.0
// sequence point: lock (y)
IL_0007: ldloc.0
IL_0008: stloc.1
IL_0009: ldc.i4.0
IL_000a: stloc.2
.try
{
IL_000b: ldloc.1
IL_000c: ldloca.s V_2
IL_000e: call ""void System.Threading.Monitor.Enter(object, ref bool)""
IL_0013: nop
// sequence point: if (!x)
IL_0014: ldarg.1
IL_0015: ldc.i4.0
IL_0016: ceq
IL_0018: stloc.3
// sequence point: <hidden>
IL_0019: ldloc.3
IL_001a: brfalse.s IL_0025
// sequence point: System.Console.Write(1);
IL_001c: ldc.i4.1
IL_001d: call ""void System.Console.Write(int)""
IL_0022: nop
// sequence point: <hidden>
IL_0023: br.s IL_002c
// sequence point: System.Console.Write(2);
IL_0025: ldc.i4.2
IL_0026: call ""void System.Console.Write(int)""
IL_002b: nop
// sequence point: <hidden>
IL_002c: leave.s IL_0039
}
finally
{
// sequence point: <hidden>
IL_002e: ldloc.2
IL_002f: brfalse.s IL_0038
IL_0031: ldloc.1
IL_0032: call ""void System.Threading.Monitor.Exit(object)""
IL_0037: nop
// sequence point: <hidden>
IL_0038: endfinally
}
// sequence point: }
IL_0039: ret
}
", sequencePoints: "C.F", source: source);
}
#endregion
#region Using Declaration
[WorkItem(37417, "https://github.com/dotnet/roslyn/issues/37417")]
[Fact]
public void UsingDeclaration_BodyBlockScope()
{
var source = WithWindowsLineBreaks(@"
using System;
using System.IO;
class C
{
static void Main()
{
using MemoryStream m = new MemoryStream(), n = new MemoryStream();
Console.WriteLine(1);
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
// TODO: https://github.com/dotnet/roslyn/issues/37417
// Duplicate sequence point at `}`
v.VerifyIL("C.Main", sequencePoints: "C.Main", source: source, expectedIL: @"
{
// Code size 45 (0x2d)
.maxstack 1
.locals init (System.IO.MemoryStream V_0, //m
System.IO.MemoryStream V_1) //n
// sequence point: {
IL_0000: nop
// sequence point: using MemoryStream m = new MemoryStream()
IL_0001: newobj ""System.IO.MemoryStream..ctor()""
IL_0006: stloc.0
.try
{
// sequence point: n = new MemoryStream()
IL_0007: newobj ""System.IO.MemoryStream..ctor()""
IL_000c: stloc.1
.try
{
// sequence point: Console.WriteLine(1);
IL_000d: ldc.i4.1
IL_000e: call ""void System.Console.WriteLine(int)""
IL_0013: nop
// sequence point: }
IL_0014: leave.s IL_002c
}
finally
{
// sequence point: <hidden>
IL_0016: ldloc.1
IL_0017: brfalse.s IL_0020
IL_0019: ldloc.1
IL_001a: callvirt ""void System.IDisposable.Dispose()""
IL_001f: nop
// sequence point: <hidden>
IL_0020: endfinally
}
}
finally
{
// sequence point: <hidden>
IL_0021: ldloc.0
IL_0022: brfalse.s IL_002b
IL_0024: ldloc.0
IL_0025: callvirt ""void System.IDisposable.Dispose()""
IL_002a: nop
// sequence point: <hidden>
IL_002b: endfinally
}
// sequence point: }
IL_002c: ret
}
");
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""30"" />
<slot kind=""0"" offset=""54"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""50"" document=""1"" />
<entry offset=""0x7"" startLine=""8"" startColumn=""52"" endLine=""8"" endColumn=""74"" document=""1"" />
<entry offset=""0xd"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""30"" document=""1"" />
<entry offset=""0x14"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
<entry offset=""0x16"" hidden=""true"" document=""1"" />
<entry offset=""0x20"" hidden=""true"" document=""1"" />
<entry offset=""0x21"" hidden=""true"" document=""1"" />
<entry offset=""0x2b"" hidden=""true"" document=""1"" />
<entry offset=""0x2c"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2d"">
<namespace name=""System"" />
<namespace name=""System.IO"" />
<local name=""m"" il_index=""0"" il_start=""0x0"" il_end=""0x2d"" attributes=""0"" />
<local name=""n"" il_index=""1"" il_start=""0x0"" il_end=""0x2d"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(37417, "https://github.com/dotnet/roslyn/issues/37417")]
[Fact]
public void UsingDeclaration_BodyBlockScopeWithReturn()
{
var source = WithWindowsLineBreaks(@"
using System;
using System.IO;
class C
{
static int Main()
{
using MemoryStream m = new MemoryStream();
Console.WriteLine(1);
return 1;
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
// TODO: https://github.com/dotnet/roslyn/issues/37417
// Duplicate sequence point at `}`
v.VerifyIL("C.Main", sequencePoints: "C.Main", source: source, expectedIL: @"
{
// Code size 31 (0x1f)
.maxstack 1
.locals init (System.IO.MemoryStream V_0, //m
int V_1)
// sequence point: {
IL_0000: nop
// sequence point: using MemoryStream m = new MemoryStream();
IL_0001: newobj ""System.IO.MemoryStream..ctor()""
IL_0006: stloc.0
.try
{
// sequence point: Console.WriteLine(1);
IL_0007: ldc.i4.1
IL_0008: call ""void System.Console.WriteLine(int)""
IL_000d: nop
// sequence point: return 1;
IL_000e: ldc.i4.1
IL_000f: stloc.1
IL_0010: leave.s IL_001d
}
finally
{
// sequence point: <hidden>
IL_0012: ldloc.0
IL_0013: brfalse.s IL_001c
IL_0015: ldloc.0
IL_0016: callvirt ""void System.IDisposable.Dispose()""
IL_001b: nop
// sequence point: <hidden>
IL_001c: endfinally
}
// sequence point: }
IL_001d: ldloc.1
IL_001e: ret
}
");
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""30"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""51"" document=""1"" />
<entry offset=""0x7"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""30"" document=""1"" />
<entry offset=""0xe"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""18"" document=""1"" />
<entry offset=""0x12"" hidden=""true"" document=""1"" />
<entry offset=""0x1c"" hidden=""true"" document=""1"" />
<entry offset=""0x1d"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1f"">
<namespace name=""System"" />
<namespace name=""System.IO"" />
<local name=""m"" il_index=""0"" il_start=""0x0"" il_end=""0x1f"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(37417, "https://github.com/dotnet/roslyn/issues/37417")]
[Fact]
public void UsingDeclaration_IfBodyScope()
{
var source = WithWindowsLineBreaks(@"
using System;
using System.IO;
class C
{
public static bool G() => true;
static void Main()
{
if (G())
{
using var m = new MemoryStream();
Console.WriteLine(1);
}
Console.WriteLine(2);
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
// TODO: https://github.com/dotnet/roslyn/issues/37417
// In this case the sequence point `}` is not emitted on the leave instruction,
// but to a nop instruction following the disposal.
v.VerifyIL("C.Main", sequencePoints: "C.Main", source: source, expectedIL: @"
{
// Code size 46 (0x2e)
.maxstack 1
.locals init (bool V_0,
System.IO.MemoryStream V_1) //m
// sequence point: {
IL_0000: nop
// sequence point: if (G())
IL_0001: call ""bool C.G()""
IL_0006: stloc.0
// sequence point: <hidden>
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0026
// sequence point: {
IL_000a: nop
// sequence point: using var m = new MemoryStream();
IL_000b: newobj ""System.IO.MemoryStream..ctor()""
IL_0010: stloc.1
.try
{
// sequence point: Console.WriteLine(1);
IL_0011: ldc.i4.1
IL_0012: call ""void System.Console.WriteLine(int)""
IL_0017: nop
IL_0018: leave.s IL_0025
}
finally
{
// sequence point: <hidden>
IL_001a: ldloc.1
IL_001b: brfalse.s IL_0024
IL_001d: ldloc.1
IL_001e: callvirt ""void System.IDisposable.Dispose()""
IL_0023: nop
// sequence point: <hidden>
IL_0024: endfinally
}
// sequence point: }
IL_0025: nop
// sequence point: Console.WriteLine(2);
IL_0026: ldc.i4.2
IL_0027: call ""void System.Console.WriteLine(int)""
IL_002c: nop
// sequence point: }
IL_002d: ret
}
");
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" />
<encLocalSlotMap>
<slot kind=""1"" offset=""11"" />
<slot kind=""0"" offset=""55"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""17"" document=""1"" />
<entry offset=""0x7"" hidden=""true"" document=""1"" />
<entry offset=""0xa"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0xb"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""46"" document=""1"" />
<entry offset=""0x11"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""34"" document=""1"" />
<entry offset=""0x1a"" hidden=""true"" document=""1"" />
<entry offset=""0x24"" hidden=""true"" document=""1"" />
<entry offset=""0x25"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" />
<entry offset=""0x26"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""30"" document=""1"" />
<entry offset=""0x2d"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2e"">
<scope startOffset=""0xa"" endOffset=""0x26"">
<local name=""m"" il_index=""1"" il_start=""0xa"" il_end=""0x26"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
#endregion
// LockStatement tested in CodeGenLock
#region Anonymous Type
[Fact]
public void AnonymousType_Empty()
{
var source = WithWindowsLineBreaks(@"
class Program
{
static void Main(string[] args)
{
var o = new {};
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""24"" document=""1"" />
<entry offset=""0x7"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x8"">
<local name=""o"" il_index=""0"" il_start=""0x0"" il_end=""0x8"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void AnonymousType_NonEmpty()
{
var source = WithWindowsLineBreaks(@"
class Program
{
static void Main(string[] args)
{
var o = new { a = 1 };
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""31"" document=""1"" />
<entry offset=""0x8"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x9"">
<local name=""o"" il_index=""0"" il_start=""0x0"" il_end=""0x9"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region FixedStatement
[Fact]
public void FixedStatementSingleAddress()
{
var source = WithWindowsLineBreaks(@"
using System;
unsafe class C
{
int x;
static void Main()
{
C c = new C();
fixed (int* p = &c.x)
{
*p = 1;
}
Console.WriteLine(c.x);
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
<slot kind=""0"" offset=""47"" />
<slot kind=""9"" offset=""47"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""23"" document=""1"" />
<entry offset=""0xe"" startLine=""11"" startColumn=""16"" endLine=""11"" endColumn=""29"" document=""1"" />
<entry offset=""0x11"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" />
<entry offset=""0x12"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""20"" document=""1"" />
<entry offset=""0x15"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" />
<entry offset=""0x16"" hidden=""true"" document=""1"" />
<entry offset=""0x19"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""32"" document=""1"" />
<entry offset=""0x25"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x26"">
<namespace name=""System"" />
<local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x26"" attributes=""0"" />
<scope startOffset=""0x7"" endOffset=""0x19"">
<local name=""p"" il_index=""1"" il_start=""0x7"" il_end=""0x19"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void FixedStatementSingleString()
{
var source = WithWindowsLineBreaks(@"
using System;
unsafe class C
{
static void Main()
{
fixed (char* p = ""hello"")
{
Console.WriteLine(*p);
}
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""24"" />
<slot kind=""9"" offset=""24"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x7"" startLine=""8"" startColumn=""16"" endLine=""8"" endColumn=""33"" document=""1"" />
<entry offset=""0x15"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x16"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""35"" document=""1"" />
<entry offset=""0x1e"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0x1f"" hidden=""true"" document=""1"" />
<entry offset=""0x21"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x22"">
<namespace name=""System"" />
<scope startOffset=""0x1"" endOffset=""0x21"">
<local name=""p"" il_index=""0"" il_start=""0x1"" il_end=""0x21"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void FixedStatementSingleArray()
{
var source = WithWindowsLineBreaks(@"
using System;
unsafe class C
{
int[] a = new int[1];
static void Main()
{
C c = new C();
Console.Write(c.a[0]);
fixed (int* p = c.a)
{
(*p)++;
}
Console.Write(c.a[0]);
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
<slot kind=""0"" offset=""79"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""23"" document=""1"" />
<entry offset=""0x7"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""31"" document=""1"" />
<entry offset=""0x15"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""28"" document=""1"" />
<entry offset=""0x32"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x33"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""20"" document=""1"" />
<entry offset=""0x39"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" />
<entry offset=""0x3a"" hidden=""true"" document=""1"" />
<entry offset=""0x3c"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""31"" document=""1"" />
<entry offset=""0x4a"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x4b"">
<namespace name=""System"" />
<local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x4b"" attributes=""0"" />
<scope startOffset=""0x15"" endOffset=""0x3c"">
<local name=""p"" il_index=""1"" il_start=""0x15"" il_end=""0x3c"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Main"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""26"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void FixedStatementMultipleAddresses()
{
var source = WithWindowsLineBreaks(@"
using System;
unsafe class C
{
int x;
int y;
static void Main()
{
C c = new C();
fixed (int* p = &c.x, q = &c.y)
{
*p = 1;
*q = 2;
}
Console.WriteLine(c.x + c.y);
}
}
");
// NOTE: stop on each declarator.
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
<slot kind=""0"" offset=""47"" />
<slot kind=""0"" offset=""57"" />
<slot kind=""9"" offset=""47"" />
<slot kind=""9"" offset=""57"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""23"" document=""1"" />
<entry offset=""0xe"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""29"" document=""1"" />
<entry offset=""0x19"" startLine=""12"" startColumn=""31"" endLine=""12"" endColumn=""39"" document=""1"" />
<entry offset=""0x1d"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x1e"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""20"" document=""1"" />
<entry offset=""0x21"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""20"" document=""1"" />
<entry offset=""0x24"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""1"" />
<entry offset=""0x25"" hidden=""true"" document=""1"" />
<entry offset=""0x2c"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""38"" document=""1"" />
<entry offset=""0x3f"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x40"">
<namespace name=""System"" />
<local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x40"" attributes=""0"" />
<scope startOffset=""0x7"" endOffset=""0x2c"">
<local name=""p"" il_index=""1"" il_start=""0x7"" il_end=""0x2c"" attributes=""0"" />
<local name=""q"" il_index=""2"" il_start=""0x7"" il_end=""0x2c"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void FixedStatementMultipleStrings()
{
var source = WithWindowsLineBreaks(@"
using System;
unsafe class C
{
static void Main()
{
fixed (char* p = ""hello"", q = ""goodbye"")
{
Console.Write(*p);
Console.Write(*q);
}
}
}
");
// NOTE: stop on each declarator.
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""24"" />
<slot kind=""0"" offset=""37"" />
<slot kind=""9"" offset=""24"" />
<slot kind=""9"" offset=""37"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x7"" startLine=""8"" startColumn=""16"" endLine=""8"" endColumn=""33"" document=""1"" />
<entry offset=""0x1b"" startLine=""8"" startColumn=""35"" endLine=""8"" endColumn=""48"" document=""1"" />
<entry offset=""0x29"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x2a"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""31"" document=""1"" />
<entry offset=""0x32"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""31"" document=""1"" />
<entry offset=""0x3a"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" />
<entry offset=""0x3b"" hidden=""true"" document=""1"" />
<entry offset=""0x3f"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x40"">
<namespace name=""System"" />
<scope startOffset=""0x1"" endOffset=""0x3f"">
<local name=""p"" il_index=""0"" il_start=""0x1"" il_end=""0x3f"" attributes=""0"" />
<local name=""q"" il_index=""1"" il_start=""0x1"" il_end=""0x3f"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void FixedStatementMultipleArrays()
{
var source = WithWindowsLineBreaks(@"
using System;
unsafe class C
{
int[] a = new int[1];
int[] b = new int[1];
static void Main()
{
C c = new C();
Console.Write(c.a[0]);
Console.Write(c.b[0]);
fixed (int* p = c.a, q = c.b)
{
*p = 1;
*q = 2;
}
Console.Write(c.a[0]);
Console.Write(c.b[0]);
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
<slot kind=""0"" offset=""111"" />
<slot kind=""0"" offset=""120"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""23"" document=""1"" />
<entry offset=""0x7"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""31"" document=""1"" />
<entry offset=""0x15"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""31"" document=""1"" />
<entry offset=""0x23"" startLine=""14"" startColumn=""16"" endLine=""14"" endColumn=""28"" document=""1"" />
<entry offset=""0x40"" startLine=""14"" startColumn=""30"" endLine=""14"" endColumn=""37"" document=""1"" />
<entry offset=""0x60"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" />
<entry offset=""0x61"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""20"" document=""1"" />
<entry offset=""0x64"" startLine=""17"" startColumn=""13"" endLine=""17"" endColumn=""20"" document=""1"" />
<entry offset=""0x67"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""10"" document=""1"" />
<entry offset=""0x68"" hidden=""true"" document=""1"" />
<entry offset=""0x6d"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""31"" document=""1"" />
<entry offset=""0x7b"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""31"" document=""1"" />
<entry offset=""0x89"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x8a"">
<namespace name=""System"" />
<local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x8a"" attributes=""0"" />
<scope startOffset=""0x23"" endOffset=""0x6d"">
<local name=""p"" il_index=""1"" il_start=""0x23"" il_end=""0x6d"" attributes=""0"" />
<local name=""q"" il_index=""2"" il_start=""0x23"" il_end=""0x6d"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Main"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""26"" document=""1"" />
<entry offset=""0xc"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""26"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void FixedStatementMultipleMixed()
{
var source = WithWindowsLineBreaks(@"
using System;
unsafe class C
{
char c = 'a';
char[] a = new char[1];
static void Main()
{
C c = new C();
fixed (char* p = &c.c, q = c.a, r = ""hello"")
{
Console.Write((int)*p);
Console.Write((int)*q);
Console.Write((int)*r);
}
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugDll);
c.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
<slot kind=""0"" offset=""48"" />
<slot kind=""0"" offset=""58"" />
<slot kind=""0"" offset=""67"" />
<slot kind=""9"" offset=""48"" />
<slot kind=""temp"" />
<slot kind=""9"" offset=""67"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""23"" document=""1"" />
<entry offset=""0xf"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""30"" document=""1"" />
<entry offset=""0x13"" startLine=""12"" startColumn=""32"" endLine=""12"" endColumn=""39"" document=""1"" />
<entry offset=""0x3a"" startLine=""12"" startColumn=""41"" endLine=""12"" endColumn=""52"" document=""1"" />
<entry offset=""0x49"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x4a"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""36"" document=""1"" />
<entry offset=""0x52"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""36"" document=""1"" />
<entry offset=""0x5a"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""36"" document=""1"" />
<entry offset=""0x62"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" />
<entry offset=""0x63"" hidden=""true"" document=""1"" />
<entry offset=""0x6d"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x6e"">
<namespace name=""System"" />
<local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x6e"" attributes=""0"" />
<scope startOffset=""0x7"" endOffset=""0x6d"">
<local name=""p"" il_index=""1"" il_start=""0x7"" il_end=""0x6d"" attributes=""0"" />
<local name=""q"" il_index=""2"" il_start=""0x7"" il_end=""0x6d"" attributes=""0"" />
<local name=""r"" il_index=""3"" il_start=""0x7"" il_end=""0x6d"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Main"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""18"" document=""1"" />
<entry offset=""0x8"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""28"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
#endregion
#region Line Directives
[Fact]
public void LineDirective()
{
var source = @"
#line 50 ""foo.cs""
using System;
unsafe class C
{
static void Main()
{
Console.Write(1);
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""foo.cs"" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""56"" startColumn=""5"" endLine=""56"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""57"" startColumn=""9"" endLine=""57"" endColumn=""26"" document=""1"" />
<entry offset=""0x8"" startLine=""58"" startColumn=""5"" endLine=""58"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x9"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")]
[Fact]
public void DisabledLineDirective()
{
var source = @"
#if false
#line 50 ""foo.cs""
#endif
using System;
unsafe class C
{
static void Main()
{
Console.Write(1);
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""26"" document=""1"" />
<entry offset=""0x8"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x9"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void TestLineDirectivesHidden()
{
var text1 = WithWindowsLineBreaks(@"
using System;
public class C
{
public void Foo()
{
foreach (var x in new int[] { 1, 2, 3, 4 })
{
Console.WriteLine(x);
}
#line hidden
foreach (var x in new int[] { 1, 2, 3, 4 })
{
Console.WriteLine(x);
}
#line default
foreach (var x in new int[] { 1, 2, 3, 4 })
{
Console.WriteLine(x);
}
}
}
");
var compilation = CreateCompilation(text1, options: TestOptions.DebugDll);
compilation.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Foo"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""6"" offset=""11"" />
<slot kind=""8"" offset=""11"" />
<slot kind=""0"" offset=""11"" />
<slot kind=""6"" offset=""137"" />
<slot kind=""8"" offset=""137"" />
<slot kind=""0"" offset=""137"" />
<slot kind=""6"" offset=""264"" />
<slot kind=""8"" offset=""264"" />
<slot kind=""0"" offset=""264"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""16"" document=""1"" />
<entry offset=""0x2"" startLine=""7"" startColumn=""27"" endLine=""7"" endColumn=""51"" document=""1"" />
<entry offset=""0x16"" hidden=""true"" document=""1"" />
<entry offset=""0x18"" startLine=""7"" startColumn=""18"" endLine=""7"" endColumn=""23"" document=""1"" />
<entry offset=""0x1c"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" />
<entry offset=""0x1d"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""34"" document=""1"" />
<entry offset=""0x24"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" />
<entry offset=""0x25"" hidden=""true"" document=""1"" />
<entry offset=""0x29"" startLine=""7"" startColumn=""24"" endLine=""7"" endColumn=""26"" document=""1"" />
<entry offset=""0x2f"" hidden=""true"" document=""1"" />
<entry offset=""0x30"" hidden=""true"" document=""1"" />
<entry offset=""0x45"" hidden=""true"" document=""1"" />
<entry offset=""0x47"" hidden=""true"" document=""1"" />
<entry offset=""0x4d"" hidden=""true"" document=""1"" />
<entry offset=""0x4e"" hidden=""true"" document=""1"" />
<entry offset=""0x56"" hidden=""true"" document=""1"" />
<entry offset=""0x57"" hidden=""true"" document=""1"" />
<entry offset=""0x5d"" hidden=""true"" document=""1"" />
<entry offset=""0x64"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""16"" document=""1"" />
<entry offset=""0x65"" startLine=""19"" startColumn=""27"" endLine=""19"" endColumn=""51"" document=""1"" />
<entry offset=""0x7b"" hidden=""true"" document=""1"" />
<entry offset=""0x7d"" startLine=""19"" startColumn=""18"" endLine=""19"" endColumn=""23"" document=""1"" />
<entry offset=""0x84"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""10"" document=""1"" />
<entry offset=""0x85"" startLine=""21"" startColumn=""13"" endLine=""21"" endColumn=""34"" document=""1"" />
<entry offset=""0x8d"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" />
<entry offset=""0x8e"" hidden=""true"" document=""1"" />
<entry offset=""0x94"" startLine=""19"" startColumn=""24"" endLine=""19"" endColumn=""26"" document=""1"" />
<entry offset=""0x9c"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x9d"">
<namespace name=""System"" />
<scope startOffset=""0x18"" endOffset=""0x25"">
<local name=""x"" il_index=""2"" il_start=""0x18"" il_end=""0x25"" attributes=""0"" />
</scope>
<scope startOffset=""0x47"" endOffset=""0x57"">
<local name=""x"" il_index=""5"" il_start=""0x47"" il_end=""0x57"" attributes=""0"" />
</scope>
<scope startOffset=""0x7d"" endOffset=""0x8e"">
<local name=""x"" il_index=""8"" il_start=""0x7d"" il_end=""0x8e"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void HiddenMethods()
{
var src = @"
using System;
class C
{
#line hidden
public static void H()
{
F();
}
#line default
public static void G()
{
F();
}
#line hidden
public static void F()
{
{
const int z = 1;
var (x, y) = (1,2);
Console.WriteLine(x + z);
}
{
dynamic x = 1;
Console.WriteLine(x);
}
}
}";
var c = CreateCompilationWithMscorlib40AndSystemCore(src, references: new[] { CSharpRef, ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""G"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""13"" document=""1"" />
<entry offset=""0x7"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x8"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void HiddenEntryPoint()
{
var src = @"
class C
{
#line hidden
public static void Main()
{
}
}";
var c = CreateCompilationWithMscorlib40AndSystemCore(src, references: new[] { CSharpRef, ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe);
// Note: Dev10 emitted a hidden sequence point to #line hidden method,
// which enabled the debugger to locate the first user visible sequence point starting from the entry point.
// Roslyn does not emit such sequence point. We could potentially synthesize one but that would defeat the purpose of
// #line hidden directive.
c.VerifyPdb(@"
<symbols>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"" format=""windows"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
</method>
</methods>
</symbols>",
// When converting from Portable to Windows the PDB writer doesn't create an entry for the Main method
// and thus there is no entry point record either.
options: PdbValidationOptions.SkipConversionValidation);
}
[Fact]
public void HiddenIterator()
{
var src = WithWindowsLineBreaks(@"
using System;
using System.Collections.Generic;
class C
{
public static void Main()
{
F();
}
#line hidden
public static IEnumerable<int> F()
{
{
const int z = 1;
var (x, y) = (1,2);
Console.WriteLine(x + z);
}
{
dynamic x = 1;
Console.WriteLine(x);
}
yield return 1;
}
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(src, references: new[] { CSharpRef, ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
// We don't really need the debug info for kickoff method when the entire iterator method is hidden,
// but it doesn't hurt and removing it would need extra effort that's unnecessary.
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""13"" document=""1"" />
<entry offset=""0x7"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x8"">
<namespace name=""System"" />
<namespace name=""System.Collections.Generic"" />
</scope>
</method>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<forwardIterator name=""<F>d__1"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""61"" />
<slot kind=""0"" offset=""64"" />
<slot kind=""0"" offset=""158"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
</methods>
</symbols>");
}
#endregion
#region Nested Types
[Fact]
public void NestedTypes()
{
string source = WithWindowsLineBreaks(@"
using System;
namespace N
{
public class C
{
public class D<T>
{
public class E
{
public static void f(int a)
{
Console.WriteLine();
}
}
}
}
}
");
var c = CreateCompilation(Parse(source, filename: "file.cs"));
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""file.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""F7-03-46-2C-11-16-DE-85-F9-DD-5C-76-F6-55-D9-13-E0-95-DE-14"" />
</files>
<methods>
<method containingType=""N.C+D`1+E"" name=""f"" parameterNames=""a"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""14"" startColumn=""6"" endLine=""14"" endColumn=""26"" document=""1"" />
<entry offset=""0x5"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x6"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region Expression Bodied Members
[Fact]
public void ExpressionBodiedProperty()
{
var source = WithWindowsLineBreaks(@"
class C
{
public int P => M();
public int M()
{
return 2;
}
}");
var comp = CreateCompilationWithMscorlib45(source);
comp.VerifyDiagnostics();
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""get_P"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""21"" endLine=""4"" endColumn=""24"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_P"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""18"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void ExpressionBodiedIndexer()
{
var comp = CreateCompilationWithMscorlib45(@"
using System;
class C
{
public int this[Int32 i] => M();
public int M()
{
return 2;
}
}");
comp.VerifyDiagnostics();
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""get_Item"" parameterNames=""i"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""33"" endLine=""6"" endColumn=""36"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x7"">
<namespace name=""System"" />
</scope>
</method>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_Item"" parameterNames=""i"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""18"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void ExpressionBodiedMethod()
{
var comp = CreateCompilationWithMscorlib45(@"
using System;
class C
{
public Int32 P => 2;
}");
comp.VerifyDiagnostics();
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""get_P"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""23"" endLine=""6"" endColumn=""24"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void ExpressionBodiedOperator()
{
var comp = CreateCompilationWithMscorlib45(@"
class C
{
public static C operator ++(C c) => c;
}");
comp.VerifyDiagnostics();
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""op_Increment"" parameterNames=""c"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""41"" endLine=""4"" endColumn=""42"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void ExpressionBodiedConversion()
{
var comp = CreateCompilationWithMscorlib45(@"
using System;
class C
{
public static explicit operator C(Int32 i) => new C();
}");
comp.VerifyDiagnostics();
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""op_Explicit"" parameterNames=""i"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""51"" endLine=""6"" endColumn=""58"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x6"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")]
[Fact]
public void ExpressionBodiedConstructor()
{
var comp = CreateCompilationWithMscorlib45(@"
using System;
class C
{
public int X;
public C(Int32 x) => X = x;
}");
comp.VerifyDiagnostics();
comp.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"" parameterNames=""x"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""22"" document=""1"" />
<entry offset=""0x6"" startLine=""7"" startColumn=""26"" endLine=""7"" endColumn=""31"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xe"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")]
[Fact]
public void ExpressionBodiedDestructor()
{
var comp = CreateCompilationWithMscorlib45(@"
class C
{
public int X;
~C() => X = 0;
}");
comp.VerifyDiagnostics();
comp.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Finalize"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""13"" endLine=""5"" endColumn=""18"" document=""1"" />
<entry offset=""0x9"" hidden=""true"" document=""1"" />
<entry offset=""0x10"" hidden=""true"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")]
[Fact]
public void ExpressionBodiedAccessor()
{
var comp = CreateCompilationWithMscorlib45(@"
class C
{
public int x;
public int X
{
get => x;
set => x = value;
}
public event System.Action E
{
add => x = 1;
remove => x = 0;
}
}");
comp.VerifyDiagnostics();
comp.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""get_X"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""16"" endLine=""7"" endColumn=""17"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""set_X"" parameterNames=""value"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_X"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""16"" endLine=""8"" endColumn=""25"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""add_E"" parameterNames=""value"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_X"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""21"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""remove_E"" parameterNames=""value"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_X"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""13"" startColumn=""19"" endLine=""13"" endColumn=""24"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
#endregion
#region Synthesized Methods
[Fact]
public void ImportsInLambda()
{
var source = WithWindowsLineBreaks(
@"using System.Collections.Generic;
using System.Linq;
class C
{
static void M()
{
System.Action f = () =>
{
var c = new[] { 1, 2, 3 };
c.Select(i => i);
};
f();
}
}");
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, references: new[] { SystemCoreRef });
c.VerifyPdb("C+<>c.<M>b__0_0",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c"" name=""<M>b__0_0"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""M"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""63"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""39"" document=""1"" />
<entry offset=""0x13"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""30"" document=""1"" />
<entry offset=""0x39"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x3a"">
<local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x3a"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void ImportsInIterator()
{
var source = WithWindowsLineBreaks(
@"using System.Collections.Generic;
using System.Linq;
class C
{
static IEnumerable<object> F()
{
var c = new[] { 1, 2, 3 };
foreach (var i in c.Select(i => i))
{
yield return i;
}
}
}");
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, references: new[] { SystemCoreRef });
c.VerifyPdb("C+<F>d__0.MoveNext",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<F>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C+<>c"" methodName=""<F>b__0_0"" parameterNames=""i"" />
<hoistedLocalScopes>
<slot startOffset=""0x27"" endOffset=""0xd5"" />
<slot />
<slot startOffset=""0x7f"" endOffset=""0xb6"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""temp"" />
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x27"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
<entry offset=""0x28"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""35"" document=""1"" />
<entry offset=""0x3f"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""16"" document=""1"" />
<entry offset=""0x40"" startLine=""8"" startColumn=""27"" endLine=""8"" endColumn=""43"" document=""1"" />
<entry offset=""0x7d"" hidden=""true"" document=""1"" />
<entry offset=""0x7f"" startLine=""8"" startColumn=""18"" endLine=""8"" endColumn=""23"" document=""1"" />
<entry offset=""0x90"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x91"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""28"" document=""1"" />
<entry offset=""0xad"" hidden=""true"" document=""1"" />
<entry offset=""0xb5"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0xb6"" startLine=""8"" startColumn=""24"" endLine=""8"" endColumn=""26"" document=""1"" />
<entry offset=""0xd1"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
<entry offset=""0xd5"" hidden=""true"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void ImportsInAsync()
{
var source = WithWindowsLineBreaks(
@"using System.Linq;
using System.Threading.Tasks;
class C
{
static async Task F()
{
var c = new[] { 1, 2, 3 };
c.Select(i => i);
}
}");
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, references: new[] { SystemCoreRef });
c.VerifyPdb("C+<F>d__0.MoveNext",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<F>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C+<>c"" methodName=""<F>b__0_0"" parameterNames=""i"" />
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0x87"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
<entry offset=""0x8"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""35"" document=""1"" />
<entry offset=""0x1f"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""26"" document=""1"" />
<entry offset=""0x4c"" hidden=""true"" document=""1"" />
<entry offset=""0x6b"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x73"" hidden=""true"" document=""1"" />
</sequencePoints>
<asyncInfo>
<kickoffMethod declaringType=""C"" methodName=""F"" />
</asyncInfo>
</method>
</methods>
</symbols>");
}
[WorkItem(2501, "https://github.com/dotnet/roslyn/issues/2501")]
[Fact]
public void ImportsInAsyncLambda()
{
var source = WithWindowsLineBreaks(
@"using System.Linq;
class C
{
static void M()
{
System.Action f = async () =>
{
var c = new[] { 1, 2, 3 };
c.Select(i => i);
};
}
}");
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, references: new[] { SystemCoreRef });
c.VerifyPdb("C+<>c.<M>b__0_0",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c"" name=""<M>b__0_0"">
<customDebugInfo>
<forwardIterator name=""<<M>b__0_0>d"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""69"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
</methods>
</symbols>");
c.VerifyPdb("C+<>c+<<M>b__0_0>d.MoveNext",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c+<<M>b__0_0>d"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""M"" />
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0x87"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""50"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" />
<entry offset=""0x8"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""39"" document=""1"" />
<entry offset=""0x1f"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""30"" document=""1"" />
<entry offset=""0x4c"" hidden=""true"" document=""1"" />
<entry offset=""0x6b"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" />
<entry offset=""0x73"" hidden=""true"" document=""1"" />
</sequencePoints>
<asyncInfo>
<catchHandler offset=""0x4c"" />
<kickoffMethod declaringType=""C+<>c"" methodName=""<M>b__0_0"" />
</asyncInfo>
</method>
</methods>
</symbols>");
}
#endregion
#region Patterns
[Fact]
public void SyntaxOffset_IsPattern()
{
var source = @"class C { bool F(object o) => o is int i && o is 3 && o is bool; }";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.F", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"" parameterNames=""o"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""12"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""31"" endLine=""1"" endColumn=""64"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2d"">
<local name=""i"" il_index=""0"" il_start=""0x0"" il_end=""0x2d"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")]
[Fact]
public void Patterns_SwitchStatement()
{
string source = WithWindowsLineBreaks(@"
class C
{
public void Deconstruct() { }
public void Deconstruct(out int x) { x = 1; }
public void Deconstruct(out int x, out object y) { x = 2; y = new C(); }
}
class D
{
public int P { get; set; }
public D Q { get; set; }
public C R { get; set; }
}
class Program
{
static object F() => new C();
static bool B() => true;
static int G(int x) => x;
static int Main()
{
switch (F())
{
// declaration pattern
case int x when G(x) > 10: return 1;
// discard pattern
case bool _: return 2;
// var pattern
case var (y, z): return 3;
// constant pattern
case 4.0: return 4;
// positional patterns
case C() when B(): return 5;
case (): return 6;
case C(int p, C(int q)): return 7;
case C(x: int p): return 8;
// property pattern
case D { P: 1, Q: D { P: 2 }, R: C(int z) }: return 9;
default: return 10;
};
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerify(c, verify: Verification.Skipped);
verifier.VerifyIL("Program.Main", sequencePoints: "Program.Main", expectedIL: @"
{
// Code size 432 (0x1b0)
.maxstack 3
.locals init (int V_0, //x
object V_1, //y
object V_2, //z
int V_3, //p
int V_4, //q
int V_5, //p
int V_6, //z
object V_7,
System.Runtime.CompilerServices.ITuple V_8,
int V_9,
double V_10,
C V_11,
object V_12,
C V_13,
D V_14,
int V_15,
D V_16,
int V_17,
C V_18,
object V_19,
int V_20)
// sequence point: {
IL_0000: nop
// sequence point: switch (F())
IL_0001: call ""object Program.F()""
IL_0006: stloc.s V_19
// sequence point: <hidden>
IL_0008: ldloc.s V_19
IL_000a: stloc.s V_7
// sequence point: <hidden>
IL_000c: ldloc.s V_7
IL_000e: isinst ""int""
IL_0013: brfalse.s IL_0022
IL_0015: ldloc.s V_7
IL_0017: unbox.any ""int""
IL_001c: stloc.0
// sequence point: <hidden>
IL_001d: br IL_014d
IL_0022: ldloc.s V_7
IL_0024: isinst ""bool""
IL_0029: brtrue IL_015e
IL_002e: ldloc.s V_7
IL_0030: isinst ""System.Runtime.CompilerServices.ITuple""
IL_0035: stloc.s V_8
IL_0037: ldloc.s V_8
IL_0039: brfalse.s IL_0080
IL_003b: ldloc.s V_8
IL_003d: callvirt ""int System.Runtime.CompilerServices.ITuple.Length.get""
IL_0042: stloc.s V_9
// sequence point: <hidden>
IL_0044: ldloc.s V_9
IL_0046: ldc.i4.2
IL_0047: bne.un.s IL_0060
IL_0049: ldloc.s V_8
IL_004b: ldc.i4.0
IL_004c: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get""
IL_0051: stloc.1
// sequence point: <hidden>
IL_0052: ldloc.s V_8
IL_0054: ldc.i4.1
IL_0055: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get""
IL_005a: stloc.2
// sequence point: <hidden>
IL_005b: br IL_0163
IL_0060: ldloc.s V_7
IL_0062: isinst ""C""
IL_0067: brtrue IL_016f
IL_006c: br.s IL_0077
IL_006e: ldloc.s V_9
IL_0070: brfalse IL_018c
IL_0075: br.s IL_00b5
IL_0077: ldloc.s V_9
IL_0079: brfalse IL_018c
IL_007e: br.s IL_00f5
IL_0080: ldloc.s V_7
IL_0082: isinst ""double""
IL_0087: brfalse.s IL_00a7
IL_0089: ldloc.s V_7
IL_008b: unbox.any ""double""
IL_0090: stloc.s V_10
// sequence point: <hidden>
IL_0092: ldloc.s V_10
IL_0094: ldc.r8 4
IL_009d: beq IL_016a
IL_00a2: br IL_01a7
IL_00a7: ldloc.s V_7
IL_00a9: isinst ""C""
IL_00ae: brtrue IL_017b
IL_00b3: br.s IL_00f5
IL_00b5: ldloc.s V_7
IL_00b7: castclass ""C""
IL_00bc: stloc.s V_11
// sequence point: <hidden>
IL_00be: ldloc.s V_11
IL_00c0: ldloca.s V_3
IL_00c2: ldloca.s V_12
IL_00c4: callvirt ""void C.Deconstruct(out int, out object)""
IL_00c9: nop
// sequence point: <hidden>
IL_00ca: ldloc.s V_12
IL_00cc: isinst ""C""
IL_00d1: stloc.s V_13
IL_00d3: ldloc.s V_13
IL_00d5: brfalse.s IL_00e6
IL_00d7: ldloc.s V_13
IL_00d9: ldloca.s V_4
IL_00db: callvirt ""void C.Deconstruct(out int)""
IL_00e0: nop
// sequence point: <hidden>
IL_00e1: br IL_0191
IL_00e6: ldloc.s V_11
IL_00e8: ldloca.s V_5
IL_00ea: callvirt ""void C.Deconstruct(out int)""
IL_00ef: nop
// sequence point: <hidden>
IL_00f0: br IL_0198
IL_00f5: ldloc.s V_7
IL_00f7: isinst ""D""
IL_00fc: stloc.s V_14
IL_00fe: ldloc.s V_14
IL_0100: brfalse IL_01a7
IL_0105: ldloc.s V_14
IL_0107: callvirt ""int D.P.get""
IL_010c: stloc.s V_15
// sequence point: <hidden>
IL_010e: ldloc.s V_15
IL_0110: ldc.i4.1
IL_0111: bne.un IL_01a7
IL_0116: ldloc.s V_14
IL_0118: callvirt ""D D.Q.get""
IL_011d: stloc.s V_16
// sequence point: <hidden>
IL_011f: ldloc.s V_16
IL_0121: brfalse IL_01a7
IL_0126: ldloc.s V_16
IL_0128: callvirt ""int D.P.get""
IL_012d: stloc.s V_17
// sequence point: <hidden>
IL_012f: ldloc.s V_17
IL_0131: ldc.i4.2
IL_0132: bne.un.s IL_01a7
IL_0134: ldloc.s V_14
IL_0136: callvirt ""C D.R.get""
IL_013b: stloc.s V_18
// sequence point: <hidden>
IL_013d: ldloc.s V_18
IL_013f: brfalse.s IL_01a7
IL_0141: ldloc.s V_18
IL_0143: ldloca.s V_6
IL_0145: callvirt ""void C.Deconstruct(out int)""
IL_014a: nop
// sequence point: <hidden>
IL_014b: br.s IL_019f
// sequence point: when G(x) > 10
IL_014d: ldloc.0
IL_014e: call ""int Program.G(int)""
IL_0153: ldc.i4.s 10
IL_0155: bgt.s IL_0159
// sequence point: <hidden>
IL_0157: br.s IL_01a7
// sequence point: return 1;
IL_0159: ldc.i4.1
IL_015a: stloc.s V_20
IL_015c: br.s IL_01ad
// sequence point: return 2;
IL_015e: ldc.i4.2
IL_015f: stloc.s V_20
IL_0161: br.s IL_01ad
// sequence point: <hidden>
IL_0163: br.s IL_0165
// sequence point: return 3;
IL_0165: ldc.i4.3
IL_0166: stloc.s V_20
IL_0168: br.s IL_01ad
// sequence point: return 4;
IL_016a: ldc.i4.4
IL_016b: stloc.s V_20
IL_016d: br.s IL_01ad
// sequence point: when B()
IL_016f: call ""bool Program.B()""
IL_0174: brtrue.s IL_0187
// sequence point: <hidden>
IL_0176: br IL_006e
// sequence point: when B()
IL_017b: call ""bool Program.B()""
IL_0180: brtrue.s IL_0187
// sequence point: <hidden>
IL_0182: br IL_00b5
// sequence point: return 5;
IL_0187: ldc.i4.5
IL_0188: stloc.s V_20
IL_018a: br.s IL_01ad
// sequence point: return 6;
IL_018c: ldc.i4.6
IL_018d: stloc.s V_20
IL_018f: br.s IL_01ad
// sequence point: <hidden>
IL_0191: br.s IL_0193
// sequence point: return 7;
IL_0193: ldc.i4.7
IL_0194: stloc.s V_20
IL_0196: br.s IL_01ad
// sequence point: <hidden>
IL_0198: br.s IL_019a
// sequence point: return 8;
IL_019a: ldc.i4.8
IL_019b: stloc.s V_20
IL_019d: br.s IL_01ad
// sequence point: <hidden>
IL_019f: br.s IL_01a1
// sequence point: return 9;
IL_01a1: ldc.i4.s 9
IL_01a3: stloc.s V_20
IL_01a5: br.s IL_01ad
// sequence point: return 10;
IL_01a7: ldc.i4.s 10
IL_01a9: stloc.s V_20
IL_01ab: br.s IL_01ad
// sequence point: }
IL_01ad: ldloc.s V_20
IL_01af: ret
}
", source: source);
verifier.VerifyPdb("Program.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Deconstruct"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""93"" />
<slot kind=""0"" offset=""244"" />
<slot kind=""0"" offset=""247"" />
<slot kind=""0"" offset=""465"" />
<slot kind=""0"" offset=""474"" />
<slot kind=""0"" offset=""516"" />
<slot kind=""0"" offset=""617"" />
<slot kind=""35"" offset=""11"" />
<slot kind=""35"" offset=""11"" ordinal=""1"" />
<slot kind=""35"" offset=""11"" ordinal=""2"" />
<slot kind=""35"" offset=""11"" ordinal=""3"" />
<slot kind=""35"" offset=""11"" ordinal=""4"" />
<slot kind=""35"" offset=""11"" ordinal=""5"" />
<slot kind=""35"" offset=""11"" ordinal=""6"" />
<slot kind=""35"" offset=""11"" ordinal=""7"" />
<slot kind=""35"" offset=""11"" ordinal=""8"" />
<slot kind=""35"" offset=""11"" ordinal=""9"" />
<slot kind=""35"" offset=""11"" ordinal=""10"" />
<slot kind=""35"" offset=""11"" ordinal=""11"" />
<slot kind=""1"" offset=""11"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""21"" document=""1"" />
<entry offset=""0x8"" hidden=""true"" document=""1"" />
<entry offset=""0xc"" hidden=""true"" document=""1"" />
<entry offset=""0x1d"" hidden=""true"" document=""1"" />
<entry offset=""0x44"" hidden=""true"" document=""1"" />
<entry offset=""0x52"" hidden=""true"" document=""1"" />
<entry offset=""0x5b"" hidden=""true"" document=""1"" />
<entry offset=""0x92"" hidden=""true"" document=""1"" />
<entry offset=""0xbe"" hidden=""true"" document=""1"" />
<entry offset=""0xca"" hidden=""true"" document=""1"" />
<entry offset=""0xe1"" hidden=""true"" document=""1"" />
<entry offset=""0xf0"" hidden=""true"" document=""1"" />
<entry offset=""0x10e"" hidden=""true"" document=""1"" />
<entry offset=""0x11f"" hidden=""true"" document=""1"" />
<entry offset=""0x12f"" hidden=""true"" document=""1"" />
<entry offset=""0x13d"" hidden=""true"" document=""1"" />
<entry offset=""0x14b"" hidden=""true"" document=""1"" />
<entry offset=""0x14d"" startLine=""27"" startColumn=""24"" endLine=""27"" endColumn=""38"" document=""1"" />
<entry offset=""0x157"" hidden=""true"" document=""1"" />
<entry offset=""0x159"" startLine=""27"" startColumn=""40"" endLine=""27"" endColumn=""49"" document=""1"" />
<entry offset=""0x15e"" startLine=""30"" startColumn=""26"" endLine=""30"" endColumn=""35"" document=""1"" />
<entry offset=""0x163"" hidden=""true"" document=""1"" />
<entry offset=""0x165"" startLine=""33"" startColumn=""30"" endLine=""33"" endColumn=""39"" document=""1"" />
<entry offset=""0x16a"" startLine=""36"" startColumn=""23"" endLine=""36"" endColumn=""32"" document=""1"" />
<entry offset=""0x16f"" startLine=""39"" startColumn=""22"" endLine=""39"" endColumn=""30"" document=""1"" />
<entry offset=""0x176"" hidden=""true"" document=""1"" />
<entry offset=""0x17b"" startLine=""39"" startColumn=""22"" endLine=""39"" endColumn=""30"" document=""1"" />
<entry offset=""0x182"" hidden=""true"" document=""1"" />
<entry offset=""0x187"" startLine=""39"" startColumn=""32"" endLine=""39"" endColumn=""41"" document=""1"" />
<entry offset=""0x18c"" startLine=""40"" startColumn=""22"" endLine=""40"" endColumn=""31"" document=""1"" />
<entry offset=""0x191"" hidden=""true"" document=""1"" />
<entry offset=""0x193"" startLine=""41"" startColumn=""38"" endLine=""41"" endColumn=""47"" document=""1"" />
<entry offset=""0x198"" hidden=""true"" document=""1"" />
<entry offset=""0x19a"" startLine=""42"" startColumn=""31"" endLine=""42"" endColumn=""40"" document=""1"" />
<entry offset=""0x19f"" hidden=""true"" document=""1"" />
<entry offset=""0x1a1"" startLine=""45"" startColumn=""58"" endLine=""45"" endColumn=""67"" document=""1"" />
<entry offset=""0x1a7"" startLine=""47"" startColumn=""22"" endLine=""47"" endColumn=""32"" document=""1"" />
<entry offset=""0x1ad"" startLine=""49"" startColumn=""5"" endLine=""49"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1b0"">
<scope startOffset=""0x14d"" endOffset=""0x15e"">
<local name=""x"" il_index=""0"" il_start=""0x14d"" il_end=""0x15e"" attributes=""0"" />
</scope>
<scope startOffset=""0x163"" endOffset=""0x16a"">
<local name=""y"" il_index=""1"" il_start=""0x163"" il_end=""0x16a"" attributes=""0"" />
<local name=""z"" il_index=""2"" il_start=""0x163"" il_end=""0x16a"" attributes=""0"" />
</scope>
<scope startOffset=""0x191"" endOffset=""0x198"">
<local name=""p"" il_index=""3"" il_start=""0x191"" il_end=""0x198"" attributes=""0"" />
<local name=""q"" il_index=""4"" il_start=""0x191"" il_end=""0x198"" attributes=""0"" />
</scope>
<scope startOffset=""0x198"" endOffset=""0x19f"">
<local name=""p"" il_index=""5"" il_start=""0x198"" il_end=""0x19f"" attributes=""0"" />
</scope>
<scope startOffset=""0x19f"" endOffset=""0x1a7"">
<local name=""z"" il_index=""6"" il_start=""0x19f"" il_end=""0x1a7"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")]
[Fact]
public void Patterns_SwitchExpression()
{
string source = WithWindowsLineBreaks(@"
class C
{
public void Deconstruct() { }
public void Deconstruct(out int x) { x = 1; }
public void Deconstruct(out int x, out object y) { x = 2; y = new C(); }
}
class D
{
public int P { get; set; }
public D Q { get; set; }
public C R { get; set; }
}
class Program
{
static object F() => new C();
static bool B() => true;
static int G(int x) => x;
static void Main()
{
var a = F() switch
{
// declaration pattern
int x when G(x) > 10 => 1,
// discard pattern
bool _ => 2,
// var pattern
var (y, z) => 3,
// constant pattern
4.0 => 4,
// positional patterns
C() when B() => 5,
() => 6,
C(int p, C(int q)) => 7,
C(x: int p) => 8,
// property pattern
D { P: 1, Q: D { P: 2 }, R: C (int z) } => 9,
_ => 10,
};
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerify(c, verify: Verification.Skipped);
// note no sequence points emitted within the switch expression
verifier.VerifyIL("Program.Main", sequencePoints: "Program.Main", expectedIL: @"
{
// Code size 437 (0x1b5)
.maxstack 3
.locals init (int V_0, //a
int V_1, //x
object V_2, //y
object V_3, //z
int V_4, //p
int V_5, //q
int V_6, //p
int V_7, //z
int V_8,
object V_9,
System.Runtime.CompilerServices.ITuple V_10,
int V_11,
double V_12,
C V_13,
object V_14,
C V_15,
D V_16,
int V_17,
D V_18,
int V_19,
C V_20)
-IL_0000: nop
-IL_0001: call ""object Program.F()""
IL_0006: stloc.s V_9
IL_0008: ldc.i4.1
IL_0009: brtrue.s IL_000c
-IL_000b: nop
~IL_000c: ldloc.s V_9
IL_000e: isinst ""int""
IL_0013: brfalse.s IL_0022
IL_0015: ldloc.s V_9
IL_0017: unbox.any ""int""
IL_001c: stloc.1
~IL_001d: br IL_014d
IL_0022: ldloc.s V_9
IL_0024: isinst ""bool""
IL_0029: brtrue IL_015e
IL_002e: ldloc.s V_9
IL_0030: isinst ""System.Runtime.CompilerServices.ITuple""
IL_0035: stloc.s V_10
IL_0037: ldloc.s V_10
IL_0039: brfalse.s IL_0080
IL_003b: ldloc.s V_10
IL_003d: callvirt ""int System.Runtime.CompilerServices.ITuple.Length.get""
IL_0042: stloc.s V_11
~IL_0044: ldloc.s V_11
IL_0046: ldc.i4.2
IL_0047: bne.un.s IL_0060
IL_0049: ldloc.s V_10
IL_004b: ldc.i4.0
IL_004c: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get""
IL_0051: stloc.2
~IL_0052: ldloc.s V_10
IL_0054: ldc.i4.1
IL_0055: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get""
IL_005a: stloc.3
~IL_005b: br IL_0163
IL_0060: ldloc.s V_9
IL_0062: isinst ""C""
IL_0067: brtrue IL_016f
IL_006c: br.s IL_0077
IL_006e: ldloc.s V_11
IL_0070: brfalse IL_018c
IL_0075: br.s IL_00b5
IL_0077: ldloc.s V_11
IL_0079: brfalse IL_018c
IL_007e: br.s IL_00f5
IL_0080: ldloc.s V_9
IL_0082: isinst ""double""
IL_0087: brfalse.s IL_00a7
IL_0089: ldloc.s V_9
IL_008b: unbox.any ""double""
IL_0090: stloc.s V_12
~IL_0092: ldloc.s V_12
IL_0094: ldc.r8 4
IL_009d: beq IL_016a
IL_00a2: br IL_01a7
IL_00a7: ldloc.s V_9
IL_00a9: isinst ""C""
IL_00ae: brtrue IL_017b
IL_00b3: br.s IL_00f5
IL_00b5: ldloc.s V_9
IL_00b7: castclass ""C""
IL_00bc: stloc.s V_13
~IL_00be: ldloc.s V_13
IL_00c0: ldloca.s V_4
IL_00c2: ldloca.s V_14
IL_00c4: callvirt ""void C.Deconstruct(out int, out object)""
IL_00c9: nop
~IL_00ca: ldloc.s V_14
IL_00cc: isinst ""C""
IL_00d1: stloc.s V_15
IL_00d3: ldloc.s V_15
IL_00d5: brfalse.s IL_00e6
IL_00d7: ldloc.s V_15
IL_00d9: ldloca.s V_5
IL_00db: callvirt ""void C.Deconstruct(out int)""
IL_00e0: nop
~IL_00e1: br IL_0191
IL_00e6: ldloc.s V_13
IL_00e8: ldloca.s V_6
IL_00ea: callvirt ""void C.Deconstruct(out int)""
IL_00ef: nop
~IL_00f0: br IL_0198
IL_00f5: ldloc.s V_9
IL_00f7: isinst ""D""
IL_00fc: stloc.s V_16
IL_00fe: ldloc.s V_16
IL_0100: brfalse IL_01a7
IL_0105: ldloc.s V_16
IL_0107: callvirt ""int D.P.get""
IL_010c: stloc.s V_17
~IL_010e: ldloc.s V_17
IL_0110: ldc.i4.1
IL_0111: bne.un IL_01a7
IL_0116: ldloc.s V_16
IL_0118: callvirt ""D D.Q.get""
IL_011d: stloc.s V_18
~IL_011f: ldloc.s V_18
IL_0121: brfalse IL_01a7
IL_0126: ldloc.s V_18
IL_0128: callvirt ""int D.P.get""
IL_012d: stloc.s V_19
~IL_012f: ldloc.s V_19
IL_0131: ldc.i4.2
IL_0132: bne.un.s IL_01a7
IL_0134: ldloc.s V_16
IL_0136: callvirt ""C D.R.get""
IL_013b: stloc.s V_20
~IL_013d: ldloc.s V_20
IL_013f: brfalse.s IL_01a7
IL_0141: ldloc.s V_20
IL_0143: ldloca.s V_7
IL_0145: callvirt ""void C.Deconstruct(out int)""
IL_014a: nop
~IL_014b: br.s IL_019f
-IL_014d: ldloc.1
IL_014e: call ""int Program.G(int)""
IL_0153: ldc.i4.s 10
IL_0155: bgt.s IL_0159
~IL_0157: br.s IL_01a7
-IL_0159: ldc.i4.1
IL_015a: stloc.s V_8
IL_015c: br.s IL_01ad
-IL_015e: ldc.i4.2
IL_015f: stloc.s V_8
IL_0161: br.s IL_01ad
~IL_0163: br.s IL_0165
-IL_0165: ldc.i4.3
IL_0166: stloc.s V_8
IL_0168: br.s IL_01ad
-IL_016a: ldc.i4.4
IL_016b: stloc.s V_8
IL_016d: br.s IL_01ad
-IL_016f: call ""bool Program.B()""
IL_0174: brtrue.s IL_0187
~IL_0176: br IL_006e
-IL_017b: call ""bool Program.B()""
IL_0180: brtrue.s IL_0187
~IL_0182: br IL_00b5
-IL_0187: ldc.i4.5
IL_0188: stloc.s V_8
IL_018a: br.s IL_01ad
-IL_018c: ldc.i4.6
IL_018d: stloc.s V_8
IL_018f: br.s IL_01ad
~IL_0191: br.s IL_0193
-IL_0193: ldc.i4.7
IL_0194: stloc.s V_8
IL_0196: br.s IL_01ad
~IL_0198: br.s IL_019a
-IL_019a: ldc.i4.8
IL_019b: stloc.s V_8
IL_019d: br.s IL_01ad
~IL_019f: br.s IL_01a1
-IL_01a1: ldc.i4.s 9
IL_01a3: stloc.s V_8
IL_01a5: br.s IL_01ad
-IL_01a7: ldc.i4.s 10
IL_01a9: stloc.s V_8
IL_01ab: br.s IL_01ad
~IL_01ad: ldc.i4.1
IL_01ae: brtrue.s IL_01b1
-IL_01b0: nop
~IL_01b1: ldloc.s V_8
IL_01b3: stloc.0
-IL_01b4: ret
}
");
verifier.VerifyPdb("Program.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Deconstruct"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""0"" offset=""94"" />
<slot kind=""0"" offset=""225"" />
<slot kind=""0"" offset=""228"" />
<slot kind=""0"" offset=""406"" />
<slot kind=""0"" offset=""415"" />
<slot kind=""0"" offset=""447"" />
<slot kind=""0"" offset=""539"" />
<slot kind=""temp"" />
<slot kind=""35"" offset=""23"" />
<slot kind=""35"" offset=""23"" ordinal=""1"" />
<slot kind=""35"" offset=""23"" ordinal=""2"" />
<slot kind=""35"" offset=""23"" ordinal=""3"" />
<slot kind=""35"" offset=""23"" ordinal=""4"" />
<slot kind=""35"" offset=""23"" ordinal=""5"" />
<slot kind=""35"" offset=""23"" ordinal=""6"" />
<slot kind=""35"" offset=""23"" ordinal=""7"" />
<slot kind=""35"" offset=""23"" ordinal=""8"" />
<slot kind=""35"" offset=""23"" ordinal=""9"" />
<slot kind=""35"" offset=""23"" ordinal=""10"" />
<slot kind=""35"" offset=""23"" ordinal=""11"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""24"" startColumn=""9"" endLine=""48"" endColumn=""11"" document=""1"" />
<entry offset=""0xb"" startLine=""24"" startColumn=""21"" endLine=""48"" endColumn=""10"" document=""1"" />
<entry offset=""0xc"" hidden=""true"" document=""1"" />
<entry offset=""0x1d"" hidden=""true"" document=""1"" />
<entry offset=""0x44"" hidden=""true"" document=""1"" />
<entry offset=""0x52"" hidden=""true"" document=""1"" />
<entry offset=""0x5b"" hidden=""true"" document=""1"" />
<entry offset=""0x92"" hidden=""true"" document=""1"" />
<entry offset=""0xbe"" hidden=""true"" document=""1"" />
<entry offset=""0xca"" hidden=""true"" document=""1"" />
<entry offset=""0xe1"" hidden=""true"" document=""1"" />
<entry offset=""0xf0"" hidden=""true"" document=""1"" />
<entry offset=""0x10e"" hidden=""true"" document=""1"" />
<entry offset=""0x11f"" hidden=""true"" document=""1"" />
<entry offset=""0x12f"" hidden=""true"" document=""1"" />
<entry offset=""0x13d"" hidden=""true"" document=""1"" />
<entry offset=""0x14b"" hidden=""true"" document=""1"" />
<entry offset=""0x14d"" startLine=""27"" startColumn=""19"" endLine=""27"" endColumn=""33"" document=""1"" />
<entry offset=""0x157"" hidden=""true"" document=""1"" />
<entry offset=""0x159"" startLine=""27"" startColumn=""37"" endLine=""27"" endColumn=""38"" document=""1"" />
<entry offset=""0x15e"" startLine=""30"" startColumn=""23"" endLine=""30"" endColumn=""24"" document=""1"" />
<entry offset=""0x163"" hidden=""true"" document=""1"" />
<entry offset=""0x165"" startLine=""33"" startColumn=""27"" endLine=""33"" endColumn=""28"" document=""1"" />
<entry offset=""0x16a"" startLine=""36"" startColumn=""20"" endLine=""36"" endColumn=""21"" document=""1"" />
<entry offset=""0x16f"" startLine=""39"" startColumn=""17"" endLine=""39"" endColumn=""25"" document=""1"" />
<entry offset=""0x176"" hidden=""true"" document=""1"" />
<entry offset=""0x17b"" startLine=""39"" startColumn=""17"" endLine=""39"" endColumn=""25"" document=""1"" />
<entry offset=""0x182"" hidden=""true"" document=""1"" />
<entry offset=""0x187"" startLine=""39"" startColumn=""29"" endLine=""39"" endColumn=""30"" document=""1"" />
<entry offset=""0x18c"" startLine=""40"" startColumn=""19"" endLine=""40"" endColumn=""20"" document=""1"" />
<entry offset=""0x191"" hidden=""true"" document=""1"" />
<entry offset=""0x193"" startLine=""41"" startColumn=""35"" endLine=""41"" endColumn=""36"" document=""1"" />
<entry offset=""0x198"" hidden=""true"" document=""1"" />
<entry offset=""0x19a"" startLine=""42"" startColumn=""28"" endLine=""42"" endColumn=""29"" document=""1"" />
<entry offset=""0x19f"" hidden=""true"" document=""1"" />
<entry offset=""0x1a1"" startLine=""45"" startColumn=""56"" endLine=""45"" endColumn=""57"" document=""1"" />
<entry offset=""0x1a7"" startLine=""47"" startColumn=""18"" endLine=""47"" endColumn=""20"" document=""1"" />
<entry offset=""0x1ad"" hidden=""true"" document=""1"" />
<entry offset=""0x1b0"" startLine=""24"" startColumn=""9"" endLine=""48"" endColumn=""11"" document=""1"" />
<entry offset=""0x1b1"" hidden=""true"" document=""1"" />
<entry offset=""0x1b4"" startLine=""49"" startColumn=""5"" endLine=""49"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1b5"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x1b5"" attributes=""0"" />
<scope startOffset=""0x14d"" endOffset=""0x15e"">
<local name=""x"" il_index=""1"" il_start=""0x14d"" il_end=""0x15e"" attributes=""0"" />
</scope>
<scope startOffset=""0x163"" endOffset=""0x16a"">
<local name=""y"" il_index=""2"" il_start=""0x163"" il_end=""0x16a"" attributes=""0"" />
<local name=""z"" il_index=""3"" il_start=""0x163"" il_end=""0x16a"" attributes=""0"" />
</scope>
<scope startOffset=""0x191"" endOffset=""0x198"">
<local name=""p"" il_index=""4"" il_start=""0x191"" il_end=""0x198"" attributes=""0"" />
<local name=""q"" il_index=""5"" il_start=""0x191"" il_end=""0x198"" attributes=""0"" />
</scope>
<scope startOffset=""0x198"" endOffset=""0x19f"">
<local name=""p"" il_index=""6"" il_start=""0x198"" il_end=""0x19f"" attributes=""0"" />
</scope>
<scope startOffset=""0x19f"" endOffset=""0x1a7"">
<local name=""z"" il_index=""7"" il_start=""0x19f"" il_end=""0x1a7"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")]
[Fact]
public void Patterns_IsPattern()
{
string source = WithWindowsLineBreaks(@"
class C
{
public void Deconstruct() { }
public void Deconstruct(out int x) { x = 1; }
public void Deconstruct(out int x, out object y) { x = 2; y = new C(); }
}
class D
{
public int P { get; set; }
public D Q { get; set; }
public C R { get; set; }
}
class Program
{
static object F() => new C();
static bool B() => true;
static int G(int x) => x;
static bool M()
{
object obj = F();
return
// declaration pattern
obj is int x ||
// discard pattern
obj is bool _ ||
// var pattern
obj is var (y, z1) ||
// constant pattern
obj is 4.0 ||
// positional patterns
obj is C() ||
obj is () ||
obj is C(int p1, C(int q)) ||
obj is C(x: int p2) ||
// property pattern
obj is D { P: 1, Q: D { P: 2 }, R: C(int z2) };
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerify(c, verify: Verification.Skipped);
verifier.VerifyIL("Program.M", sequencePoints: "Program.M", expectedIL: @"
{
// Code size 301 (0x12d)
.maxstack 3
.locals init (object V_0, //obj
int V_1, //x
object V_2, //y
object V_3, //z1
int V_4, //p1
int V_5, //q
int V_6, //p2
int V_7, //z2
System.Runtime.CompilerServices.ITuple V_8,
C V_9,
object V_10,
C V_11,
D V_12,
D V_13,
bool V_14)
-IL_0000: nop
-IL_0001: call ""object Program.F()""
IL_0006: stloc.0
-IL_0007: ldloc.0
IL_0008: isinst ""int""
IL_000d: brfalse.s IL_001b
IL_000f: ldloc.0
IL_0010: unbox.any ""int""
IL_0015: stloc.1
IL_0016: br IL_0125
IL_001b: ldloc.0
IL_001c: isinst ""bool""
IL_0021: brtrue IL_0125
IL_0026: ldloc.0
IL_0027: isinst ""System.Runtime.CompilerServices.ITuple""
IL_002c: stloc.s V_8
IL_002e: ldloc.s V_8
IL_0030: brfalse.s IL_0053
IL_0032: ldloc.s V_8
IL_0034: callvirt ""int System.Runtime.CompilerServices.ITuple.Length.get""
IL_0039: ldc.i4.2
IL_003a: bne.un.s IL_0053
IL_003c: ldloc.s V_8
IL_003e: ldc.i4.0
IL_003f: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get""
IL_0044: stloc.2
IL_0045: ldloc.s V_8
IL_0047: ldc.i4.1
IL_0048: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get""
IL_004d: stloc.3
IL_004e: br IL_0125
IL_0053: ldloc.0
IL_0054: isinst ""double""
IL_0059: brfalse.s IL_006f
IL_005b: ldloc.0
IL_005c: unbox.any ""double""
IL_0061: ldc.r8 4
IL_006a: beq IL_0125
IL_006f: ldloc.0
IL_0070: isinst ""C""
IL_0075: brtrue IL_0125
IL_007a: ldloc.0
IL_007b: isinst ""System.Runtime.CompilerServices.ITuple""
IL_0080: stloc.s V_8
IL_0082: ldloc.s V_8
IL_0084: brfalse.s IL_0092
IL_0086: ldloc.s V_8
IL_0088: callvirt ""int System.Runtime.CompilerServices.ITuple.Length.get""
IL_008d: brfalse IL_0125
IL_0092: ldloc.0
IL_0093: isinst ""C""
IL_0098: stloc.s V_9
IL_009a: ldloc.s V_9
IL_009c: brfalse.s IL_00c3
IL_009e: ldloc.s V_9
IL_00a0: ldloca.s V_4
IL_00a2: ldloca.s V_10
IL_00a4: callvirt ""void C.Deconstruct(out int, out object)""
IL_00a9: nop
IL_00aa: ldloc.s V_10
IL_00ac: isinst ""C""
IL_00b1: stloc.s V_11
IL_00b3: ldloc.s V_11
IL_00b5: brfalse.s IL_00c3
IL_00b7: ldloc.s V_11
IL_00b9: ldloca.s V_5
IL_00bb: callvirt ""void C.Deconstruct(out int)""
IL_00c0: nop
IL_00c1: br.s IL_0125
IL_00c3: ldloc.0
IL_00c4: isinst ""C""
IL_00c9: stloc.s V_11
IL_00cb: ldloc.s V_11
IL_00cd: brfalse.s IL_00db
IL_00cf: ldloc.s V_11
IL_00d1: ldloca.s V_6
IL_00d3: callvirt ""void C.Deconstruct(out int)""
IL_00d8: nop
IL_00d9: br.s IL_0125
IL_00db: ldloc.0
IL_00dc: isinst ""D""
IL_00e1: stloc.s V_12
IL_00e3: ldloc.s V_12
IL_00e5: brfalse.s IL_0122
IL_00e7: ldloc.s V_12
IL_00e9: callvirt ""int D.P.get""
IL_00ee: ldc.i4.1
IL_00ef: bne.un.s IL_0122
IL_00f1: ldloc.s V_12
IL_00f3: callvirt ""D D.Q.get""
IL_00f8: stloc.s V_13
IL_00fa: ldloc.s V_13
IL_00fc: brfalse.s IL_0122
IL_00fe: ldloc.s V_13
IL_0100: callvirt ""int D.P.get""
IL_0105: ldc.i4.2
IL_0106: bne.un.s IL_0122
IL_0108: ldloc.s V_12
IL_010a: callvirt ""C D.R.get""
IL_010f: stloc.s V_11
IL_0111: ldloc.s V_11
IL_0113: brfalse.s IL_0122
IL_0115: ldloc.s V_11
IL_0117: ldloca.s V_7
IL_0119: callvirt ""void C.Deconstruct(out int)""
IL_011e: nop
IL_011f: ldc.i4.1
IL_0120: br.s IL_0123
IL_0122: ldc.i4.0
IL_0123: br.s IL_0126
IL_0125: ldc.i4.1
IL_0126: stloc.s V_14
IL_0128: br.s IL_012a
-IL_012a: ldloc.s V_14
IL_012c: ret
}
");
verifier.VerifyPdb("Program.M", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""M"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Deconstruct"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""18"" />
<slot kind=""0"" offset=""106"" />
<slot kind=""0"" offset=""230"" />
<slot kind=""0"" offset=""233"" />
<slot kind=""0"" offset=""419"" />
<slot kind=""0"" offset=""429"" />
<slot kind=""0"" offset=""465"" />
<slot kind=""0"" offset=""561"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""26"" document=""1"" />
<entry offset=""0x7"" startLine=""25"" startColumn=""9"" endLine=""45"" endColumn=""60"" document=""1"" />
<entry offset=""0x12a"" startLine=""46"" startColumn=""5"" endLine=""46"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x12d"">
<local name=""obj"" il_index=""0"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
<local name=""x"" il_index=""1"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
<local name=""y"" il_index=""2"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
<local name=""z1"" il_index=""3"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
<local name=""p1"" il_index=""4"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
<local name=""q"" il_index=""5"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
<local name=""p2"" il_index=""6"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
<local name=""z2"" il_index=""7"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")]
[WorkItem(37232, "https://github.com/dotnet/roslyn/issues/37232")]
[WorkItem(37237, "https://github.com/dotnet/roslyn/issues/37237")]
[Fact]
public void Patterns_SwitchExpression_Closures()
{
string source = WithWindowsLineBreaks(@"
using System;
public class C
{
static int M()
{
return F() switch
{
1 => F() switch
{
C { P: int p, Q: C { P: int q } } => G(() => p + q),
_ => 10
},
2 => F() switch
{
C { P: int r } => G(() => r),
_ => 20
},
C { Q: int s } => G(() => s),
_ => 0
}
switch
{
var t when t > 0 => G(() => t),
_ => 0
};
}
object P { get; set; }
object Q { get; set; }
static object F() => null;
static int G(Func<int> f) => 0;
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var verifier = CompileAndVerify(c);
verifier.VerifyIL("C.M", sequencePoints: "C.M", source: source, expectedIL: @"
{
// Code size 472 (0x1d8)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
int V_1,
C.<>c__DisplayClass0_1 V_2, //CS$<>8__locals1
int V_3,
object V_4,
int V_5,
C V_6,
object V_7,
C.<>c__DisplayClass0_2 V_8, //CS$<>8__locals2
int V_9,
object V_10,
C V_11,
object V_12,
object V_13,
C V_14,
object V_15,
C.<>c__DisplayClass0_3 V_16, //CS$<>8__locals3
object V_17,
C V_18,
object V_19,
int V_20)
// sequence point: {
IL_0000: nop
// sequence point: <hidden>
IL_0001: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0006: stloc.0
// sequence point: <hidden>
IL_0007: newobj ""C.<>c__DisplayClass0_1..ctor()""
IL_000c: stloc.2
IL_000d: call ""object C.F()""
IL_0012: stloc.s V_4
IL_0014: ldc.i4.1
IL_0015: brtrue.s IL_0018
// sequence point: switch ... }
IL_0017: nop
// sequence point: <hidden>
IL_0018: ldloc.s V_4
IL_001a: isinst ""int""
IL_001f: brfalse.s IL_003e
IL_0021: ldloc.s V_4
IL_0023: unbox.any ""int""
IL_0028: stloc.s V_5
// sequence point: <hidden>
IL_002a: ldloc.s V_5
IL_002c: ldc.i4.1
IL_002d: beq.s IL_0075
IL_002f: br.s IL_0031
IL_0031: ldloc.s V_5
IL_0033: ldc.i4.2
IL_0034: beq IL_0116
IL_0039: br IL_0194
IL_003e: ldloc.s V_4
IL_0040: isinst ""C""
IL_0045: stloc.s V_6
IL_0047: ldloc.s V_6
IL_0049: brfalse IL_0194
IL_004e: ldloc.s V_6
IL_0050: callvirt ""object C.Q.get""
IL_0055: stloc.s V_7
// sequence point: <hidden>
IL_0057: ldloc.s V_7
IL_0059: isinst ""int""
IL_005e: brfalse IL_0194
IL_0063: ldloc.2
IL_0064: ldloc.s V_7
IL_0066: unbox.any ""int""
IL_006b: stfld ""int C.<>c__DisplayClass0_1.<s>5__3""
// sequence point: <hidden>
IL_0070: br IL_017e
// sequence point: <hidden>
IL_0075: newobj ""C.<>c__DisplayClass0_2..ctor()""
IL_007a: stloc.s V_8
IL_007c: call ""object C.F()""
IL_0081: stloc.s V_10
IL_0083: ldc.i4.1
IL_0084: brtrue.s IL_0087
// sequence point: switch ...
IL_0086: nop
// sequence point: <hidden>
IL_0087: ldloc.s V_10
IL_0089: isinst ""C""
IL_008e: stloc.s V_11
IL_0090: ldloc.s V_11
IL_0092: brfalse.s IL_0104
IL_0094: ldloc.s V_11
IL_0096: callvirt ""object C.P.get""
IL_009b: stloc.s V_12
// sequence point: <hidden>
IL_009d: ldloc.s V_12
IL_009f: isinst ""int""
IL_00a4: brfalse.s IL_0104
IL_00a6: ldloc.s V_8
IL_00a8: ldloc.s V_12
IL_00aa: unbox.any ""int""
IL_00af: stfld ""int C.<>c__DisplayClass0_2.<p>5__4""
// sequence point: <hidden>
IL_00b4: ldloc.s V_11
IL_00b6: callvirt ""object C.Q.get""
IL_00bb: stloc.s V_13
// sequence point: <hidden>
IL_00bd: ldloc.s V_13
IL_00bf: isinst ""C""
IL_00c4: stloc.s V_14
IL_00c6: ldloc.s V_14
IL_00c8: brfalse.s IL_0104
IL_00ca: ldloc.s V_14
IL_00cc: callvirt ""object C.P.get""
IL_00d1: stloc.s V_15
// sequence point: <hidden>
IL_00d3: ldloc.s V_15
IL_00d5: isinst ""int""
IL_00da: brfalse.s IL_0104
IL_00dc: ldloc.s V_8
IL_00de: ldloc.s V_15
IL_00e0: unbox.any ""int""
IL_00e5: stfld ""int C.<>c__DisplayClass0_2.<q>5__5""
// sequence point: <hidden>
IL_00ea: br.s IL_00ec
// sequence point: <hidden>
IL_00ec: br.s IL_00ee
// sequence point: G(() => p + q)
IL_00ee: ldloc.s V_8
IL_00f0: ldftn ""int C.<>c__DisplayClass0_2.<M>b__2()""
IL_00f6: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_00fb: call ""int C.G(System.Func<int>)""
IL_0100: stloc.s V_9
IL_0102: br.s IL_010a
// sequence point: 10
IL_0104: ldc.i4.s 10
IL_0106: stloc.s V_9
IL_0108: br.s IL_010a
// sequence point: <hidden>
IL_010a: ldc.i4.1
IL_010b: brtrue.s IL_010e
// sequence point: switch ... }
IL_010d: nop
// sequence point: F() switch ...
IL_010e: ldloc.s V_9
IL_0110: stloc.3
IL_0111: br IL_0198
// sequence point: <hidden>
IL_0116: newobj ""C.<>c__DisplayClass0_3..ctor()""
IL_011b: stloc.s V_16
IL_011d: call ""object C.F()""
IL_0122: stloc.s V_17
IL_0124: ldc.i4.1
IL_0125: brtrue.s IL_0128
// sequence point: switch ...
IL_0127: nop
// sequence point: <hidden>
IL_0128: ldloc.s V_17
IL_012a: isinst ""C""
IL_012f: stloc.s V_18
IL_0131: ldloc.s V_18
IL_0133: brfalse.s IL_016f
IL_0135: ldloc.s V_18
IL_0137: callvirt ""object C.P.get""
IL_013c: stloc.s V_19
// sequence point: <hidden>
IL_013e: ldloc.s V_19
IL_0140: isinst ""int""
IL_0145: brfalse.s IL_016f
IL_0147: ldloc.s V_16
IL_0149: ldloc.s V_19
IL_014b: unbox.any ""int""
IL_0150: stfld ""int C.<>c__DisplayClass0_3.<r>5__6""
// sequence point: <hidden>
IL_0155: br.s IL_0157
// sequence point: <hidden>
IL_0157: br.s IL_0159
// sequence point: G(() => r)
IL_0159: ldloc.s V_16
IL_015b: ldftn ""int C.<>c__DisplayClass0_3.<M>b__3()""
IL_0161: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_0166: call ""int C.G(System.Func<int>)""
IL_016b: stloc.s V_9
IL_016d: br.s IL_0175
// sequence point: 20
IL_016f: ldc.i4.s 20
IL_0171: stloc.s V_9
IL_0173: br.s IL_0175
// sequence point: <hidden>
IL_0175: ldc.i4.1
IL_0176: brtrue.s IL_0179
// sequence point: F() switch ...
IL_0178: nop
// sequence point: F() switch ...
IL_0179: ldloc.s V_9
IL_017b: stloc.3
IL_017c: br.s IL_0198
// sequence point: <hidden>
IL_017e: br.s IL_0180
// sequence point: G(() => s)
IL_0180: ldloc.2
IL_0181: ldftn ""int C.<>c__DisplayClass0_1.<M>b__1()""
IL_0187: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_018c: call ""int C.G(System.Func<int>)""
IL_0191: stloc.3
IL_0192: br.s IL_0198
// sequence point: 0
IL_0194: ldc.i4.0
IL_0195: stloc.3
IL_0196: br.s IL_0198
// sequence point: <hidden>
IL_0198: ldc.i4.1
IL_0199: brtrue.s IL_019c
// sequence point: return F() s ... };
IL_019b: nop
// sequence point: <hidden>
IL_019c: ldloc.0
IL_019d: ldloc.3
IL_019e: stfld ""int C.<>c__DisplayClass0_0.<t>5__2""
IL_01a3: ldc.i4.1
IL_01a4: brtrue.s IL_01a7
// sequence point: switch ... }
IL_01a6: nop
// sequence point: <hidden>
IL_01a7: br.s IL_01a9
// sequence point: when t > 0
IL_01a9: ldloc.0
IL_01aa: ldfld ""int C.<>c__DisplayClass0_0.<t>5__2""
IL_01af: ldc.i4.0
IL_01b0: bgt.s IL_01b4
// sequence point: <hidden>
IL_01b2: br.s IL_01c8
// sequence point: G(() => t)
IL_01b4: ldloc.0
IL_01b5: ldftn ""int C.<>c__DisplayClass0_0.<M>b__0()""
IL_01bb: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_01c0: call ""int C.G(System.Func<int>)""
IL_01c5: stloc.1
IL_01c6: br.s IL_01cc
// sequence point: 0
IL_01c8: ldc.i4.0
IL_01c9: stloc.1
IL_01ca: br.s IL_01cc
// sequence point: <hidden>
IL_01cc: ldc.i4.1
IL_01cd: brtrue.s IL_01d0
// sequence point: return F() s ... };
IL_01cf: nop
// sequence point: <hidden>
IL_01d0: ldloc.1
IL_01d1: stloc.s V_20
IL_01d3: br.s IL_01d5
// sequence point: }
IL_01d5: ldloc.s V_20
IL_01d7: ret
}
");
verifier.VerifyPdb("C.M", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""30"" offset=""11"" />
<slot kind=""temp"" />
<slot kind=""30"" offset=""22"" />
<slot kind=""temp"" />
<slot kind=""35"" offset=""22"" />
<slot kind=""35"" offset=""22"" ordinal=""1"" />
<slot kind=""35"" offset=""22"" ordinal=""2"" />
<slot kind=""35"" offset=""22"" ordinal=""3"" />
<slot kind=""30"" offset=""63"" />
<slot kind=""temp"" />
<slot kind=""35"" offset=""63"" />
<slot kind=""35"" offset=""63"" ordinal=""1"" />
<slot kind=""35"" offset=""63"" ordinal=""2"" />
<slot kind=""35"" offset=""63"" ordinal=""3"" />
<slot kind=""35"" offset=""63"" ordinal=""4"" />
<slot kind=""35"" offset=""63"" ordinal=""5"" />
<slot kind=""30"" offset=""238"" />
<slot kind=""35"" offset=""238"" />
<slot kind=""35"" offset=""238"" ordinal=""1"" />
<slot kind=""35"" offset=""238"" ordinal=""2"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""11"" />
<closure offset=""22"" />
<closure offset=""63"" />
<closure offset=""238"" />
<lambda offset=""511"" closure=""0"" />
<lambda offset=""407"" closure=""1"" />
<lambda offset=""157"" closure=""2"" />
<lambda offset=""313"" closure=""3"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" hidden=""true"" document=""1"" />
<entry offset=""0x17"" startLine=""7"" startColumn=""20"" endLine=""21"" endColumn=""10"" document=""1"" />
<entry offset=""0x18"" hidden=""true"" document=""1"" />
<entry offset=""0x2a"" hidden=""true"" document=""1"" />
<entry offset=""0x57"" hidden=""true"" document=""1"" />
<entry offset=""0x70"" hidden=""true"" document=""1"" />
<entry offset=""0x75"" hidden=""true"" document=""1"" />
<entry offset=""0x86"" startLine=""9"" startColumn=""22"" endLine=""13"" endColumn=""19"" document=""1"" />
<entry offset=""0x87"" hidden=""true"" document=""1"" />
<entry offset=""0x9d"" hidden=""true"" document=""1"" />
<entry offset=""0xb4"" hidden=""true"" document=""1"" />
<entry offset=""0xbd"" hidden=""true"" document=""1"" />
<entry offset=""0xd3"" hidden=""true"" document=""1"" />
<entry offset=""0xea"" hidden=""true"" document=""1"" />
<entry offset=""0xec"" hidden=""true"" document=""1"" />
<entry offset=""0xee"" startLine=""11"" startColumn=""59"" endLine=""11"" endColumn=""73"" document=""1"" />
<entry offset=""0x104"" startLine=""12"" startColumn=""27"" endLine=""12"" endColumn=""29"" document=""1"" />
<entry offset=""0x10a"" hidden=""true"" document=""1"" />
<entry offset=""0x10d"" startLine=""7"" startColumn=""20"" endLine=""21"" endColumn=""10"" document=""1"" />
<entry offset=""0x10e"" startLine=""9"" startColumn=""18"" endLine=""13"" endColumn=""19"" document=""1"" />
<entry offset=""0x116"" hidden=""true"" document=""1"" />
<entry offset=""0x127"" startLine=""14"" startColumn=""22"" endLine=""18"" endColumn=""19"" document=""1"" />
<entry offset=""0x128"" hidden=""true"" document=""1"" />
<entry offset=""0x13e"" hidden=""true"" document=""1"" />
<entry offset=""0x155"" hidden=""true"" document=""1"" />
<entry offset=""0x157"" hidden=""true"" document=""1"" />
<entry offset=""0x159"" startLine=""16"" startColumn=""40"" endLine=""16"" endColumn=""50"" document=""1"" />
<entry offset=""0x16f"" startLine=""17"" startColumn=""27"" endLine=""17"" endColumn=""29"" document=""1"" />
<entry offset=""0x175"" hidden=""true"" document=""1"" />
<entry offset=""0x178"" startLine=""9"" startColumn=""18"" endLine=""13"" endColumn=""19"" document=""1"" />
<entry offset=""0x179"" startLine=""14"" startColumn=""18"" endLine=""18"" endColumn=""19"" document=""1"" />
<entry offset=""0x17e"" hidden=""true"" document=""1"" />
<entry offset=""0x180"" startLine=""19"" startColumn=""31"" endLine=""19"" endColumn=""41"" document=""1"" />
<entry offset=""0x194"" startLine=""20"" startColumn=""18"" endLine=""20"" endColumn=""19"" document=""1"" />
<entry offset=""0x198"" hidden=""true"" document=""1"" />
<entry offset=""0x19b"" startLine=""7"" startColumn=""9"" endLine=""26"" endColumn=""11"" document=""1"" />
<entry offset=""0x19c"" hidden=""true"" document=""1"" />
<entry offset=""0x1a6"" startLine=""22"" startColumn=""9"" endLine=""26"" endColumn=""10"" document=""1"" />
<entry offset=""0x1a7"" hidden=""true"" document=""1"" />
<entry offset=""0x1a9"" startLine=""24"" startColumn=""19"" endLine=""24"" endColumn=""29"" document=""1"" />
<entry offset=""0x1b2"" hidden=""true"" document=""1"" />
<entry offset=""0x1b4"" startLine=""24"" startColumn=""33"" endLine=""24"" endColumn=""43"" document=""1"" />
<entry offset=""0x1c8"" startLine=""25"" startColumn=""18"" endLine=""25"" endColumn=""19"" document=""1"" />
<entry offset=""0x1cc"" hidden=""true"" document=""1"" />
<entry offset=""0x1cf"" startLine=""7"" startColumn=""9"" endLine=""26"" endColumn=""11"" document=""1"" />
<entry offset=""0x1d0"" hidden=""true"" document=""1"" />
<entry offset=""0x1d5"" startLine=""27"" startColumn=""5"" endLine=""27"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1d8"">
<namespace name=""System"" />
<scope startOffset=""0x1"" endOffset=""0x1d5"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x1"" il_end=""0x1d5"" attributes=""0"" />
<scope startOffset=""0x7"" endOffset=""0x1a3"">
<local name=""CS$<>8__locals1"" il_index=""2"" il_start=""0x7"" il_end=""0x1a3"" attributes=""0"" />
<scope startOffset=""0x75"" endOffset=""0x111"">
<local name=""CS$<>8__locals2"" il_index=""8"" il_start=""0x75"" il_end=""0x111"" attributes=""0"" />
</scope>
<scope startOffset=""0x116"" endOffset=""0x17c"">
<local name=""CS$<>8__locals3"" il_index=""16"" il_start=""0x116"" il_end=""0x17c"" attributes=""0"" />
</scope>
</scope>
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(50321, "https://github.com/dotnet/roslyn/issues/50321")]
[ConditionalFact(typeof(CoreClrOnly))]
public void NestedSwitchExpressions_Closures_01()
{
string source = WithWindowsLineBreaks(
@"using System;
class C
{
static int F(object o)
{
return o switch
{
int i => new Func<int>(() => i + i switch
{
1 => 2,
_ => 3
})(),
_ => 4
};
}
}");
var verifier = CompileAndVerify(source, options: TestOptions.DebugDll);
verifier.VerifyTypeIL("C",
@".class private auto ansi beforefieldinit C
extends [netstandard]System.Object
{
// Nested Types
.class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0'
extends [netstandard]System.Object
{
.custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
01 00 00 00
)
// Fields
.field public int32 '<i>5__2'
// Methods
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x20a1
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [netstandard]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method '<>c__DisplayClass0_0'::.ctor
.method assembly hidebysig
instance int32 '<F>b__0' () cil managed
{
// Method begins at RVA 0x20ac
// Code size 38 (0x26)
.maxstack 2
.locals init (
[0] int32,
[1] int32
)
IL_0000: ldarg.0
IL_0001: ldfld int32 C/'<>c__DisplayClass0_0'::'<i>5__2'
IL_0006: stloc.0
IL_0007: ldc.i4.1
IL_0008: brtrue.s IL_000b
IL_000a: nop
IL_000b: ldarg.0
IL_000c: ldfld int32 C/'<>c__DisplayClass0_0'::'<i>5__2'
IL_0011: ldc.i4.1
IL_0012: beq.s IL_0016
IL_0014: br.s IL_001a
IL_0016: ldc.i4.2
IL_0017: stloc.1
IL_0018: br.s IL_001e
IL_001a: ldc.i4.3
IL_001b: stloc.1
IL_001c: br.s IL_001e
IL_001e: ldc.i4.1
IL_001f: brtrue.s IL_0022
IL_0021: nop
IL_0022: ldloc.0
IL_0023: ldloc.1
IL_0024: add
IL_0025: ret
} // end of method '<>c__DisplayClass0_0'::'<F>b__0'
} // end of class <>c__DisplayClass0_0
// Methods
.method private hidebysig static
int32 F (
object o
) cil managed
{
// Method begins at RVA 0x2050
// Code size 69 (0x45)
.maxstack 2
.locals init (
[0] class C/'<>c__DisplayClass0_0',
[1] int32,
[2] int32
)
IL_0000: nop
IL_0001: newobj instance void C/'<>c__DisplayClass0_0'::.ctor()
IL_0006: stloc.0
IL_0007: ldc.i4.1
IL_0008: brtrue.s IL_000b
IL_000a: nop
IL_000b: ldarg.0
IL_000c: isinst [netstandard]System.Int32
IL_0011: brfalse.s IL_0037
IL_0013: ldloc.0
IL_0014: ldarg.0
IL_0015: unbox.any [netstandard]System.Int32
IL_001a: stfld int32 C/'<>c__DisplayClass0_0'::'<i>5__2'
IL_001f: br.s IL_0021
IL_0021: br.s IL_0023
IL_0023: ldloc.0
IL_0024: ldftn instance int32 C/'<>c__DisplayClass0_0'::'<F>b__0'()
IL_002a: newobj instance void class [netstandard]System.Func`1<int32>::.ctor(object, native int)
IL_002f: callvirt instance !0 class [netstandard]System.Func`1<int32>::Invoke()
IL_0034: stloc.1
IL_0035: br.s IL_003b
IL_0037: ldc.i4.4
IL_0038: stloc.1
IL_0039: br.s IL_003b
IL_003b: ldc.i4.1
IL_003c: brtrue.s IL_003f
IL_003e: nop
IL_003f: ldloc.1
IL_0040: stloc.2
IL_0041: br.s IL_0043
IL_0043: ldloc.2
IL_0044: ret
} // end of method C::F
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x20a1
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [netstandard]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method C::.ctor
} // end of class C
");
verifier.VerifyPdb(
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"" parameterNames=""o"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""30"" offset=""11"" />
<slot kind=""temp"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""11"" />
<lambda offset=""80"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" hidden=""true"" document=""1"" />
<entry offset=""0xa"" startLine=""6"" startColumn=""18"" endLine=""14"" endColumn=""10"" document=""1"" />
<entry offset=""0xb"" hidden=""true"" document=""1"" />
<entry offset=""0x1f"" hidden=""true"" document=""1"" />
<entry offset=""0x21"" hidden=""true"" document=""1"" />
<entry offset=""0x23"" startLine=""8"" startColumn=""22"" endLine=""12"" endColumn=""17"" document=""1"" />
<entry offset=""0x37"" startLine=""13"" startColumn=""18"" endLine=""13"" endColumn=""19"" document=""1"" />
<entry offset=""0x3b"" hidden=""true"" document=""1"" />
<entry offset=""0x3e"" startLine=""6"" startColumn=""9"" endLine=""14"" endColumn=""11"" document=""1"" />
<entry offset=""0x3f"" hidden=""true"" document=""1"" />
<entry offset=""0x43"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x45"">
<namespace name=""System"" />
<scope startOffset=""0x1"" endOffset=""0x43"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x1"" il_end=""0x43"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""C+<>c__DisplayClass0_0"" name=""<F>b__0"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" parameterNames=""o"" />
<encLocalSlotMap>
<slot kind=""28"" offset=""86"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""42"" endLine=""12"" endColumn=""14"" document=""1"" />
<entry offset=""0xa"" startLine=""8"" startColumn=""48"" endLine=""12"" endColumn=""14"" document=""1"" />
<entry offset=""0xb"" hidden=""true"" document=""1"" />
<entry offset=""0x16"" startLine=""10"" startColumn=""22"" endLine=""10"" endColumn=""23"" document=""1"" />
<entry offset=""0x1a"" startLine=""11"" startColumn=""22"" endLine=""11"" endColumn=""23"" document=""1"" />
<entry offset=""0x1e"" hidden=""true"" document=""1"" />
<entry offset=""0x21"" startLine=""8"" startColumn=""42"" endLine=""12"" endColumn=""14"" document=""1"" />
<entry offset=""0x22"" hidden=""true"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(50321, "https://github.com/dotnet/roslyn/issues/50321")]
[ConditionalFact(typeof(CoreClrOnly))]
public void NestedSwitchExpressions_Closures_02()
{
string source = WithWindowsLineBreaks(
@"using System;
class C
{
static string F(object o)
{
return o switch
{
int i => new Func<string>(() => ""1"" + i switch
{
1 => new Func<string>(() => ""2"" + i)(),
_ => ""3""
})(),
_ => ""4""
};
}
}");
var verifier = CompileAndVerify(source, options: TestOptions.DebugDll);
verifier.VerifyTypeIL("C",
@".class private auto ansi beforefieldinit C
extends [netstandard]System.Object
{
// Nested Types
.class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0'
extends [netstandard]System.Object
{
.custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
01 00 00 00
)
// Fields
.field public int32 '<i>5__2'
.field public class [netstandard]System.Func`1<string> '<>9__1'
// Methods
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x20a5
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [netstandard]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method '<>c__DisplayClass0_0'::.ctor
.method assembly hidebysig
instance string '<F>b__0' () cil managed
{
// Method begins at RVA 0x20b0
// Code size 78 (0x4e)
.maxstack 3
.locals init (
[0] string,
[1] class [netstandard]System.Func`1<string>
)
IL_0000: ldc.i4.1
IL_0001: brtrue.s IL_0004
IL_0003: nop
IL_0004: ldarg.0
IL_0005: ldfld int32 C/'<>c__DisplayClass0_0'::'<i>5__2'
IL_000a: ldc.i4.1
IL_000b: beq.s IL_000f
IL_000d: br.s IL_0036
IL_000f: ldarg.0
IL_0010: ldfld class [netstandard]System.Func`1<string> C/'<>c__DisplayClass0_0'::'<>9__1'
IL_0015: dup
IL_0016: brtrue.s IL_002e
IL_0018: pop
IL_0019: ldarg.0
IL_001a: ldarg.0
IL_001b: ldftn instance string C/'<>c__DisplayClass0_0'::'<F>b__1'()
IL_0021: newobj instance void class [netstandard]System.Func`1<string>::.ctor(object, native int)
IL_0026: dup
IL_0027: stloc.1
IL_0028: stfld class [netstandard]System.Func`1<string> C/'<>c__DisplayClass0_0'::'<>9__1'
IL_002d: ldloc.1
IL_002e: callvirt instance !0 class [netstandard]System.Func`1<string>::Invoke()
IL_0033: stloc.0
IL_0034: br.s IL_003e
IL_0036: ldstr ""3""
IL_003b: stloc.0
IL_003c: br.s IL_003e
IL_003e: ldc.i4.1
IL_003f: brtrue.s IL_0042
IL_0041: nop
IL_0042: ldstr ""1""
IL_0047: ldloc.0
IL_0048: call string [netstandard]System.String::Concat(string, string)
IL_004d: ret
} // end of method '<>c__DisplayClass0_0'::'<F>b__0'
.method assembly hidebysig
instance string '<F>b__1' () cil managed
{
// Method begins at RVA 0x210a
// Code size 22 (0x16)
.maxstack 8
IL_0000: ldstr ""2""
IL_0005: ldarg.0
IL_0006: ldflda int32 C/'<>c__DisplayClass0_0'::'<i>5__2'
IL_000b: call instance string [netstandard]System.Int32::ToString()
IL_0010: call string [netstandard]System.String::Concat(string, string)
IL_0015: ret
} // end of method '<>c__DisplayClass0_0'::'<F>b__1'
} // end of class <>c__DisplayClass0_0
// Methods
.method private hidebysig static
string F (
object o
) cil managed
{
// Method begins at RVA 0x2050
// Code size 73 (0x49)
.maxstack 2
.locals init (
[0] class C/'<>c__DisplayClass0_0',
[1] string,
[2] string
)
IL_0000: nop
IL_0001: newobj instance void C/'<>c__DisplayClass0_0'::.ctor()
IL_0006: stloc.0
IL_0007: ldc.i4.1
IL_0008: brtrue.s IL_000b
IL_000a: nop
IL_000b: ldarg.0
IL_000c: isinst [netstandard]System.Int32
IL_0011: brfalse.s IL_0037
IL_0013: ldloc.0
IL_0014: ldarg.0
IL_0015: unbox.any [netstandard]System.Int32
IL_001a: stfld int32 C/'<>c__DisplayClass0_0'::'<i>5__2'
IL_001f: br.s IL_0021
IL_0021: br.s IL_0023
IL_0023: ldloc.0
IL_0024: ldftn instance string C/'<>c__DisplayClass0_0'::'<F>b__0'()
IL_002a: newobj instance void class [netstandard]System.Func`1<string>::.ctor(object, native int)
IL_002f: callvirt instance !0 class [netstandard]System.Func`1<string>::Invoke()
IL_0034: stloc.1
IL_0035: br.s IL_003f
IL_0037: ldstr ""4""
IL_003c: stloc.1
IL_003d: br.s IL_003f
IL_003f: ldc.i4.1
IL_0040: brtrue.s IL_0043
IL_0042: nop
IL_0043: ldloc.1
IL_0044: stloc.2
IL_0045: br.s IL_0047
IL_0047: ldloc.2
IL_0048: ret
} // end of method C::F
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x20a5
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [netstandard]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method C::.ctor
} // end of class C
");
verifier.VerifyPdb(
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"" parameterNames=""o"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""30"" offset=""11"" />
<slot kind=""temp"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""11"" />
<lambda offset=""83"" closure=""0"" />
<lambda offset=""158"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" hidden=""true"" document=""1"" />
<entry offset=""0xa"" startLine=""6"" startColumn=""18"" endLine=""14"" endColumn=""10"" document=""1"" />
<entry offset=""0xb"" hidden=""true"" document=""1"" />
<entry offset=""0x1f"" hidden=""true"" document=""1"" />
<entry offset=""0x21"" hidden=""true"" document=""1"" />
<entry offset=""0x23"" startLine=""8"" startColumn=""22"" endLine=""12"" endColumn=""17"" document=""1"" />
<entry offset=""0x37"" startLine=""13"" startColumn=""18"" endLine=""13"" endColumn=""21"" document=""1"" />
<entry offset=""0x3f"" hidden=""true"" document=""1"" />
<entry offset=""0x42"" startLine=""6"" startColumn=""9"" endLine=""14"" endColumn=""11"" document=""1"" />
<entry offset=""0x43"" hidden=""true"" document=""1"" />
<entry offset=""0x47"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x49"">
<namespace name=""System"" />
<scope startOffset=""0x1"" endOffset=""0x47"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x1"" il_end=""0x47"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""C+<>c__DisplayClass0_0"" name=""<F>b__0"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" parameterNames=""o"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""45"" endLine=""12"" endColumn=""14"" document=""1"" />
<entry offset=""0x3"" startLine=""8"" startColumn=""53"" endLine=""12"" endColumn=""14"" document=""1"" />
<entry offset=""0x4"" hidden=""true"" document=""1"" />
<entry offset=""0xf"" startLine=""10"" startColumn=""22"" endLine=""10"" endColumn=""55"" document=""1"" />
<entry offset=""0x36"" startLine=""11"" startColumn=""22"" endLine=""11"" endColumn=""25"" document=""1"" />
<entry offset=""0x3e"" hidden=""true"" document=""1"" />
<entry offset=""0x41"" startLine=""8"" startColumn=""45"" endLine=""12"" endColumn=""14"" document=""1"" />
<entry offset=""0x42"" hidden=""true"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C+<>c__DisplayClass0_0"" name=""<F>b__1"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" parameterNames=""o"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""45"" endLine=""10"" endColumn=""52"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(37261, "https://github.com/dotnet/roslyn/issues/37261")]
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SwitchExpression_MethodBody()
{
string source = @"
using System;
public class C
{
static int M() => F() switch
{
1 => 1,
C { P: int p, Q: C { P: int q } } => G(() => p + q),
_ => 0
};
object P { get; set; }
object Q { get; set; }
static object F() => null;
static int G(Func<int> f) => 0;
}
";
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var verifier = CompileAndVerify(c);
verifier.VerifyIL("C.M", sequencePoints: "C.M", source: source, expectedIL: @"
{
// Code size 171 (0xab)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
int V_1,
object V_2,
int V_3,
C V_4,
object V_5,
object V_6,
C V_7,
object V_8)
// sequence point: <hidden>
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: call ""object C.F()""
IL_000b: stloc.2
IL_000c: ldc.i4.1
IL_000d: brtrue.s IL_0010
// sequence point: switch ... }
IL_000f: nop
// sequence point: <hidden>
IL_0010: ldloc.2
IL_0011: isinst ""int""
IL_0016: brfalse.s IL_0025
IL_0018: ldloc.2
IL_0019: unbox.any ""int""
IL_001e: stloc.3
// sequence point: <hidden>
IL_001f: ldloc.3
IL_0020: ldc.i4.1
IL_0021: beq.s IL_0087
IL_0023: br.s IL_00a1
IL_0025: ldloc.2
IL_0026: isinst ""C""
IL_002b: stloc.s V_4
IL_002d: ldloc.s V_4
IL_002f: brfalse.s IL_00a1
IL_0031: ldloc.s V_4
IL_0033: callvirt ""object C.P.get""
IL_0038: stloc.s V_5
// sequence point: <hidden>
IL_003a: ldloc.s V_5
IL_003c: isinst ""int""
IL_0041: brfalse.s IL_00a1
IL_0043: ldloc.0
IL_0044: ldloc.s V_5
IL_0046: unbox.any ""int""
IL_004b: stfld ""int C.<>c__DisplayClass0_0.<p>5__2""
// sequence point: <hidden>
IL_0050: ldloc.s V_4
IL_0052: callvirt ""object C.Q.get""
IL_0057: stloc.s V_6
// sequence point: <hidden>
IL_0059: ldloc.s V_6
IL_005b: isinst ""C""
IL_0060: stloc.s V_7
IL_0062: ldloc.s V_7
IL_0064: brfalse.s IL_00a1
IL_0066: ldloc.s V_7
IL_0068: callvirt ""object C.P.get""
IL_006d: stloc.s V_8
// sequence point: <hidden>
IL_006f: ldloc.s V_8
IL_0071: isinst ""int""
IL_0076: brfalse.s IL_00a1
IL_0078: ldloc.0
IL_0079: ldloc.s V_8
IL_007b: unbox.any ""int""
IL_0080: stfld ""int C.<>c__DisplayClass0_0.<q>5__3""
// sequence point: <hidden>
IL_0085: br.s IL_008b
// sequence point: 1
IL_0087: ldc.i4.1
IL_0088: stloc.1
IL_0089: br.s IL_00a5
// sequence point: <hidden>
IL_008b: br.s IL_008d
// sequence point: G(() => p + q)
IL_008d: ldloc.0
IL_008e: ldftn ""int C.<>c__DisplayClass0_0.<M>b__0()""
IL_0094: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_0099: call ""int C.G(System.Func<int>)""
IL_009e: stloc.1
IL_009f: br.s IL_00a5
// sequence point: 0
IL_00a1: ldc.i4.0
IL_00a2: stloc.1
IL_00a3: br.s IL_00a5
// sequence point: <hidden>
IL_00a5: ldc.i4.1
IL_00a6: brtrue.s IL_00a9
// sequence point: F() switch ... }
IL_00a8: nop
// sequence point: <hidden>
IL_00a9: ldloc.1
IL_00aa: ret
}
");
verifier.VerifyPdb("C.M", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""30"" offset=""7"" />
<slot kind=""temp"" />
<slot kind=""35"" offset=""7"" />
<slot kind=""35"" offset=""7"" ordinal=""1"" />
<slot kind=""35"" offset=""7"" ordinal=""2"" />
<slot kind=""35"" offset=""7"" ordinal=""3"" />
<slot kind=""35"" offset=""7"" ordinal=""4"" />
<slot kind=""35"" offset=""7"" ordinal=""5"" />
<slot kind=""35"" offset=""7"" ordinal=""6"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""7"" />
<lambda offset=""92"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0xf"" startLine=""5"" startColumn=""27"" endLine=""10"" endColumn=""6"" document=""1"" />
<entry offset=""0x10"" hidden=""true"" document=""1"" />
<entry offset=""0x1f"" hidden=""true"" document=""1"" />
<entry offset=""0x3a"" hidden=""true"" document=""1"" />
<entry offset=""0x50"" hidden=""true"" document=""1"" />
<entry offset=""0x59"" hidden=""true"" document=""1"" />
<entry offset=""0x6f"" hidden=""true"" document=""1"" />
<entry offset=""0x85"" hidden=""true"" document=""1"" />
<entry offset=""0x87"" startLine=""7"" startColumn=""14"" endLine=""7"" endColumn=""15"" document=""1"" />
<entry offset=""0x8b"" hidden=""true"" document=""1"" />
<entry offset=""0x8d"" startLine=""8"" startColumn=""46"" endLine=""8"" endColumn=""60"" document=""1"" />
<entry offset=""0xa1"" startLine=""9"" startColumn=""14"" endLine=""9"" endColumn=""15"" document=""1"" />
<entry offset=""0xa5"" hidden=""true"" document=""1"" />
<entry offset=""0xa8"" startLine=""5"" startColumn=""23"" endLine=""10"" endColumn=""6"" document=""1"" />
<entry offset=""0xa9"" hidden=""true"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xab"">
<namespace name=""System"" />
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0xab"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(37261, "https://github.com/dotnet/roslyn/issues/37261")]
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SwitchExpression_MethodBody_02()
{
string source = @"
using System;
public class C
{
static Action M1(int x) => () => { _ = x; };
static Action M2(int x) => x switch { _ => () => { _ = x; } };
}
";
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var verifier = CompileAndVerify(c);
verifier.VerifyIL("C.M1", sequencePoints: "C.M1", source: source, expectedIL: @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0
// sequence point: <hidden>
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldarg.0
IL_0008: stfld ""int C.<>c__DisplayClass0_0.x""
// sequence point: () => { _ = x; }
IL_000d: ldloc.0
IL_000e: ldftn ""void C.<>c__DisplayClass0_0.<M1>b__0()""
IL_0014: newobj ""System.Action..ctor(object, System.IntPtr)""
IL_0019: ret
}
");
verifier.VerifyIL("C.M2", sequencePoints: "C.M2", source: source, expectedIL: @"
{
// Code size 40 (0x28)
.maxstack 2
.locals init (C.<>c__DisplayClass1_0 V_0, //CS$<>8__locals0
System.Action V_1)
// sequence point: <hidden>
IL_0000: newobj ""C.<>c__DisplayClass1_0..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldarg.0
IL_0008: stfld ""int C.<>c__DisplayClass1_0.x""
// sequence point: x switch { _ => () => { _ = x; } }
IL_000d: ldc.i4.1
IL_000e: brtrue.s IL_0011
// sequence point: switch { _ => () => { _ = x; } }
IL_0010: nop
// sequence point: <hidden>
IL_0011: br.s IL_0013
// sequence point: () => { _ = x; }
IL_0013: ldloc.0
IL_0014: ldftn ""void C.<>c__DisplayClass1_0.<M2>b__0()""
IL_001a: newobj ""System.Action..ctor(object, System.IntPtr)""
IL_001f: stloc.1
IL_0020: br.s IL_0022
// sequence point: <hidden>
IL_0022: ldc.i4.1
IL_0023: brtrue.s IL_0026
// sequence point: x switch { _ => () => { _ = x; } }
IL_0025: nop
// sequence point: <hidden>
IL_0026: ldloc.1
IL_0027: ret
}
");
verifier.VerifyPdb("C.M1", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M1"" parameterNames=""x"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""30"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""0"" />
<lambda offset=""9"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""5"" startColumn=""32"" endLine=""5"" endColumn=""48"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1a"">
<namespace name=""System"" />
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x1a"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
verifier.VerifyPdb("C.M2", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M2"" parameterNames=""x"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""M1"" parameterNames=""x"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""0"" />
<slot kind=""temp"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>1</methodOrdinal>
<closure offset=""0"" />
<lambda offset=""25"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""6"" startColumn=""32"" endLine=""6"" endColumn=""66"" document=""1"" />
<entry offset=""0x10"" startLine=""6"" startColumn=""34"" endLine=""6"" endColumn=""66"" document=""1"" />
<entry offset=""0x11"" hidden=""true"" document=""1"" />
<entry offset=""0x13"" startLine=""6"" startColumn=""48"" endLine=""6"" endColumn=""64"" document=""1"" />
<entry offset=""0x22"" hidden=""true"" document=""1"" />
<entry offset=""0x25"" startLine=""6"" startColumn=""32"" endLine=""6"" endColumn=""66"" document=""1"" />
<entry offset=""0x26"" hidden=""true"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x28"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x28"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SyntaxOffset_OutVarInInitializers_SwitchExpression()
{
var source =
@"class C
{
static int G(out int x) => throw null;
static int F(System.Func<int> x) => throw null;
C() { }
int y1 = G(out var z) switch { _ => F(() => z) }; // line 7
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""-26"" />
<slot kind=""temp"" />
<slot kind=""35"" offset=""-26"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>2</methodOrdinal>
<closure offset=""-26"" />
<lambda offset=""-4"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x6"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""54"" document=""1"" />
<entry offset=""0x15"" startLine=""7"" startColumn=""27"" endLine=""7"" endColumn=""53"" document=""1"" />
<entry offset=""0x16"" hidden=""true"" document=""1"" />
<entry offset=""0x18"" startLine=""7"" startColumn=""41"" endLine=""7"" endColumn=""51"" document=""1"" />
<entry offset=""0x2c"" hidden=""true"" document=""1"" />
<entry offset=""0x2f"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""54"" document=""1"" />
<entry offset=""0x30"" hidden=""true"" document=""1"" />
<entry offset=""0x37"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""8"" document=""1"" />
<entry offset=""0x3e"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""10"" document=""1"" />
<entry offset=""0x3f"" startLine=""5"" startColumn=""11"" endLine=""5"" endColumn=""12"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x40"">
<scope startOffset=""0x0"" endOffset=""0x37"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x37"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(43468, "https://github.com/dotnet/roslyn/issues/43468")]
[Fact]
public void HiddenSequencePointAtSwitchExpressionFinalMergePoint()
{
var source =
@"class C
{
static int M(int x)
{
var y = x switch
{
1 => 2,
_ => 3,
};
return y;
}
}
";
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var verifier = CompileAndVerify(c);
verifier.VerifyIL("C.M", sequencePoints: "C.M", source: source, expectedIL: @"
{
// Code size 31 (0x1f)
.maxstack 2
.locals init (int V_0, //y
int V_1,
int V_2)
// sequence point: {
IL_0000: nop
// sequence point: var y = x sw ... };
IL_0001: ldc.i4.1
IL_0002: brtrue.s IL_0005
// sequence point: switch ... }
IL_0004: nop
// sequence point: <hidden>
IL_0005: ldarg.0
IL_0006: ldc.i4.1
IL_0007: beq.s IL_000b
IL_0009: br.s IL_000f
// sequence point: 2
IL_000b: ldc.i4.2
IL_000c: stloc.1
IL_000d: br.s IL_0013
// sequence point: 3
IL_000f: ldc.i4.3
IL_0010: stloc.1
IL_0011: br.s IL_0013
// sequence point: <hidden>
IL_0013: ldc.i4.1
IL_0014: brtrue.s IL_0017
// sequence point: var y = x sw ... };
IL_0016: nop
// sequence point: <hidden>
IL_0017: ldloc.1
IL_0018: stloc.0
// sequence point: return y;
IL_0019: ldloc.0
IL_001a: stloc.2
IL_001b: br.s IL_001d
// sequence point: }
IL_001d: ldloc.2
IL_001e: ret
}
");
}
[WorkItem(12378, "https://github.com/dotnet/roslyn/issues/12378")]
[WorkItem(13971, "https://github.com/dotnet/roslyn/issues/13971")]
[Fact]
public void Patterns_SwitchStatement_Constant()
{
string source = WithWindowsLineBreaks(
@"class Program
{
static void M(object o)
{
switch (o)
{
case 1 when o == null:
case 4:
case 2 when o == null:
break;
case 1 when o != null:
case 5:
case 3 when o != null:
break;
default:
break;
case 1:
break;
}
switch (o)
{
case 1:
break;
default:
break;
}
switch (o)
{
default:
break;
}
}
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
CompileAndVerify(c).VerifyIL(qualifiedMethodName: "Program.M", sequencePoints: "Program.M", source: source,
expectedIL: @"{
// Code size 123 (0x7b)
.maxstack 2
.locals init (object V_0,
int V_1,
object V_2,
object V_3,
int V_4,
object V_5,
object V_6,
object V_7)
// sequence point: {
IL_0000: nop
// sequence point: switch (o)
IL_0001: ldarg.0
IL_0002: stloc.2
// sequence point: <hidden>
IL_0003: ldloc.2
IL_0004: stloc.0
// sequence point: <hidden>
IL_0005: ldloc.0
IL_0006: isinst ""int""
IL_000b: brfalse.s IL_004a
IL_000d: ldloc.0
IL_000e: unbox.any ""int""
IL_0013: stloc.1
// sequence point: <hidden>
IL_0014: ldloc.1
IL_0015: ldc.i4.1
IL_0016: sub
IL_0017: switch (
IL_0032,
IL_0037,
IL_0043,
IL_003c,
IL_0048)
IL_0030: br.s IL_004a
// sequence point: when o == null
IL_0032: ldarg.0
IL_0033: brfalse.s IL_003c
// sequence point: <hidden>
IL_0035: br.s IL_003e
// sequence point: when o == null
IL_0037: ldarg.0
IL_0038: brfalse.s IL_003c
// sequence point: <hidden>
IL_003a: br.s IL_004a
// sequence point: break;
IL_003c: br.s IL_004e
// sequence point: when o != null
IL_003e: ldarg.0
IL_003f: brtrue.s IL_0048
// sequence point: <hidden>
IL_0041: br.s IL_004c
// sequence point: when o != null
IL_0043: ldarg.0
IL_0044: brtrue.s IL_0048
// sequence point: <hidden>
IL_0046: br.s IL_004a
// sequence point: break;
IL_0048: br.s IL_004e
// sequence point: break;
IL_004a: br.s IL_004e
// sequence point: break;
IL_004c: br.s IL_004e
// sequence point: switch (o)
IL_004e: ldarg.0
IL_004f: stloc.s V_5
// sequence point: <hidden>
IL_0051: ldloc.s V_5
IL_0053: stloc.3
// sequence point: <hidden>
IL_0054: ldloc.3
IL_0055: isinst ""int""
IL_005a: brfalse.s IL_006d
IL_005c: ldloc.3
IL_005d: unbox.any ""int""
IL_0062: stloc.s V_4
// sequence point: <hidden>
IL_0064: ldloc.s V_4
IL_0066: ldc.i4.1
IL_0067: beq.s IL_006b
IL_0069: br.s IL_006d
// sequence point: break;
IL_006b: br.s IL_006f
// sequence point: break;
IL_006d: br.s IL_006f
// sequence point: switch (o)
IL_006f: ldarg.0
IL_0070: stloc.s V_7
// sequence point: <hidden>
IL_0072: ldloc.s V_7
IL_0074: stloc.s V_6
// sequence point: <hidden>
IL_0076: br.s IL_0078
// sequence point: break;
IL_0078: br.s IL_007a
// sequence point: }
IL_007a: ret
}");
c.VerifyPdb(
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""M"" parameterNames=""o"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""35"" offset=""11"" />
<slot kind=""35"" offset=""11"" ordinal=""1"" />
<slot kind=""1"" offset=""11"" />
<slot kind=""35"" offset=""378"" />
<slot kind=""35"" offset=""378"" ordinal=""1"" />
<slot kind=""1"" offset=""378"" />
<slot kind=""35"" offset=""511"" />
<slot kind=""1"" offset=""511"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""19"" document=""1"" />
<entry offset=""0x3"" hidden=""true"" document=""1"" />
<entry offset=""0x5"" hidden=""true"" document=""1"" />
<entry offset=""0x14"" hidden=""true"" document=""1"" />
<entry offset=""0x32"" startLine=""7"" startColumn=""20"" endLine=""7"" endColumn=""34"" document=""1"" />
<entry offset=""0x35"" hidden=""true"" document=""1"" />
<entry offset=""0x37"" startLine=""9"" startColumn=""20"" endLine=""9"" endColumn=""34"" document=""1"" />
<entry offset=""0x3a"" hidden=""true"" document=""1"" />
<entry offset=""0x3c"" startLine=""10"" startColumn=""17"" endLine=""10"" endColumn=""23"" document=""1"" />
<entry offset=""0x3e"" startLine=""11"" startColumn=""20"" endLine=""11"" endColumn=""34"" document=""1"" />
<entry offset=""0x41"" hidden=""true"" document=""1"" />
<entry offset=""0x43"" startLine=""13"" startColumn=""20"" endLine=""13"" endColumn=""34"" document=""1"" />
<entry offset=""0x46"" hidden=""true"" document=""1"" />
<entry offset=""0x48"" startLine=""14"" startColumn=""17"" endLine=""14"" endColumn=""23"" document=""1"" />
<entry offset=""0x4a"" startLine=""16"" startColumn=""17"" endLine=""16"" endColumn=""23"" document=""1"" />
<entry offset=""0x4c"" startLine=""18"" startColumn=""17"" endLine=""18"" endColumn=""23"" document=""1"" />
<entry offset=""0x4e"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""19"" document=""1"" />
<entry offset=""0x51"" hidden=""true"" document=""1"" />
<entry offset=""0x54"" hidden=""true"" document=""1"" />
<entry offset=""0x64"" hidden=""true"" document=""1"" />
<entry offset=""0x6b"" startLine=""23"" startColumn=""17"" endLine=""23"" endColumn=""23"" document=""1"" />
<entry offset=""0x6d"" startLine=""25"" startColumn=""17"" endLine=""25"" endColumn=""23"" document=""1"" />
<entry offset=""0x6f"" startLine=""27"" startColumn=""9"" endLine=""27"" endColumn=""19"" document=""1"" />
<entry offset=""0x72"" hidden=""true"" document=""1"" />
<entry offset=""0x76"" hidden=""true"" document=""1"" />
<entry offset=""0x78"" startLine=""30"" startColumn=""17"" endLine=""30"" endColumn=""23"" document=""1"" />
<entry offset=""0x7a"" startLine=""32"" startColumn=""5"" endLine=""32"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")]
[Fact]
public void Patterns_SwitchStatement_Tuple()
{
string source = WithWindowsLineBreaks(@"
public class C
{
static int F(int i)
{
switch (G())
{
case (1, 2): return 3;
default: return 0;
};
}
static (object, object) G() => (2, 3);
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: s_valueTupleRefs);
var cv = CompileAndVerify(c);
cv.VerifyIL("C.F", @"
{
// Code size 80 (0x50)
.maxstack 2
.locals init (System.ValueTuple<object, object> V_0,
object V_1,
int V_2,
object V_3,
int V_4,
System.ValueTuple<object, object> V_5,
int V_6)
IL_0000: nop
IL_0001: call ""System.ValueTuple<object, object> C.G()""
IL_0006: stloc.s V_5
IL_0008: ldloc.s V_5
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: ldfld ""object System.ValueTuple<object, object>.Item1""
IL_0011: stloc.1
IL_0012: ldloc.1
IL_0013: isinst ""int""
IL_0018: brfalse.s IL_0048
IL_001a: ldloc.1
IL_001b: unbox.any ""int""
IL_0020: stloc.2
IL_0021: ldloc.2
IL_0022: ldc.i4.1
IL_0023: bne.un.s IL_0048
IL_0025: ldloc.0
IL_0026: ldfld ""object System.ValueTuple<object, object>.Item2""
IL_002b: stloc.3
IL_002c: ldloc.3
IL_002d: isinst ""int""
IL_0032: brfalse.s IL_0048
IL_0034: ldloc.3
IL_0035: unbox.any ""int""
IL_003a: stloc.s V_4
IL_003c: ldloc.s V_4
IL_003e: ldc.i4.2
IL_003f: beq.s IL_0043
IL_0041: br.s IL_0048
IL_0043: ldc.i4.3
IL_0044: stloc.s V_6
IL_0046: br.s IL_004d
IL_0048: ldc.i4.0
IL_0049: stloc.s V_6
IL_004b: br.s IL_004d
IL_004d: ldloc.s V_6
IL_004f: ret
}
");
c.VerifyPdb("C.F", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"" parameterNames=""i"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""35"" offset=""11"" />
<slot kind=""35"" offset=""11"" ordinal=""1"" />
<slot kind=""35"" offset=""11"" ordinal=""2"" />
<slot kind=""35"" offset=""11"" ordinal=""3"" />
<slot kind=""35"" offset=""11"" ordinal=""4"" />
<slot kind=""1"" offset=""11"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""21"" document=""1"" />
<entry offset=""0x8"" hidden=""true"" document=""1"" />
<entry offset=""0xb"" hidden=""true"" document=""1"" />
<entry offset=""0x12"" hidden=""true"" document=""1"" />
<entry offset=""0x21"" hidden=""true"" document=""1"" />
<entry offset=""0x2c"" hidden=""true"" document=""1"" />
<entry offset=""0x3c"" hidden=""true"" document=""1"" />
<entry offset=""0x43"" startLine=""8"" startColumn=""26"" endLine=""8"" endColumn=""35"" document=""1"" />
<entry offset=""0x48"" startLine=""9"" startColumn=""22"" endLine=""9"" endColumn=""31"" document=""1"" />
<entry offset=""0x4d"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
#endregion
#region Tuples
[Fact]
public void SyntaxOffset_TupleDeconstruction()
{
var source = @"class C { int F() { (int a, (_, int c)) = (1, (2, 3)); return a + c; } }";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: s_valueTupleRefs);
c.VerifyPdb("C.F", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""7"" />
<slot kind=""0"" offset=""18"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""19"" endLine=""1"" endColumn=""20"" document=""1"" />
<entry offset=""0x1"" startLine=""1"" startColumn=""21"" endLine=""1"" endColumn=""55"" document=""1"" />
<entry offset=""0x5"" startLine=""1"" startColumn=""56"" endLine=""1"" endColumn=""69"" document=""1"" />
<entry offset=""0xb"" startLine=""1"" startColumn=""70"" endLine=""1"" endColumn=""71"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xd"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0xd"" attributes=""0"" />
<local name=""c"" il_index=""1"" il_start=""0x0"" il_end=""0xd"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void TestDeconstruction()
{
var source = @"
public class C
{
public static (int, int) F() => (1, 2);
public static void Main()
{
int x, y;
(x, y) = F();
System.Console.WriteLine(x + y);
}
}
";
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.Main", @"
{
// Code size 29 (0x1d)
.maxstack 2
.locals init (int V_0, //x
int V_1) //y
// sequence point: {
IL_0000: nop
// sequence point: (x, y) = F();
IL_0001: call ""System.ValueTuple<int, int> C.F()""
IL_0006: dup
IL_0007: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_000c: stloc.0
IL_000d: ldfld ""int System.ValueTuple<int, int>.Item2""
IL_0012: stloc.1
// sequence point: System.Console.WriteLine(x + y);
IL_0013: ldloc.0
IL_0014: ldloc.1
IL_0015: add
IL_0016: call ""void System.Console.WriteLine(int)""
IL_001b: nop
// sequence point: }
IL_001c: ret
}
", sequencePoints: "C.Main", source: source);
}
[Fact]
public void SyntaxOffset_TupleParenthesized()
{
var source = @"class C { int F() { (int, (int, int)) x = (1, (2, 3)); return x.Item1 + x.Item2.Item1 + x.Item2.Item2; } }";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: s_valueTupleRefs);
c.VerifyPdb("C.F", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""20"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""19"" endLine=""1"" endColumn=""20"" document=""1"" />
<entry offset=""0x1"" startLine=""1"" startColumn=""21"" endLine=""1"" endColumn=""55"" document=""1"" />
<entry offset=""0x10"" startLine=""1"" startColumn=""56"" endLine=""1"" endColumn=""103"" document=""1"" />
<entry offset=""0x31"" startLine=""1"" startColumn=""104"" endLine=""1"" endColumn=""105"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x33"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x33"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>"
);
}
[Fact]
public void SyntaxOffset_TupleVarDefined()
{
var source = @"class C { int F() { var x = (1, 2); return x.Item1 + x.Item2; } }";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: s_valueTupleRefs);
c.VerifyPdb("C.F", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""6"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""19"" endLine=""1"" endColumn=""20"" document=""1"" />
<entry offset=""0x1"" startLine=""1"" startColumn=""21"" endLine=""1"" endColumn=""36"" document=""1"" />
<entry offset=""0xa"" startLine=""1"" startColumn=""37"" endLine=""1"" endColumn=""62"" document=""1"" />
<entry offset=""0x1a"" startLine=""1"" startColumn=""63"" endLine=""1"" endColumn=""64"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1c"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void SyntaxOffset_TupleIgnoreDeconstructionIfVariableDeclared()
{
var source = @"class C { int F() { (int x, int y) a = (1, 2); return a.Item1 + a.Item2; } }";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: s_valueTupleRefs);
c.VerifyPdb("C.F", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<tupleElementNames>
<local elementNames=""|x|y"" slotIndex=""0"" localName=""a"" scopeStart=""0x0"" scopeEnd=""0x0"" />
</tupleElementNames>
<encLocalSlotMap>
<slot kind=""0"" offset=""17"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""19"" endLine=""1"" endColumn=""20"" document=""1"" />
<entry offset=""0x1"" startLine=""1"" startColumn=""21"" endLine=""1"" endColumn=""47"" document=""1"" />
<entry offset=""0x9"" startLine=""1"" startColumn=""48"" endLine=""1"" endColumn=""73"" document=""1"" />
<entry offset=""0x19"" startLine=""1"" startColumn=""74"" endLine=""1"" endColumn=""75"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1b"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x1b"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region OutVar
[Fact]
public void SyntaxOffset_OutVarInConstructor()
{
var source = @"
class B
{
B(out int z) { z = 2; }
}
class C
{
int F = G(out var v1);
int P => G(out var v2);
C()
: base(out var v3)
{
G(out var v4);
}
int G(out int x)
{
x = 1;
return 2;
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyDiagnostics(
// (9,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'C.G(out int)'
// int F = G(out var v1);
Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "G").WithArguments("C.G(out int)").WithLocation(9, 13),
// (13,7): error CS1729: 'object' does not contain a constructor that takes 1 arguments
// : base(out var v3)
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "base").WithArguments("object", "1").WithLocation(13, 7));
}
[Fact]
public void SyntaxOffset_OutVarInMethod()
{
var source = @"class C { int G(out int x) { int z = 1; G(out var y); G(out var w); return x = y; } }";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.G", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""G"" parameterNames=""x"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""6"" />
<slot kind=""0"" offset=""23"" />
<slot kind=""0"" offset=""37"" />
<slot kind=""temp"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""28"" endLine=""1"" endColumn=""29"" document=""1"" />
<entry offset=""0x1"" startLine=""1"" startColumn=""30"" endLine=""1"" endColumn=""40"" document=""1"" />
<entry offset=""0x3"" startLine=""1"" startColumn=""41"" endLine=""1"" endColumn=""54"" document=""1"" />
<entry offset=""0xc"" startLine=""1"" startColumn=""55"" endLine=""1"" endColumn=""68"" document=""1"" />
<entry offset=""0x15"" startLine=""1"" startColumn=""69"" endLine=""1"" endColumn=""82"" document=""1"" />
<entry offset=""0x1f"" startLine=""1"" startColumn=""83"" endLine=""1"" endColumn=""84"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x22"">
<local name=""z"" il_index=""0"" il_start=""0x0"" il_end=""0x22"" attributes=""0"" />
<local name=""y"" il_index=""1"" il_start=""0x0"" il_end=""0x22"" attributes=""0"" />
<local name=""w"" il_index=""2"" il_start=""0x0"" il_end=""0x22"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInInitializers_01()
{
var source = WithWindowsLineBreaks(
@"
class C : A
{
int x = G(out var x);
int y {get;} = G(out var y);
C() : base(G(out var z))
{
}
static int G(out int x)
{
throw null;
}
}
class A
{
public A(int x) {}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""-36"" />
<slot kind=""0"" offset=""-22"" />
<slot kind=""0"" offset=""-3"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""26"" document=""1"" />
<entry offset=""0xd"" startLine=""5"" startColumn=""20"" endLine=""5"" endColumn=""32"" document=""1"" />
<entry offset=""0x1a"" startLine=""7"" startColumn=""11"" endLine=""7"" endColumn=""29"" document=""1"" />
<entry offset=""0x28"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
<entry offset=""0x29"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2a"">
<scope startOffset=""0x0"" endOffset=""0xd"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0xd"" attributes=""0"" />
</scope>
<scope startOffset=""0xd"" endOffset=""0x1a"">
<local name=""y"" il_index=""1"" il_start=""0xd"" il_end=""0x1a"" attributes=""0"" />
</scope>
<scope startOffset=""0x1a"" endOffset=""0x2a"">
<local name=""z"" il_index=""2"" il_start=""0x1a"" il_end=""0x2a"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInInitializers_02()
{
var source = WithWindowsLineBreaks(
@"
class C : A
{
C() : base(G(out var x))
{
int y = 1;
y++;
}
static int G(out int x)
{
throw null;
}
}
class A
{
public A(int x) {}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""-3"" />
<slot kind=""0"" offset=""16"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""11"" endLine=""4"" endColumn=""29"" document=""1"" />
<entry offset=""0xe"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0xf"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""19"" document=""1"" />
<entry offset=""0x11"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""13"" document=""1"" />
<entry offset=""0x15"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x16"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x16"" attributes=""0"" />
<scope startOffset=""0xe"" endOffset=""0x16"">
<local name=""y"" il_index=""1"" il_start=""0xe"" il_end=""0x16"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInInitializers_03()
{
var source = WithWindowsLineBreaks(
@"
class C : A
{
C() : base(G(out var x))
=> G(out var y);
static int G(out int x)
{
throw null;
}
}
class A
{
public A(int x) {}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""-3"" />
<slot kind=""0"" offset=""13"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""11"" endLine=""4"" endColumn=""29"" document=""1"" />
<entry offset=""0xe"" startLine=""5"" startColumn=""8"" endLine=""5"" endColumn=""20"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x17"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x17"" attributes=""0"" />
<scope startOffset=""0xe"" endOffset=""0x17"">
<local name=""y"" il_index=""1"" il_start=""0xe"" il_end=""0x17"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInInitializers_04()
{
var source = WithWindowsLineBreaks(
@"
class C
{
static int G(out int x)
{
throw null;
}
static int F(System.Func<int> x)
{
throw null;
}
C()
{
}
#line 2000
int y1 = G(out var z) + F(() => z);
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""-25"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>2</methodOrdinal>
<closure offset=""-25"" />
<lambda offset=""-2"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x6"" startLine=""2000"" startColumn=""5"" endLine=""2000"" endColumn=""40"" document=""1"" />
<entry offset=""0x29"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""8"" document=""1"" />
<entry offset=""0x30"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" />
<entry offset=""0x31"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x32"">
<scope startOffset=""0x0"" endOffset=""0x29"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x29"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c__DisplayClass2_0.<.ctor>b__0", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c__DisplayClass2_0"" name=""<.ctor>b__0"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""2000"" startColumn=""37"" endLine=""2000"" endColumn=""38"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInInitializers_05()
{
var source = WithWindowsLineBreaks(
@"
class C
{
static int G(out int x)
{
throw null;
}
static int F(System.Func<int> x)
{
throw null;
}
#line 2000
int y1 { get; } = G(out var z) + F(() => z);
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""-25"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>5</methodOrdinal>
<closure offset=""-25"" />
<lambda offset=""-2"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x6"" startLine=""2000"" startColumn=""23"" endLine=""2000"" endColumn=""48"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x31"">
<scope startOffset=""0x0"" endOffset=""0x29"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x29"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c__DisplayClass5_0.<.ctor>b__0", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c__DisplayClass5_0"" name=""<.ctor>b__0"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""2000"" startColumn=""46"" endLine=""2000"" endColumn=""47"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInInitializers_06()
{
var source = WithWindowsLineBreaks(
@"
class C
{
static int G(out int x)
{
throw null;
}
static int F(System.Func<int> x)
{
throw null;
}
#line 2000
int y1 = G(out var z) + F(() => z), y2 = G(out var u) + F(() => u);
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C..ctor", sequencePoints: "C..ctor", expectedIL: @"
{
// Code size 90 (0x5a)
.maxstack 4
.locals init (C.<>c__DisplayClass4_0 V_0, //CS$<>8__locals0
C.<>c__DisplayClass4_1 V_1) //CS$<>8__locals1
~IL_0000: newobj ""C.<>c__DisplayClass4_0..ctor()""
IL_0005: stloc.0
-IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass4_0.z""
IL_000d: call ""int C.G(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass4_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.F(System.Func<int>)""
IL_0023: add
IL_0024: stfld ""int C.y1""
~IL_0029: newobj ""C.<>c__DisplayClass4_1..ctor()""
IL_002e: stloc.1
-IL_002f: ldarg.0
IL_0030: ldloc.1
IL_0031: ldflda ""int C.<>c__DisplayClass4_1.u""
IL_0036: call ""int C.G(out int)""
IL_003b: ldloc.1
IL_003c: ldftn ""int C.<>c__DisplayClass4_1.<.ctor>b__1()""
IL_0042: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_0047: call ""int C.F(System.Func<int>)""
IL_004c: add
IL_004d: stfld ""int C.y2""
IL_0052: ldarg.0
IL_0053: call ""object..ctor()""
IL_0058: nop
IL_0059: ret
}
");
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""-52"" />
<slot kind=""30"" offset=""-25"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>4</methodOrdinal>
<closure offset=""-52"" />
<closure offset=""-25"" />
<lambda offset=""-29"" closure=""0"" />
<lambda offset=""-2"" closure=""1"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x6"" startLine=""2000"" startColumn=""5"" endLine=""2000"" endColumn=""39"" document=""1"" />
<entry offset=""0x29"" hidden=""true"" document=""1"" />
<entry offset=""0x2f"" startLine=""2000"" startColumn=""41"" endLine=""2000"" endColumn=""71"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x5a"">
<scope startOffset=""0x0"" endOffset=""0x29"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x29"" attributes=""0"" />
</scope>
<scope startOffset=""0x29"" endOffset=""0x52"">
<local name=""CS$<>8__locals1"" il_index=""1"" il_start=""0x29"" il_end=""0x52"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c__DisplayClass4_0.<.ctor>b__0", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c__DisplayClass4_0"" name=""<.ctor>b__0"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""2000"" startColumn=""37"" endLine=""2000"" endColumn=""38"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c__DisplayClass4_1.<.ctor>b__1", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c__DisplayClass4_1"" name=""<.ctor>b__1"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""2000"" startColumn=""69"" endLine=""2000"" endColumn=""70"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInInitializers_07()
{
var source = WithWindowsLineBreaks(
@"
class C : A
{
#line 2000
C() : base(G(out var z)+ F(() => z))
{
}
static int G(out int x)
{
throw null;
}
static int F(System.Func<int> x)
{
throw null;
}
}
class A
{
public A(int x) {}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""30"" offset=""-1"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""-1"" />
<lambda offset=""-3"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x6"" startLine=""2000"" startColumn=""11"" endLine=""2000"" endColumn=""41"" document=""1"" />
<entry offset=""0x2a"" startLine=""2001"" startColumn=""5"" endLine=""2001"" endColumn=""6"" document=""1"" />
<entry offset=""0x2b"" startLine=""2002"" startColumn=""5"" endLine=""2002"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2c"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x2c"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c__DisplayClass0_0.<.ctor>b__0", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c__DisplayClass0_0"" name=""<.ctor>b__0"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""2000"" startColumn=""38"" endLine=""2000"" endColumn=""39"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInQuery_01()
{
var source = WithWindowsLineBreaks(
@"
using System.Linq;
class C
{
C()
{
var q = from a in new [] {1}
where
G(out var x1) > a
select a;
}
static int G(out int x)
{
throw null;
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<lambda offset=""88"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""8"" document=""1"" />
<entry offset=""0x7"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x8"" startLine=""8"" startColumn=""9"" endLine=""11"" endColumn=""26"" document=""1"" />
<entry offset=""0x37"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x38"">
<namespace name=""System.Linq"" />
<scope startOffset=""0x7"" endOffset=""0x38"">
<local name=""q"" il_index=""0"" il_start=""0x7"" il_end=""0x38"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c.<.ctor>b__0_0", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c"" name=""<.ctor>b__0_0"" parameterNames=""a"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""98"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""23"" endLine=""10"" endColumn=""40"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xb"">
<local name=""x1"" il_index=""0"" il_start=""0x0"" il_end=""0xb"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInQuery_02()
{
var source = WithWindowsLineBreaks(
@"
using System.Linq;
class C
{
C()
#line 2000
{
var q = from a in new [] {1}
where
G(out var x1) > F(() => x1)
select a;
}
static int G(out int x)
{
throw null;
}
static int F(System.Func<int> x)
{
throw null;
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""88"" />
<lambda offset=""88"" />
<lambda offset=""112"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""8"" document=""1"" />
<entry offset=""0x7"" startLine=""2000"" startColumn=""5"" endLine=""2000"" endColumn=""6"" document=""1"" />
<entry offset=""0x8"" startLine=""2001"" startColumn=""9"" endLine=""2004"" endColumn=""26"" document=""1"" />
<entry offset=""0x37"" startLine=""2005"" startColumn=""5"" endLine=""2005"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x38"">
<namespace name=""System.Linq"" />
<scope startOffset=""0x7"" endOffset=""0x38"">
<local name=""q"" il_index=""0"" il_start=""0x7"" il_end=""0x38"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c.<.ctor>b__0_0", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c"" name=""<.ctor>b__0_0"" parameterNames=""a"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""88"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x6"" startLine=""2003"" startColumn=""23"" endLine=""2003"" endColumn=""50"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x25"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x25"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c__DisplayClass0_0.<.ctor>b__1", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c__DisplayClass0_0"" name=""<.ctor>b__1"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""2003"" startColumn=""47"" endLine=""2003"" endColumn=""49"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInSwitchExpression()
{
var source = @"class C { static object G() => N(out var x) switch { null => x switch {1 => 1, _ => 2 }, _ => 1 }; static object N(out int x) { x = 1; return null; } }";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.G", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""G"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
<slot kind=""temp"" />
<slot kind=""35"" offset=""16"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""32"" endLine=""1"" endColumn=""99"" document=""1"" />
<entry offset=""0xb"" startLine=""1"" startColumn=""45"" endLine=""1"" endColumn=""99"" document=""1"" />
<entry offset=""0xc"" hidden=""true"" document=""1"" />
<entry offset=""0x11"" hidden=""true"" document=""1"" />
<entry offset=""0x14"" startLine=""1"" startColumn=""64"" endLine=""1"" endColumn=""89"" document=""1"" />
<entry offset=""0x15"" hidden=""true"" document=""1"" />
<entry offset=""0x1b"" startLine=""1"" startColumn=""78"" endLine=""1"" endColumn=""79"" document=""1"" />
<entry offset=""0x1f"" startLine=""1"" startColumn=""86"" endLine=""1"" endColumn=""87"" document=""1"" />
<entry offset=""0x23"" hidden=""true"" document=""1"" />
<entry offset=""0x26"" startLine=""1"" startColumn=""45"" endLine=""1"" endColumn=""99"" document=""1"" />
<entry offset=""0x27"" startLine=""1"" startColumn=""62"" endLine=""1"" endColumn=""89"" document=""1"" />
<entry offset=""0x2b"" startLine=""1"" startColumn=""96"" endLine=""1"" endColumn=""97"" document=""1"" />
<entry offset=""0x2f"" hidden=""true"" document=""1"" />
<entry offset=""0x32"" startLine=""1"" startColumn=""32"" endLine=""1"" endColumn=""99"" document=""1"" />
<entry offset=""0x33"" hidden=""true"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x3a"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x3a"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
#endregion
[WorkItem(4370, "https://github.com/dotnet/roslyn/issues/4370")]
[Fact]
public void HeadingHiddenSequencePointsPickUpDocumentFromVisibleSequencePoint()
{
var source = WithWindowsLineBreaks(
@"#line 1 ""C:\Async.cs""
#pragma checksum ""C:\Async.cs"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""DBEB2A067B2F0E0D678A002C587A2806056C3DCE""
using System.Threading.Tasks;
public class C
{
public async void M1()
{
}
}
");
var tree = SyntaxFactory.ParseSyntaxTree(source, encoding: Encoding.UTF8, path: "HIDDEN.cs");
var c = CSharpCompilation.Create("Compilation", new[] { tree }, new[] { MscorlibRef_v46 }, options: TestOptions.DebugDll.WithDebugPlusMode(true));
c.VerifyPdb(
@"<symbols>
<files>
<file id=""1"" name=""C:\Async.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""DB-EB-2A-06-7B-2F-0E-0D-67-8A-00-2C-58-7A-28-06-05-6C-3D-CE"" />
<file id=""2"" name=""HIDDEN.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""8A-92-EE-2F-D6-6F-C0-69-F4-A8-54-CB-11-BE-A3-06-76-2C-9C-98"" />
</files>
<methods>
<method containingType=""C"" name=""M1"">
<customDebugInfo>
<forwardIterator name=""<M1>d__0"" />
</customDebugInfo>
</method>
<method containingType=""C+<M1>d__0"" name=""MoveNext"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
<entry offset=""0xa"" hidden=""true"" document=""1"" />
<entry offset=""0x22"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x2a"" hidden=""true"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x37"">
<namespace name=""System.Threading.Tasks"" />
</scope>
<asyncInfo>
<catchHandler offset=""0xa"" />
<kickoffMethod declaringType=""C"" methodName=""M1"" />
</asyncInfo>
</method>
</methods>
</symbols>
", format: DebugInformationFormat.Pdb);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""HIDDEN.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""8A-92-EE-2F-D6-6F-C0-69-F4-A8-54-CB-11-BE-A3-06-76-2C-9C-98"" />
<file id=""2"" name=""C:\Async.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""DB-EB-2A-06-7B-2F-0E-0D-67-8A-00-2C-58-7A-28-06-05-6C-3D-CE"" />
</files>
<methods>
<method containingType=""C+<M1>d__0"" name=""MoveNext"">
<customDebugInfo>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""2"" />
<entry offset=""0x7"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""2"" />
<entry offset=""0xa"" hidden=""true"" document=""2"" />
<entry offset=""0x22"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""2"" />
<entry offset=""0x2a"" hidden=""true"" document=""2"" />
</sequencePoints>
<asyncInfo>
<catchHandler offset=""0xa"" />
<kickoffMethod declaringType=""C"" methodName=""M1"" />
</asyncInfo>
</method>
</methods>
</symbols>", format: DebugInformationFormat.PortablePdb);
}
[WorkItem(12923, "https://github.com/dotnet/roslyn/issues/12923")]
[Fact]
public void SequencePointsForConstructorWithHiddenInitializer()
{
string initializerSource = WithWindowsLineBreaks(@"
#line hidden
partial class C
{
int i = 42;
}
");
string constructorSource = WithWindowsLineBreaks(@"
partial class C
{
C()
{
}
}
");
var c = CreateCompilation(
new[] { Parse(initializerSource, "initializer.cs"), Parse(constructorSource, "constructor.cs") },
options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""constructor.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""EA-D6-0A-16-6C-6A-BC-C1-5D-98-0F-B7-4B-78-13-93-FB-C7-C2-5A"" />
<file id=""2"" name=""initializer.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""84-32-24-D7-FE-32-63-BA-41-D5-17-A2-D5-90-23-B8-12-3C-AF-D5"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x8"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""8"" document=""1"" />
<entry offset=""0xf"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x10"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
", format: DebugInformationFormat.Pdb);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""initializer.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""84-32-24-D7-FE-32-63-BA-41-D5-17-A2-D5-90-23-B8-12-3C-AF-D5"" />
<file id=""2"" name=""constructor.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""EA-D6-0A-16-6C-6A-BC-C1-5D-98-0F-B7-4B-78-13-93-FB-C7-C2-5A"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""2"" />
<entry offset=""0x8"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""8"" document=""2"" />
<entry offset=""0xf"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""2"" />
<entry offset=""0x10"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""2"" />
</sequencePoints>
</method>
</methods>
</symbols>", format: DebugInformationFormat.PortablePdb);
}
[WorkItem(14437, "https://github.com/dotnet/roslyn/issues/14437")]
[Fact]
public void LocalFunctionSequencePoints()
{
string source = WithWindowsLineBreaks(
@"class Program
{
static int Main(string[] args)
{ // 4
int Local1(string[] a)
=>
a.Length; // 7
int Local2(string[] a)
{ // 9
return a.Length; // 10
} // 11
return Local1(args) + Local2(args); // 12
} // 13
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<lambda offset=""115"" />
<lambda offset=""202"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" />
<entry offset=""0x3"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""44"" document=""1"" />
<entry offset=""0x13"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""Program"" name=""<Main>g__Local1|0_0"" parameterNames=""a"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""13"" endLine=""7"" endColumn=""21"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""Program"" name=""<Main>g__Local2|0_1"" parameterNames=""a"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" />
<encLocalSlotMap>
<slot kind=""21"" offset=""202"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""29"" document=""1"" />
<entry offset=""0x7"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void SwitchInAsyncMethod()
{
var source = @"
using System;
class Program
{
public static async void Test()
{
int i = 0;
switch (i)
{
case 1:
break;
}
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 89 (0x59)
.maxstack 2
.locals init (int V_0,
int V_1,
System.Exception V_2)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Test>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: int i = 0;
IL_0008: ldarg.0
IL_0009: ldc.i4.0
IL_000a: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: switch (i)
IL_000f: ldarg.0
IL_0010: ldarg.0
IL_0011: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_0016: stloc.1
// sequence point: <hidden>
IL_0017: ldloc.1
IL_0018: stfld ""int Program.<Test>d__0.<>s__2""
// sequence point: <hidden>
IL_001d: ldarg.0
IL_001e: ldfld ""int Program.<Test>d__0.<>s__2""
IL_0023: ldc.i4.1
IL_0024: beq.s IL_0028
IL_0026: br.s IL_002a
// sequence point: break;
IL_0028: br.s IL_002a
// sequence point: <hidden>
IL_002a: leave.s IL_0044
}
catch System.Exception
{
// async: catch handler, sequence point: <hidden>
IL_002c: stloc.2
IL_002d: ldarg.0
IL_002e: ldc.i4.s -2
IL_0030: stfld ""int Program.<Test>d__0.<>1__state""
IL_0035: ldarg.0
IL_0036: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_003b: ldloc.2
IL_003c: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)""
IL_0041: nop
IL_0042: leave.s IL_0058
}
// sequence point: }
IL_0044: ldarg.0
IL_0045: ldc.i4.s -2
IL_0047: stfld ""int Program.<Test>d__0.<>1__state""
// sequence point: <hidden>
IL_004c: ldarg.0
IL_004d: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_0052: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()""
IL_0057: nop
IL_0058: ret
}", sequencePoints: "Program+<Test>d__0.MoveNext", source: source);
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void WhileInAsyncMethod()
{
var source = @"
using System;
class Program
{
public static async void Test()
{
int i = 0;
while (i == 1)
Console.WriteLine();
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 83 (0x53)
.maxstack 2
.locals init (int V_0,
bool V_1,
System.Exception V_2)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Test>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: int i = 0;
IL_0008: ldarg.0
IL_0009: ldc.i4.0
IL_000a: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: <hidden>
IL_000f: br.s IL_0017
// sequence point: Console.WriteLine();
IL_0011: call ""void System.Console.WriteLine()""
IL_0016: nop
// sequence point: while (i == 1)
IL_0017: ldarg.0
IL_0018: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_001d: ldc.i4.1
IL_001e: ceq
IL_0020: stloc.1
// sequence point: <hidden>
IL_0021: ldloc.1
IL_0022: brtrue.s IL_0011
IL_0024: leave.s IL_003e
}
catch System.Exception
{
// async: catch handler, sequence point: <hidden>
IL_0026: stloc.2
IL_0027: ldarg.0
IL_0028: ldc.i4.s -2
IL_002a: stfld ""int Program.<Test>d__0.<>1__state""
IL_002f: ldarg.0
IL_0030: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_0035: ldloc.2
IL_0036: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)""
IL_003b: nop
IL_003c: leave.s IL_0052
}
// sequence point: }
IL_003e: ldarg.0
IL_003f: ldc.i4.s -2
IL_0041: stfld ""int Program.<Test>d__0.<>1__state""
// sequence point: <hidden>
IL_0046: ldarg.0
IL_0047: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_004c: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()""
IL_0051: nop
IL_0052: ret
}
", sequencePoints: "Program+<Test>d__0.MoveNext", source: source);
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ForInAsyncMethod()
{
var source = @"
using System;
class Program
{
public static async void Test()
{
for (int i = 0; i > 1; i--)
Console.WriteLine();
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 99 (0x63)
.maxstack 3
.locals init (int V_0,
int V_1,
bool V_2,
System.Exception V_3)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Test>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: int i = 0
IL_0008: ldarg.0
IL_0009: ldc.i4.0
IL_000a: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: <hidden>
IL_000f: br.s IL_0027
// sequence point: Console.WriteLine();
IL_0011: call ""void System.Console.WriteLine()""
IL_0016: nop
// sequence point: i--
IL_0017: ldarg.0
IL_0018: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_001d: stloc.1
IL_001e: ldarg.0
IL_001f: ldloc.1
IL_0020: ldc.i4.1
IL_0021: sub
IL_0022: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: i > 1
IL_0027: ldarg.0
IL_0028: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_002d: ldc.i4.1
IL_002e: cgt
IL_0030: stloc.2
// sequence point: <hidden>
IL_0031: ldloc.2
IL_0032: brtrue.s IL_0011
IL_0034: leave.s IL_004e
}
catch System.Exception
{
// async: catch handler, sequence point: <hidden>
IL_0036: stloc.3
IL_0037: ldarg.0
IL_0038: ldc.i4.s -2
IL_003a: stfld ""int Program.<Test>d__0.<>1__state""
IL_003f: ldarg.0
IL_0040: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_0045: ldloc.3
IL_0046: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)""
IL_004b: nop
IL_004c: leave.s IL_0062
}
// sequence point: }
IL_004e: ldarg.0
IL_004f: ldc.i4.s -2
IL_0051: stfld ""int Program.<Test>d__0.<>1__state""
// sequence point: <hidden>
IL_0056: ldarg.0
IL_0057: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_005c: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()""
IL_0061: nop
IL_0062: ret
}
", sequencePoints: "Program+<Test>d__0.MoveNext", source: source);
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ForWithInnerLocalsInAsyncMethod()
{
var source = @"
using System;
class Program
{
public static async void Test()
{
for (int i = M(out var x); i > 1; i--)
Console.WriteLine();
}
public static int M(out int x) { x = 0; return 0; }
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 109 (0x6d)
.maxstack 3
.locals init (int V_0,
int V_1,
bool V_2,
System.Exception V_3)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Test>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: int i = M(out var x)
IL_0008: ldarg.0
IL_0009: ldarg.0
IL_000a: ldflda ""int Program.<Test>d__0.<x>5__2""
IL_000f: call ""int Program.M(out int)""
IL_0014: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: <hidden>
IL_0019: br.s IL_0031
// sequence point: Console.WriteLine();
IL_001b: call ""void System.Console.WriteLine()""
IL_0020: nop
// sequence point: i--
IL_0021: ldarg.0
IL_0022: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_0027: stloc.1
IL_0028: ldarg.0
IL_0029: ldloc.1
IL_002a: ldc.i4.1
IL_002b: sub
IL_002c: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: i > 1
IL_0031: ldarg.0
IL_0032: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_0037: ldc.i4.1
IL_0038: cgt
IL_003a: stloc.2
// sequence point: <hidden>
IL_003b: ldloc.2
IL_003c: brtrue.s IL_001b
IL_003e: leave.s IL_0058
}
catch System.Exception
{
// async: catch handler, sequence point: <hidden>
IL_0040: stloc.3
IL_0041: ldarg.0
IL_0042: ldc.i4.s -2
IL_0044: stfld ""int Program.<Test>d__0.<>1__state""
IL_0049: ldarg.0
IL_004a: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_004f: ldloc.3
IL_0050: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)""
IL_0055: nop
IL_0056: leave.s IL_006c
}
// sequence point: }
IL_0058: ldarg.0
IL_0059: ldc.i4.s -2
IL_005b: stfld ""int Program.<Test>d__0.<>1__state""
// sequence point: <hidden>
IL_0060: ldarg.0
IL_0061: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_0066: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()""
IL_006b: nop
IL_006c: ret
}
", sequencePoints: "Program+<Test>d__0.MoveNext", source: source);
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
[WorkItem(23525, "https://github.com/dotnet/roslyn/issues/23525")]
public void InvalidCharacterInPdbPath()
{
using (var outStream = Temp.CreateFile().Open())
{
var compilation = CreateCompilation("");
var result = compilation.Emit(outStream, options: new EmitOptions(pdbFilePath: "test\\?.pdb", debugInformationFormat: DebugInformationFormat.Embedded));
// This is fine because EmitOptions just controls what is written into the PE file and it's
// valid for this to be an illegal file name (path map can easily create these).
Assert.True(result.Success);
}
}
[Fact]
[WorkItem(38954, "https://github.com/dotnet/roslyn/issues/38954")]
public void FilesOneWithNoMethodBody()
{
string source1 = WithWindowsLineBreaks(@"
using System;
class C
{
public static void Main()
{
Console.WriteLine();
}
}
");
string source2 = WithWindowsLineBreaks(@"
// no code
");
var tree1 = Parse(source1, "f:/build/goo.cs");
var tree2 = Parse(source2, "f:/build/nocode.cs");
var c = CreateCompilation(new[] { tree1, tree2 }, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""f:/build/goo.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""5D-7D-CF-1B-79-12-0E-0A-80-13-E0-98-7E-5C-AA-3B-63-D8-7E-4F"" />
<file id=""2"" name=""f:/build/nocode.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""8B-1D-3F-75-E0-A8-8F-90-B2-D3-52-CF-71-9B-17-29-3C-70-7A-42"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""29"" document=""1"" />
<entry offset=""0x7"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x8"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
[WorkItem(38954, "https://github.com/dotnet/roslyn/issues/38954")]
public void SingleFileWithNoMethodBody()
{
string source = WithWindowsLineBreaks(@"
// no code
");
var tree = Parse(source, "f:/build/nocode.cs");
var c = CreateCompilation(new[] { tree }, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""f:/build/nocode.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""8B-1D-3F-75-E0-A8-8F-90-B2-D3-52-CF-71-9B-17-29-3C-70-7A-42"" />
</files>
<methods />
</symbols>
");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using System.Text;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.PdbUtilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB
{
public class PDBTests : CSharpPDBTestBase
{
private static readonly MetadataReference[] s_valueTupleRefs = new[] { SystemRuntimeFacadeRef, ValueTupleRef };
#region General
[Fact]
public void EmitDebugInfoForSourceTextWithoutEncoding1()
{
var tree1 = SyntaxFactory.ParseSyntaxTree("class A { }", encoding: null, path: "Foo.cs");
var tree2 = SyntaxFactory.ParseSyntaxTree("class B { }", encoding: null, path: "");
var tree3 = SyntaxFactory.ParseSyntaxTree(SourceText.From("class C { }", encoding: null), path: "Bar.cs");
var tree4 = SyntaxFactory.ParseSyntaxTree("class D { }", encoding: Encoding.UTF8, path: "Baz.cs");
var comp = CSharpCompilation.Create("Compilation", new[] { tree1, tree2, tree3, tree4 }, new[] { MscorlibRef }, options: TestOptions.ReleaseDll);
var result = comp.Emit(new MemoryStream(), pdbStream: new MemoryStream());
result.Diagnostics.Verify(
// Foo.cs(1,1): error CS8055: Cannot emit debug information for a source text without encoding.
Diagnostic(ErrorCode.ERR_EncodinglessSyntaxTree, "class A { }").WithLocation(1, 1),
// Bar.cs(1,1): error CS8055: Cannot emit debug information for a source text without encoding.
Diagnostic(ErrorCode.ERR_EncodinglessSyntaxTree, "class C { }").WithLocation(1, 1));
Assert.False(result.Success);
}
[Fact]
public void EmitDebugInfoForSourceTextWithoutEncoding2()
{
var tree1 = SyntaxFactory.ParseSyntaxTree("class A { public void F() { } }", encoding: Encoding.Unicode, path: "Foo.cs");
var tree2 = SyntaxFactory.ParseSyntaxTree("class B { public void F() { } }", encoding: null, path: "");
var tree3 = SyntaxFactory.ParseSyntaxTree("class C { public void F() { } }", encoding: new UTF8Encoding(true, false), path: "Bar.cs");
var tree4 = SyntaxFactory.ParseSyntaxTree(SourceText.From("class D { public void F() { } }", new UTF8Encoding(false, false)), path: "Baz.cs");
var comp = CSharpCompilation.Create("Compilation", new[] { tree1, tree2, tree3, tree4 }, new[] { MscorlibRef }, options: TestOptions.ReleaseDll);
var result = comp.Emit(new MemoryStream(), pdbStream: new MemoryStream());
result.Diagnostics.Verify();
Assert.True(result.Success);
var hash1 = CryptographicHashProvider.ComputeSha1(Encoding.Unicode.GetBytesWithPreamble(tree1.ToString())).ToArray();
var hash3 = CryptographicHashProvider.ComputeSha1(new UTF8Encoding(true, false).GetBytesWithPreamble(tree3.ToString())).ToArray();
var hash4 = CryptographicHashProvider.ComputeSha1(new UTF8Encoding(false, false).GetBytesWithPreamble(tree4.ToString())).ToArray();
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""Foo.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""" + BitConverter.ToString(hash1) + @""" />
<file id=""2"" name="""" language=""C#"" />
<file id=""3"" name=""Bar.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""" + BitConverter.ToString(hash3) + @""" />
<file id=""4"" name=""Baz.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""" + BitConverter.ToString(hash4) + @""" />
</files>
</symbols>", options: PdbValidationOptions.ExcludeMethods);
}
[WorkItem(846584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/846584")]
[ConditionalFact(typeof(WindowsOnly))]
public void RelativePathForExternalSource_Sha1_Windows()
{
var text1 = WithWindowsLineBreaks(@"
#pragma checksum ""..\Test2.cs"" ""{406ea660-64cf-4c82-b6f0-42d48172a799}"" ""BA8CBEA9C2EFABD90D53B616FB80A081""
public class C
{
public void InitializeComponent() {
#line 4 ""..\Test2.cs""
InitializeComponent();
#line default
}
}
");
var compilation = CreateCompilation(
new[] { Parse(text1, @"C:\Folder1\Folder2\Test1.cs") },
options: TestOptions.DebugDll.WithSourceReferenceResolver(SourceFileResolver.Default));
compilation.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""C:\Folder1\Folder2\Test1.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""40-A6-20-02-2E-60-7D-4F-2D-A8-F4-A6-ED-2E-0E-49-8D-9F-D7-EB"" />
<file id=""2"" name=""C:\Folder1\Test2.cs"" language=""C#"" checksumAlgorithm=""406ea660-64cf-4c82-b6f0-42d48172a799"" checksum=""BA-8C-BE-A9-C2-EF-AB-D9-0D-53-B6-16-FB-80-A0-81"" />
</files>
<methods>
<method containingType=""C"" name=""InitializeComponent"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""39"" endLine=""6"" endColumn=""40"" document=""1"" />
<entry offset=""0x1"" startLine=""4"" startColumn=""9"" endLine=""4"" endColumn=""31"" document=""2"" />
<entry offset=""0x8"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(846584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/846584")]
[ConditionalFact(typeof(UnixLikeOnly))]
public void RelativePathForExternalSource_Sha1_Unix()
{
var text1 = WithWindowsLineBreaks(@"
#pragma checksum ""../Test2.cs"" ""{406ea660-64cf-4c82-b6f0-42d48172a799}"" ""BA8CBEA9C2EFABD90D53B616FB80A081""
public class C
{
public void InitializeComponent() {
#line 4 ""../Test2.cs""
InitializeComponent();
#line default
}
}
");
var compilation = CreateCompilation(
new[] { Parse(text1, @"/Folder1/Folder2/Test1.cs") },
options: TestOptions.DebugDll.WithSourceReferenceResolver(SourceFileResolver.Default));
compilation.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""/Folder1/Folder2/Test1.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""82-08-07-BA-BA-52-02-D8-1D-1F-7C-E7-95-8A-6C-04-64-FF-50-31"" />
<file id=""2"" name=""/Folder1/Test2.cs"" language=""C#"" checksumAlgorithm=""406ea660-64cf-4c82-b6f0-42d48172a799"" checksum=""BA-8C-BE-A9-C2-EF-AB-D9-0D-53-B6-16-FB-80-A0-81"" />
</files>
<methods>
<method containingType=""C"" name=""InitializeComponent"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""39"" endLine=""6"" endColumn=""40"" document=""1"" />
<entry offset=""0x1"" startLine=""4"" startColumn=""9"" endLine=""4"" endColumn=""31"" document=""2"" />
<entry offset=""0x8"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SymWriterErrors()
{
var source0 =
@"class C
{
}";
var compilation = CreateCompilation(source0, options: TestOptions.DebugDll);
// Verify full metadata contains expected rows.
var result = compilation.Emit(
peStream: new MemoryStream(),
metadataPEStream: null,
pdbStream: new MemoryStream(),
xmlDocumentationStream: null,
cancellationToken: default,
win32Resources: null,
manifestResources: null,
options: null,
debugEntryPoint: null,
sourceLinkStream: null,
embeddedTexts: null,
rebuildData: null,
testData: new CompilationTestData() { SymWriterFactory = _ => new MockSymUnmanagedWriter() });
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'MockSymUnmanagedWriter error message'
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("MockSymUnmanagedWriter error message"));
Assert.False(result.Success);
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SymWriterErrors2()
{
var source0 =
@"class C
{
}";
var compilation = CreateCompilation(source0, options: TestOptions.DebugDll);
// Verify full metadata contains expected rows.
var result = compilation.Emit(
peStream: new MemoryStream(),
metadataPEStream: null,
pdbStream: new MemoryStream(),
xmlDocumentationStream: null,
cancellationToken: default,
win32Resources: null,
manifestResources: null,
options: null,
debugEntryPoint: null,
sourceLinkStream: null,
embeddedTexts: null,
rebuildData: null,
testData: new CompilationTestData() { SymWriterFactory = SymWriterTestUtilities.ThrowingFactory });
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'The version of Windows PDB writer is older than required: '<lib name>''
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments(string.Format(CodeAnalysisResources.SymWriterOlderVersionThanRequired, "<lib name>")));
Assert.False(result.Success);
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SymWriterErrors3()
{
var source0 =
@"class C
{
}";
var compilation = CreateCompilation(source0, options: TestOptions.DebugDll.WithDeterministic(true));
// Verify full metadata contains expected rows.
var result = compilation.Emit(
peStream: new MemoryStream(),
metadataPEStream: null,
pdbStream: new MemoryStream(),
xmlDocumentationStream: null,
cancellationToken: default,
win32Resources: null,
manifestResources: null,
options: null,
debugEntryPoint: null,
sourceLinkStream: null,
embeddedTexts: null,
rebuildData: null,
testData: new CompilationTestData() { SymWriterFactory = SymWriterTestUtilities.ThrowingFactory });
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'Windows PDB writer doesn't support deterministic compilation: '<lib name>''
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments(string.Format(CodeAnalysisResources.SymWriterNotDeterministic, "<lib name>")));
Assert.False(result.Success);
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SymWriterErrors4()
{
var source0 =
@"class C
{
}";
var compilation = CreateCompilation(source0);
// Verify full metadata contains expected rows.
var result = compilation.Emit(
peStream: new MemoryStream(),
metadataPEStream: null,
pdbStream: new MemoryStream(),
xmlDocumentationStream: null,
cancellationToken: default,
win32Resources: null,
manifestResources: null,
options: null,
debugEntryPoint: null,
sourceLinkStream: null,
embeddedTexts: null,
rebuildData: null,
testData: new CompilationTestData() { SymWriterFactory = _ => throw new DllNotFoundException("xxx") });
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'xxx'
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("xxx"));
Assert.False(result.Success);
}
[WorkItem(1067635, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067635")]
[Fact]
public void SuppressDynamicAndEncCDIForWinRT()
{
var source = @"
public class C
{
public static void F()
{
dynamic a = 1;
int b = 2;
foreach (var x in new[] { 1,2,3 })
{
System.Console.WriteLine(a * b);
}
}
}
";
var debug = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugWinMD);
debug.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""23"" document=""1"" />
<entry offset=""0x8"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""19"" document=""1"" />
<entry offset=""0xa"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""16"" document=""1"" />
<entry offset=""0xb"" startLine=""8"" startColumn=""27"" endLine=""8"" endColumn=""42"" document=""1"" />
<entry offset=""0x1f"" hidden=""true"" document=""1"" />
<entry offset=""0x24"" startLine=""8"" startColumn=""18"" endLine=""8"" endColumn=""23"" document=""1"" />
<entry offset=""0x29"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x2a"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""45"" document=""1"" />
<entry offset=""0xe6"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0xe7"" hidden=""true"" document=""1"" />
<entry offset=""0xeb"" startLine=""8"" startColumn=""24"" endLine=""8"" endColumn=""26"" document=""1"" />
<entry offset=""0xf4"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xf5"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0xf5"" attributes=""0"" />
<local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0xf5"" attributes=""0"" />
<scope startOffset=""0x24"" endOffset=""0xe7"">
<local name=""x"" il_index=""4"" il_start=""0x24"" il_end=""0xe7"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>", format: DebugInformationFormat.Pdb, options: PdbValidationOptions.SkipConversionValidation);
var release = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.ReleaseWinMD);
release.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""23"" document=""1"" />
<entry offset=""0x7"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""19"" document=""1"" />
<entry offset=""0x9"" startLine=""8"" startColumn=""27"" endLine=""8"" endColumn=""42"" document=""1"" />
<entry offset=""0x1d"" hidden=""true"" document=""1"" />
<entry offset=""0x22"" startLine=""8"" startColumn=""18"" endLine=""8"" endColumn=""23"" document=""1"" />
<entry offset=""0x26"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""45"" document=""1"" />
<entry offset=""0xdd"" hidden=""true"" document=""1"" />
<entry offset=""0xe1"" startLine=""8"" startColumn=""24"" endLine=""8"" endColumn=""26"" document=""1"" />
<entry offset=""0xea"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xeb"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0xeb"" attributes=""0"" />
<local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0xeb"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>", format: DebugInformationFormat.Pdb, options: PdbValidationOptions.SkipConversionValidation);
}
[WorkItem(1067635, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067635")]
[Fact]
public void SuppressTupleElementNamesCDIForWinRT()
{
var source =
@"class C
{
static void F()
{
(int A, int B) o = (1, 2);
}
}";
var debug = CreateCompilation(source, options: TestOptions.DebugWinMD);
debug.VerifyPdb(
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""35"" document=""1"" />
<entry offset=""0x9"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xa"">
<local name=""o"" il_index=""0"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>", format: DebugInformationFormat.Pdb, options: PdbValidationOptions.SkipConversionValidation);
var release = CreateCompilation(source, options: TestOptions.ReleaseWinMD);
release.VerifyPdb(
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>", format: DebugInformationFormat.Pdb, options: PdbValidationOptions.SkipConversionValidation);
}
[Fact]
public void DuplicateDocuments()
{
var source1 = @"class C { static void F() { } }";
var source2 = @"class D { static void F() { } }";
var tree1 = Parse(source1, @"foo.cs");
var tree2 = Parse(source2, @"foo.cs");
var comp = CreateCompilation(new[] { tree1, tree2 });
// the first file wins (checksum CB 22 ...)
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""foo.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""CB-22-D8-03-D3-27-32-64-2C-BC-7D-67-5D-E3-CB-AC-D1-64-25-83"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""29"" endLine=""1"" endColumn=""30"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""D"" name=""F"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""29"" endLine=""1"" endColumn=""30"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
public void CustomDebugEntryPoint_DLL()
{
var source = @"class C { static void F() { } }";
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var f = c.GetMember<MethodSymbol>("C.F");
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""F"" />
<methods/>
</symbols>", debugEntryPoint: f.GetPublicSymbol(), options: PdbValidationOptions.ExcludeScopes | PdbValidationOptions.ExcludeSequencePoints | PdbValidationOptions.ExcludeCustomDebugInformation);
var peReader = new PEReader(c.EmitToArray(debugEntryPoint: f.GetPublicSymbol()));
int peEntryPointToken = peReader.PEHeaders.CorHeader.EntryPointTokenOrRelativeVirtualAddress;
Assert.Equal(0, peEntryPointToken);
}
[Fact]
public void CustomDebugEntryPoint_EXE()
{
var source = @"class M { static void Main() { } } class C { static void F<S>() { } }";
var c = CreateCompilation(source, options: TestOptions.DebugExe);
var f = c.GetMember<MethodSymbol>("C.F");
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""F"" />
<methods/>
</symbols>", debugEntryPoint: f.GetPublicSymbol(), options: PdbValidationOptions.ExcludeScopes | PdbValidationOptions.ExcludeSequencePoints | PdbValidationOptions.ExcludeCustomDebugInformation);
var peReader = new PEReader(c.EmitToArray(debugEntryPoint: f.GetPublicSymbol()));
int peEntryPointToken = peReader.PEHeaders.CorHeader.EntryPointTokenOrRelativeVirtualAddress;
var mdReader = peReader.GetMetadataReader();
var methodDef = mdReader.GetMethodDefinition((MethodDefinitionHandle)MetadataTokens.Handle(peEntryPointToken));
Assert.Equal("Main", mdReader.GetString(methodDef.Name));
}
[Fact]
public void CustomDebugEntryPoint_Errors()
{
var source1 = @"class C { static void F() { } } class D<T> { static void G<S>() {} }";
var source2 = @"class C { static void F() { } }";
var c1 = CreateCompilation(source1, options: TestOptions.DebugDll);
var c2 = CreateCompilation(source2, options: TestOptions.DebugDll);
var f1 = c1.GetMember<MethodSymbol>("C.F");
var f2 = c2.GetMember<MethodSymbol>("C.F");
var g = c1.GetMember<MethodSymbol>("D.G");
var d = c1.GetMember<NamedTypeSymbol>("D");
Assert.NotNull(f1);
Assert.NotNull(f2);
Assert.NotNull(g);
Assert.NotNull(d);
var stInt = c1.GetSpecialType(SpecialType.System_Int32);
var d_t_g_int = g.Construct(stInt);
var d_int = d.Construct(stInt);
var d_int_g = d_int.GetMember<MethodSymbol>("G");
var d_int_g_int = d_int_g.Construct(stInt);
var result = c1.Emit(new MemoryStream(), new MemoryStream(), debugEntryPoint: f2.GetPublicSymbol());
result.Diagnostics.Verify(
// error CS8096: Debug entry point must be a definition of a source method in the current compilation.
Diagnostic(ErrorCode.ERR_DebugEntryPointNotSourceMethodDefinition));
result = c1.Emit(new MemoryStream(), new MemoryStream(), debugEntryPoint: d_t_g_int.GetPublicSymbol());
result.Diagnostics.Verify(
// error CS8096: Debug entry point must be a definition of a source method in the current compilation.
Diagnostic(ErrorCode.ERR_DebugEntryPointNotSourceMethodDefinition));
result = c1.Emit(new MemoryStream(), new MemoryStream(), debugEntryPoint: d_int_g.GetPublicSymbol());
result.Diagnostics.Verify(
// error CS8096: Debug entry point must be a definition of a source method in the current compilation.
Diagnostic(ErrorCode.ERR_DebugEntryPointNotSourceMethodDefinition));
result = c1.Emit(new MemoryStream(), new MemoryStream(), debugEntryPoint: d_int_g_int.GetPublicSymbol());
result.Diagnostics.Verify(
// error CS8096: Debug entry point must be a definition of a source method in the current compilation.
Diagnostic(ErrorCode.ERR_DebugEntryPointNotSourceMethodDefinition));
}
[Fact]
[WorkItem(768862, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/768862")]
public void TestLargeLineDelta()
{
var verbatim = string.Join("\r\n", Enumerable.Repeat("x", 1000));
var source = $@"
class C {{ public static void Main() => System.Console.WriteLine(@""{verbatim}""); }}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""2"" startColumn=""40"" endLine=""1001"" endColumn=""4"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
", format: DebugInformationFormat.PortablePdb);
// Native PDBs only support spans with line delta <= 127 (7 bit)
// https://github.com/Microsoft/microsoft-pdb/blob/main/include/cvinfo.h#L4621
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""2"" startColumn=""40"" endLine=""129"" endColumn=""4"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
", format: DebugInformationFormat.Pdb);
}
[Fact]
[WorkItem(20118, "https://github.com/dotnet/roslyn/issues/20118")]
public void TestLargeStartAndEndColumn_SameLine()
{
var spaces = new string(' ', 0x10000);
var source = $@"
class C
{{
public static void Main() =>
{spaces}System.Console.WriteLine(""{spaces}"");
}}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""65533"" endLine=""5"" endColumn=""65534"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
[WorkItem(20118, "https://github.com/dotnet/roslyn/issues/20118")]
public void TestLargeStartAndEndColumn_DifferentLine()
{
var spaces = new string(' ', 0x10000);
var source = $@"
class C
{{
public static void Main() =>
{spaces}System.Console.WriteLine(
""{spaces}"");
}}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""65534"" endLine=""6"" endColumn=""65534"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
#endregion
#region Method Bodies
[Fact]
public void TestBasic()
{
var source = WithWindowsLineBreaks(@"
class Program
{
Program() { }
static void Main(string[] args)
{
Program p = new Program();
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("Program.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<forward declaringType=""Program"" methodName="".ctor"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""19"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""35"" document=""1"" />
<entry offset=""0x7"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x8"">
<local name=""p"" il_index=""0"" il_start=""0x0"" il_end=""0x8"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void TestSimpleLocals()
{
var source = WithWindowsLineBreaks(@"
class C
{
void Method()
{ //local at method scope
object version = 6;
System.Console.WriteLine(""version {0}"", version);
{
//a scope that defines no locals
{
//a nested local
object foob = 1;
System.Console.WriteLine(""foob {0}"", foob);
}
{
//a nested local
int foob1 = 1;
System.Console.WriteLine(""foob1 {0}"", foob1);
}
System.Console.WriteLine(""Eva"");
}
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.Method", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Method"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""44"" />
<slot kind=""0"" offset=""246"" />
<slot kind=""0"" offset=""402"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""28"" document=""1"" />
<entry offset=""0x8"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""58"" document=""1"" />
<entry offset=""0x14"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" />
<entry offset=""0x15"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""14"" document=""1"" />
<entry offset=""0x16"" startLine=""12"" startColumn=""17"" endLine=""12"" endColumn=""33"" document=""1"" />
<entry offset=""0x1d"" startLine=""13"" startColumn=""17"" endLine=""13"" endColumn=""60"" document=""1"" />
<entry offset=""0x29"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""14"" document=""1"" />
<entry offset=""0x2a"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""14"" document=""1"" />
<entry offset=""0x2b"" startLine=""17"" startColumn=""17"" endLine=""17"" endColumn=""31"" document=""1"" />
<entry offset=""0x2d"" startLine=""18"" startColumn=""17"" endLine=""18"" endColumn=""62"" document=""1"" />
<entry offset=""0x3e"" startLine=""19"" startColumn=""13"" endLine=""19"" endColumn=""14"" document=""1"" />
<entry offset=""0x3f"" startLine=""20"" startColumn=""13"" endLine=""20"" endColumn=""45"" document=""1"" />
<entry offset=""0x4a"" startLine=""21"" startColumn=""9"" endLine=""21"" endColumn=""10"" document=""1"" />
<entry offset=""0x4b"" startLine=""22"" startColumn=""5"" endLine=""22"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x4c"">
<local name=""version"" il_index=""0"" il_start=""0x0"" il_end=""0x4c"" attributes=""0"" />
<scope startOffset=""0x15"" endOffset=""0x2a"">
<local name=""foob"" il_index=""1"" il_start=""0x15"" il_end=""0x2a"" attributes=""0"" />
</scope>
<scope startOffset=""0x2a"" endOffset=""0x3f"">
<local name=""foob1"" il_index=""2"" il_start=""0x2a"" il_end=""0x3f"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
[WorkItem(7244, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/7244")]
public void ConstructorsWithoutInitializers()
{
var source = WithWindowsLineBreaks(
@"class C
{
C()
{
object o;
}
C(object x)
{
object y = x;
}
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""18"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""3"" startColumn=""5"" endLine=""3"" endColumn=""8"" document=""1"" />
<entry offset=""0x7"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" />
<entry offset=""0x8"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x9"">
<scope startOffset=""0x7"" endOffset=""0x9"">
<local name=""o"" il_index=""0"" il_start=""0x7"" il_end=""0x9"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""C"" name="".ctor"" parameterNames=""x"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""18"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""16"" document=""1"" />
<entry offset=""0x7"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
<entry offset=""0x8"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""22"" document=""1"" />
<entry offset=""0xa"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xb"">
<scope startOffset=""0x7"" endOffset=""0xb"">
<local name=""y"" il_index=""0"" il_start=""0x7"" il_end=""0xb"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(7244, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/7244")]
[Fact]
public void ConstructorsWithInitializers()
{
var source = WithWindowsLineBreaks(
@"class C
{
static object G = 1;
object F = G;
C()
{
object o;
}
C(object x)
{
object y = x;
}
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""18"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""18"" document=""1"" />
<entry offset=""0xb"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""8"" document=""1"" />
<entry offset=""0x12"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
<entry offset=""0x13"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x14"">
<scope startOffset=""0x12"" endOffset=""0x14"">
<local name=""o"" il_index=""0"" il_start=""0x12"" il_end=""0x14"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""C"" name="".ctor"" parameterNames=""x"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""18"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""18"" document=""1"" />
<entry offset=""0xb"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""16"" document=""1"" />
<entry offset=""0x12"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
<entry offset=""0x13"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""22"" document=""1"" />
<entry offset=""0x15"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x16"">
<scope startOffset=""0x12"" endOffset=""0x16"">
<local name=""y"" il_index=""0"" il_start=""0x12"" il_end=""0x16"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
/// <summary>
/// Although the debugging info attached to DebuggerHidden method is not used by the debugger
/// (the debugger doesn't ever stop in the method) Dev11 emits the info and so do we.
///
/// StepThrough method needs the information if JustMyCode is disabled and a breakpoint is set within the method.
/// NonUserCode method needs the information if JustMyCode is disabled.
///
/// It's up to the tool that consumes the debugging information, not the compiler to decide whether to ignore the info or not.
/// BTW, the information can actually be retrieved at runtime from the PDB file via Reflection StackTrace.
/// </summary>
[Fact]
public void MethodsWithDebuggerAttributes()
{
var source = WithWindowsLineBreaks(@"
using System;
using System.Diagnostics;
class Program
{
[DebuggerHidden]
static void Hidden()
{
int x = 1;
Console.WriteLine(x);
}
[DebuggerStepThrough]
static void StepThrough()
{
int y = 1;
Console.WriteLine(y);
}
[DebuggerNonUserCode]
static void NonUserCode()
{
int z = 1;
Console.WriteLine(z);
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Hidden"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""19"" document=""1"" />
<entry offset=""0x3"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""30"" document=""1"" />
<entry offset=""0xa"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xb"">
<namespace name=""System"" />
<namespace name=""System.Diagnostics"" />
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0xb"" attributes=""0"" />
</scope>
</method>
<method containingType=""Program"" name=""StepThrough"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""Hidden"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""19"" document=""1"" />
<entry offset=""0x3"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""30"" document=""1"" />
<entry offset=""0xa"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xb"">
<local name=""y"" il_index=""0"" il_start=""0x0"" il_end=""0xb"" attributes=""0"" />
</scope>
</method>
<method containingType=""Program"" name=""NonUserCode"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""Hidden"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""19"" document=""1"" />
<entry offset=""0x3"" startLine=""25"" startColumn=""9"" endLine=""25"" endColumn=""30"" document=""1"" />
<entry offset=""0xa"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xb"">
<local name=""z"" il_index=""0"" il_start=""0x0"" il_end=""0xb"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
/// <summary>
/// If a synthesized method contains any user code,
/// the method must have a sequence point at
/// offset 0 for correct stepping behavior.
/// </summary>
[WorkItem(804681, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/804681")]
[Fact]
public void SequencePointAtOffset0()
{
string source = WithWindowsLineBreaks(
@"using System;
class C
{
static Func<object, int> F = x =>
{
Func<object, int> f = o => 1;
Func<Func<object, int>, Func<object, int>> g = h => y => h(y);
return g(f)(null);
};
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".cctor"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLambdaMap>
<methodOrdinal>2</methodOrdinal>
<closure offset=""-45"" />
<lambda offset=""-147"" />
<lambda offset=""-109"" />
<lambda offset=""-45"" />
<lambda offset=""-40"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""9"" endColumn=""7"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x16"">
<namespace name=""System"" />
</scope>
</method>
<method containingType=""C+<>c__DisplayClass2_0"" name=""<.cctor>b__3"" parameterNames=""y"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".cctor"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""66"" endLine=""7"" endColumn=""70"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C+<>c"" name=""<.cctor>b__2_0"" parameterNames=""x"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".cctor"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""-118"" />
<slot kind=""0"" offset=""-54"" />
<slot kind=""21"" offset=""-147"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""38"" document=""1"" />
<entry offset=""0x21"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""71"" document=""1"" />
<entry offset=""0x41"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""27"" document=""1"" />
<entry offset=""0x51"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x53"">
<local name=""f"" il_index=""0"" il_start=""0x0"" il_end=""0x53"" attributes=""0"" />
<local name=""g"" il_index=""1"" il_start=""0x0"" il_end=""0x53"" attributes=""0"" />
</scope>
</method>
<method containingType=""C+<>c"" name=""<.cctor>b__2_1"" parameterNames=""o"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".cctor"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""36"" endLine=""6"" endColumn=""37"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C+<>c"" name=""<.cctor>b__2_2"" parameterNames=""h"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".cctor"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""-45"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""7"" startColumn=""61"" endLine=""7"" endColumn=""70"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1a"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x1a"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
/// <summary>
/// Leading trivia is not included in the syntax offset.
/// </summary>
[Fact]
public void SyntaxOffsetInPresenceOfTrivia_Methods()
{
string source = @"
class C
{
public static void Main1() /*Comment1*/{/*Comment2*/int a = 1;/*Comment3*/}/*Comment4*/
public static void Main2() {/*Comment2*/int a = 2;/*Comment3*/}/*Comment4*/
}";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
// verify that both syntax offsets are the same
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main1"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""17"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""44"" endLine=""4"" endColumn=""45"" document=""1"" />
<entry offset=""0x1"" startLine=""4"" startColumn=""57"" endLine=""4"" endColumn=""67"" document=""1"" />
<entry offset=""0x3"" startLine=""4"" startColumn=""79"" endLine=""4"" endColumn=""80"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x4"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" />
</scope>
</method>
<method containingType=""C"" name=""Main2"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Main1"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""17"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""32"" endLine=""5"" endColumn=""33"" document=""1"" />
<entry offset=""0x1"" startLine=""5"" startColumn=""45"" endLine=""5"" endColumn=""55"" document=""1"" />
<entry offset=""0x3"" startLine=""5"" startColumn=""67"" endLine=""5"" endColumn=""68"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x4"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
/// <summary>
/// Leading and trailing trivia are not included in the syntax offset.
/// </summary>
[Fact]
public void SyntaxOffsetInPresenceOfTrivia_Initializers()
{
string source = @"
using System;
class C1
{
public static Func<int> e=() => 0;
public static Func<int> f/*Comment0*/=/*Comment1*/() => 1;/*Comment2*/
public static Func<int> g=() => 2;
}
class C2
{
public static Func<int> e=() => 0;
public static Func<int> f=/*Comment1*/() => 1;
public static Func<int> g=() => 2;
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
// verify that syntax offsets of both .cctor's are the same
c.VerifyPdb("C1..cctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C1"" name="".cctor"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLambdaMap>
<methodOrdinal>4</methodOrdinal>
<lambda offset=""-29"" />
<lambda offset=""-9"" />
<lambda offset=""-1"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""39"" document=""1"" />
<entry offset=""0x15"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""63"" document=""1"" />
<entry offset=""0x2a"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""39"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x40"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
c.VerifyPdb("C2..cctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C2"" name="".cctor"">
<customDebugInfo>
<forward declaringType=""C1"" methodName="".cctor"" />
<encLambdaMap>
<methodOrdinal>4</methodOrdinal>
<lambda offset=""-29"" />
<lambda offset=""-9"" />
<lambda offset=""-1"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""39"" document=""1"" />
<entry offset=""0x15"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""51"" document=""1"" />
<entry offset=""0x2a"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""39"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
#endregion
#region ReturnStatement
[Fact]
public void Return_Method1()
{
var source = WithWindowsLineBreaks(@"
class Program
{
static int Main()
{
return 1;
}
}
");
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
// In order to place a breakpoint on the closing brace we need to save the return expression value to
// a local and then load it again (since sequence point needs an empty stack). This variable has to be marked as long-lived.
v.VerifyIL("Program.Main", @"
{
// Code size 7 (0x7)
.maxstack 1
.locals init (int V_0)
-IL_0000: nop
-IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: br.s IL_0005
-IL_0005: ldloc.0
IL_0006: ret
}", sequencePoints: "Program.Main");
v.VerifyPdb("Program.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""18"" document=""1"" />
<entry offset=""0x5"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void Return_Property1()
{
var source = WithWindowsLineBreaks(@"
class C
{
static int P
{
get { return 1; }
}
}
");
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
// In order to place a breakpoint on the closing brace we need to save the return expression value to
// a local and then load it again (since sequence point needs an empty stack). This variable has to be marked as long-lived.
v.VerifyIL("C.P.get", @"
{
// Code size 7 (0x7)
.maxstack 1
.locals init (int V_0)
-IL_0000: nop
-IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: br.s IL_0005
-IL_0005: ldloc.0
IL_0006: ret
}", sequencePoints: "C.get_P");
v.VerifyPdb("C.get_P", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""get_P"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""13"" endLine=""6"" endColumn=""14"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""15"" endLine=""6"" endColumn=""24"" document=""1"" />
<entry offset=""0x5"" startLine=""6"" startColumn=""25"" endLine=""6"" endColumn=""26"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void Return_Void1()
{
var source = @"
class Program
{
static void Main()
{
return;
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.Main", @"
{
// Code size 4 (0x4)
.maxstack 0
-IL_0000: nop
-IL_0001: br.s IL_0003
-IL_0003: ret
}", sequencePoints: "Program.Main");
}
[Fact]
public void Return_ExpressionBodied1()
{
var source = @"
class Program
{
static int Main() => 1;
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.Main", @"
{
// Code size 2 (0x2)
.maxstack 1
-IL_0000: ldc.i4.1
IL_0001: ret
}", sequencePoints: "Program.Main");
}
[Fact]
public void Return_FromExceptionHandler1()
{
var source = WithWindowsLineBreaks(@"
using System;
class Program
{
static int Main()
{
try
{
Console.WriteLine();
return 1;
}
catch (Exception)
{
return 2;
}
}
}
");
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.Main", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (int V_0)
-IL_0000: nop
.try
{
-IL_0001: nop
-IL_0002: call ""void System.Console.WriteLine()""
IL_0007: nop
-IL_0008: ldc.i4.1
IL_0009: stloc.0
IL_000a: leave.s IL_0012
}
catch System.Exception
{
-IL_000c: pop
-IL_000d: nop
-IL_000e: ldc.i4.2
IL_000f: stloc.0
IL_0010: leave.s IL_0012
}
-IL_0012: ldloc.0
IL_0013: ret
}", sequencePoints: "Program.Main");
v.VerifyPdb("Program.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x2"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""33"" document=""1"" />
<entry offset=""0x8"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""22"" document=""1"" />
<entry offset=""0xc"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""26"" document=""1"" />
<entry offset=""0xd"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" />
<entry offset=""0xe"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""22"" document=""1"" />
<entry offset=""0x12"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x14"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region IfStatement
[Fact]
public void IfStatement()
{
var source = WithWindowsLineBreaks(@"
class C
{
void Method()
{
bool b = true;
if (b)
{
string s = ""true"";
System.Console.WriteLine(s);
}
else
{
string s = ""false"";
int i = 1;
while (i < 100)
{
int j = i, k = 1;
System.Console.WriteLine(j);
i = j + k;
}
i = i + 1;
}
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.Method", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Method"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""19"" />
<slot kind=""1"" offset=""38"" />
<slot kind=""0"" offset=""76"" />
<slot kind=""0"" offset=""188"" />
<slot kind=""0"" offset=""218"" />
<slot kind=""0"" offset=""292"" />
<slot kind=""0"" offset=""299"" />
<slot kind=""1"" offset=""240"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""23"" document=""1"" />
<entry offset=""0x3"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""15"" document=""1"" />
<entry offset=""0x5"" hidden=""true"" document=""1"" />
<entry offset=""0x8"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" />
<entry offset=""0x9"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""31"" document=""1"" />
<entry offset=""0xf"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""41"" document=""1"" />
<entry offset=""0x16"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0x17"" hidden=""true"" document=""1"" />
<entry offset=""0x19"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x1a"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""32"" document=""1"" />
<entry offset=""0x20"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""23"" document=""1"" />
<entry offset=""0x23"" hidden=""true"" document=""1"" />
<entry offset=""0x25"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""14"" document=""1"" />
<entry offset=""0x26"" startLine=""19"" startColumn=""17"" endLine=""19"" endColumn=""26"" document=""1"" />
<entry offset=""0x2a"" startLine=""19"" startColumn=""28"" endLine=""19"" endColumn=""33"" document=""1"" />
<entry offset=""0x2d"" startLine=""20"" startColumn=""17"" endLine=""20"" endColumn=""45"" document=""1"" />
<entry offset=""0x35"" startLine=""21"" startColumn=""17"" endLine=""21"" endColumn=""27"" document=""1"" />
<entry offset=""0x3c"" startLine=""22"" startColumn=""13"" endLine=""22"" endColumn=""14"" document=""1"" />
<entry offset=""0x3d"" startLine=""17"" startColumn=""13"" endLine=""17"" endColumn=""28"" document=""1"" />
<entry offset=""0x45"" hidden=""true"" document=""1"" />
<entry offset=""0x49"" startLine=""24"" startColumn=""13"" endLine=""24"" endColumn=""23"" document=""1"" />
<entry offset=""0x4f"" startLine=""25"" startColumn=""9"" endLine=""25"" endColumn=""10"" document=""1"" />
<entry offset=""0x50"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x51"">
<local name=""b"" il_index=""0"" il_start=""0x0"" il_end=""0x51"" attributes=""0"" />
<scope startOffset=""0x8"" endOffset=""0x17"">
<local name=""s"" il_index=""2"" il_start=""0x8"" il_end=""0x17"" attributes=""0"" />
</scope>
<scope startOffset=""0x19"" endOffset=""0x50"">
<local name=""s"" il_index=""3"" il_start=""0x19"" il_end=""0x50"" attributes=""0"" />
<local name=""i"" il_index=""4"" il_start=""0x19"" il_end=""0x50"" attributes=""0"" />
<scope startOffset=""0x25"" endOffset=""0x3d"">
<local name=""j"" il_index=""5"" il_start=""0x25"" il_end=""0x3d"" attributes=""0"" />
<local name=""k"" il_index=""6"" il_start=""0x25"" il_end=""0x3d"" attributes=""0"" />
</scope>
</scope>
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region WhileStatement
[WorkItem(538299, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538299")]
[Fact]
public void WhileStatement()
{
var source = @"using System;
public class SeqPointForWhile
{
public static void Main()
{
SeqPointForWhile obj = new SeqPointForWhile();
obj.While(234);
}
int field;
public void While(int p)
{
while (p > 0) // SeqPt should be generated at the end of loop
{
p = (int)(p / 2);
if (p > 100)
{
continue;
}
else if (p > 10)
{
int x = p;
field = x;
}
else
{
int x = p;
Console.WriteLine(x);
break;
}
}
field = -1;
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe);
// Offset 0x01 should be:
// <entry offset=""0x1"" hidden=""true"" document=""1"" />
// Move original offset 0x01 to 0x33
// <entry offset=""0x33"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""22"" document=""1"" />
//
// Note: 16707566 == 0x00FEEFEE
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""SeqPointForWhile"" methodName=""Main"" />
<methods>
<method containingType=""SeqPointForWhile"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""55"" document=""1"" />
<entry offset=""0x5"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""24"" document=""1"" />
<entry offset=""0xf"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x10"">
<namespace name=""System"" />
</scope>
</method>
<method containingType=""SeqPointForWhile"" name=""While"" parameterNames=""p"">
<customDebugInfo>
<forward declaringType=""SeqPointForWhile"" methodName=""Main"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x2"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""30"" document=""1"" />
<entry offset=""0x7"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""25"" document=""1"" />
<entry offset=""0xc"" startLine=""22"" startColumn=""18"" endLine=""22"" endColumn=""29"" document=""1"" />
<entry offset=""0x11"" startLine=""24"" startColumn=""17"" endLine=""24"" endColumn=""27"" document=""1"" />
<entry offset=""0x13"" startLine=""25"" startColumn=""17"" endLine=""25"" endColumn=""27"" document=""1"" />
<entry offset=""0x1a"" hidden=""true"" document=""1"" />
<entry offset=""0x1c"" startLine=""29"" startColumn=""17"" endLine=""29"" endColumn=""27"" document=""1"" />
<entry offset=""0x1d"" startLine=""30"" startColumn=""17"" endLine=""30"" endColumn=""38"" document=""1"" />
<entry offset=""0x22"" startLine=""31"" startColumn=""17"" endLine=""31"" endColumn=""23"" document=""1"" />
<entry offset=""0x24"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""22"" document=""1"" />
<entry offset=""0x28"" startLine=""34"" startColumn=""9"" endLine=""34"" endColumn=""20"" document=""1"" />
<entry offset=""0x2f"" startLine=""35"" startColumn=""5"" endLine=""35"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x30"">
<scope startOffset=""0x11"" endOffset=""0x1a"">
<local name=""x"" il_index=""0"" il_start=""0x11"" il_end=""0x1a"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region ForStatement
[Fact]
public void ForStatement1()
{
var source = WithWindowsLineBreaks(@"
class C
{
static bool F(int i) { return true; }
static void G(int i) { }
static void M()
{
for (int i = 1; F(i); G(i))
{
System.Console.WriteLine(1);
}
}
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.M", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" parameterNames=""i"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""20"" />
<slot kind=""1"" offset=""11"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""14"" endLine=""9"" endColumn=""23"" document=""1"" />
<entry offset=""0x3"" hidden=""true"" document=""1"" />
<entry offset=""0x5"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" />
<entry offset=""0x6"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""41"" document=""1"" />
<entry offset=""0xd"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" />
<entry offset=""0xe"" startLine=""9"" startColumn=""31"" endLine=""9"" endColumn=""35"" document=""1"" />
<entry offset=""0x15"" startLine=""9"" startColumn=""25"" endLine=""9"" endColumn=""29"" document=""1"" />
<entry offset=""0x1c"" hidden=""true"" document=""1"" />
<entry offset=""0x1f"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x20"">
<scope startOffset=""0x1"" endOffset=""0x1f"">
<local name=""i"" il_index=""0"" il_start=""0x1"" il_end=""0x1f"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void ForStatement2()
{
var source = @"
class C
{
static void M()
{
for (;;)
{
System.Console.WriteLine(1);
}
}
}";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.M", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" hidden=""true"" document=""1"" />
<entry offset=""0x3"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" />
<entry offset=""0x4"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""41"" document=""1"" />
<entry offset=""0xb"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0xc"" hidden=""true"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
public void ForStatement3()
{
var source = WithWindowsLineBreaks(@"
class C
{
static void M()
{
int i = 0;
for (;;i++)
{
System.Console.WriteLine(i);
}
}
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.M", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""19"" document=""1"" />
<entry offset=""0x3"" hidden=""true"" document=""1"" />
<entry offset=""0x5"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" />
<entry offset=""0x6"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""41"" document=""1"" />
<entry offset=""0xd"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" />
<entry offset=""0xe"" startLine=""7"" startColumn=""16"" endLine=""7"" endColumn=""19"" document=""1"" />
<entry offset=""0x12"" hidden=""true"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x14"">
<local name=""i"" il_index=""0"" il_start=""0x0"" il_end=""0x14"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region ForEachStatement
[Fact]
public void ForEachStatement_String()
{
var source = @"
public class C
{
public static void Main()
{
foreach (var c in ""hello"")
{
System.Console.WriteLine(c);
}
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe);
// Sequence points:
// 1) Open brace at start of method
// 2) 'foreach'
// 3) '"hello"'
// 4) Hidden initial jump (of for loop)
// 5) 'var c'
// 6) Open brace of loop
// 7) Loop body
// 8) Close brace of loop
// 9) Hidden index increment.
// 10) 'in'
// 11) Close brace at end of method
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""27"" endLine=""6"" endColumn=""34"" document=""1"" />
<entry offset=""0x8"" hidden=""true"" document=""1"" />
<entry offset=""0xa"" startLine=""6"" startColumn=""18"" endLine=""6"" endColumn=""23"" document=""1"" />
<entry offset=""0x11"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""41"" document=""1"" />
<entry offset=""0x16"" hidden=""true"" document=""1"" />
<entry offset=""0x1a"" startLine=""6"" startColumn=""24"" endLine=""6"" endColumn=""26"" document=""1"" />
<entry offset=""0x23"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void ForEachStatement_Array()
{
var source = WithWindowsLineBreaks(@"
public class C
{
public static void Main()
{
foreach (var x in new int[2])
{
System.Console.WriteLine(x);
}
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
// Sequence points:
// 1) Open brace at start of method
// 2) 'foreach'
// 3) 'new int[2]'
// 4) Hidden initial jump (of for loop)
// 5) 'var c'
// 6) Open brace of loop
// 7) Loop body
// 8) Close brace of loop
// 9) Hidden index increment.
// 10) 'in'
// 11) Close brace at end of method
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""6"" offset=""11"" />
<slot kind=""8"" offset=""11"" />
<slot kind=""0"" offset=""11"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""16"" document=""1"" />
<entry offset=""0x2"" startLine=""6"" startColumn=""27"" endLine=""6"" endColumn=""37"" document=""1"" />
<entry offset=""0xb"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""6"" startColumn=""18"" endLine=""6"" endColumn=""23"" document=""1"" />
<entry offset=""0x11"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" />
<entry offset=""0x12"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""41"" document=""1"" />
<entry offset=""0x19"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x1a"" hidden=""true"" document=""1"" />
<entry offset=""0x1e"" startLine=""6"" startColumn=""24"" endLine=""6"" endColumn=""26"" document=""1"" />
<entry offset=""0x24"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x25"">
<scope startOffset=""0xd"" endOffset=""0x1a"">
<local name=""x"" il_index=""2"" il_start=""0xd"" il_end=""0x1a"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(544937, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544937")]
[Fact]
public void ForEachStatement_MultiDimensionalArray()
{
var source = @"
public class C
{
public static void Main()
{
foreach (var x in new int[2, 3])
{
System.Console.WriteLine(x);
}
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
// Sequence points:
// 1) Open brace at start of method
// 2) 'foreach'
// 3) 'new int[2, 3]'
// 4) Hidden initial jump (of for loop)
// 5) 'var c'
// 6) Open brace of loop
// 7) Loop body
// 8) Close brace of loop
// 9) 'in'
// 10) Close brace at end of method
v.VerifyIL("C.Main", @"
{
// Code size 88 (0x58)
.maxstack 3
.locals init (int[,] V_0,
int V_1,
int V_2,
int V_3,
int V_4,
int V_5) //x
-IL_0000: nop
-IL_0001: nop
-IL_0002: ldc.i4.2
IL_0003: ldc.i4.3
IL_0004: newobj ""int[*,*]..ctor""
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: ldc.i4.0
IL_000c: callvirt ""int System.Array.GetUpperBound(int)""
IL_0011: stloc.1
IL_0012: ldloc.0
IL_0013: ldc.i4.1
IL_0014: callvirt ""int System.Array.GetUpperBound(int)""
IL_0019: stloc.2
IL_001a: ldloc.0
IL_001b: ldc.i4.0
IL_001c: callvirt ""int System.Array.GetLowerBound(int)""
IL_0021: stloc.3
~IL_0022: br.s IL_0053
IL_0024: ldloc.0
IL_0025: ldc.i4.1
IL_0026: callvirt ""int System.Array.GetLowerBound(int)""
IL_002b: stloc.s V_4
~IL_002d: br.s IL_004a
-IL_002f: ldloc.0
IL_0030: ldloc.3
IL_0031: ldloc.s V_4
IL_0033: call ""int[*,*].Get""
IL_0038: stloc.s V_5
-IL_003a: nop
-IL_003b: ldloc.s V_5
IL_003d: call ""void System.Console.WriteLine(int)""
IL_0042: nop
-IL_0043: nop
~IL_0044: ldloc.s V_4
IL_0046: ldc.i4.1
IL_0047: add
IL_0048: stloc.s V_4
-IL_004a: ldloc.s V_4
IL_004c: ldloc.2
IL_004d: ble.s IL_002f
~IL_004f: ldloc.3
IL_0050: ldc.i4.1
IL_0051: add
IL_0052: stloc.3
-IL_0053: ldloc.3
IL_0054: ldloc.1
IL_0055: ble.s IL_0024
-IL_0057: ret
}
", sequencePoints: "C.Main");
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ConditionalInAsyncMethod()
{
var source = WithWindowsLineBreaks(@"
using System;
class Program
{
public static async void Test()
{
int i = 0;
if (i != 0)
Console
.WriteLine();
}
}
");
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 81 (0x51)
.maxstack 2
.locals init (int V_0,
bool V_1,
System.Exception V_2)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Test>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: int i = 0;
IL_0008: ldarg.0
IL_0009: ldc.i4.0
IL_000a: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: if (i != 0)
IL_000f: ldarg.0
IL_0010: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_0015: ldc.i4.0
IL_0016: cgt.un
IL_0018: stloc.1
// sequence point: <hidden>
IL_0019: ldloc.1
IL_001a: brfalse.s IL_0022
// sequence point: Console ... .WriteLine()
IL_001c: call ""void System.Console.WriteLine()""
IL_0021: nop
// sequence point: <hidden>
IL_0022: leave.s IL_003c
}
catch System.Exception
{
// async: catch handler, sequence point: <hidden>
IL_0024: stloc.2
IL_0025: ldarg.0
IL_0026: ldc.i4.s -2
IL_0028: stfld ""int Program.<Test>d__0.<>1__state""
IL_002d: ldarg.0
IL_002e: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_0033: ldloc.2
IL_0034: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)""
IL_0039: nop
IL_003a: leave.s IL_0050
}
// sequence point: }
IL_003c: ldarg.0
IL_003d: ldc.i4.s -2
IL_003f: stfld ""int Program.<Test>d__0.<>1__state""
// sequence point: <hidden>
IL_0044: ldarg.0
IL_0045: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_004a: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()""
IL_004f: nop
IL_0050: ret
}
", sequencePoints: "Program+<Test>d__0.MoveNext", source: source);
v.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Test"">
<customDebugInfo>
<forwardIterator name=""<Test>d__0"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
<method containingType=""Program+<Test>d__0"" name=""MoveNext"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0x51"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""1"" offset=""33"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x8"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""19"" document=""1"" />
<entry offset=""0xf"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""20"" document=""1"" />
<entry offset=""0x19"" hidden=""true"" document=""1"" />
<entry offset=""0x1c"" startLine=""11"" startColumn=""13"" endLine=""12"" endColumn=""30"" document=""1"" />
<entry offset=""0x22"" hidden=""true"" document=""1"" />
<entry offset=""0x24"" hidden=""true"" document=""1"" />
<entry offset=""0x3c"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
<entry offset=""0x44"" hidden=""true"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x51"">
<namespace name=""System"" />
</scope>
<asyncInfo>
<catchHandler offset=""0x24"" />
<kickoffMethod declaringType=""Program"" methodName=""Test"" />
</asyncInfo>
</method>
</methods>
</symbols>");
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ConditionalBeforeLocalFunction()
{
var source = @"
class C
{
void M()
{
int i = 0;
if (i != 0)
{
return;
}
string local()
{
throw null;
}
System.Console.Write(1);
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("C.M", @"
{
// Code size 23 (0x17)
.maxstack 2
.locals init (int V_0, //i
bool V_1)
// sequence point: {
IL_0000: nop
// sequence point: int i = 0;
IL_0001: ldc.i4.0
IL_0002: stloc.0
// sequence point: if (i != 0)
IL_0003: ldloc.0
IL_0004: ldc.i4.0
IL_0005: cgt.un
IL_0007: stloc.1
// sequence point: <hidden>
IL_0008: ldloc.1
IL_0009: brfalse.s IL_000e
// sequence point: {
IL_000b: nop
// sequence point: return;
IL_000c: br.s IL_0016
// sequence point: <hidden>
IL_000e: nop
// sequence point: System.Console.Write(1);
IL_000f: ldc.i4.1
IL_0010: call ""void System.Console.Write(int)""
IL_0015: nop
// sequence point: }
IL_0016: ret
}
", sequencePoints: "C.M", source: source);
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ConditionalInAsyncMethodWithExplicitReturn()
{
var source = @"
using System;
class Program
{
public static async void Test()
{
int i = 0;
if (i != 0)
Console
.WriteLine();
return;
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 81 (0x51)
.maxstack 2
.locals init (int V_0,
bool V_1,
System.Exception V_2)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Test>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: int i = 0;
IL_0008: ldarg.0
IL_0009: ldc.i4.0
IL_000a: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: if (i != 0)
IL_000f: ldarg.0
IL_0010: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_0015: ldc.i4.0
IL_0016: cgt.un
IL_0018: stloc.1
// sequence point: <hidden>
IL_0019: ldloc.1
IL_001a: brfalse.s IL_0022
// sequence point: Console ... .WriteLine()
IL_001c: call ""void System.Console.WriteLine()""
IL_0021: nop
// sequence point: return;
IL_0022: leave.s IL_003c
}
catch System.Exception
{
// async: catch handler, sequence point: <hidden>
IL_0024: stloc.2
IL_0025: ldarg.0
IL_0026: ldc.i4.s -2
IL_0028: stfld ""int Program.<Test>d__0.<>1__state""
IL_002d: ldarg.0
IL_002e: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_0033: ldloc.2
IL_0034: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)""
IL_0039: nop
IL_003a: leave.s IL_0050
}
// sequence point: }
IL_003c: ldarg.0
IL_003d: ldc.i4.s -2
IL_003f: stfld ""int Program.<Test>d__0.<>1__state""
// sequence point: <hidden>
IL_0044: ldarg.0
IL_0045: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_004a: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()""
IL_004f: nop
IL_0050: ret
}
", sequencePoints: "Program+<Test>d__0.MoveNext", source: source);
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ConditionalInSimpleMethod()
{
var source = @"
using System;
class Program
{
public static void Test()
{
int i = 0;
if (i != 0)
Console.WriteLine();
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.Test()", @"
{
// Code size 18 (0x12)
.maxstack 2
.locals init (int V_0, //i
bool V_1)
// sequence point: {
IL_0000: nop
// sequence point: int i = 0;
IL_0001: ldc.i4.0
IL_0002: stloc.0
// sequence point: if (i != 0)
IL_0003: ldloc.0
IL_0004: ldc.i4.0
IL_0005: cgt.un
IL_0007: stloc.1
// sequence point: <hidden>
IL_0008: ldloc.1
IL_0009: brfalse.s IL_0011
// sequence point: Console.WriteLine();
IL_000b: call ""void System.Console.WriteLine()""
IL_0010: nop
// sequence point: }
IL_0011: ret
}
", sequencePoints: "Program.Test", source: source);
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ElseConditionalInAsyncMethod()
{
var source = WithWindowsLineBreaks(@"
using System;
class Program
{
public static async void Test()
{
int i = 0;
if (i != 0)
Console.WriteLine(""one"");
else
Console.WriteLine(""other"");
}
}
");
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 99 (0x63)
.maxstack 2
.locals init (int V_0,
bool V_1,
System.Exception V_2)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Test>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: int i = 0;
IL_0008: ldarg.0
IL_0009: ldc.i4.0
IL_000a: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: if (i != 0)
IL_000f: ldarg.0
IL_0010: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_0015: ldc.i4.0
IL_0016: cgt.un
IL_0018: stloc.1
// sequence point: <hidden>
IL_0019: ldloc.1
IL_001a: brfalse.s IL_0029
// sequence point: Console.WriteLine(""one"");
IL_001c: ldstr ""one""
IL_0021: call ""void System.Console.WriteLine(string)""
IL_0026: nop
// sequence point: <hidden>
IL_0027: br.s IL_0034
// sequence point: Console.WriteLine(""other"");
IL_0029: ldstr ""other""
IL_002e: call ""void System.Console.WriteLine(string)""
IL_0033: nop
// sequence point: <hidden>
IL_0034: leave.s IL_004e
}
catch System.Exception
{
// async: catch handler, sequence point: <hidden>
IL_0036: stloc.2
IL_0037: ldarg.0
IL_0038: ldc.i4.s -2
IL_003a: stfld ""int Program.<Test>d__0.<>1__state""
IL_003f: ldarg.0
IL_0040: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_0045: ldloc.2
IL_0046: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)""
IL_004b: nop
IL_004c: leave.s IL_0062
}
// sequence point: }
IL_004e: ldarg.0
IL_004f: ldc.i4.s -2
IL_0051: stfld ""int Program.<Test>d__0.<>1__state""
// sequence point: <hidden>
IL_0056: ldarg.0
IL_0057: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_005c: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()""
IL_0061: nop
IL_0062: ret
}
", sequencePoints: "Program+<Test>d__0.MoveNext", source: source);
v.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Test"">
<customDebugInfo>
<forwardIterator name=""<Test>d__0"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
<method containingType=""Program+<Test>d__0"" name=""MoveNext"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0x63"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""1"" offset=""33"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x8"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""19"" document=""1"" />
<entry offset=""0xf"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""20"" document=""1"" />
<entry offset=""0x19"" hidden=""true"" document=""1"" />
<entry offset=""0x1c"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""38"" document=""1"" />
<entry offset=""0x27"" hidden=""true"" document=""1"" />
<entry offset=""0x29"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""40"" document=""1"" />
<entry offset=""0x34"" hidden=""true"" document=""1"" />
<entry offset=""0x36"" hidden=""true"" document=""1"" />
<entry offset=""0x4e"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" />
<entry offset=""0x56"" hidden=""true"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x63"">
<namespace name=""System"" />
</scope>
<asyncInfo>
<catchHandler offset=""0x36"" />
<kickoffMethod declaringType=""Program"" methodName=""Test"" />
</asyncInfo>
</method>
</methods>
</symbols>");
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ConditionalInTry()
{
var source = WithWindowsLineBreaks(@"
using System;
class Program
{
public static void Test()
{
try
{
int i = 0;
if (i != 0)
Console.WriteLine();
}
catch { }
}
}
");
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.Test", @"
{
// Code size 27 (0x1b)
.maxstack 2
.locals init (int V_0, //i
bool V_1)
// sequence point: {
IL_0000: nop
.try
{
// sequence point: {
IL_0001: nop
// sequence point: int i = 0;
IL_0002: ldc.i4.0
IL_0003: stloc.0
// sequence point: if (i != 0)
IL_0004: ldloc.0
IL_0005: ldc.i4.0
IL_0006: cgt.un
IL_0008: stloc.1
// sequence point: <hidden>
IL_0009: ldloc.1
IL_000a: brfalse.s IL_0012
// sequence point: Console.WriteLine();
IL_000c: call ""void System.Console.WriteLine()""
IL_0011: nop
// sequence point: }
IL_0012: nop
IL_0013: leave.s IL_001a
}
catch object
{
// sequence point: catch
IL_0015: pop
// sequence point: {
IL_0016: nop
// sequence point: }
IL_0017: nop
IL_0018: leave.s IL_001a
}
// sequence point: }
IL_001a: ret
}
", sequencePoints: "Program.Test", source: source);
v.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Test"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""43"" />
<slot kind=""1"" offset=""65"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x2"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""23"" document=""1"" />
<entry offset=""0x4"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""24"" document=""1"" />
<entry offset=""0x9"" hidden=""true"" document=""1"" />
<entry offset=""0xc"" startLine=""13"" startColumn=""17"" endLine=""13"" endColumn=""37"" document=""1"" />
<entry offset=""0x12"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" />
<entry offset=""0x15"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""14"" document=""1"" />
<entry offset=""0x16"" startLine=""15"" startColumn=""15"" endLine=""15"" endColumn=""16"" document=""1"" />
<entry offset=""0x17"" startLine=""15"" startColumn=""17"" endLine=""15"" endColumn=""18"" document=""1"" />
<entry offset=""0x1a"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1b"">
<namespace name=""System"" />
<scope startOffset=""0x1"" endOffset=""0x13"">
<local name=""i"" il_index=""0"" il_start=""0x1"" il_end=""0x13"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(544937, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544937")]
[Fact]
public void ForEachStatement_MultiDimensionalArrayBreakAndContinue()
{
var source = @"
using System;
class C
{
static void Main()
{
int[, ,] array = new[,,]
{
{ {1, 2}, {3, 4} },
{ {5, 6}, {7, 8} },
};
foreach (int i in array)
{
if (i % 2 == 1) continue;
if (i > 4) break;
Console.WriteLine(i);
}
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll.WithModuleName("MODULE"));
// Stepping:
// After "continue", step to "in".
// After "break", step to first sequence point following loop body (in this case, method close brace).
v.VerifyIL("C.Main", @"
{
// Code size 169 (0xa9)
.maxstack 4
.locals init (int[,,] V_0, //array
int[,,] V_1,
int V_2,
int V_3,
int V_4,
int V_5,
int V_6,
int V_7,
int V_8, //i
bool V_9,
bool V_10)
-IL_0000: nop
-IL_0001: ldc.i4.2
IL_0002: ldc.i4.2
IL_0003: ldc.i4.2
IL_0004: newobj ""int[*,*,*]..ctor""
IL_0009: dup
IL_000a: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=32 <PrivateImplementationDetails>.8B4B2444E57AED8C2D05A1293255DA1B048C63224317D4666230760935FA4A18""
IL_000f: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_0014: stloc.0
-IL_0015: nop
-IL_0016: ldloc.0
IL_0017: stloc.1
IL_0018: ldloc.1
IL_0019: ldc.i4.0
IL_001a: callvirt ""int System.Array.GetUpperBound(int)""
IL_001f: stloc.2
IL_0020: ldloc.1
IL_0021: ldc.i4.1
IL_0022: callvirt ""int System.Array.GetUpperBound(int)""
IL_0027: stloc.3
IL_0028: ldloc.1
IL_0029: ldc.i4.2
IL_002a: callvirt ""int System.Array.GetUpperBound(int)""
IL_002f: stloc.s V_4
IL_0031: ldloc.1
IL_0032: ldc.i4.0
IL_0033: callvirt ""int System.Array.GetLowerBound(int)""
IL_0038: stloc.s V_5
~IL_003a: br.s IL_00a3
IL_003c: ldloc.1
IL_003d: ldc.i4.1
IL_003e: callvirt ""int System.Array.GetLowerBound(int)""
IL_0043: stloc.s V_6
~IL_0045: br.s IL_0098
IL_0047: ldloc.1
IL_0048: ldc.i4.2
IL_0049: callvirt ""int System.Array.GetLowerBound(int)""
IL_004e: stloc.s V_7
~IL_0050: br.s IL_008c
-IL_0052: ldloc.1
IL_0053: ldloc.s V_5
IL_0055: ldloc.s V_6
IL_0057: ldloc.s V_7
IL_0059: call ""int[*,*,*].Get""
IL_005e: stloc.s V_8
-IL_0060: nop
-IL_0061: ldloc.s V_8
IL_0063: ldc.i4.2
IL_0064: rem
IL_0065: ldc.i4.1
IL_0066: ceq
IL_0068: stloc.s V_9
~IL_006a: ldloc.s V_9
IL_006c: brfalse.s IL_0070
-IL_006e: br.s IL_0086
-IL_0070: ldloc.s V_8
IL_0072: ldc.i4.4
IL_0073: cgt
IL_0075: stloc.s V_10
~IL_0077: ldloc.s V_10
IL_0079: brfalse.s IL_007d
-IL_007b: br.s IL_00a8
-IL_007d: ldloc.s V_8
IL_007f: call ""void System.Console.WriteLine(int)""
IL_0084: nop
-IL_0085: nop
~IL_0086: ldloc.s V_7
IL_0088: ldc.i4.1
IL_0089: add
IL_008a: stloc.s V_7
-IL_008c: ldloc.s V_7
IL_008e: ldloc.s V_4
IL_0090: ble.s IL_0052
~IL_0092: ldloc.s V_6
IL_0094: ldc.i4.1
IL_0095: add
IL_0096: stloc.s V_6
-IL_0098: ldloc.s V_6
IL_009a: ldloc.3
IL_009b: ble.s IL_0047
~IL_009d: ldloc.s V_5
IL_009f: ldc.i4.1
IL_00a0: add
IL_00a1: stloc.s V_5
-IL_00a3: ldloc.s V_5
IL_00a5: ldloc.2
IL_00a6: ble.s IL_003c
-IL_00a8: ret
}
", sequencePoints: "C.Main");
}
[Fact]
public void ForEachStatement_Enumerator()
{
var source = @"
public class C
{
public static void Main()
{
foreach (var x in new System.Collections.Generic.List<int>())
{
System.Console.WriteLine(x);
}
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
// Sequence points:
// 1) Open brace at start of method
// 2) 'foreach'
// 3) 'new System.Collections.Generic.List<int>()'
// 4) Hidden initial jump (of while loop)
// 5) 'var c'
// 6) Open brace of loop
// 7) Loop body
// 8) Close brace of loop
// 9) 'in'
// 10) hidden point in Finally
// 11) Close brace at end of method
v.VerifyIL("C.Main", @"
{
// Code size 59 (0x3b)
.maxstack 1
.locals init (System.Collections.Generic.List<int>.Enumerator V_0,
int V_1) //x
-IL_0000: nop
-IL_0001: nop
-IL_0002: newobj ""System.Collections.Generic.List<int>..ctor()""
IL_0007: call ""System.Collections.Generic.List<int>.Enumerator System.Collections.Generic.List<int>.GetEnumerator()""
IL_000c: stloc.0
.try
{
~IL_000d: br.s IL_0020
-IL_000f: ldloca.s V_0
IL_0011: call ""int System.Collections.Generic.List<int>.Enumerator.Current.get""
IL_0016: stloc.1
-IL_0017: nop
-IL_0018: ldloc.1
IL_0019: call ""void System.Console.WriteLine(int)""
IL_001e: nop
-IL_001f: nop
-IL_0020: ldloca.s V_0
IL_0022: call ""bool System.Collections.Generic.List<int>.Enumerator.MoveNext()""
IL_0027: brtrue.s IL_000f
IL_0029: leave.s IL_003a
}
finally
{
~IL_002b: ldloca.s V_0
IL_002d: constrained. ""System.Collections.Generic.List<int>.Enumerator""
IL_0033: callvirt ""void System.IDisposable.Dispose()""
IL_0038: nop
IL_0039: endfinally
}
-IL_003a: ret
}
", sequencePoints: "C.Main");
}
[WorkItem(718501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/718501")]
[Fact]
public void ForEachNops()
{
string source = WithWindowsLineBreaks(@"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
private static List<List<int>> l = new List<List<int>>();
static void Main(string[] args)
{
foreach (var i in l.AsEnumerable())
{
switch (i.Count)
{
case 1:
break;
default:
if (i.Count != 0)
{
}
break;
}
}
}
}
");
// we just want this to compile without crashing/asserting
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("Program.Main", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""3"" />
</using>
<encLocalSlotMap>
<slot kind=""5"" offset=""15"" />
<slot kind=""0"" offset=""15"" />
<slot kind=""35"" offset=""83"" />
<slot kind=""1"" offset=""83"" />
<slot kind=""1"" offset=""237"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0x1"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""20"" document=""1"" />
<entry offset=""0x2"" startLine=""12"" startColumn=""31"" endLine=""12"" endColumn=""47"" document=""1"" />
<entry offset=""0x12"" hidden=""true"" document=""1"" />
<entry offset=""0x14"" startLine=""12"" startColumn=""22"" endLine=""12"" endColumn=""27"" document=""1"" />
<entry offset=""0x1b"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""14"" document=""1"" />
<entry offset=""0x1c"" startLine=""14"" startColumn=""17"" endLine=""14"" endColumn=""33"" document=""1"" />
<entry offset=""0x23"" hidden=""true"" document=""1"" />
<entry offset=""0x25"" hidden=""true"" document=""1"" />
<entry offset=""0x2b"" startLine=""17"" startColumn=""25"" endLine=""17"" endColumn=""31"" document=""1"" />
<entry offset=""0x2d"" startLine=""20"" startColumn=""25"" endLine=""20"" endColumn=""42"" document=""1"" />
<entry offset=""0x38"" hidden=""true"" document=""1"" />
<entry offset=""0x3c"" startLine=""21"" startColumn=""25"" endLine=""21"" endColumn=""26"" document=""1"" />
<entry offset=""0x3d"" startLine=""22"" startColumn=""25"" endLine=""22"" endColumn=""26"" document=""1"" />
<entry offset=""0x3e"" startLine=""24"" startColumn=""25"" endLine=""24"" endColumn=""31"" document=""1"" />
<entry offset=""0x40"" startLine=""26"" startColumn=""13"" endLine=""26"" endColumn=""14"" document=""1"" />
<entry offset=""0x41"" startLine=""12"" startColumn=""28"" endLine=""12"" endColumn=""30"" document=""1"" />
<entry offset=""0x4b"" hidden=""true"" document=""1"" />
<entry offset=""0x55"" hidden=""true"" document=""1"" />
<entry offset=""0x56"" startLine=""27"" startColumn=""9"" endLine=""27"" endColumn=""10"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x57"">
<namespace name=""System"" />
<namespace name=""System.Collections.Generic"" />
<namespace name=""System.Linq"" />
<scope startOffset=""0x14"" endOffset=""0x41"">
<local name=""i"" il_index=""1"" il_start=""0x14"" il_end=""0x41"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>"
);
}
[Fact]
public void ForEachStatement_Deconstruction()
{
var source = WithWindowsLineBreaks(@"
public class C
{
public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) };
public static void Main()
{
foreach (var (c, (d, e)) in F())
{
System.Console.WriteLine(c);
}
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.Main", @"
{
// Code size 70 (0x46)
.maxstack 2
.locals init (System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_0,
int V_1,
int V_2, //c
bool V_3, //d
double V_4, //e
System.ValueTuple<bool, double> V_5)
// sequence point: {
IL_0000: nop
// sequence point: foreach
IL_0001: nop
// sequence point: F()
IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()""
IL_0007: stloc.0
IL_0008: ldc.i4.0
IL_0009: stloc.1
// sequence point: <hidden>
IL_000a: br.s IL_003f
// sequence point: var (c, (d, e))
IL_000c: ldloc.0
IL_000d: ldloc.1
IL_000e: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>""
IL_0013: dup
IL_0014: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2""
IL_0019: stloc.s V_5
IL_001b: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1""
IL_0020: stloc.2
IL_0021: ldloc.s V_5
IL_0023: ldfld ""bool System.ValueTuple<bool, double>.Item1""
IL_0028: stloc.3
IL_0029: ldloc.s V_5
IL_002b: ldfld ""double System.ValueTuple<bool, double>.Item2""
IL_0030: stloc.s V_4
// sequence point: {
IL_0032: nop
// sequence point: System.Console.WriteLine(c);
IL_0033: ldloc.2
IL_0034: call ""void System.Console.WriteLine(int)""
IL_0039: nop
// sequence point: }
IL_003a: nop
// sequence point: <hidden>
IL_003b: ldloc.1
IL_003c: ldc.i4.1
IL_003d: add
IL_003e: stloc.1
// sequence point: in
IL_003f: ldloc.1
IL_0040: ldloc.0
IL_0041: ldlen
IL_0042: conv.i4
IL_0043: blt.s IL_000c
// sequence point: }
IL_0045: ret
}
", sequencePoints: "C.Main", source: source);
v.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""50"" endLine=""4"" endColumn=""76"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
<encLocalSlotMap>
<slot kind=""6"" offset=""11"" />
<slot kind=""8"" offset=""11"" />
<slot kind=""0"" offset=""25"" />
<slot kind=""0"" offset=""29"" />
<slot kind=""0"" offset=""32"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""16"" document=""1"" />
<entry offset=""0x2"" startLine=""8"" startColumn=""37"" endLine=""8"" endColumn=""40"" document=""1"" />
<entry offset=""0xa"" hidden=""true"" document=""1"" />
<entry offset=""0xc"" startLine=""8"" startColumn=""18"" endLine=""8"" endColumn=""33"" document=""1"" />
<entry offset=""0x32"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x33"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""41"" document=""1"" />
<entry offset=""0x3a"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0x3b"" hidden=""true"" document=""1"" />
<entry offset=""0x3f"" startLine=""8"" startColumn=""34"" endLine=""8"" endColumn=""36"" document=""1"" />
<entry offset=""0x45"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x46"">
<scope startOffset=""0xc"" endOffset=""0x3b"">
<local name=""c"" il_index=""2"" il_start=""0xc"" il_end=""0x3b"" attributes=""0"" />
<local name=""d"" il_index=""3"" il_start=""0xc"" il_end=""0x3b"" attributes=""0"" />
<local name=""e"" il_index=""4"" il_start=""0xc"" il_end=""0x3b"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region Switch
[Fact]
public void SwitchWithPattern_01()
{
string source = WithWindowsLineBreaks(@"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
private static List<List<int>> l = new List<List<int>>();
static void Main(string[] args)
{
Student s = new Student();
s.Name = ""Bozo"";
s.GPA = 2.3;
Operate(s);
}
static string Operate(Person p)
{
switch (p)
{
case Student s when s.GPA > 3.5:
return $""Student {s.Name} ({s.GPA:N1})"";
case Student s:
return $""Student {s.Name} ({s.GPA:N1})"";
case Teacher t:
return $""Teacher {t.Name} of {t.Subject}"";
default:
return $""Person {p.Name}"";
}
}
}
class Person { public string Name; }
class Teacher : Person { public string Subject; }
class Student : Person { public double GPA; }
");
// we just want this to compile without crashing/asserting
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("Program.Operate",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Operate"" parameterNames=""p"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""59"" />
<slot kind=""0"" offset=""163"" />
<slot kind=""0"" offset=""250"" />
<slot kind=""35"" offset=""11"" />
<slot kind=""1"" offset=""11"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""19"" document=""1"" />
<entry offset=""0x4"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" hidden=""true"" document=""1"" />
<entry offset=""0x1d"" startLine=""22"" startColumn=""28"" endLine=""22"" endColumn=""44"" document=""1"" />
<entry offset=""0x2e"" hidden=""true"" document=""1"" />
<entry offset=""0x30"" startLine=""23"" startColumn=""17"" endLine=""23"" endColumn=""57"" document=""1"" />
<entry offset=""0x4f"" hidden=""true"" document=""1"" />
<entry offset=""0x53"" startLine=""25"" startColumn=""17"" endLine=""25"" endColumn=""57"" document=""1"" />
<entry offset=""0x72"" hidden=""true"" document=""1"" />
<entry offset=""0x74"" startLine=""27"" startColumn=""17"" endLine=""27"" endColumn=""59"" document=""1"" />
<entry offset=""0x93"" startLine=""29"" startColumn=""17"" endLine=""29"" endColumn=""43"" document=""1"" />
<entry offset=""0xa7"" startLine=""31"" startColumn=""5"" endLine=""31"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xaa"">
<scope startOffset=""0x1d"" endOffset=""0x4f"">
<local name=""s"" il_index=""0"" il_start=""0x1d"" il_end=""0x4f"" attributes=""0"" />
</scope>
<scope startOffset=""0x4f"" endOffset=""0x72"">
<local name=""s"" il_index=""1"" il_start=""0x4f"" il_end=""0x72"" attributes=""0"" />
</scope>
<scope startOffset=""0x72"" endOffset=""0x93"">
<local name=""t"" il_index=""2"" il_start=""0x72"" il_end=""0x93"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void SwitchWithPattern_02()
{
string source = WithWindowsLineBreaks(@"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
private static List<List<int>> l = new List<List<int>>();
static void Main(string[] args)
{
Student s = new Student();
s.Name = ""Bozo"";
s.GPA = 2.3;
Operate(s);
}
static System.Func<string> Operate(Person p)
{
switch (p)
{
case Student s when s.GPA > 3.5:
return () => $""Student {s.Name} ({s.GPA:N1})"";
case Student s:
return () => $""Student {s.Name} ({s.GPA:N1})"";
case Teacher t:
return () => $""Teacher {t.Name} of {t.Subject}"";
default:
return () => $""Person {p.Name}"";
}
}
}
class Person { public string Name; }
class Teacher : Person { public string Subject; }
class Student : Person { public double GPA; }
");
// we just want this to compile without crashing/asserting
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("Program.Operate",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Operate"" parameterNames=""p"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""0"" />
<slot kind=""30"" offset=""11"" />
<slot kind=""35"" offset=""11"" />
<slot kind=""1"" offset=""11"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>2</methodOrdinal>
<closure offset=""0"" />
<closure offset=""11"" />
<lambda offset=""109"" closure=""1"" />
<lambda offset=""202"" closure=""1"" />
<lambda offset=""295"" closure=""1"" />
<lambda offset=""383"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" />
<entry offset=""0xe"" hidden=""true"" document=""1"" />
<entry offset=""0x1b"" hidden=""true"" document=""1"" />
<entry offset=""0x1d"" hidden=""true"" document=""1"" />
<entry offset=""0x47"" startLine=""22"" startColumn=""28"" endLine=""22"" endColumn=""44"" document=""1"" />
<entry offset=""0x5d"" hidden=""true"" document=""1"" />
<entry offset=""0x5f"" startLine=""23"" startColumn=""17"" endLine=""23"" endColumn=""63"" document=""1"" />
<entry offset=""0x6f"" hidden=""true"" document=""1"" />
<entry offset=""0x7d"" startLine=""25"" startColumn=""17"" endLine=""25"" endColumn=""63"" document=""1"" />
<entry offset=""0x8d"" hidden=""true"" document=""1"" />
<entry offset=""0x8f"" startLine=""27"" startColumn=""17"" endLine=""27"" endColumn=""65"" document=""1"" />
<entry offset=""0x9f"" startLine=""29"" startColumn=""17"" endLine=""29"" endColumn=""49"" document=""1"" />
<entry offset=""0xaf"" startLine=""31"" startColumn=""5"" endLine=""31"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xb2"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0xb2"" attributes=""0"" />
<scope startOffset=""0xe"" endOffset=""0xaf"">
<local name=""CS$<>8__locals1"" il_index=""1"" il_start=""0xe"" il_end=""0xaf"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void SwitchWithPatternAndLocalFunctions()
{
string source = WithWindowsLineBreaks(@"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
private static List<List<int>> l = new List<List<int>>();
static void Main(string[] args)
{
Student s = new Student();
s.Name = ""Bozo"";
s.GPA = 2.3;
Operate(s);
}
static System.Func<string> Operate(Person p)
{
switch (p)
{
case Student s when s.GPA > 3.5:
string f1() => $""Student {s.Name} ({s.GPA:N1})"";
return f1;
case Student s:
string f2() => $""Student {s.Name} ({s.GPA:N1})"";
return f2;
case Teacher t:
string f3() => $""Teacher {t.Name} of {t.Subject}"";
return f3;
default:
string f4() => $""Person {p.Name}"";
return f4;
}
}
}
class Person { public string Name; }
class Teacher : Person { public string Subject; }
class Student : Person { public double GPA; }
");
// we just want this to compile without crashing/asserting
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("Program.Operate", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Operate"" parameterNames=""p"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""0"" />
<slot kind=""30"" offset=""11"" />
<slot kind=""35"" offset=""11"" />
<slot kind=""1"" offset=""11"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>2</methodOrdinal>
<closure offset=""0"" />
<closure offset=""11"" />
<lambda offset=""111"" closure=""1"" />
<lambda offset=""234"" closure=""1"" />
<lambda offset=""357"" closure=""1"" />
<lambda offset=""475"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" />
<entry offset=""0xe"" hidden=""true"" document=""1"" />
<entry offset=""0x1b"" hidden=""true"" document=""1"" />
<entry offset=""0x1d"" hidden=""true"" document=""1"" />
<entry offset=""0x47"" startLine=""22"" startColumn=""28"" endLine=""22"" endColumn=""44"" document=""1"" />
<entry offset=""0x5d"" hidden=""true"" document=""1"" />
<entry offset=""0x60"" startLine=""24"" startColumn=""17"" endLine=""24"" endColumn=""27"" document=""1"" />
<entry offset=""0x70"" hidden=""true"" document=""1"" />
<entry offset=""0x7f"" startLine=""27"" startColumn=""17"" endLine=""27"" endColumn=""27"" document=""1"" />
<entry offset=""0x8f"" hidden=""true"" document=""1"" />
<entry offset=""0x92"" startLine=""30"" startColumn=""17"" endLine=""30"" endColumn=""27"" document=""1"" />
<entry offset=""0xa2"" hidden=""true"" document=""1"" />
<entry offset=""0xa3"" startLine=""33"" startColumn=""17"" endLine=""33"" endColumn=""27"" document=""1"" />
<entry offset=""0xb3"" startLine=""35"" startColumn=""5"" endLine=""35"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xb6"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0xb6"" attributes=""0"" />
<scope startOffset=""0xe"" endOffset=""0xb3"">
<local name=""CS$<>8__locals1"" il_index=""1"" il_start=""0xe"" il_end=""0xb3"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(17090, "https://github.com/dotnet/roslyn/issues/17090"), WorkItem(19731, "https://github.com/dotnet/roslyn/issues/19731")]
[Fact]
public void SwitchWithConstantPattern()
{
string source = @"
using System;
class Program
{
static void Main(string[] args)
{
M1();
M2();
}
static void M1()
{
switch
(1)
{
case 0 when true:
;
case 1:
Console.Write(1);
break;
case 2:
;
}
}
static void M2()
{
switch
(nameof(M2))
{
case nameof(M1) when true:
;
case nameof(M2):
Console.Write(nameof(M2));
break;
case nameof(Main):
;
}
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugExe);
c.VerifyDiagnostics();
var verifier = CompileAndVerify(c, expectedOutput: "1M2");
verifier.VerifyIL(qualifiedMethodName: "Program.M1", sequencePoints: "Program.M1", source: source,
expectedIL: @"{
// Code size 17 (0x11)
.maxstack 1
.locals init (int V_0,
int V_1)
// sequence point: {
IL_0000: nop
// sequence point: switch ... (1
IL_0001: ldc.i4.1
IL_0002: stloc.1
IL_0003: ldc.i4.1
IL_0004: stloc.0
// sequence point: <hidden>
IL_0005: br.s IL_0007
// sequence point: Console.Write(1);
IL_0007: ldc.i4.1
IL_0008: call ""void System.Console.Write(int)""
IL_000d: nop
// sequence point: break;
IL_000e: br.s IL_0010
// sequence point: }
IL_0010: ret
}");
verifier.VerifyIL(qualifiedMethodName: "Program.M2", sequencePoints: "Program.M2", source: source,
expectedIL: @"{
// Code size 29 (0x1d)
.maxstack 1
.locals init (string V_0,
string V_1)
// sequence point: {
IL_0000: nop
// sequence point: switch ... (nameof(M2)
IL_0001: ldstr ""M2""
IL_0006: stloc.1
IL_0007: ldstr ""M2""
IL_000c: stloc.0
// sequence point: <hidden>
IL_000d: br.s IL_000f
// sequence point: Console.Write(nameof(M2));
IL_000f: ldstr ""M2""
IL_0014: call ""void System.Console.Write(string)""
IL_0019: nop
// sequence point: break;
IL_001a: br.s IL_001c
// sequence point: }
IL_001c: ret
}");
// Check the release code generation too.
c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe);
c.VerifyDiagnostics();
verifier = CompileAndVerify(c, expectedOutput: "1M2");
verifier.VerifyIL("Program.M1",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: call ""void System.Console.Write(int)""
IL_0006: ret
}");
verifier.VerifyIL("Program.M2",
@"{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldstr ""M2""
IL_0005: call ""void System.Console.Write(string)""
IL_000a: ret
}");
}
[WorkItem(19734, "https://github.com/dotnet/roslyn/issues/19734")]
[Fact]
public void SwitchWithConstantGenericPattern_01()
{
string source = @"
using System;
class Program
{
static void Main(string[] args)
{
M1<int>(); // 1
M1<long>(); // 2
M2<string>(); // 3
M2<int>(); // 4
}
static void M1<T>()
{
switch (1)
{
case T t:
Console.Write(1);
break;
case int i:
Console.Write(2);
break;
}
}
static void M2<T>()
{
switch (nameof(M2))
{
case T t:
Console.Write(3);
break;
case string s:
Console.Write(4);
break;
case null:
;
}
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_1);
c.VerifyDiagnostics();
var verifier = CompileAndVerify(c, expectedOutput: "1234");
verifier.VerifyIL(qualifiedMethodName: "Program.M1<T>", sequencePoints: "Program.M1", source: source,
expectedIL: @"{
// Code size 60 (0x3c)
.maxstack 1
.locals init (T V_0, //t
int V_1, //i
int V_2)
// sequence point: {
IL_0000: nop
// sequence point: switch (1)
IL_0001: ldc.i4.1
IL_0002: stloc.2
IL_0003: ldc.i4.1
IL_0004: stloc.1
// sequence point: <hidden>
IL_0005: ldloc.1
IL_0006: box ""int""
IL_000b: isinst ""T""
IL_0010: brfalse.s IL_0030
IL_0012: ldloc.1
IL_0013: box ""int""
IL_0018: isinst ""T""
IL_001d: unbox.any ""T""
IL_0022: stloc.0
// sequence point: <hidden>
IL_0023: br.s IL_0025
// sequence point: <hidden>
IL_0025: br.s IL_0027
// sequence point: Console.Write(1);
IL_0027: ldc.i4.1
IL_0028: call ""void System.Console.Write(int)""
IL_002d: nop
// sequence point: break;
IL_002e: br.s IL_003b
// sequence point: <hidden>
IL_0030: br.s IL_0032
// sequence point: Console.Write(2);
IL_0032: ldc.i4.2
IL_0033: call ""void System.Console.Write(int)""
IL_0038: nop
// sequence point: break;
IL_0039: br.s IL_003b
// sequence point: }
IL_003b: ret
}");
verifier.VerifyIL(qualifiedMethodName: "Program.M2<T>", sequencePoints: "Program.M2", source: source,
expectedIL: @"{
// Code size 58 (0x3a)
.maxstack 1
.locals init (T V_0, //t
string V_1, //s
string V_2)
// sequence point: {
IL_0000: nop
// sequence point: switch (nameof(M2))
IL_0001: ldstr ""M2""
IL_0006: stloc.2
IL_0007: ldstr ""M2""
IL_000c: stloc.1
// sequence point: <hidden>
IL_000d: ldloc.1
IL_000e: isinst ""T""
IL_0013: brfalse.s IL_002e
IL_0015: ldloc.1
IL_0016: isinst ""T""
IL_001b: unbox.any ""T""
IL_0020: stloc.0
// sequence point: <hidden>
IL_0021: br.s IL_0023
// sequence point: <hidden>
IL_0023: br.s IL_0025
// sequence point: Console.Write(3);
IL_0025: ldc.i4.3
IL_0026: call ""void System.Console.Write(int)""
IL_002b: nop
// sequence point: break;
IL_002c: br.s IL_0039
// sequence point: <hidden>
IL_002e: br.s IL_0030
// sequence point: Console.Write(4);
IL_0030: ldc.i4.4
IL_0031: call ""void System.Console.Write(int)""
IL_0036: nop
// sequence point: break;
IL_0037: br.s IL_0039
// sequence point: }
IL_0039: ret
}");
// Check the release code generation too.
c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_1);
c.VerifyDiagnostics();
verifier = CompileAndVerify(c, expectedOutput: "1234");
verifier.VerifyIL("Program.M1<T>",
@"{
// Code size 29 (0x1d)
.maxstack 1
.locals init (int V_0) //i
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: box ""int""
IL_0008: isinst ""T""
IL_000d: brfalse.s IL_0016
IL_000f: ldc.i4.1
IL_0010: call ""void System.Console.Write(int)""
IL_0015: ret
IL_0016: ldc.i4.2
IL_0017: call ""void System.Console.Write(int)""
IL_001c: ret
}");
verifier.VerifyIL("Program.M2<T>",
@"{
// Code size 28 (0x1c)
.maxstack 1
.locals init (string V_0) //s
IL_0000: ldstr ""M2""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: isinst ""T""
IL_000c: brfalse.s IL_0015
IL_000e: ldc.i4.3
IL_000f: call ""void System.Console.Write(int)""
IL_0014: ret
IL_0015: ldc.i4.4
IL_0016: call ""void System.Console.Write(int)""
IL_001b: ret
}");
}
[WorkItem(19734, "https://github.com/dotnet/roslyn/issues/19734")]
[Fact]
public void SwitchWithConstantGenericPattern_02()
{
string source = @"
using System;
class Program
{
static void Main(string[] args)
{
M2<string>(); // 6
M2<int>(); // 6
}
static void M2<T>()
{
const string x = null;
switch (x)
{
case T t:
;
case string s:
;
case null:
Console.Write(6);
break;
}
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_1);
c.VerifyDiagnostics();
var verifier = CompileAndVerify(c, expectedOutput: "66");
verifier.VerifyIL(qualifiedMethodName: "Program.M2<T>", sequencePoints: "Program.M2", source: source,
expectedIL: @"{
// Code size 17 (0x11)
.maxstack 1
.locals init (T V_0, //t
string V_1, //s
string V_2,
string V_3)
// sequence point: {
IL_0000: nop
// sequence point: switch (x)
IL_0001: ldnull
IL_0002: stloc.3
IL_0003: ldnull
IL_0004: stloc.2
// sequence point: <hidden>
IL_0005: br.s IL_0007
// sequence point: Console.Write(6);
IL_0007: ldc.i4.6
IL_0008: call ""void System.Console.Write(int)""
IL_000d: nop
// sequence point: break;
IL_000e: br.s IL_0010
// sequence point: }
IL_0010: ret
}");
// Check the release code generation too.
c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_1);
c.VerifyDiagnostics();
verifier = CompileAndVerify(c, expectedOutput: "66");
verifier.VerifyIL("Program.M2<T>",
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldc.i4.6
IL_0001: call ""void System.Console.Write(int)""
IL_0006: ret
}");
}
[Fact]
[WorkItem(31665, "https://github.com/dotnet/roslyn/issues/31665")]
public void TestSequencePoints_31665()
{
var source = @"
using System;
internal class Program
{
private static void Main(string[] args)
{
var s = ""1"";
if (true)
switch (s)
{
case ""1"":
Console.Out.WriteLine(""Input was 1"");
break;
default:
throw new Exception(""Default case"");
}
else
Console.Out.WriteLine(""Too many inputs"");
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.Main(string[])", @"
{
// Code size 60 (0x3c)
.maxstack 2
.locals init (string V_0, //s
bool V_1,
string V_2,
string V_3)
// sequence point: {
IL_0000: nop
// sequence point: var s = ""1"";
IL_0001: ldstr ""1""
IL_0006: stloc.0
// sequence point: if (true)
IL_0007: ldc.i4.1
IL_0008: stloc.1
// sequence point: switch (s)
IL_0009: ldloc.0
IL_000a: stloc.3
// sequence point: <hidden>
IL_000b: ldloc.3
IL_000c: stloc.2
// sequence point: <hidden>
IL_000d: ldloc.2
IL_000e: ldstr ""1""
IL_0013: call ""bool string.op_Equality(string, string)""
IL_0018: brtrue.s IL_001c
IL_001a: br.s IL_002e
// sequence point: Console.Out.WriteLine(""Input was 1"");
IL_001c: call ""System.IO.TextWriter System.Console.Out.get""
IL_0021: ldstr ""Input was 1""
IL_0026: callvirt ""void System.IO.TextWriter.WriteLine(string)""
IL_002b: nop
// sequence point: break;
IL_002c: br.s IL_0039
// sequence point: throw new Exception(""Default case"");
IL_002e: ldstr ""Default case""
IL_0033: newobj ""System.Exception..ctor(string)""
IL_0038: throw
// sequence point: <hidden>
IL_0039: br.s IL_003b
// sequence point: }
IL_003b: ret
}
", sequencePoints: "Program.Main", source: source);
}
[Fact]
[WorkItem(17076, "https://github.com/dotnet/roslyn/issues/17076")]
public void TestSequencePoints_17076()
{
var source = @"
using System.Threading.Tasks;
internal class Program
{
private static void Main(string[] args)
{
M(new Node()).GetAwaiter().GetResult();
}
static async Task M(Node node)
{
while (node != null)
{
if (node is A a)
{
await Task.Yield();
return;
}
else if (node is B b)
{
await Task.Yield();
return;
}
node = node.Parent;
}
}
}
class Node
{
public Node Parent = null;
}
class A : Node { }
class B : Node { }
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<M>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 403 (0x193)
.maxstack 3
.locals init (int V_0,
bool V_1,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_2,
System.Runtime.CompilerServices.YieldAwaitable V_3,
Program.<M>d__1 V_4,
bool V_5,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_6,
bool V_7,
System.Exception V_8)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<M>d__1.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: <hidden>
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0012
IL_000a: br.s IL_000c
IL_000c: ldloc.0
IL_000d: ldc.i4.1
IL_000e: beq.s IL_0014
IL_0010: br.s IL_0019
IL_0012: br.s IL_007e
IL_0014: br IL_0109
// sequence point: {
IL_0019: nop
// sequence point: <hidden>
IL_001a: br IL_0150
// sequence point: {
IL_001f: nop
// sequence point: if (node is A a)
IL_0020: ldarg.0
IL_0021: ldarg.0
IL_0022: ldfld ""Node Program.<M>d__1.node""
IL_0027: isinst ""A""
IL_002c: stfld ""A Program.<M>d__1.<a>5__1""
IL_0031: ldarg.0
IL_0032: ldfld ""A Program.<M>d__1.<a>5__1""
IL_0037: ldnull
IL_0038: cgt.un
IL_003a: stloc.1
// sequence point: <hidden>
IL_003b: ldloc.1
IL_003c: brfalse.s IL_00a7
// sequence point: {
IL_003e: nop
// sequence point: await Task.Yield();
IL_003f: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_0044: stloc.3
IL_0045: ldloca.s V_3
IL_0047: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_004c: stloc.2
// sequence point: <hidden>
IL_004d: ldloca.s V_2
IL_004f: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_0054: brtrue.s IL_009a
IL_0056: ldarg.0
IL_0057: ldc.i4.0
IL_0058: dup
IL_0059: stloc.0
IL_005a: stfld ""int Program.<M>d__1.<>1__state""
// async: yield
IL_005f: ldarg.0
IL_0060: ldloc.2
IL_0061: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1""
IL_0066: ldarg.0
IL_0067: stloc.s V_4
IL_0069: ldarg.0
IL_006a: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<M>d__1.<>t__builder""
IL_006f: ldloca.s V_2
IL_0071: ldloca.s V_4
IL_0073: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Program.<M>d__1>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Program.<M>d__1)""
IL_0078: nop
IL_0079: leave IL_0192
// async: resume
IL_007e: ldarg.0
IL_007f: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1""
IL_0084: stloc.2
IL_0085: ldarg.0
IL_0086: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1""
IL_008b: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_0091: ldarg.0
IL_0092: ldc.i4.m1
IL_0093: dup
IL_0094: stloc.0
IL_0095: stfld ""int Program.<M>d__1.<>1__state""
IL_009a: ldloca.s V_2
IL_009c: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_00a1: nop
// sequence point: return;
IL_00a2: leave IL_017e
// sequence point: if (node is B b)
IL_00a7: ldarg.0
IL_00a8: ldarg.0
IL_00a9: ldfld ""Node Program.<M>d__1.node""
IL_00ae: isinst ""B""
IL_00b3: stfld ""B Program.<M>d__1.<b>5__2""
IL_00b8: ldarg.0
IL_00b9: ldfld ""B Program.<M>d__1.<b>5__2""
IL_00be: ldnull
IL_00bf: cgt.un
IL_00c1: stloc.s V_5
// sequence point: <hidden>
IL_00c3: ldloc.s V_5
IL_00c5: brfalse.s IL_0130
// sequence point: {
IL_00c7: nop
// sequence point: await Task.Yield();
IL_00c8: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_00cd: stloc.3
IL_00ce: ldloca.s V_3
IL_00d0: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_00d5: stloc.s V_6
// sequence point: <hidden>
IL_00d7: ldloca.s V_6
IL_00d9: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_00de: brtrue.s IL_0126
IL_00e0: ldarg.0
IL_00e1: ldc.i4.1
IL_00e2: dup
IL_00e3: stloc.0
IL_00e4: stfld ""int Program.<M>d__1.<>1__state""
// async: yield
IL_00e9: ldarg.0
IL_00ea: ldloc.s V_6
IL_00ec: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1""
IL_00f1: ldarg.0
IL_00f2: stloc.s V_4
IL_00f4: ldarg.0
IL_00f5: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<M>d__1.<>t__builder""
IL_00fa: ldloca.s V_6
IL_00fc: ldloca.s V_4
IL_00fe: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Program.<M>d__1>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Program.<M>d__1)""
IL_0103: nop
IL_0104: leave IL_0192
// async: resume
IL_0109: ldarg.0
IL_010a: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1""
IL_010f: stloc.s V_6
IL_0111: ldarg.0
IL_0112: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1""
IL_0117: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_011d: ldarg.0
IL_011e: ldc.i4.m1
IL_011f: dup
IL_0120: stloc.0
IL_0121: stfld ""int Program.<M>d__1.<>1__state""
IL_0126: ldloca.s V_6
IL_0128: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_012d: nop
// sequence point: return;
IL_012e: leave.s IL_017e
// sequence point: <hidden>
IL_0130: ldarg.0
IL_0131: ldnull
IL_0132: stfld ""B Program.<M>d__1.<b>5__2""
// sequence point: node = node.Parent;
IL_0137: ldarg.0
IL_0138: ldarg.0
IL_0139: ldfld ""Node Program.<M>d__1.node""
IL_013e: ldfld ""Node Node.Parent""
IL_0143: stfld ""Node Program.<M>d__1.node""
// sequence point: }
IL_0148: nop
IL_0149: ldarg.0
IL_014a: ldnull
IL_014b: stfld ""A Program.<M>d__1.<a>5__1""
// sequence point: while (node != null)
IL_0150: ldarg.0
IL_0151: ldfld ""Node Program.<M>d__1.node""
IL_0156: ldnull
IL_0157: cgt.un
IL_0159: stloc.s V_7
// sequence point: <hidden>
IL_015b: ldloc.s V_7
IL_015d: brtrue IL_001f
IL_0162: leave.s IL_017e
}
catch System.Exception
{
// sequence point: <hidden>
IL_0164: stloc.s V_8
IL_0166: ldarg.0
IL_0167: ldc.i4.s -2
IL_0169: stfld ""int Program.<M>d__1.<>1__state""
IL_016e: ldarg.0
IL_016f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<M>d__1.<>t__builder""
IL_0174: ldloc.s V_8
IL_0176: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_017b: nop
IL_017c: leave.s IL_0192
}
// sequence point: }
IL_017e: ldarg.0
IL_017f: ldc.i4.s -2
IL_0181: stfld ""int Program.<M>d__1.<>1__state""
// sequence point: <hidden>
IL_0186: ldarg.0
IL_0187: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<M>d__1.<>t__builder""
IL_018c: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_0191: nop
IL_0192: ret
}
", sequencePoints: "Program+<M>d__1.MoveNext", source: source);
}
[Fact]
[WorkItem(28288, "https://github.com/dotnet/roslyn/issues/28288")]
public void TestSequencePoints_28288()
{
var source = @"
using System.Threading.Tasks;
public class C
{
public static async Task Main()
{
object o = new C();
switch (o)
{
case C c:
System.Console.Write(1);
break;
default:
return;
}
if (M() != null)
{
}
}
private static object M()
{
return new C();
}
}";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("C.<Main>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 162 (0xa2)
.maxstack 2
.locals init (int V_0,
object V_1,
bool V_2,
System.Exception V_3)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<Main>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: object o = new C();
IL_0008: ldarg.0
IL_0009: newobj ""C..ctor()""
IL_000e: stfld ""object C.<Main>d__0.<o>5__1""
// sequence point: switch (o)
IL_0013: ldarg.0
IL_0014: ldarg.0
IL_0015: ldfld ""object C.<Main>d__0.<o>5__1""
IL_001a: stloc.1
// sequence point: <hidden>
IL_001b: ldloc.1
IL_001c: stfld ""object C.<Main>d__0.<>s__3""
// sequence point: <hidden>
IL_0021: ldarg.0
IL_0022: ldarg.0
IL_0023: ldfld ""object C.<Main>d__0.<>s__3""
IL_0028: isinst ""C""
IL_002d: stfld ""C C.<Main>d__0.<c>5__2""
IL_0032: ldarg.0
IL_0033: ldfld ""C C.<Main>d__0.<c>5__2""
IL_0038: brtrue.s IL_003c
IL_003a: br.s IL_0047
// sequence point: <hidden>
IL_003c: br.s IL_003e
// sequence point: System.Console.Write(1);
IL_003e: ldc.i4.1
IL_003f: call ""void System.Console.Write(int)""
IL_0044: nop
// sequence point: break;
IL_0045: br.s IL_0049
// sequence point: return;
IL_0047: leave.s IL_0086
// sequence point: <hidden>
IL_0049: ldarg.0
IL_004a: ldnull
IL_004b: stfld ""C C.<Main>d__0.<c>5__2""
IL_0050: ldarg.0
IL_0051: ldnull
IL_0052: stfld ""object C.<Main>d__0.<>s__3""
// sequence point: if (M() != null)
IL_0057: call ""object C.M()""
IL_005c: ldnull
IL_005d: cgt.un
IL_005f: stloc.2
// sequence point: <hidden>
IL_0060: ldloc.2
IL_0061: brfalse.s IL_0065
// sequence point: {
IL_0063: nop
// sequence point: }
IL_0064: nop
// sequence point: <hidden>
IL_0065: leave.s IL_0086
}
catch System.Exception
{
// sequence point: <hidden>
IL_0067: stloc.3
IL_0068: ldarg.0
IL_0069: ldc.i4.s -2
IL_006b: stfld ""int C.<Main>d__0.<>1__state""
IL_0070: ldarg.0
IL_0071: ldnull
IL_0072: stfld ""object C.<Main>d__0.<o>5__1""
IL_0077: ldarg.0
IL_0078: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder""
IL_007d: ldloc.3
IL_007e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_0083: nop
IL_0084: leave.s IL_00a1
}
// sequence point: }
IL_0086: ldarg.0
IL_0087: ldc.i4.s -2
IL_0089: stfld ""int C.<Main>d__0.<>1__state""
// sequence point: <hidden>
IL_008e: ldarg.0
IL_008f: ldnull
IL_0090: stfld ""object C.<Main>d__0.<o>5__1""
IL_0095: ldarg.0
IL_0096: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder""
IL_009b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_00a0: nop
IL_00a1: ret
}
", sequencePoints: "C+<Main>d__0.MoveNext", source: source);
}
[Fact]
public void SwitchExpressionWithPattern()
{
string source = WithWindowsLineBreaks(@"
class C
{
static string M(object o)
{
return o switch
{
int i => $""Number: {i}"",
_ => ""Don't know""
};
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.M",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"" parameterNames=""o"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""55"" />
<slot kind=""temp"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""10"" endColumn=""11"" document=""1"" />
<entry offset=""0x4"" startLine=""6"" startColumn=""18"" endLine=""10"" endColumn=""10"" document=""1"" />
<entry offset=""0x5"" hidden=""true"" document=""1"" />
<entry offset=""0x14"" hidden=""true"" document=""1"" />
<entry offset=""0x16"" hidden=""true"" document=""1"" />
<entry offset=""0x18"" startLine=""8"" startColumn=""22"" endLine=""8"" endColumn=""36"" document=""1"" />
<entry offset=""0x2b"" startLine=""9"" startColumn=""18"" endLine=""9"" endColumn=""30"" document=""1"" />
<entry offset=""0x33"" hidden=""true"" document=""1"" />
<entry offset=""0x36"" startLine=""6"" startColumn=""9"" endLine=""10"" endColumn=""11"" document=""1"" />
<entry offset=""0x37"" hidden=""true"" document=""1"" />
<entry offset=""0x3b"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x3d"">
<scope startOffset=""0x16"" endOffset=""0x2b"">
<local name=""i"" il_index=""0"" il_start=""0x16"" il_end=""0x2b"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region DoStatement
[Fact]
public void DoStatement()
{
var source = WithWindowsLineBreaks(
@"using System;
public class SeqPointForWhile
{
public static void Main()
{
SeqPointForWhile obj = new SeqPointForWhile();
obj.While(234);
}
int field;
public void While(int p)
{
do
{
p = (int)(p / 2);
if (p > 100)
{
continue;
}
else if (p > 10)
{
field = 1;
}
else
{
break;
}
} while (p > 0); // SeqPt should be generated for [while (p > 0);]
field = -1;
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""SeqPointForWhile"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""28"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""55"" document=""1"" />
<entry offset=""0x7"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""24"" document=""1"" />
<entry offset=""0x13"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x14"">
<namespace name=""System"" />
<local name=""obj"" il_index=""0"" il_start=""0x0"" il_end=""0x14"" attributes=""0"" />
</scope>
</method>
<method containingType=""SeqPointForWhile"" name=""While"" parameterNames=""p"">
<customDebugInfo>
<forward declaringType=""SeqPointForWhile"" methodName=""Main"" />
<encLocalSlotMap>
<slot kind=""1"" offset=""71"" />
<slot kind=""1"" offset=""159"" />
<slot kind=""1"" offset=""11"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" />
<entry offset=""0x2"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""30"" document=""1"" />
<entry offset=""0x7"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""25"" document=""1"" />
<entry offset=""0xd"" hidden=""true"" document=""1"" />
<entry offset=""0x10"" startLine=""19"" startColumn=""13"" endLine=""19"" endColumn=""14"" document=""1"" />
<entry offset=""0x11"" startLine=""20"" startColumn=""17"" endLine=""20"" endColumn=""26"" document=""1"" />
<entry offset=""0x13"" startLine=""22"" startColumn=""18"" endLine=""22"" endColumn=""29"" document=""1"" />
<entry offset=""0x19"" hidden=""true"" document=""1"" />
<entry offset=""0x1c"" startLine=""23"" startColumn=""13"" endLine=""23"" endColumn=""14"" document=""1"" />
<entry offset=""0x1d"" startLine=""24"" startColumn=""17"" endLine=""24"" endColumn=""27"" document=""1"" />
<entry offset=""0x24"" startLine=""25"" startColumn=""13"" endLine=""25"" endColumn=""14"" document=""1"" />
<entry offset=""0x25"" hidden=""true"" document=""1"" />
<entry offset=""0x27"" startLine=""27"" startColumn=""13"" endLine=""27"" endColumn=""14"" document=""1"" />
<entry offset=""0x28"" startLine=""28"" startColumn=""17"" endLine=""28"" endColumn=""23"" document=""1"" />
<entry offset=""0x2a"" startLine=""30"" startColumn=""9"" endLine=""30"" endColumn=""10"" document=""1"" />
<entry offset=""0x2b"" startLine=""30"" startColumn=""11"" endLine=""30"" endColumn=""25"" document=""1"" />
<entry offset=""0x30"" hidden=""true"" document=""1"" />
<entry offset=""0x33"" startLine=""32"" startColumn=""9"" endLine=""32"" endColumn=""20"" document=""1"" />
<entry offset=""0x3a"" startLine=""33"" startColumn=""5"" endLine=""33"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
#endregion
#region Constructor
[WorkItem(538317, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538317")]
[Fact]
public void ConstructorSequencePoints1()
{
var source = WithWindowsLineBreaks(
@"namespace NS
{
public class MyClass
{
int intTest;
public MyClass()
{
intTest = 123;
}
public MyClass(params int[] values)
{
intTest = values[0] + values[1] + values[2];
}
public static int Main()
{
int intI = 1, intJ = 8;
int intK = 3;
// Can't step into Ctor
MyClass mc = new MyClass();
// Can't step into Ctor
mc = new MyClass(intI, intJ, intK);
return mc.intTest - 12;
}
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
// Dev10 vs. Roslyn
//
// Default Ctor (no param)
// Dev10 Roslyn
// ======================================================================================
// Code size 18 (0x12) // Code size 16 (0x10)
// .maxstack 8 .maxstack 8
//* IL_0000: ldarg.0 *IL_0000: ldarg.0
// IL_0001: call IL_0001: callvirt
// instance void [mscorlib]System.Object::.ctor() instance void [mscorlib]System.Object::.ctor()
// IL_0006: nop *IL_0006: nop
//* IL_0007: nop
//* IL_0008: ldarg.0 *IL_0007: ldarg.0
// IL_0009: ldc.i4.s 123 IL_0008: ldc.i4.s 123
// IL_000b: stfld int32 NS.MyClass::intTest IL_000a: stfld int32 NS.MyClass::intTest
// IL_0010: nop
//* IL_0011: ret *IL_000f: ret
// -----------------------------------------------------------------------------------------
// SeqPoint: 0, 7 ,8, 0x10 0, 6, 7, 0xf
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""NS.MyClass"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""25"" document=""1"" />
<entry offset=""0x7"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" />
<entry offset=""0x8"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""27"" document=""1"" />
<entry offset=""0x10"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""NS.MyClass"" name="".ctor"" parameterNames=""values"">
<customDebugInfo>
<forward declaringType=""NS.MyClass"" methodName="".ctor"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""44"" document=""1"" />
<entry offset=""0x7"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" />
<entry offset=""0x8"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""57"" document=""1"" />
<entry offset=""0x19"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""NS.MyClass"" name=""Main"">
<customDebugInfo>
<forward declaringType=""NS.MyClass"" methodName="".ctor"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""19"" />
<slot kind=""0"" offset=""29"" />
<slot kind=""0"" offset=""56"" />
<slot kind=""0"" offset=""126"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" />
<entry offset=""0x1"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""25"" document=""1"" />
<entry offset=""0x3"" startLine=""18"" startColumn=""27"" endLine=""18"" endColumn=""35"" document=""1"" />
<entry offset=""0x5"" startLine=""19"" startColumn=""13"" endLine=""19"" endColumn=""26"" document=""1"" />
<entry offset=""0x7"" startLine=""22"" startColumn=""13"" endLine=""22"" endColumn=""40"" document=""1"" />
<entry offset=""0xd"" startLine=""25"" startColumn=""13"" endLine=""25"" endColumn=""48"" document=""1"" />
<entry offset=""0x25"" startLine=""27"" startColumn=""13"" endLine=""27"" endColumn=""36"" document=""1"" />
<entry offset=""0x32"" startLine=""28"" startColumn=""9"" endLine=""28"" endColumn=""10"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x35"">
<local name=""intI"" il_index=""0"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" />
<local name=""intJ"" il_index=""1"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" />
<local name=""intK"" il_index=""2"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" />
<local name=""mc"" il_index=""3"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void ConstructorSequencePoints2()
{
TestSequencePoints(
@"using System;
class D
{
public D() : [|base()|]
{
}
}", TestOptions.DebugDll);
TestSequencePoints(
@"using System;
class D
{
static D()
[|{|]
}
}", TestOptions.DebugDll);
TestSequencePoints(
@"using System;
class A : Attribute {}
class D
{
[A]
public D() : [|base()|]
{
}
}", TestOptions.DebugDll);
TestSequencePoints(
@"using System;
class A : Attribute {}
class D
{
[A]
public D()
: [|base()|]
{
}
}", TestOptions.DebugDll);
TestSequencePoints(
@"using System;
class A : Attribute {}
class C { }
class D
{
[A]
[|public D()|]
{
}
}", TestOptions.DebugDll);
}
#endregion
#region Destructor
[Fact]
public void Destructors()
{
var source = @"
using System;
public class Base
{
~Base()
{
Console.WriteLine();
}
}
public class Derived : Base
{
~Derived()
{
Console.WriteLine();
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Base"" name=""Finalize"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x2"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""29"" document=""1"" />
<entry offset=""0xa"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x12"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x13"">
<namespace name=""System"" />
</scope>
</method>
<method containingType=""Derived"" name=""Finalize"">
<customDebugInfo>
<forward declaringType=""Base"" methodName=""Finalize"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
<entry offset=""0x2"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""29"" document=""1"" />
<entry offset=""0xa"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" />
<entry offset=""0x12"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
#endregion
#region Field and Property Initializers
[Fact]
[WorkItem(50611, "https://github.com/dotnet/roslyn/issues/50611")]
public void TestPartialClassFieldInitializers()
{
var text1 = WithWindowsLineBreaks(@"
public partial class C
{
int x = 1;
}
");
var text2 = WithWindowsLineBreaks(@"
public partial class C
{
int y = 1;
static void Main()
{
C c = new C();
}
}
");
// Having a unique name here may be important. The infrastructure of the pdb to xml conversion
// loads the assembly into the ReflectionOnlyLoadFrom context.
// So it's probably a good idea to have a new name for each assembly.
var compilation = CreateCompilation(new SyntaxTree[] { Parse(text1, "a.cs"), Parse(text2, "b.cs") });
compilation.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name=""b.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""BB-7A-A6-D2-B2-32-59-43-8C-98-7F-E1-98-8D-F0-94-68-E9-EB-80"" />
<file id=""2"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""B4-EA-18-73-D2-0E-7F-15-51-4C-68-86-40-DF-E3-C3-97-9D-F6-B7"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Main"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""15"" document=""2"" />
<entry offset=""0x7"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""15"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>", format: DebugInformationFormat.Pdb);
compilation.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""B4-EA-18-73-D2-0E-7F-15-51-4C-68-86-40-DF-E3-C3-97-9D-F6-B7"" />
<file id=""2"" name=""b.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""BB-7A-A6-D2-B2-32-59-43-8C-98-7F-E1-98-8D-F0-94-68-E9-EB-80"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""15"" document=""1"" />
<entry offset=""0x7"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""15"" document=""2"" />
</sequencePoints>
</method>
</methods>
</symbols>", format: DebugInformationFormat.PortablePdb);
}
[Fact]
[WorkItem(50611, "https://github.com/dotnet/roslyn/issues/50611")]
public void TestPartialClassFieldInitializersWithLineDirectives()
{
var text1 = WithWindowsLineBreaks(@"
using System;
public partial class C
{
int x = 1;
#line 12 ""foo.cs""
int z = Math.Abs(-3);
int w = Math.Abs(4);
#line 17 ""bar.cs""
double zed = Math.Sin(5);
}
#pragma checksum ""mah.cs"" ""{406EA660-64CF-4C82-B6F0-42D48172A799}"" ""ab007f1d23d9""
");
var text2 = WithWindowsLineBreaks(@"
using System;
public partial class C
{
int y = 1;
int x2 = 1;
#line 12 ""foo2.cs""
int z2 = Math.Abs(-3);
int w2 = Math.Abs(4);
}
");
var text3 = WithWindowsLineBreaks(@"
using System;
public partial class C
{
#line 112 ""mah.cs""
int y3 = 1;
int x3 = 1;
int z3 = Math.Abs(-3);
#line default
int w3 = Math.Abs(4);
double zed3 = Math.Sin(5);
C() {
Console.WriteLine(""hi"");
}
static void Main()
{
C c = new C();
}
}
");
//Having a unique name here may be important. The infrastructure of the pdb to xml conversion
//loads the assembly into the ReflectionOnlyLoadFrom context.
//So it's probably a good idea to have a new name for each assembly.
var compilation = CreateCompilation(new[] { Parse(text1, "a.cs"), Parse(text2, "b.cs"), Parse(text3, "a.cs") }, options: TestOptions.DebugDll);
compilation.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""E2-3B-47-02-DC-E4-8D-B4-FF-00-67-90-31-68-74-C0-06-D7-39-0E"" />
<file id=""2"" name=""b.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""DB-CE-E5-E9-CB-53-E5-EF-C1-7F-2C-53-EC-02-FE-5C-34-2C-EF-94"" />
<file id=""3"" name=""foo.cs"" language=""C#"" />
<file id=""4"" name=""bar.cs"" language=""C#"" />
<file id=""5"" name=""foo2.cs"" language=""C#"" />
<file id=""6"" name=""mah.cs"" language=""C#"" checksumAlgorithm=""406ea660-64cf-4c82-b6f0-42d48172a799"" checksum=""AB-00-7F-1D-23-D9"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""15"" document=""1"" />
<entry offset=""0x7"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""26"" document=""3"" />
<entry offset=""0x14"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""25"" document=""3"" />
<entry offset=""0x20"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""30"" document=""4"" />
<entry offset=""0x34"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""15"" document=""2"" />
<entry offset=""0x3b"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""16"" document=""2"" />
<entry offset=""0x42"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""27"" document=""5"" />
<entry offset=""0x4f"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""26"" document=""5"" />
<entry offset=""0x5b"" startLine=""112"" startColumn=""5"" endLine=""112"" endColumn=""16"" document=""6"" />
<entry offset=""0x62"" startLine=""113"" startColumn=""5"" endLine=""113"" endColumn=""16"" document=""6"" />
<entry offset=""0x69"" startLine=""114"" startColumn=""5"" endLine=""114"" endColumn=""27"" document=""6"" />
<entry offset=""0x76"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""26"" document=""1"" />
<entry offset=""0x82"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""31"" document=""1"" />
<entry offset=""0x96"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""8"" document=""1"" />
<entry offset=""0x9d"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x9e"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""33"" document=""1"" />
<entry offset=""0xa9"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>", format: DebugInformationFormat.PortablePdb);
}
[WorkItem(543313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543313")]
[Fact]
public void TestFieldInitializerExpressionLambda()
{
var source = @"
class C
{
int x = ((System.Func<int, int>)(z => z))(1);
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLambdaMap>
<methodOrdinal>1</methodOrdinal>
<lambda offset=""-6"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""50"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C+<>c"" name=""<.ctor>b__1_0"" parameterNames=""z"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""43"" endLine=""4"" endColumn=""44"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void FieldInitializerSequencePointSpans()
{
var source = @"
class C
{
int x = 1, y = 2;
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""14"" document=""1"" />
<entry offset=""0x7"" startLine=""4"" startColumn=""16"" endLine=""4"" endColumn=""21"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
#endregion
#region Auto-Property
[WorkItem(820806, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/820806")]
[Fact]
public void BreakpointForAutoImplementedProperty()
{
var source = @"
public class C
{
public static int AutoProp1 { get; private set; }
internal string AutoProp2 { get; set; }
internal protected C AutoProp3 { internal get; set; }
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugDll);
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""get_AutoProp1"">
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""35"" endLine=""4"" endColumn=""39"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""set_AutoProp1"" parameterNames=""value"">
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""40"" endLine=""4"" endColumn=""52"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""get_AutoProp2"">
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""33"" endLine=""5"" endColumn=""37"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""set_AutoProp2"" parameterNames=""value"">
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""38"" endLine=""5"" endColumn=""42"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""get_AutoProp3"">
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""38"" endLine=""6"" endColumn=""51"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""set_AutoProp3"" parameterNames=""value"">
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""52"" endLine=""6"" endColumn=""56"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void PropertyDeclaration()
{
TestSequencePoints(
@"using System;
public class C
{
int P { [|get;|] set; }
}", TestOptions.DebugDll);
TestSequencePoints(
@"using System;
public class C
{
int P { get; [|set;|] }
}", TestOptions.DebugDll);
TestSequencePoints(
@"using System;
public class C
{
int P { get [|{|] return 0; } }
}", TestOptions.DebugDll);
TestSequencePoints(
@"using System;
public class C
{
int P { get; } = [|int.Parse(""42"")|];
}", TestOptions.DebugDll, TestOptions.Regular);
}
#endregion
#region ReturnStatement
[Fact]
public void Return_Implicit()
{
var source = @"class C
{
static void Main()
{
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void Return_Explicit()
{
var source = @"class C
{
static void Main()
{
return;
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""16"" document=""1"" />
<entry offset=""0x3"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(538298, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538298")]
[Fact]
public void RegressSeqPtEndOfMethodAfterReturn()
{
var source = WithWindowsLineBreaks(
@"using System;
public class SeqPointAfterReturn
{
public static int Main()
{
int ret = 0;
ReturnVoid(100);
if (field != ""Even"")
ret = 1;
ReturnVoid(99);
if (field != ""Odd"")
ret = ret + 1;
string rets = ReturnValue(101);
if (rets != ""Odd"")
ret = ret + 1;
rets = ReturnValue(102);
if (rets != ""Even"")
ret = ret + 1;
return ret;
}
static string field;
public static void ReturnVoid(int p)
{
int x = (int)(p % 2);
if (x == 0)
{
field = ""Even"";
}
else
{
field = ""Odd"";
}
}
public static string ReturnValue(int p)
{
int x = (int)(p % 2);
if (x == 0)
{
return ""Even"";
}
else
{
return ""Odd"";
}
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
// Expected are current actual output plus Two extra expected SeqPt:
// <entry offset=""0x73"" startLine=""25"" startColumn=""5"" endLine=""25"" endColumn=""6"" document=""1"" />
// <entry offset=""0x22"" startLine=""52"" startColumn=""5"" endLine=""52"" endColumn=""6"" document=""1"" />
//
// Note: NOT include other differences between Roslyn and Dev10, as they are filed in separated bugs
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""SeqPointAfterReturn"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""0"" offset=""204"" />
<slot kind=""1"" offset=""59"" />
<slot kind=""1"" offset=""138"" />
<slot kind=""1"" offset=""238"" />
<slot kind=""1"" offset=""330"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""21"" document=""1"" />
<entry offset=""0x3"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""25"" document=""1"" />
<entry offset=""0xb"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""29"" document=""1"" />
<entry offset=""0x1b"" hidden=""true"" document=""1"" />
<entry offset=""0x1e"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""21"" document=""1"" />
<entry offset=""0x20"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""24"" document=""1"" />
<entry offset=""0x28"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""28"" document=""1"" />
<entry offset=""0x38"" hidden=""true"" document=""1"" />
<entry offset=""0x3b"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""27"" document=""1"" />
<entry offset=""0x3f"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""40"" document=""1"" />
<entry offset=""0x47"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""27"" document=""1"" />
<entry offset=""0x54"" hidden=""true"" document=""1"" />
<entry offset=""0x58"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""27"" document=""1"" />
<entry offset=""0x5c"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""33"" document=""1"" />
<entry offset=""0x64"" startLine=""21"" startColumn=""9"" endLine=""21"" endColumn=""28"" document=""1"" />
<entry offset=""0x71"" hidden=""true"" document=""1"" />
<entry offset=""0x75"" startLine=""22"" startColumn=""13"" endLine=""22"" endColumn=""27"" document=""1"" />
<entry offset=""0x79"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""20"" document=""1"" />
<entry offset=""0x7e"" startLine=""25"" startColumn=""5"" endLine=""25"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x81"">
<namespace name=""System"" />
<local name=""ret"" il_index=""0"" il_start=""0x0"" il_end=""0x81"" attributes=""0"" />
<local name=""rets"" il_index=""1"" il_start=""0x0"" il_end=""0x81"" attributes=""0"" />
</scope>
</method>
<method containingType=""SeqPointAfterReturn"" name=""ReturnVoid"" parameterNames=""p"">
<customDebugInfo>
<forward declaringType=""SeqPointAfterReturn"" methodName=""Main"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""1"" offset=""42"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""29"" startColumn=""5"" endLine=""29"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""30"" startColumn=""9"" endLine=""30"" endColumn=""30"" document=""1"" />
<entry offset=""0x5"" startLine=""31"" startColumn=""9"" endLine=""31"" endColumn=""20"" document=""1"" />
<entry offset=""0xa"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""32"" startColumn=""9"" endLine=""32"" endColumn=""10"" document=""1"" />
<entry offset=""0xe"" startLine=""33"" startColumn=""13"" endLine=""33"" endColumn=""28"" document=""1"" />
<entry offset=""0x18"" startLine=""34"" startColumn=""9"" endLine=""34"" endColumn=""10"" document=""1"" />
<entry offset=""0x19"" hidden=""true"" document=""1"" />
<entry offset=""0x1b"" startLine=""36"" startColumn=""9"" endLine=""36"" endColumn=""10"" document=""1"" />
<entry offset=""0x1c"" startLine=""37"" startColumn=""13"" endLine=""37"" endColumn=""27"" document=""1"" />
<entry offset=""0x26"" startLine=""38"" startColumn=""9"" endLine=""38"" endColumn=""10"" document=""1"" />
<entry offset=""0x27"" startLine=""39"" startColumn=""5"" endLine=""39"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x28"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x28"" attributes=""0"" />
</scope>
</method>
<method containingType=""SeqPointAfterReturn"" name=""ReturnValue"" parameterNames=""p"">
<customDebugInfo>
<forward declaringType=""SeqPointAfterReturn"" methodName=""Main"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""1"" offset=""42"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""42"" startColumn=""5"" endLine=""42"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""43"" startColumn=""9"" endLine=""43"" endColumn=""30"" document=""1"" />
<entry offset=""0x5"" startLine=""44"" startColumn=""9"" endLine=""44"" endColumn=""20"" document=""1"" />
<entry offset=""0xa"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""45"" startColumn=""9"" endLine=""45"" endColumn=""10"" document=""1"" />
<entry offset=""0xe"" startLine=""46"" startColumn=""13"" endLine=""46"" endColumn=""27"" document=""1"" />
<entry offset=""0x16"" startLine=""49"" startColumn=""9"" endLine=""49"" endColumn=""10"" document=""1"" />
<entry offset=""0x17"" startLine=""50"" startColumn=""13"" endLine=""50"" endColumn=""26"" document=""1"" />
<entry offset=""0x1f"" startLine=""52"" startColumn=""5"" endLine=""52"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x21"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region Exception Handling
[WorkItem(542064, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542064")]
[Fact]
public void ExceptionHandling()
{
var source = WithWindowsLineBreaks(@"
class Test
{
static int Main()
{
int ret = 0; // stop 1
try
{ // stop 2
throw new System.Exception(); // stop 3
}
catch (System.Exception e) // stop 4
{ // stop 5
ret = 1; // stop 6
}
try
{ // stop 7
throw new System.Exception(); // stop 8
}
catch // stop 9
{ // stop 10
return ret; // stop 11
}
}
}
");
// Dev12 inserts an additional sequence point on catch clause, just before
// the exception object is assigned to the variable. We don't place that sequence point.
// Also the scope of he exception variable is different.
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("Test.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Test"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""0"" offset=""147"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""21"" document=""1"" />
<entry offset=""0x3"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" />
<entry offset=""0x4"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""42"" document=""1"" />
<entry offset=""0xa"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""35"" document=""1"" />
<entry offset=""0xb"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" />
<entry offset=""0xc"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""21"" document=""1"" />
<entry offset=""0xe"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" />
<entry offset=""0x11"" hidden=""true"" document=""1"" />
<entry offset=""0x12"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" />
<entry offset=""0x13"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""42"" document=""1"" />
<entry offset=""0x19"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""14"" document=""1"" />
<entry offset=""0x1a"" startLine=""21"" startColumn=""9"" endLine=""21"" endColumn=""10"" document=""1"" />
<entry offset=""0x1b"" startLine=""22"" startColumn=""13"" endLine=""22"" endColumn=""24"" document=""1"" />
<entry offset=""0x1f"" startLine=""25"" startColumn=""5"" endLine=""25"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x21"">
<local name=""ret"" il_index=""0"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" />
<scope startOffset=""0xa"" endOffset=""0x11"">
<local name=""e"" il_index=""1"" il_start=""0xa"" il_end=""0x11"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(2911, "https://github.com/dotnet/roslyn/issues/2911")]
[Fact]
public void ExceptionHandling_Filter_Debug1()
{
var source = WithWindowsLineBreaks(@"
using System;
using System.IO;
class Test
{
static string filter(Exception e)
{
return null;
}
static void Main()
{
try
{
throw new InvalidOperationException();
}
catch (IOException e) when (filter(e) != null)
{
Console.WriteLine();
}
catch (Exception e) when (filter(e) != null)
{
Console.WriteLine();
}
}
}
");
var v = CompileAndVerify(CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll));
v.VerifyIL("Test.Main", @"
{
// Code size 89 (0x59)
.maxstack 2
.locals init (System.IO.IOException V_0, //e
bool V_1,
System.Exception V_2, //e
bool V_3)
-IL_0000: nop
.try
{
-IL_0001: nop
-IL_0002: newobj ""System.InvalidOperationException..ctor()""
IL_0007: throw
}
filter
{
~IL_0008: isinst ""System.IO.IOException""
IL_000d: dup
IL_000e: brtrue.s IL_0014
IL_0010: pop
IL_0011: ldc.i4.0
IL_0012: br.s IL_0023
IL_0014: stloc.0
-IL_0015: ldloc.0
IL_0016: call ""string Test.filter(System.Exception)""
IL_001b: ldnull
IL_001c: cgt.un
IL_001e: stloc.1
~IL_001f: ldloc.1
IL_0020: ldc.i4.0
IL_0021: cgt.un
IL_0023: endfilter
} // end filter
{ // handler
~IL_0025: pop
-IL_0026: nop
-IL_0027: call ""void System.Console.WriteLine()""
IL_002c: nop
-IL_002d: nop
IL_002e: leave.s IL_0058
}
filter
{
~IL_0030: isinst ""System.Exception""
IL_0035: dup
IL_0036: brtrue.s IL_003c
IL_0038: pop
IL_0039: ldc.i4.0
IL_003a: br.s IL_004b
IL_003c: stloc.2
-IL_003d: ldloc.2
IL_003e: call ""string Test.filter(System.Exception)""
IL_0043: ldnull
IL_0044: cgt.un
IL_0046: stloc.3
~IL_0047: ldloc.3
IL_0048: ldc.i4.0
IL_0049: cgt.un
IL_004b: endfilter
} // end filter
{ // handler
~IL_004d: pop
-IL_004e: nop
-IL_004f: call ""void System.Console.WriteLine()""
IL_0054: nop
-IL_0055: nop
IL_0056: leave.s IL_0058
}
-IL_0058: ret
}
", sequencePoints: "Test.Main");
v.VerifyPdb("Test.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Test"" name=""Main"">
<customDebugInfo>
<forward declaringType=""Test"" methodName=""filter"" parameterNames=""e"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""104"" />
<slot kind=""1"" offset=""120"" />
<slot kind=""0"" offset=""216"" />
<slot kind=""1"" offset=""230"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" />
<entry offset=""0x2"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""51"" document=""1"" />
<entry offset=""0x8"" hidden=""true"" document=""1"" />
<entry offset=""0x15"" startLine=""18"" startColumn=""31"" endLine=""18"" endColumn=""55"" document=""1"" />
<entry offset=""0x1f"" hidden=""true"" document=""1"" />
<entry offset=""0x25"" hidden=""true"" document=""1"" />
<entry offset=""0x26"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""1"" />
<entry offset=""0x27"" startLine=""20"" startColumn=""13"" endLine=""20"" endColumn=""33"" document=""1"" />
<entry offset=""0x2d"" startLine=""21"" startColumn=""9"" endLine=""21"" endColumn=""10"" document=""1"" />
<entry offset=""0x30"" hidden=""true"" document=""1"" />
<entry offset=""0x3d"" startLine=""22"" startColumn=""29"" endLine=""22"" endColumn=""53"" document=""1"" />
<entry offset=""0x47"" hidden=""true"" document=""1"" />
<entry offset=""0x4d"" hidden=""true"" document=""1"" />
<entry offset=""0x4e"" startLine=""23"" startColumn=""9"" endLine=""23"" endColumn=""10"" document=""1"" />
<entry offset=""0x4f"" startLine=""24"" startColumn=""13"" endLine=""24"" endColumn=""33"" document=""1"" />
<entry offset=""0x55"" startLine=""25"" startColumn=""9"" endLine=""25"" endColumn=""10"" document=""1"" />
<entry offset=""0x58"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x59"">
<scope startOffset=""0x8"" endOffset=""0x30"">
<local name=""e"" il_index=""0"" il_start=""0x8"" il_end=""0x30"" attributes=""0"" />
</scope>
<scope startOffset=""0x30"" endOffset=""0x58"">
<local name=""e"" il_index=""2"" il_start=""0x30"" il_end=""0x58"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(2911, "https://github.com/dotnet/roslyn/issues/2911")]
[Fact]
public void ExceptionHandling_Filter_Debug2()
{
var source = WithWindowsLineBreaks(@"
class Test
{
static void Main()
{
try
{
throw new System.Exception();
}
catch when (F())
{
System.Console.WriteLine();
}
}
private static bool F()
{
return true;
}
}
");
var v = CompileAndVerify(CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll));
v.VerifyIL("Test.Main", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (bool V_0)
-IL_0000: nop
.try
{
-IL_0001: nop
-IL_0002: newobj ""System.Exception..ctor()""
IL_0007: throw
}
filter
{
~IL_0008: pop
-IL_0009: call ""bool Test.F()""
IL_000e: stloc.0
~IL_000f: ldloc.0
IL_0010: ldc.i4.0
IL_0011: cgt.un
IL_0013: endfilter
} // end filter
{ // handler
~IL_0015: pop
-IL_0016: nop
-IL_0017: call ""void System.Console.WriteLine()""
IL_001c: nop
-IL_001d: nop
IL_001e: leave.s IL_0020
}
-IL_0020: ret
}
", sequencePoints: "Test.Main");
v.VerifyPdb("Test.Main", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Test"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""1"" offset=""95"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" />
<entry offset=""0x2"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""42"" document=""1"" />
<entry offset=""0x8"" hidden=""true"" document=""1"" />
<entry offset=""0x9"" startLine=""10"" startColumn=""15"" endLine=""10"" endColumn=""25"" document=""1"" />
<entry offset=""0xf"" hidden=""true"" document=""1"" />
<entry offset=""0x15"" hidden=""true"" document=""1"" />
<entry offset=""0x16"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0x17"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""40"" document=""1"" />
<entry offset=""0x1d"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x20"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(2911, "https://github.com/dotnet/roslyn/issues/2911")]
[Fact]
public void ExceptionHandling_Filter_Debug3()
{
var source = WithWindowsLineBreaks(@"
class Test
{
static bool a = true;
static void Main()
{
try
{
throw new System.Exception();
}
catch when (a)
{
System.Console.WriteLine();
}
}
}
");
var v = CompileAndVerify(CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll));
v.VerifyIL("Test.Main", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (bool V_0)
-IL_0000: nop
.try
{
-IL_0001: nop
-IL_0002: newobj ""System.Exception..ctor()""
IL_0007: throw
}
filter
{
~IL_0008: pop
-IL_0009: ldsfld ""bool Test.a""
IL_000e: stloc.0
~IL_000f: ldloc.0
IL_0010: ldc.i4.0
IL_0011: cgt.un
IL_0013: endfilter
} // end filter
{ // handler
~IL_0015: pop
-IL_0016: nop
-IL_0017: call ""void System.Console.WriteLine()""
IL_001c: nop
-IL_001d: nop
IL_001e: leave.s IL_0020
}
-IL_0020: ret
}
", sequencePoints: "Test.Main");
v.VerifyPdb("Test.Main", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Test"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""1"" offset=""95"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x2"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""42"" document=""1"" />
<entry offset=""0x8"" hidden=""true"" document=""1"" />
<entry offset=""0x9"" startLine=""12"" startColumn=""15"" endLine=""12"" endColumn=""23"" document=""1"" />
<entry offset=""0xf"" hidden=""true"" document=""1"" />
<entry offset=""0x15"" hidden=""true"" document=""1"" />
<entry offset=""0x16"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x17"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""40"" document=""1"" />
<entry offset=""0x1d"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" />
<entry offset=""0x20"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(2911, "https://github.com/dotnet/roslyn/issues/2911")]
[Fact]
public void ExceptionHandling_Filter_Release3()
{
var source = @"
class Test
{
static bool a = true;
static void Main()
{
try
{
throw new System.Exception();
}
catch when (a)
{
System.Console.WriteLine();
}
}
}
";
var v = CompileAndVerify(CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseDll));
v.VerifyIL("Test.Main", @"
{
// Code size 26 (0x1a)
.maxstack 2
.try
{
-IL_0000: newobj ""System.Exception..ctor()""
IL_0005: throw
}
filter
{
~IL_0006: pop
-IL_0007: ldsfld ""bool Test.a""
IL_000c: ldc.i4.0
IL_000d: cgt.un
IL_000f: endfilter
} // end filter
{ // handler
~IL_0011: pop
-IL_0012: call ""void System.Console.WriteLine()""
-IL_0017: leave.s IL_0019
}
-IL_0019: ret
}
", sequencePoints: "Test.Main");
v.VerifyPdb("Test.Main", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Test"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""42"" document=""1"" />
<entry offset=""0x6"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" startLine=""12"" startColumn=""15"" endLine=""12"" endColumn=""23"" document=""1"" />
<entry offset=""0x11"" hidden=""true"" document=""1"" />
<entry offset=""0x12"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""40"" document=""1"" />
<entry offset=""0x17"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" />
<entry offset=""0x19"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(778655, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/778655")]
[Fact]
public void BranchToStartOfTry()
{
string source = WithWindowsLineBreaks(@"
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
string str = null;
bool isEmpty = string.IsNullOrEmpty(str);
// isEmpty is always true here, so it should never go thru this if statement.
if (!isEmpty)
{
throw new Exception();
}
try
{
Console.WriteLine();
}
catch
{
}
}
}
");
// Note the hidden sequence point @IL_0019.
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""18"" />
<slot kind=""0"" offset=""44"" />
<slot kind=""1"" offset=""177"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""27"" document=""1"" />
<entry offset=""0x3"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""50"" document=""1"" />
<entry offset=""0xa"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""22"" document=""1"" />
<entry offset=""0xf"" hidden=""true"" document=""1"" />
<entry offset=""0x12"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x13"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""35"" document=""1"" />
<entry offset=""0x19"" hidden=""true"" document=""1"" />
<entry offset=""0x1a"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" />
<entry offset=""0x1b"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""33"" document=""1"" />
<entry offset=""0x21"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""1"" />
<entry offset=""0x24"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""14"" document=""1"" />
<entry offset=""0x25"" startLine=""21"" startColumn=""9"" endLine=""21"" endColumn=""10"" document=""1"" />
<entry offset=""0x26"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" />
<entry offset=""0x29"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2a"">
<namespace name=""System"" />
<namespace name=""System.Collections.Generic"" />
<local name=""str"" il_index=""0"" il_start=""0x0"" il_end=""0x2a"" attributes=""0"" />
<local name=""isEmpty"" il_index=""1"" il_start=""0x0"" il_end=""0x2a"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region UsingStatement
[Fact]
public void UsingStatement_EmbeddedStatement()
{
var source = WithWindowsLineBreaks(@"
public class DisposableClass : System.IDisposable
{
public DisposableClass(int a) { }
public void Dispose() { }
}
class C
{
static void Main()
{
using (DisposableClass a = new DisposableClass(1), b = new DisposableClass(2))
System.Console.WriteLine(""First"");
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.Main", sequencePoints: "C.Main", source: source, expectedIL: @"
{
// Code size 53 (0x35)
.maxstack 1
.locals init (DisposableClass V_0, //a
DisposableClass V_1) //b
// sequence point: {
IL_0000: nop
// sequence point: DisposableClass a = new DisposableClass(1)
IL_0001: ldc.i4.1
IL_0002: newobj ""DisposableClass..ctor(int)""
IL_0007: stloc.0
.try
{
// sequence point: b = new DisposableClass(2)
IL_0008: ldc.i4.2
IL_0009: newobj ""DisposableClass..ctor(int)""
IL_000e: stloc.1
.try
{
// sequence point: System.Console.WriteLine(""First"");
IL_000f: ldstr ""First""
IL_0014: call ""void System.Console.WriteLine(string)""
IL_0019: nop
IL_001a: leave.s IL_0027
}
finally
{
// sequence point: <hidden>
IL_001c: ldloc.1
IL_001d: brfalse.s IL_0026
IL_001f: ldloc.1
IL_0020: callvirt ""void System.IDisposable.Dispose()""
IL_0025: nop
// sequence point: <hidden>
IL_0026: endfinally
}
// sequence point: <hidden>
IL_0027: leave.s IL_0034
}
finally
{
// sequence point: <hidden>
IL_0029: ldloc.0
IL_002a: brfalse.s IL_0033
IL_002c: ldloc.0
IL_002d: callvirt ""void System.IDisposable.Dispose()""
IL_0032: nop
// sequence point: <hidden>
IL_0033: endfinally
}
// sequence point: }
IL_0034: ret
}
");
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<forward declaringType=""DisposableClass"" methodName="".ctor"" parameterNames=""a"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""34"" />
<slot kind=""0"" offset=""62"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""58"" document=""1"" />
<entry offset=""0x8"" startLine=""12"" startColumn=""60"" endLine=""12"" endColumn=""86"" document=""1"" />
<entry offset=""0xf"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""47"" document=""1"" />
<entry offset=""0x1c"" hidden=""true"" document=""1"" />
<entry offset=""0x26"" hidden=""true"" document=""1"" />
<entry offset=""0x27"" hidden=""true"" document=""1"" />
<entry offset=""0x29"" hidden=""true"" document=""1"" />
<entry offset=""0x33"" hidden=""true"" document=""1"" />
<entry offset=""0x34"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x35"">
<scope startOffset=""0x1"" endOffset=""0x34"">
<local name=""a"" il_index=""0"" il_start=""0x1"" il_end=""0x34"" attributes=""0"" />
<local name=""b"" il_index=""1"" il_start=""0x1"" il_end=""0x34"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void UsingStatement_Block()
{
var source = WithWindowsLineBreaks(@"
public class DisposableClass : System.IDisposable
{
public DisposableClass(int a) { }
public void Dispose() { }
}
class C
{
static void Main()
{
using (DisposableClass c = new DisposableClass(3), d = new DisposableClass(4))
{
System.Console.WriteLine(""Second"");
}
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.Main", sequencePoints: "C.Main", source: source, expectedIL: @"
{
// Code size 55 (0x37)
.maxstack 1
.locals init (DisposableClass V_0, //c
DisposableClass V_1) //d
// sequence point: {
IL_0000: nop
// sequence point: DisposableClass c = new DisposableClass(3)
IL_0001: ldc.i4.3
IL_0002: newobj ""DisposableClass..ctor(int)""
IL_0007: stloc.0
.try
{
// sequence point: d = new DisposableClass(4)
IL_0008: ldc.i4.4
IL_0009: newobj ""DisposableClass..ctor(int)""
IL_000e: stloc.1
.try
{
// sequence point: {
IL_000f: nop
// sequence point: System.Console.WriteLine(""Second"");
IL_0010: ldstr ""Second""
IL_0015: call ""void System.Console.WriteLine(string)""
IL_001a: nop
// sequence point: }
IL_001b: nop
IL_001c: leave.s IL_0029
}
finally
{
// sequence point: <hidden>
IL_001e: ldloc.1
IL_001f: brfalse.s IL_0028
IL_0021: ldloc.1
IL_0022: callvirt ""void System.IDisposable.Dispose()""
IL_0027: nop
// sequence point: <hidden>
IL_0028: endfinally
}
// sequence point: <hidden>
IL_0029: leave.s IL_0036
}
finally
{
// sequence point: <hidden>
IL_002b: ldloc.0
IL_002c: brfalse.s IL_0035
IL_002e: ldloc.0
IL_002f: callvirt ""void System.IDisposable.Dispose()""
IL_0034: nop
// sequence point: <hidden>
IL_0035: endfinally
}
// sequence point: }
IL_0036: ret
}
"
);
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<forward declaringType=""DisposableClass"" methodName="".ctor"" parameterNames=""a"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""34"" />
<slot kind=""0"" offset=""62"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""58"" document=""1"" />
<entry offset=""0x8"" startLine=""12"" startColumn=""60"" endLine=""12"" endColumn=""86"" document=""1"" />
<entry offset=""0xf"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x10"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""48"" document=""1"" />
<entry offset=""0x1b"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" />
<entry offset=""0x1e"" hidden=""true"" document=""1"" />
<entry offset=""0x28"" hidden=""true"" document=""1"" />
<entry offset=""0x29"" hidden=""true"" document=""1"" />
<entry offset=""0x2b"" hidden=""true"" document=""1"" />
<entry offset=""0x35"" hidden=""true"" document=""1"" />
<entry offset=""0x36"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x37"">
<scope startOffset=""0x1"" endOffset=""0x36"">
<local name=""c"" il_index=""0"" il_start=""0x1"" il_end=""0x36"" attributes=""0"" />
<local name=""d"" il_index=""1"" il_start=""0x1"" il_end=""0x36"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(18844, "https://github.com/dotnet/roslyn/issues/18844")]
[Fact]
public void UsingStatement_EmbeddedConditional()
{
var source = @"
class C
{
bool F()
{
bool x = true;
bool value = false;
using (var stream = new System.IO.MemoryStream())
if (x)
{
value = true;
}
else
value = false;
return value;
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.F", @"
{
// Code size 45 (0x2d)
.maxstack 1
.locals init (bool V_0, //x
bool V_1, //value
System.IO.MemoryStream V_2, //stream
bool V_3,
bool V_4)
// sequence point: {
IL_0000: nop
// sequence point: bool x = true;
IL_0001: ldc.i4.1
IL_0002: stloc.0
// sequence point: bool value = false;
IL_0003: ldc.i4.0
IL_0004: stloc.1
// sequence point: var stream = new System.IO.MemoryStream()
IL_0005: newobj ""System.IO.MemoryStream..ctor()""
IL_000a: stloc.2
.try
{
// sequence point: if (x)
IL_000b: ldloc.0
IL_000c: stloc.3
// sequence point: <hidden>
IL_000d: ldloc.3
IL_000e: brfalse.s IL_0016
// sequence point: {
IL_0010: nop
// sequence point: value = true;
IL_0011: ldc.i4.1
IL_0012: stloc.1
// sequence point: }
IL_0013: nop
// sequence point: <hidden>
IL_0014: br.s IL_0018
// sequence point: value = false;
IL_0016: ldc.i4.0
IL_0017: stloc.1
// sequence point: <hidden>
IL_0018: leave.s IL_0025
}
finally
{
// sequence point: <hidden>
IL_001a: ldloc.2
IL_001b: brfalse.s IL_0024
IL_001d: ldloc.2
IL_001e: callvirt ""void System.IDisposable.Dispose()""
IL_0023: nop
// sequence point: <hidden>
IL_0024: endfinally
}
// sequence point: return value;
IL_0025: ldloc.1
IL_0026: stloc.s V_4
IL_0028: br.s IL_002a
// sequence point: }
IL_002a: ldloc.s V_4
IL_002c: ret
}
", sequencePoints: "C.F", source: source);
}
[WorkItem(18844, "https://github.com/dotnet/roslyn/issues/18844")]
[Fact]
public void UsingStatement_EmbeddedConditional2()
{
var source = @"
class C
{
bool F()
{
bool x = true;
bool value = false;
using (var stream = new System.IO.MemoryStream())
if (x)
{
value = true;
}
else
{
value = false;
}
return value;
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.F", @"
{
// Code size 47 (0x2f)
.maxstack 1
.locals init (bool V_0, //x
bool V_1, //value
System.IO.MemoryStream V_2, //stream
bool V_3,
bool V_4)
// sequence point: {
IL_0000: nop
// sequence point: bool x = true;
IL_0001: ldc.i4.1
IL_0002: stloc.0
// sequence point: bool value = false;
IL_0003: ldc.i4.0
IL_0004: stloc.1
// sequence point: var stream = new System.IO.MemoryStream()
IL_0005: newobj ""System.IO.MemoryStream..ctor()""
IL_000a: stloc.2
.try
{
// sequence point: if (x)
IL_000b: ldloc.0
IL_000c: stloc.3
// sequence point: <hidden>
IL_000d: ldloc.3
IL_000e: brfalse.s IL_0016
// sequence point: {
IL_0010: nop
// sequence point: value = true;
IL_0011: ldc.i4.1
IL_0012: stloc.1
// sequence point: }
IL_0013: nop
// sequence point: <hidden>
IL_0014: br.s IL_001a
// sequence point: {
IL_0016: nop
// sequence point: value = false;
IL_0017: ldc.i4.0
IL_0018: stloc.1
// sequence point: }
IL_0019: nop
// sequence point: <hidden>
IL_001a: leave.s IL_0027
}
finally
{
// sequence point: <hidden>
IL_001c: ldloc.2
IL_001d: brfalse.s IL_0026
IL_001f: ldloc.2
IL_0020: callvirt ""void System.IDisposable.Dispose()""
IL_0025: nop
// sequence point: <hidden>
IL_0026: endfinally
}
// sequence point: return value;
IL_0027: ldloc.1
IL_0028: stloc.s V_4
IL_002a: br.s IL_002c
// sequence point: }
IL_002c: ldloc.s V_4
IL_002e: ret
}
", sequencePoints: "C.F", source: source);
}
[WorkItem(18844, "https://github.com/dotnet/roslyn/issues/18844")]
[Fact]
public void UsingStatement_EmbeddedWhile()
{
var source = @"
class C
{
void F(bool x)
{
using (var stream = new System.IO.MemoryStream())
while (x)
x = false;
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.F", @"
{
// Code size 31 (0x1f)
.maxstack 1
.locals init (System.IO.MemoryStream V_0, //stream
bool V_1)
// sequence point: {
IL_0000: nop
// sequence point: var stream = new System.IO.MemoryStream()
IL_0001: newobj ""System.IO.MemoryStream..ctor()""
IL_0006: stloc.0
.try
{
// sequence point: <hidden>
IL_0007: br.s IL_000c
// sequence point: x = false;
IL_0009: ldc.i4.0
IL_000a: starg.s V_1
// sequence point: while (x)
IL_000c: ldarg.1
IL_000d: stloc.1
// sequence point: <hidden>
IL_000e: ldloc.1
IL_000f: brtrue.s IL_0009
IL_0011: leave.s IL_001e
}
finally
{
// sequence point: <hidden>
IL_0013: ldloc.0
IL_0014: brfalse.s IL_001d
IL_0016: ldloc.0
IL_0017: callvirt ""void System.IDisposable.Dispose()""
IL_001c: nop
// sequence point: <hidden>
IL_001d: endfinally
}
// sequence point: }
IL_001e: ret
}
", sequencePoints: "C.F", source: source);
}
[WorkItem(18844, "https://github.com/dotnet/roslyn/issues/18844")]
[Fact]
public void UsingStatement_EmbeddedFor()
{
var source = @"
class C
{
void F(bool x)
{
using (var stream = new System.IO.MemoryStream())
for ( ; x == true; )
x = false;
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.F", @"
{
// Code size 31 (0x1f)
.maxstack 1
.locals init (System.IO.MemoryStream V_0, //stream
bool V_1)
// sequence point: {
IL_0000: nop
// sequence point: var stream = new System.IO.MemoryStream()
IL_0001: newobj ""System.IO.MemoryStream..ctor()""
IL_0006: stloc.0
.try
{
// sequence point: <hidden>
IL_0007: br.s IL_000c
// sequence point: x = false;
IL_0009: ldc.i4.0
IL_000a: starg.s V_1
// sequence point: x == true
IL_000c: ldarg.1
IL_000d: stloc.1
// sequence point: <hidden>
IL_000e: ldloc.1
IL_000f: brtrue.s IL_0009
IL_0011: leave.s IL_001e
}
finally
{
// sequence point: <hidden>
IL_0013: ldloc.0
IL_0014: brfalse.s IL_001d
IL_0016: ldloc.0
IL_0017: callvirt ""void System.IDisposable.Dispose()""
IL_001c: nop
// sequence point: <hidden>
IL_001d: endfinally
}
// sequence point: }
IL_001e: ret
}
", sequencePoints: "C.F", source: source);
}
[WorkItem(18844, "https://github.com/dotnet/roslyn/issues/18844")]
[Fact]
public void LockStatement_EmbeddedIf()
{
var source = @"
class C
{
void F(bool x)
{
string y = """";
lock (y)
if (!x)
System.Console.Write(1);
else
System.Console.Write(2);
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.F", @"
{
// Code size 58 (0x3a)
.maxstack 2
.locals init (string V_0, //y
string V_1,
bool V_2,
bool V_3)
// sequence point: {
IL_0000: nop
// sequence point: string y = """";
IL_0001: ldstr """"
IL_0006: stloc.0
// sequence point: lock (y)
IL_0007: ldloc.0
IL_0008: stloc.1
IL_0009: ldc.i4.0
IL_000a: stloc.2
.try
{
IL_000b: ldloc.1
IL_000c: ldloca.s V_2
IL_000e: call ""void System.Threading.Monitor.Enter(object, ref bool)""
IL_0013: nop
// sequence point: if (!x)
IL_0014: ldarg.1
IL_0015: ldc.i4.0
IL_0016: ceq
IL_0018: stloc.3
// sequence point: <hidden>
IL_0019: ldloc.3
IL_001a: brfalse.s IL_0025
// sequence point: System.Console.Write(1);
IL_001c: ldc.i4.1
IL_001d: call ""void System.Console.Write(int)""
IL_0022: nop
// sequence point: <hidden>
IL_0023: br.s IL_002c
// sequence point: System.Console.Write(2);
IL_0025: ldc.i4.2
IL_0026: call ""void System.Console.Write(int)""
IL_002b: nop
// sequence point: <hidden>
IL_002c: leave.s IL_0039
}
finally
{
// sequence point: <hidden>
IL_002e: ldloc.2
IL_002f: brfalse.s IL_0038
IL_0031: ldloc.1
IL_0032: call ""void System.Threading.Monitor.Exit(object)""
IL_0037: nop
// sequence point: <hidden>
IL_0038: endfinally
}
// sequence point: }
IL_0039: ret
}
", sequencePoints: "C.F", source: source);
}
#endregion
#region Using Declaration
[WorkItem(37417, "https://github.com/dotnet/roslyn/issues/37417")]
[Fact]
public void UsingDeclaration_BodyBlockScope()
{
var source = WithWindowsLineBreaks(@"
using System;
using System.IO;
class C
{
static void Main()
{
using MemoryStream m = new MemoryStream(), n = new MemoryStream();
Console.WriteLine(1);
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
// TODO: https://github.com/dotnet/roslyn/issues/37417
// Duplicate sequence point at `}`
v.VerifyIL("C.Main", sequencePoints: "C.Main", source: source, expectedIL: @"
{
// Code size 45 (0x2d)
.maxstack 1
.locals init (System.IO.MemoryStream V_0, //m
System.IO.MemoryStream V_1) //n
// sequence point: {
IL_0000: nop
// sequence point: using MemoryStream m = new MemoryStream()
IL_0001: newobj ""System.IO.MemoryStream..ctor()""
IL_0006: stloc.0
.try
{
// sequence point: n = new MemoryStream()
IL_0007: newobj ""System.IO.MemoryStream..ctor()""
IL_000c: stloc.1
.try
{
// sequence point: Console.WriteLine(1);
IL_000d: ldc.i4.1
IL_000e: call ""void System.Console.WriteLine(int)""
IL_0013: nop
// sequence point: }
IL_0014: leave.s IL_002c
}
finally
{
// sequence point: <hidden>
IL_0016: ldloc.1
IL_0017: brfalse.s IL_0020
IL_0019: ldloc.1
IL_001a: callvirt ""void System.IDisposable.Dispose()""
IL_001f: nop
// sequence point: <hidden>
IL_0020: endfinally
}
}
finally
{
// sequence point: <hidden>
IL_0021: ldloc.0
IL_0022: brfalse.s IL_002b
IL_0024: ldloc.0
IL_0025: callvirt ""void System.IDisposable.Dispose()""
IL_002a: nop
// sequence point: <hidden>
IL_002b: endfinally
}
// sequence point: }
IL_002c: ret
}
");
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""30"" />
<slot kind=""0"" offset=""54"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""50"" document=""1"" />
<entry offset=""0x7"" startLine=""8"" startColumn=""52"" endLine=""8"" endColumn=""74"" document=""1"" />
<entry offset=""0xd"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""30"" document=""1"" />
<entry offset=""0x14"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
<entry offset=""0x16"" hidden=""true"" document=""1"" />
<entry offset=""0x20"" hidden=""true"" document=""1"" />
<entry offset=""0x21"" hidden=""true"" document=""1"" />
<entry offset=""0x2b"" hidden=""true"" document=""1"" />
<entry offset=""0x2c"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2d"">
<namespace name=""System"" />
<namespace name=""System.IO"" />
<local name=""m"" il_index=""0"" il_start=""0x0"" il_end=""0x2d"" attributes=""0"" />
<local name=""n"" il_index=""1"" il_start=""0x0"" il_end=""0x2d"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(37417, "https://github.com/dotnet/roslyn/issues/37417")]
[Fact]
public void UsingDeclaration_BodyBlockScopeWithReturn()
{
var source = WithWindowsLineBreaks(@"
using System;
using System.IO;
class C
{
static int Main()
{
using MemoryStream m = new MemoryStream();
Console.WriteLine(1);
return 1;
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
// TODO: https://github.com/dotnet/roslyn/issues/37417
// Duplicate sequence point at `}`
v.VerifyIL("C.Main", sequencePoints: "C.Main", source: source, expectedIL: @"
{
// Code size 31 (0x1f)
.maxstack 1
.locals init (System.IO.MemoryStream V_0, //m
int V_1)
// sequence point: {
IL_0000: nop
// sequence point: using MemoryStream m = new MemoryStream();
IL_0001: newobj ""System.IO.MemoryStream..ctor()""
IL_0006: stloc.0
.try
{
// sequence point: Console.WriteLine(1);
IL_0007: ldc.i4.1
IL_0008: call ""void System.Console.WriteLine(int)""
IL_000d: nop
// sequence point: return 1;
IL_000e: ldc.i4.1
IL_000f: stloc.1
IL_0010: leave.s IL_001d
}
finally
{
// sequence point: <hidden>
IL_0012: ldloc.0
IL_0013: brfalse.s IL_001c
IL_0015: ldloc.0
IL_0016: callvirt ""void System.IDisposable.Dispose()""
IL_001b: nop
// sequence point: <hidden>
IL_001c: endfinally
}
// sequence point: }
IL_001d: ldloc.1
IL_001e: ret
}
");
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""30"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""51"" document=""1"" />
<entry offset=""0x7"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""30"" document=""1"" />
<entry offset=""0xe"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""18"" document=""1"" />
<entry offset=""0x12"" hidden=""true"" document=""1"" />
<entry offset=""0x1c"" hidden=""true"" document=""1"" />
<entry offset=""0x1d"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1f"">
<namespace name=""System"" />
<namespace name=""System.IO"" />
<local name=""m"" il_index=""0"" il_start=""0x0"" il_end=""0x1f"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(37417, "https://github.com/dotnet/roslyn/issues/37417")]
[Fact]
public void UsingDeclaration_IfBodyScope()
{
var source = WithWindowsLineBreaks(@"
using System;
using System.IO;
class C
{
public static bool G() => true;
static void Main()
{
if (G())
{
using var m = new MemoryStream();
Console.WriteLine(1);
}
Console.WriteLine(2);
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
// TODO: https://github.com/dotnet/roslyn/issues/37417
// In this case the sequence point `}` is not emitted on the leave instruction,
// but to a nop instruction following the disposal.
v.VerifyIL("C.Main", sequencePoints: "C.Main", source: source, expectedIL: @"
{
// Code size 46 (0x2e)
.maxstack 1
.locals init (bool V_0,
System.IO.MemoryStream V_1) //m
// sequence point: {
IL_0000: nop
// sequence point: if (G())
IL_0001: call ""bool C.G()""
IL_0006: stloc.0
// sequence point: <hidden>
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0026
// sequence point: {
IL_000a: nop
// sequence point: using var m = new MemoryStream();
IL_000b: newobj ""System.IO.MemoryStream..ctor()""
IL_0010: stloc.1
.try
{
// sequence point: Console.WriteLine(1);
IL_0011: ldc.i4.1
IL_0012: call ""void System.Console.WriteLine(int)""
IL_0017: nop
IL_0018: leave.s IL_0025
}
finally
{
// sequence point: <hidden>
IL_001a: ldloc.1
IL_001b: brfalse.s IL_0024
IL_001d: ldloc.1
IL_001e: callvirt ""void System.IDisposable.Dispose()""
IL_0023: nop
// sequence point: <hidden>
IL_0024: endfinally
}
// sequence point: }
IL_0025: nop
// sequence point: Console.WriteLine(2);
IL_0026: ldc.i4.2
IL_0027: call ""void System.Console.WriteLine(int)""
IL_002c: nop
// sequence point: }
IL_002d: ret
}
");
c.VerifyPdb("C.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" />
<encLocalSlotMap>
<slot kind=""1"" offset=""11"" />
<slot kind=""0"" offset=""55"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""17"" document=""1"" />
<entry offset=""0x7"" hidden=""true"" document=""1"" />
<entry offset=""0xa"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0xb"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""46"" document=""1"" />
<entry offset=""0x11"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""34"" document=""1"" />
<entry offset=""0x1a"" hidden=""true"" document=""1"" />
<entry offset=""0x24"" hidden=""true"" document=""1"" />
<entry offset=""0x25"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" />
<entry offset=""0x26"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""30"" document=""1"" />
<entry offset=""0x2d"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2e"">
<scope startOffset=""0xa"" endOffset=""0x26"">
<local name=""m"" il_index=""1"" il_start=""0xa"" il_end=""0x26"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
#endregion
// LockStatement tested in CodeGenLock
#region Anonymous Type
[Fact]
public void AnonymousType_Empty()
{
var source = WithWindowsLineBreaks(@"
class Program
{
static void Main(string[] args)
{
var o = new {};
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""24"" document=""1"" />
<entry offset=""0x7"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x8"">
<local name=""o"" il_index=""0"" il_start=""0x0"" il_end=""0x8"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void AnonymousType_NonEmpty()
{
var source = WithWindowsLineBreaks(@"
class Program
{
static void Main(string[] args)
{
var o = new { a = 1 };
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""31"" document=""1"" />
<entry offset=""0x8"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x9"">
<local name=""o"" il_index=""0"" il_start=""0x0"" il_end=""0x9"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region FixedStatement
[Fact]
public void FixedStatementSingleAddress()
{
var source = WithWindowsLineBreaks(@"
using System;
unsafe class C
{
int x;
static void Main()
{
C c = new C();
fixed (int* p = &c.x)
{
*p = 1;
}
Console.WriteLine(c.x);
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
<slot kind=""0"" offset=""47"" />
<slot kind=""9"" offset=""47"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""23"" document=""1"" />
<entry offset=""0xe"" startLine=""11"" startColumn=""16"" endLine=""11"" endColumn=""29"" document=""1"" />
<entry offset=""0x11"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" />
<entry offset=""0x12"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""20"" document=""1"" />
<entry offset=""0x15"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" />
<entry offset=""0x16"" hidden=""true"" document=""1"" />
<entry offset=""0x19"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""32"" document=""1"" />
<entry offset=""0x25"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x26"">
<namespace name=""System"" />
<local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x26"" attributes=""0"" />
<scope startOffset=""0x7"" endOffset=""0x19"">
<local name=""p"" il_index=""1"" il_start=""0x7"" il_end=""0x19"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void FixedStatementSingleString()
{
var source = WithWindowsLineBreaks(@"
using System;
unsafe class C
{
static void Main()
{
fixed (char* p = ""hello"")
{
Console.WriteLine(*p);
}
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""24"" />
<slot kind=""9"" offset=""24"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x7"" startLine=""8"" startColumn=""16"" endLine=""8"" endColumn=""33"" document=""1"" />
<entry offset=""0x15"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x16"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""35"" document=""1"" />
<entry offset=""0x1e"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0x1f"" hidden=""true"" document=""1"" />
<entry offset=""0x21"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x22"">
<namespace name=""System"" />
<scope startOffset=""0x1"" endOffset=""0x21"">
<local name=""p"" il_index=""0"" il_start=""0x1"" il_end=""0x21"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void FixedStatementSingleArray()
{
var source = WithWindowsLineBreaks(@"
using System;
unsafe class C
{
int[] a = new int[1];
static void Main()
{
C c = new C();
Console.Write(c.a[0]);
fixed (int* p = c.a)
{
(*p)++;
}
Console.Write(c.a[0]);
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
<slot kind=""0"" offset=""79"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""23"" document=""1"" />
<entry offset=""0x7"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""31"" document=""1"" />
<entry offset=""0x15"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""28"" document=""1"" />
<entry offset=""0x32"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x33"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""20"" document=""1"" />
<entry offset=""0x39"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" />
<entry offset=""0x3a"" hidden=""true"" document=""1"" />
<entry offset=""0x3c"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""31"" document=""1"" />
<entry offset=""0x4a"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x4b"">
<namespace name=""System"" />
<local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x4b"" attributes=""0"" />
<scope startOffset=""0x15"" endOffset=""0x3c"">
<local name=""p"" il_index=""1"" il_start=""0x15"" il_end=""0x3c"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Main"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""26"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void FixedStatementMultipleAddresses()
{
var source = WithWindowsLineBreaks(@"
using System;
unsafe class C
{
int x;
int y;
static void Main()
{
C c = new C();
fixed (int* p = &c.x, q = &c.y)
{
*p = 1;
*q = 2;
}
Console.WriteLine(c.x + c.y);
}
}
");
// NOTE: stop on each declarator.
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
<slot kind=""0"" offset=""47"" />
<slot kind=""0"" offset=""57"" />
<slot kind=""9"" offset=""47"" />
<slot kind=""9"" offset=""57"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""23"" document=""1"" />
<entry offset=""0xe"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""29"" document=""1"" />
<entry offset=""0x19"" startLine=""12"" startColumn=""31"" endLine=""12"" endColumn=""39"" document=""1"" />
<entry offset=""0x1d"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x1e"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""20"" document=""1"" />
<entry offset=""0x21"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""20"" document=""1"" />
<entry offset=""0x24"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""1"" />
<entry offset=""0x25"" hidden=""true"" document=""1"" />
<entry offset=""0x2c"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""38"" document=""1"" />
<entry offset=""0x3f"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x40"">
<namespace name=""System"" />
<local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x40"" attributes=""0"" />
<scope startOffset=""0x7"" endOffset=""0x2c"">
<local name=""p"" il_index=""1"" il_start=""0x7"" il_end=""0x2c"" attributes=""0"" />
<local name=""q"" il_index=""2"" il_start=""0x7"" il_end=""0x2c"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void FixedStatementMultipleStrings()
{
var source = WithWindowsLineBreaks(@"
using System;
unsafe class C
{
static void Main()
{
fixed (char* p = ""hello"", q = ""goodbye"")
{
Console.Write(*p);
Console.Write(*q);
}
}
}
");
// NOTE: stop on each declarator.
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""24"" />
<slot kind=""0"" offset=""37"" />
<slot kind=""9"" offset=""24"" />
<slot kind=""9"" offset=""37"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x7"" startLine=""8"" startColumn=""16"" endLine=""8"" endColumn=""33"" document=""1"" />
<entry offset=""0x1b"" startLine=""8"" startColumn=""35"" endLine=""8"" endColumn=""48"" document=""1"" />
<entry offset=""0x29"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x2a"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""31"" document=""1"" />
<entry offset=""0x32"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""31"" document=""1"" />
<entry offset=""0x3a"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" />
<entry offset=""0x3b"" hidden=""true"" document=""1"" />
<entry offset=""0x3f"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x40"">
<namespace name=""System"" />
<scope startOffset=""0x1"" endOffset=""0x3f"">
<local name=""p"" il_index=""0"" il_start=""0x1"" il_end=""0x3f"" attributes=""0"" />
<local name=""q"" il_index=""1"" il_start=""0x1"" il_end=""0x3f"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void FixedStatementMultipleArrays()
{
var source = WithWindowsLineBreaks(@"
using System;
unsafe class C
{
int[] a = new int[1];
int[] b = new int[1];
static void Main()
{
C c = new C();
Console.Write(c.a[0]);
Console.Write(c.b[0]);
fixed (int* p = c.a, q = c.b)
{
*p = 1;
*q = 2;
}
Console.Write(c.a[0]);
Console.Write(c.b[0]);
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
<slot kind=""0"" offset=""111"" />
<slot kind=""0"" offset=""120"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""23"" document=""1"" />
<entry offset=""0x7"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""31"" document=""1"" />
<entry offset=""0x15"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""31"" document=""1"" />
<entry offset=""0x23"" startLine=""14"" startColumn=""16"" endLine=""14"" endColumn=""28"" document=""1"" />
<entry offset=""0x40"" startLine=""14"" startColumn=""30"" endLine=""14"" endColumn=""37"" document=""1"" />
<entry offset=""0x60"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" />
<entry offset=""0x61"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""20"" document=""1"" />
<entry offset=""0x64"" startLine=""17"" startColumn=""13"" endLine=""17"" endColumn=""20"" document=""1"" />
<entry offset=""0x67"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""10"" document=""1"" />
<entry offset=""0x68"" hidden=""true"" document=""1"" />
<entry offset=""0x6d"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""31"" document=""1"" />
<entry offset=""0x7b"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""31"" document=""1"" />
<entry offset=""0x89"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x8a"">
<namespace name=""System"" />
<local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x8a"" attributes=""0"" />
<scope startOffset=""0x23"" endOffset=""0x6d"">
<local name=""p"" il_index=""1"" il_start=""0x23"" il_end=""0x6d"" attributes=""0"" />
<local name=""q"" il_index=""2"" il_start=""0x23"" il_end=""0x6d"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Main"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""26"" document=""1"" />
<entry offset=""0xc"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""26"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void FixedStatementMultipleMixed()
{
var source = WithWindowsLineBreaks(@"
using System;
unsafe class C
{
char c = 'a';
char[] a = new char[1];
static void Main()
{
C c = new C();
fixed (char* p = &c.c, q = c.a, r = ""hello"")
{
Console.Write((int)*p);
Console.Write((int)*q);
Console.Write((int)*r);
}
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugDll);
c.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
<slot kind=""0"" offset=""48"" />
<slot kind=""0"" offset=""58"" />
<slot kind=""0"" offset=""67"" />
<slot kind=""9"" offset=""48"" />
<slot kind=""temp"" />
<slot kind=""9"" offset=""67"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""23"" document=""1"" />
<entry offset=""0xf"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""30"" document=""1"" />
<entry offset=""0x13"" startLine=""12"" startColumn=""32"" endLine=""12"" endColumn=""39"" document=""1"" />
<entry offset=""0x3a"" startLine=""12"" startColumn=""41"" endLine=""12"" endColumn=""52"" document=""1"" />
<entry offset=""0x49"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" />
<entry offset=""0x4a"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""36"" document=""1"" />
<entry offset=""0x52"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""36"" document=""1"" />
<entry offset=""0x5a"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""36"" document=""1"" />
<entry offset=""0x62"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" />
<entry offset=""0x63"" hidden=""true"" document=""1"" />
<entry offset=""0x6d"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x6e"">
<namespace name=""System"" />
<local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x6e"" attributes=""0"" />
<scope startOffset=""0x7"" endOffset=""0x6d"">
<local name=""p"" il_index=""1"" il_start=""0x7"" il_end=""0x6d"" attributes=""0"" />
<local name=""q"" il_index=""2"" il_start=""0x7"" il_end=""0x6d"" attributes=""0"" />
<local name=""r"" il_index=""3"" il_start=""0x7"" il_end=""0x6d"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Main"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""18"" document=""1"" />
<entry offset=""0x8"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""28"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
#endregion
#region Line Directives
[Fact]
public void LineDirective()
{
var source = @"
#line 50 ""foo.cs""
using System;
unsafe class C
{
static void Main()
{
Console.Write(1);
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""foo.cs"" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""56"" startColumn=""5"" endLine=""56"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""57"" startColumn=""9"" endLine=""57"" endColumn=""26"" document=""1"" />
<entry offset=""0x8"" startLine=""58"" startColumn=""5"" endLine=""58"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x9"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")]
[Fact]
public void DisabledLineDirective()
{
var source = @"
#if false
#line 50 ""foo.cs""
#endif
using System;
unsafe class C
{
static void Main()
{
Console.Write(1);
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""26"" document=""1"" />
<entry offset=""0x8"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x9"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void TestLineDirectivesHidden()
{
var text1 = WithWindowsLineBreaks(@"
using System;
public class C
{
public void Foo()
{
foreach (var x in new int[] { 1, 2, 3, 4 })
{
Console.WriteLine(x);
}
#line hidden
foreach (var x in new int[] { 1, 2, 3, 4 })
{
Console.WriteLine(x);
}
#line default
foreach (var x in new int[] { 1, 2, 3, 4 })
{
Console.WriteLine(x);
}
}
}
");
var compilation = CreateCompilation(text1, options: TestOptions.DebugDll);
compilation.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Foo"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""6"" offset=""11"" />
<slot kind=""8"" offset=""11"" />
<slot kind=""0"" offset=""11"" />
<slot kind=""6"" offset=""137"" />
<slot kind=""8"" offset=""137"" />
<slot kind=""0"" offset=""137"" />
<slot kind=""6"" offset=""264"" />
<slot kind=""8"" offset=""264"" />
<slot kind=""0"" offset=""264"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""16"" document=""1"" />
<entry offset=""0x2"" startLine=""7"" startColumn=""27"" endLine=""7"" endColumn=""51"" document=""1"" />
<entry offset=""0x16"" hidden=""true"" document=""1"" />
<entry offset=""0x18"" startLine=""7"" startColumn=""18"" endLine=""7"" endColumn=""23"" document=""1"" />
<entry offset=""0x1c"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" />
<entry offset=""0x1d"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""34"" document=""1"" />
<entry offset=""0x24"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" />
<entry offset=""0x25"" hidden=""true"" document=""1"" />
<entry offset=""0x29"" startLine=""7"" startColumn=""24"" endLine=""7"" endColumn=""26"" document=""1"" />
<entry offset=""0x2f"" hidden=""true"" document=""1"" />
<entry offset=""0x30"" hidden=""true"" document=""1"" />
<entry offset=""0x45"" hidden=""true"" document=""1"" />
<entry offset=""0x47"" hidden=""true"" document=""1"" />
<entry offset=""0x4d"" hidden=""true"" document=""1"" />
<entry offset=""0x4e"" hidden=""true"" document=""1"" />
<entry offset=""0x56"" hidden=""true"" document=""1"" />
<entry offset=""0x57"" hidden=""true"" document=""1"" />
<entry offset=""0x5d"" hidden=""true"" document=""1"" />
<entry offset=""0x64"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""16"" document=""1"" />
<entry offset=""0x65"" startLine=""19"" startColumn=""27"" endLine=""19"" endColumn=""51"" document=""1"" />
<entry offset=""0x7b"" hidden=""true"" document=""1"" />
<entry offset=""0x7d"" startLine=""19"" startColumn=""18"" endLine=""19"" endColumn=""23"" document=""1"" />
<entry offset=""0x84"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""10"" document=""1"" />
<entry offset=""0x85"" startLine=""21"" startColumn=""13"" endLine=""21"" endColumn=""34"" document=""1"" />
<entry offset=""0x8d"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" />
<entry offset=""0x8e"" hidden=""true"" document=""1"" />
<entry offset=""0x94"" startLine=""19"" startColumn=""24"" endLine=""19"" endColumn=""26"" document=""1"" />
<entry offset=""0x9c"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x9d"">
<namespace name=""System"" />
<scope startOffset=""0x18"" endOffset=""0x25"">
<local name=""x"" il_index=""2"" il_start=""0x18"" il_end=""0x25"" attributes=""0"" />
</scope>
<scope startOffset=""0x47"" endOffset=""0x57"">
<local name=""x"" il_index=""5"" il_start=""0x47"" il_end=""0x57"" attributes=""0"" />
</scope>
<scope startOffset=""0x7d"" endOffset=""0x8e"">
<local name=""x"" il_index=""8"" il_start=""0x7d"" il_end=""0x8e"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void HiddenMethods()
{
var src = WithWindowsLineBreaks(@"
using System;
class C
{
#line hidden
public static void H()
{
F();
}
#line default
public static void G()
{
F();
}
#line hidden
public static void F()
{
{
const int z = 1;
var (x, y) = (1,2);
Console.WriteLine(x + z);
}
{
dynamic x = 1;
Console.WriteLine(x);
}
}
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(src, references: new[] { CSharpRef, ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""G"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""13"" document=""1"" />
<entry offset=""0x7"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x8"">
<namespace name=""System"" />
</scope>
</method>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<encLocalSlotMap>
<slot kind=""0"" offset=""61"" />
<slot kind=""0"" offset=""64"" />
<slot kind=""0"" offset=""158"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
</methods>
</symbols>");
}
[Fact]
public void HiddenEntryPoint()
{
var src = @"
class C
{
#line hidden
public static void Main()
{
}
}";
var c = CreateCompilationWithMscorlib40AndSystemCore(src, references: new[] { CSharpRef, ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe);
// Note: Dev10 emitted a hidden sequence point to #line hidden method,
// which enabled the debugger to locate the first user visible sequence point starting from the entry point.
// Roslyn does not emit such sequence point. We could potentially synthesize one but that would defeat the purpose of
// #line hidden directive.
c.VerifyPdb(@"
<symbols>
<entryPoint declaringType=""C"" methodName=""Main"" />
<methods>
<method containingType=""C"" name=""Main"" format=""windows"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
</method>
</methods>
</symbols>",
// When converting from Portable to Windows the PDB writer doesn't create an entry for the Main method
// and thus there is no entry point record either.
options: PdbValidationOptions.SkipConversionValidation);
}
[Fact]
public void HiddenIterator()
{
var src = WithWindowsLineBreaks(@"
using System;
using System.Collections.Generic;
class C
{
public static void Main()
{
F();
}
#line hidden
public static IEnumerable<int> F()
{
{
const int z = 1;
var (x, y) = (1,2);
Console.WriteLine(x + z);
}
{
dynamic x = 1;
Console.WriteLine(x);
}
yield return 1;
}
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(src, references: new[] { CSharpRef, ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
// We don't really need the debug info for kickoff method when the entire iterator method is hidden,
// but it doesn't hurt and removing it would need extra effort that's unnecessary.
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""13"" document=""1"" />
<entry offset=""0x7"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x8"">
<namespace name=""System"" />
<namespace name=""System.Collections.Generic"" />
</scope>
</method>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<forwardIterator name=""<F>d__1"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""61"" />
<slot kind=""0"" offset=""64"" />
<slot kind=""0"" offset=""158"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
<method containingType=""C+<F>d__1"" name=""MoveNext"">
<customDebugInfo>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
</methods>
</symbols>");
}
#endregion
#region Nested Types
[Fact]
public void NestedTypes()
{
string source = WithWindowsLineBreaks(@"
using System;
namespace N
{
public class C
{
public class D<T>
{
public class E
{
public static void f(int a)
{
Console.WriteLine();
}
}
}
}
}
");
var c = CreateCompilation(Parse(source, filename: "file.cs"));
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""file.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""F7-03-46-2C-11-16-DE-85-F9-DD-5C-76-F6-55-D9-13-E0-95-DE-14"" />
</files>
<methods>
<method containingType=""N.C+D`1+E"" name=""f"" parameterNames=""a"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""14"" startColumn=""6"" endLine=""14"" endColumn=""26"" document=""1"" />
<entry offset=""0x5"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x6"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region Expression Bodied Members
[Fact]
public void ExpressionBodiedProperty()
{
var source = WithWindowsLineBreaks(@"
class C
{
public int P => M();
public int M()
{
return 2;
}
}");
var comp = CreateCompilationWithMscorlib45(source);
comp.VerifyDiagnostics();
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""get_P"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""21"" endLine=""4"" endColumn=""24"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_P"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""18"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void ExpressionBodiedIndexer()
{
var comp = CreateCompilationWithMscorlib45(@"
using System;
class C
{
public int this[Int32 i] => M();
public int M()
{
return 2;
}
}");
comp.VerifyDiagnostics();
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""get_Item"" parameterNames=""i"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""33"" endLine=""6"" endColumn=""36"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x7"">
<namespace name=""System"" />
</scope>
</method>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_Item"" parameterNames=""i"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""18"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void ExpressionBodiedMethod()
{
var comp = CreateCompilationWithMscorlib45(@"
using System;
class C
{
public Int32 P => 2;
}");
comp.VerifyDiagnostics();
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""get_P"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""23"" endLine=""6"" endColumn=""24"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void ExpressionBodiedOperator()
{
var comp = CreateCompilationWithMscorlib45(@"
class C
{
public static C operator ++(C c) => c;
}");
comp.VerifyDiagnostics();
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""op_Increment"" parameterNames=""c"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""41"" endLine=""4"" endColumn=""42"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void ExpressionBodiedConversion()
{
var comp = CreateCompilationWithMscorlib45(@"
using System;
class C
{
public static explicit operator C(Int32 i) => new C();
}");
comp.VerifyDiagnostics();
comp.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""op_Explicit"" parameterNames=""i"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""51"" endLine=""6"" endColumn=""58"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x6"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")]
[Fact]
public void ExpressionBodiedConstructor()
{
var comp = CreateCompilationWithMscorlib45(@"
using System;
class C
{
public int X;
public C(Int32 x) => X = x;
}");
comp.VerifyDiagnostics();
comp.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"" parameterNames=""x"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""22"" document=""1"" />
<entry offset=""0x6"" startLine=""7"" startColumn=""26"" endLine=""7"" endColumn=""31"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xe"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")]
[Fact]
public void ExpressionBodiedDestructor()
{
var comp = CreateCompilationWithMscorlib45(@"
class C
{
public int X;
~C() => X = 0;
}");
comp.VerifyDiagnostics();
comp.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""Finalize"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""13"" endLine=""5"" endColumn=""18"" document=""1"" />
<entry offset=""0x9"" hidden=""true"" document=""1"" />
<entry offset=""0x10"" hidden=""true"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")]
[Fact]
public void ExpressionBodiedAccessor()
{
var comp = CreateCompilationWithMscorlib45(@"
class C
{
public int x;
public int X
{
get => x;
set => x = value;
}
public event System.Action E
{
add => x = 1;
remove => x = 0;
}
}");
comp.VerifyDiagnostics();
comp.VerifyPdb(@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""get_X"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""16"" endLine=""7"" endColumn=""17"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""set_X"" parameterNames=""value"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_X"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""16"" endLine=""8"" endColumn=""25"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""add_E"" parameterNames=""value"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_X"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""21"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""remove_E"" parameterNames=""value"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""get_X"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""13"" startColumn=""19"" endLine=""13"" endColumn=""24"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
#endregion
#region Synthesized Methods
[Fact]
public void ImportsInLambda()
{
var source = WithWindowsLineBreaks(
@"using System.Collections.Generic;
using System.Linq;
class C
{
static void M()
{
System.Action f = () =>
{
var c = new[] { 1, 2, 3 };
c.Select(i => i);
};
f();
}
}");
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, references: new[] { SystemCoreRef });
c.VerifyPdb("C+<>c.<M>b__0_0",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c"" name=""<M>b__0_0"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""M"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""63"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""39"" document=""1"" />
<entry offset=""0x13"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""30"" document=""1"" />
<entry offset=""0x39"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x3a"">
<local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x3a"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void ImportsInIterator()
{
var source = WithWindowsLineBreaks(
@"using System.Collections.Generic;
using System.Linq;
class C
{
static IEnumerable<object> F()
{
var c = new[] { 1, 2, 3 };
foreach (var i in c.Select(i => i))
{
yield return i;
}
}
}");
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, references: new[] { SystemCoreRef });
c.VerifyPdb("C+<F>d__0.MoveNext",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<F>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C+<>c"" methodName=""<F>b__0_0"" parameterNames=""i"" />
<hoistedLocalScopes>
<slot startOffset=""0x27"" endOffset=""0xd5"" />
<slot />
<slot startOffset=""0x7f"" endOffset=""0xb6"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""temp"" />
<slot kind=""27"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x27"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
<entry offset=""0x28"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""35"" document=""1"" />
<entry offset=""0x3f"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""16"" document=""1"" />
<entry offset=""0x40"" startLine=""8"" startColumn=""27"" endLine=""8"" endColumn=""43"" document=""1"" />
<entry offset=""0x7d"" hidden=""true"" document=""1"" />
<entry offset=""0x7f"" startLine=""8"" startColumn=""18"" endLine=""8"" endColumn=""23"" document=""1"" />
<entry offset=""0x90"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x91"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""28"" document=""1"" />
<entry offset=""0xad"" hidden=""true"" document=""1"" />
<entry offset=""0xb5"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
<entry offset=""0xb6"" startLine=""8"" startColumn=""24"" endLine=""8"" endColumn=""26"" document=""1"" />
<entry offset=""0xd1"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
<entry offset=""0xd5"" hidden=""true"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void ImportsInAsync()
{
var source = WithWindowsLineBreaks(
@"using System.Linq;
using System.Threading.Tasks;
class C
{
static async Task F()
{
var c = new[] { 1, 2, 3 };
c.Select(i => i);
}
}");
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, references: new[] { SystemCoreRef });
c.VerifyPdb("C+<F>d__0.MoveNext",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<F>d__0"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C+<>c"" methodName=""<F>b__0_0"" parameterNames=""i"" />
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0x87"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
<entry offset=""0x8"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""35"" document=""1"" />
<entry offset=""0x1f"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""26"" document=""1"" />
<entry offset=""0x4c"" hidden=""true"" document=""1"" />
<entry offset=""0x6b"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x73"" hidden=""true"" document=""1"" />
</sequencePoints>
<asyncInfo>
<kickoffMethod declaringType=""C"" methodName=""F"" />
</asyncInfo>
</method>
</methods>
</symbols>");
}
[WorkItem(2501, "https://github.com/dotnet/roslyn/issues/2501")]
[Fact]
public void ImportsInAsyncLambda()
{
var source = WithWindowsLineBreaks(
@"using System.Linq;
class C
{
static void M()
{
System.Action f = async () =>
{
var c = new[] { 1, 2, 3 };
c.Select(i => i);
};
}
}");
var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, references: new[] { SystemCoreRef });
c.VerifyPdb("C+<>c.<M>b__0_0",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c"" name=""<M>b__0_0"">
<customDebugInfo>
<forwardIterator name=""<<M>b__0_0>d"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""69"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
</methods>
</symbols>");
c.VerifyPdb("C+<>c+<<M>b__0_0>d.MoveNext",
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c+<<M>b__0_0>d"" name=""MoveNext"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""M"" />
<hoistedLocalScopes>
<slot startOffset=""0x0"" endOffset=""0x87"" />
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind=""27"" offset=""50"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" />
<entry offset=""0x8"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""39"" document=""1"" />
<entry offset=""0x1f"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""30"" document=""1"" />
<entry offset=""0x4c"" hidden=""true"" document=""1"" />
<entry offset=""0x6b"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" />
<entry offset=""0x73"" hidden=""true"" document=""1"" />
</sequencePoints>
<asyncInfo>
<catchHandler offset=""0x4c"" />
<kickoffMethod declaringType=""C+<>c"" methodName=""<M>b__0_0"" />
</asyncInfo>
</method>
</methods>
</symbols>");
}
#endregion
#region Patterns
[Fact]
public void SyntaxOffset_IsPattern()
{
var source = @"class C { bool F(object o) => o is int i && o is 3 && o is bool; }";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.F", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"" parameterNames=""o"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""12"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""31"" endLine=""1"" endColumn=""64"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2d"">
<local name=""i"" il_index=""0"" il_start=""0x0"" il_end=""0x2d"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")]
[Fact]
public void Patterns_SwitchStatement()
{
string source = WithWindowsLineBreaks(@"
class C
{
public void Deconstruct() { }
public void Deconstruct(out int x) { x = 1; }
public void Deconstruct(out int x, out object y) { x = 2; y = new C(); }
}
class D
{
public int P { get; set; }
public D Q { get; set; }
public C R { get; set; }
}
class Program
{
static object F() => new C();
static bool B() => true;
static int G(int x) => x;
static int Main()
{
switch (F())
{
// declaration pattern
case int x when G(x) > 10: return 1;
// discard pattern
case bool _: return 2;
// var pattern
case var (y, z): return 3;
// constant pattern
case 4.0: return 4;
// positional patterns
case C() when B(): return 5;
case (): return 6;
case C(int p, C(int q)): return 7;
case C(x: int p): return 8;
// property pattern
case D { P: 1, Q: D { P: 2 }, R: C(int z) }: return 9;
default: return 10;
};
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerify(c, verify: Verification.Skipped);
verifier.VerifyIL("Program.Main", sequencePoints: "Program.Main", expectedIL: @"
{
// Code size 432 (0x1b0)
.maxstack 3
.locals init (int V_0, //x
object V_1, //y
object V_2, //z
int V_3, //p
int V_4, //q
int V_5, //p
int V_6, //z
object V_7,
System.Runtime.CompilerServices.ITuple V_8,
int V_9,
double V_10,
C V_11,
object V_12,
C V_13,
D V_14,
int V_15,
D V_16,
int V_17,
C V_18,
object V_19,
int V_20)
// sequence point: {
IL_0000: nop
// sequence point: switch (F())
IL_0001: call ""object Program.F()""
IL_0006: stloc.s V_19
// sequence point: <hidden>
IL_0008: ldloc.s V_19
IL_000a: stloc.s V_7
// sequence point: <hidden>
IL_000c: ldloc.s V_7
IL_000e: isinst ""int""
IL_0013: brfalse.s IL_0022
IL_0015: ldloc.s V_7
IL_0017: unbox.any ""int""
IL_001c: stloc.0
// sequence point: <hidden>
IL_001d: br IL_014d
IL_0022: ldloc.s V_7
IL_0024: isinst ""bool""
IL_0029: brtrue IL_015e
IL_002e: ldloc.s V_7
IL_0030: isinst ""System.Runtime.CompilerServices.ITuple""
IL_0035: stloc.s V_8
IL_0037: ldloc.s V_8
IL_0039: brfalse.s IL_0080
IL_003b: ldloc.s V_8
IL_003d: callvirt ""int System.Runtime.CompilerServices.ITuple.Length.get""
IL_0042: stloc.s V_9
// sequence point: <hidden>
IL_0044: ldloc.s V_9
IL_0046: ldc.i4.2
IL_0047: bne.un.s IL_0060
IL_0049: ldloc.s V_8
IL_004b: ldc.i4.0
IL_004c: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get""
IL_0051: stloc.1
// sequence point: <hidden>
IL_0052: ldloc.s V_8
IL_0054: ldc.i4.1
IL_0055: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get""
IL_005a: stloc.2
// sequence point: <hidden>
IL_005b: br IL_0163
IL_0060: ldloc.s V_7
IL_0062: isinst ""C""
IL_0067: brtrue IL_016f
IL_006c: br.s IL_0077
IL_006e: ldloc.s V_9
IL_0070: brfalse IL_018c
IL_0075: br.s IL_00b5
IL_0077: ldloc.s V_9
IL_0079: brfalse IL_018c
IL_007e: br.s IL_00f5
IL_0080: ldloc.s V_7
IL_0082: isinst ""double""
IL_0087: brfalse.s IL_00a7
IL_0089: ldloc.s V_7
IL_008b: unbox.any ""double""
IL_0090: stloc.s V_10
// sequence point: <hidden>
IL_0092: ldloc.s V_10
IL_0094: ldc.r8 4
IL_009d: beq IL_016a
IL_00a2: br IL_01a7
IL_00a7: ldloc.s V_7
IL_00a9: isinst ""C""
IL_00ae: brtrue IL_017b
IL_00b3: br.s IL_00f5
IL_00b5: ldloc.s V_7
IL_00b7: castclass ""C""
IL_00bc: stloc.s V_11
// sequence point: <hidden>
IL_00be: ldloc.s V_11
IL_00c0: ldloca.s V_3
IL_00c2: ldloca.s V_12
IL_00c4: callvirt ""void C.Deconstruct(out int, out object)""
IL_00c9: nop
// sequence point: <hidden>
IL_00ca: ldloc.s V_12
IL_00cc: isinst ""C""
IL_00d1: stloc.s V_13
IL_00d3: ldloc.s V_13
IL_00d5: brfalse.s IL_00e6
IL_00d7: ldloc.s V_13
IL_00d9: ldloca.s V_4
IL_00db: callvirt ""void C.Deconstruct(out int)""
IL_00e0: nop
// sequence point: <hidden>
IL_00e1: br IL_0191
IL_00e6: ldloc.s V_11
IL_00e8: ldloca.s V_5
IL_00ea: callvirt ""void C.Deconstruct(out int)""
IL_00ef: nop
// sequence point: <hidden>
IL_00f0: br IL_0198
IL_00f5: ldloc.s V_7
IL_00f7: isinst ""D""
IL_00fc: stloc.s V_14
IL_00fe: ldloc.s V_14
IL_0100: brfalse IL_01a7
IL_0105: ldloc.s V_14
IL_0107: callvirt ""int D.P.get""
IL_010c: stloc.s V_15
// sequence point: <hidden>
IL_010e: ldloc.s V_15
IL_0110: ldc.i4.1
IL_0111: bne.un IL_01a7
IL_0116: ldloc.s V_14
IL_0118: callvirt ""D D.Q.get""
IL_011d: stloc.s V_16
// sequence point: <hidden>
IL_011f: ldloc.s V_16
IL_0121: brfalse IL_01a7
IL_0126: ldloc.s V_16
IL_0128: callvirt ""int D.P.get""
IL_012d: stloc.s V_17
// sequence point: <hidden>
IL_012f: ldloc.s V_17
IL_0131: ldc.i4.2
IL_0132: bne.un.s IL_01a7
IL_0134: ldloc.s V_14
IL_0136: callvirt ""C D.R.get""
IL_013b: stloc.s V_18
// sequence point: <hidden>
IL_013d: ldloc.s V_18
IL_013f: brfalse.s IL_01a7
IL_0141: ldloc.s V_18
IL_0143: ldloca.s V_6
IL_0145: callvirt ""void C.Deconstruct(out int)""
IL_014a: nop
// sequence point: <hidden>
IL_014b: br.s IL_019f
// sequence point: when G(x) > 10
IL_014d: ldloc.0
IL_014e: call ""int Program.G(int)""
IL_0153: ldc.i4.s 10
IL_0155: bgt.s IL_0159
// sequence point: <hidden>
IL_0157: br.s IL_01a7
// sequence point: return 1;
IL_0159: ldc.i4.1
IL_015a: stloc.s V_20
IL_015c: br.s IL_01ad
// sequence point: return 2;
IL_015e: ldc.i4.2
IL_015f: stloc.s V_20
IL_0161: br.s IL_01ad
// sequence point: <hidden>
IL_0163: br.s IL_0165
// sequence point: return 3;
IL_0165: ldc.i4.3
IL_0166: stloc.s V_20
IL_0168: br.s IL_01ad
// sequence point: return 4;
IL_016a: ldc.i4.4
IL_016b: stloc.s V_20
IL_016d: br.s IL_01ad
// sequence point: when B()
IL_016f: call ""bool Program.B()""
IL_0174: brtrue.s IL_0187
// sequence point: <hidden>
IL_0176: br IL_006e
// sequence point: when B()
IL_017b: call ""bool Program.B()""
IL_0180: brtrue.s IL_0187
// sequence point: <hidden>
IL_0182: br IL_00b5
// sequence point: return 5;
IL_0187: ldc.i4.5
IL_0188: stloc.s V_20
IL_018a: br.s IL_01ad
// sequence point: return 6;
IL_018c: ldc.i4.6
IL_018d: stloc.s V_20
IL_018f: br.s IL_01ad
// sequence point: <hidden>
IL_0191: br.s IL_0193
// sequence point: return 7;
IL_0193: ldc.i4.7
IL_0194: stloc.s V_20
IL_0196: br.s IL_01ad
// sequence point: <hidden>
IL_0198: br.s IL_019a
// sequence point: return 8;
IL_019a: ldc.i4.8
IL_019b: stloc.s V_20
IL_019d: br.s IL_01ad
// sequence point: <hidden>
IL_019f: br.s IL_01a1
// sequence point: return 9;
IL_01a1: ldc.i4.s 9
IL_01a3: stloc.s V_20
IL_01a5: br.s IL_01ad
// sequence point: return 10;
IL_01a7: ldc.i4.s 10
IL_01a9: stloc.s V_20
IL_01ab: br.s IL_01ad
// sequence point: }
IL_01ad: ldloc.s V_20
IL_01af: ret
}
", source: source);
verifier.VerifyPdb("Program.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Deconstruct"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""93"" />
<slot kind=""0"" offset=""244"" />
<slot kind=""0"" offset=""247"" />
<slot kind=""0"" offset=""465"" />
<slot kind=""0"" offset=""474"" />
<slot kind=""0"" offset=""516"" />
<slot kind=""0"" offset=""617"" />
<slot kind=""35"" offset=""11"" />
<slot kind=""35"" offset=""11"" ordinal=""1"" />
<slot kind=""35"" offset=""11"" ordinal=""2"" />
<slot kind=""35"" offset=""11"" ordinal=""3"" />
<slot kind=""35"" offset=""11"" ordinal=""4"" />
<slot kind=""35"" offset=""11"" ordinal=""5"" />
<slot kind=""35"" offset=""11"" ordinal=""6"" />
<slot kind=""35"" offset=""11"" ordinal=""7"" />
<slot kind=""35"" offset=""11"" ordinal=""8"" />
<slot kind=""35"" offset=""11"" ordinal=""9"" />
<slot kind=""35"" offset=""11"" ordinal=""10"" />
<slot kind=""35"" offset=""11"" ordinal=""11"" />
<slot kind=""1"" offset=""11"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""21"" document=""1"" />
<entry offset=""0x8"" hidden=""true"" document=""1"" />
<entry offset=""0xc"" hidden=""true"" document=""1"" />
<entry offset=""0x1d"" hidden=""true"" document=""1"" />
<entry offset=""0x44"" hidden=""true"" document=""1"" />
<entry offset=""0x52"" hidden=""true"" document=""1"" />
<entry offset=""0x5b"" hidden=""true"" document=""1"" />
<entry offset=""0x92"" hidden=""true"" document=""1"" />
<entry offset=""0xbe"" hidden=""true"" document=""1"" />
<entry offset=""0xca"" hidden=""true"" document=""1"" />
<entry offset=""0xe1"" hidden=""true"" document=""1"" />
<entry offset=""0xf0"" hidden=""true"" document=""1"" />
<entry offset=""0x10e"" hidden=""true"" document=""1"" />
<entry offset=""0x11f"" hidden=""true"" document=""1"" />
<entry offset=""0x12f"" hidden=""true"" document=""1"" />
<entry offset=""0x13d"" hidden=""true"" document=""1"" />
<entry offset=""0x14b"" hidden=""true"" document=""1"" />
<entry offset=""0x14d"" startLine=""27"" startColumn=""24"" endLine=""27"" endColumn=""38"" document=""1"" />
<entry offset=""0x157"" hidden=""true"" document=""1"" />
<entry offset=""0x159"" startLine=""27"" startColumn=""40"" endLine=""27"" endColumn=""49"" document=""1"" />
<entry offset=""0x15e"" startLine=""30"" startColumn=""26"" endLine=""30"" endColumn=""35"" document=""1"" />
<entry offset=""0x163"" hidden=""true"" document=""1"" />
<entry offset=""0x165"" startLine=""33"" startColumn=""30"" endLine=""33"" endColumn=""39"" document=""1"" />
<entry offset=""0x16a"" startLine=""36"" startColumn=""23"" endLine=""36"" endColumn=""32"" document=""1"" />
<entry offset=""0x16f"" startLine=""39"" startColumn=""22"" endLine=""39"" endColumn=""30"" document=""1"" />
<entry offset=""0x176"" hidden=""true"" document=""1"" />
<entry offset=""0x17b"" startLine=""39"" startColumn=""22"" endLine=""39"" endColumn=""30"" document=""1"" />
<entry offset=""0x182"" hidden=""true"" document=""1"" />
<entry offset=""0x187"" startLine=""39"" startColumn=""32"" endLine=""39"" endColumn=""41"" document=""1"" />
<entry offset=""0x18c"" startLine=""40"" startColumn=""22"" endLine=""40"" endColumn=""31"" document=""1"" />
<entry offset=""0x191"" hidden=""true"" document=""1"" />
<entry offset=""0x193"" startLine=""41"" startColumn=""38"" endLine=""41"" endColumn=""47"" document=""1"" />
<entry offset=""0x198"" hidden=""true"" document=""1"" />
<entry offset=""0x19a"" startLine=""42"" startColumn=""31"" endLine=""42"" endColumn=""40"" document=""1"" />
<entry offset=""0x19f"" hidden=""true"" document=""1"" />
<entry offset=""0x1a1"" startLine=""45"" startColumn=""58"" endLine=""45"" endColumn=""67"" document=""1"" />
<entry offset=""0x1a7"" startLine=""47"" startColumn=""22"" endLine=""47"" endColumn=""32"" document=""1"" />
<entry offset=""0x1ad"" startLine=""49"" startColumn=""5"" endLine=""49"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1b0"">
<scope startOffset=""0x14d"" endOffset=""0x15e"">
<local name=""x"" il_index=""0"" il_start=""0x14d"" il_end=""0x15e"" attributes=""0"" />
</scope>
<scope startOffset=""0x163"" endOffset=""0x16a"">
<local name=""y"" il_index=""1"" il_start=""0x163"" il_end=""0x16a"" attributes=""0"" />
<local name=""z"" il_index=""2"" il_start=""0x163"" il_end=""0x16a"" attributes=""0"" />
</scope>
<scope startOffset=""0x191"" endOffset=""0x198"">
<local name=""p"" il_index=""3"" il_start=""0x191"" il_end=""0x198"" attributes=""0"" />
<local name=""q"" il_index=""4"" il_start=""0x191"" il_end=""0x198"" attributes=""0"" />
</scope>
<scope startOffset=""0x198"" endOffset=""0x19f"">
<local name=""p"" il_index=""5"" il_start=""0x198"" il_end=""0x19f"" attributes=""0"" />
</scope>
<scope startOffset=""0x19f"" endOffset=""0x1a7"">
<local name=""z"" il_index=""6"" il_start=""0x19f"" il_end=""0x1a7"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")]
[Fact]
public void Patterns_SwitchExpression()
{
string source = WithWindowsLineBreaks(@"
class C
{
public void Deconstruct() { }
public void Deconstruct(out int x) { x = 1; }
public void Deconstruct(out int x, out object y) { x = 2; y = new C(); }
}
class D
{
public int P { get; set; }
public D Q { get; set; }
public C R { get; set; }
}
class Program
{
static object F() => new C();
static bool B() => true;
static int G(int x) => x;
static void Main()
{
var a = F() switch
{
// declaration pattern
int x when G(x) > 10 => 1,
// discard pattern
bool _ => 2,
// var pattern
var (y, z) => 3,
// constant pattern
4.0 => 4,
// positional patterns
C() when B() => 5,
() => 6,
C(int p, C(int q)) => 7,
C(x: int p) => 8,
// property pattern
D { P: 1, Q: D { P: 2 }, R: C (int z) } => 9,
_ => 10,
};
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerify(c, verify: Verification.Skipped);
// note no sequence points emitted within the switch expression
verifier.VerifyIL("Program.Main", sequencePoints: "Program.Main", expectedIL: @"
{
// Code size 437 (0x1b5)
.maxstack 3
.locals init (int V_0, //a
int V_1, //x
object V_2, //y
object V_3, //z
int V_4, //p
int V_5, //q
int V_6, //p
int V_7, //z
int V_8,
object V_9,
System.Runtime.CompilerServices.ITuple V_10,
int V_11,
double V_12,
C V_13,
object V_14,
C V_15,
D V_16,
int V_17,
D V_18,
int V_19,
C V_20)
-IL_0000: nop
-IL_0001: call ""object Program.F()""
IL_0006: stloc.s V_9
IL_0008: ldc.i4.1
IL_0009: brtrue.s IL_000c
-IL_000b: nop
~IL_000c: ldloc.s V_9
IL_000e: isinst ""int""
IL_0013: brfalse.s IL_0022
IL_0015: ldloc.s V_9
IL_0017: unbox.any ""int""
IL_001c: stloc.1
~IL_001d: br IL_014d
IL_0022: ldloc.s V_9
IL_0024: isinst ""bool""
IL_0029: brtrue IL_015e
IL_002e: ldloc.s V_9
IL_0030: isinst ""System.Runtime.CompilerServices.ITuple""
IL_0035: stloc.s V_10
IL_0037: ldloc.s V_10
IL_0039: brfalse.s IL_0080
IL_003b: ldloc.s V_10
IL_003d: callvirt ""int System.Runtime.CompilerServices.ITuple.Length.get""
IL_0042: stloc.s V_11
~IL_0044: ldloc.s V_11
IL_0046: ldc.i4.2
IL_0047: bne.un.s IL_0060
IL_0049: ldloc.s V_10
IL_004b: ldc.i4.0
IL_004c: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get""
IL_0051: stloc.2
~IL_0052: ldloc.s V_10
IL_0054: ldc.i4.1
IL_0055: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get""
IL_005a: stloc.3
~IL_005b: br IL_0163
IL_0060: ldloc.s V_9
IL_0062: isinst ""C""
IL_0067: brtrue IL_016f
IL_006c: br.s IL_0077
IL_006e: ldloc.s V_11
IL_0070: brfalse IL_018c
IL_0075: br.s IL_00b5
IL_0077: ldloc.s V_11
IL_0079: brfalse IL_018c
IL_007e: br.s IL_00f5
IL_0080: ldloc.s V_9
IL_0082: isinst ""double""
IL_0087: brfalse.s IL_00a7
IL_0089: ldloc.s V_9
IL_008b: unbox.any ""double""
IL_0090: stloc.s V_12
~IL_0092: ldloc.s V_12
IL_0094: ldc.r8 4
IL_009d: beq IL_016a
IL_00a2: br IL_01a7
IL_00a7: ldloc.s V_9
IL_00a9: isinst ""C""
IL_00ae: brtrue IL_017b
IL_00b3: br.s IL_00f5
IL_00b5: ldloc.s V_9
IL_00b7: castclass ""C""
IL_00bc: stloc.s V_13
~IL_00be: ldloc.s V_13
IL_00c0: ldloca.s V_4
IL_00c2: ldloca.s V_14
IL_00c4: callvirt ""void C.Deconstruct(out int, out object)""
IL_00c9: nop
~IL_00ca: ldloc.s V_14
IL_00cc: isinst ""C""
IL_00d1: stloc.s V_15
IL_00d3: ldloc.s V_15
IL_00d5: brfalse.s IL_00e6
IL_00d7: ldloc.s V_15
IL_00d9: ldloca.s V_5
IL_00db: callvirt ""void C.Deconstruct(out int)""
IL_00e0: nop
~IL_00e1: br IL_0191
IL_00e6: ldloc.s V_13
IL_00e8: ldloca.s V_6
IL_00ea: callvirt ""void C.Deconstruct(out int)""
IL_00ef: nop
~IL_00f0: br IL_0198
IL_00f5: ldloc.s V_9
IL_00f7: isinst ""D""
IL_00fc: stloc.s V_16
IL_00fe: ldloc.s V_16
IL_0100: brfalse IL_01a7
IL_0105: ldloc.s V_16
IL_0107: callvirt ""int D.P.get""
IL_010c: stloc.s V_17
~IL_010e: ldloc.s V_17
IL_0110: ldc.i4.1
IL_0111: bne.un IL_01a7
IL_0116: ldloc.s V_16
IL_0118: callvirt ""D D.Q.get""
IL_011d: stloc.s V_18
~IL_011f: ldloc.s V_18
IL_0121: brfalse IL_01a7
IL_0126: ldloc.s V_18
IL_0128: callvirt ""int D.P.get""
IL_012d: stloc.s V_19
~IL_012f: ldloc.s V_19
IL_0131: ldc.i4.2
IL_0132: bne.un.s IL_01a7
IL_0134: ldloc.s V_16
IL_0136: callvirt ""C D.R.get""
IL_013b: stloc.s V_20
~IL_013d: ldloc.s V_20
IL_013f: brfalse.s IL_01a7
IL_0141: ldloc.s V_20
IL_0143: ldloca.s V_7
IL_0145: callvirt ""void C.Deconstruct(out int)""
IL_014a: nop
~IL_014b: br.s IL_019f
-IL_014d: ldloc.1
IL_014e: call ""int Program.G(int)""
IL_0153: ldc.i4.s 10
IL_0155: bgt.s IL_0159
~IL_0157: br.s IL_01a7
-IL_0159: ldc.i4.1
IL_015a: stloc.s V_8
IL_015c: br.s IL_01ad
-IL_015e: ldc.i4.2
IL_015f: stloc.s V_8
IL_0161: br.s IL_01ad
~IL_0163: br.s IL_0165
-IL_0165: ldc.i4.3
IL_0166: stloc.s V_8
IL_0168: br.s IL_01ad
-IL_016a: ldc.i4.4
IL_016b: stloc.s V_8
IL_016d: br.s IL_01ad
-IL_016f: call ""bool Program.B()""
IL_0174: brtrue.s IL_0187
~IL_0176: br IL_006e
-IL_017b: call ""bool Program.B()""
IL_0180: brtrue.s IL_0187
~IL_0182: br IL_00b5
-IL_0187: ldc.i4.5
IL_0188: stloc.s V_8
IL_018a: br.s IL_01ad
-IL_018c: ldc.i4.6
IL_018d: stloc.s V_8
IL_018f: br.s IL_01ad
~IL_0191: br.s IL_0193
-IL_0193: ldc.i4.7
IL_0194: stloc.s V_8
IL_0196: br.s IL_01ad
~IL_0198: br.s IL_019a
-IL_019a: ldc.i4.8
IL_019b: stloc.s V_8
IL_019d: br.s IL_01ad
~IL_019f: br.s IL_01a1
-IL_01a1: ldc.i4.s 9
IL_01a3: stloc.s V_8
IL_01a5: br.s IL_01ad
-IL_01a7: ldc.i4.s 10
IL_01a9: stloc.s V_8
IL_01ab: br.s IL_01ad
~IL_01ad: ldc.i4.1
IL_01ae: brtrue.s IL_01b1
-IL_01b0: nop
~IL_01b1: ldloc.s V_8
IL_01b3: stloc.0
-IL_01b4: ret
}
");
verifier.VerifyPdb("Program.Main", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Deconstruct"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""0"" offset=""94"" />
<slot kind=""0"" offset=""225"" />
<slot kind=""0"" offset=""228"" />
<slot kind=""0"" offset=""406"" />
<slot kind=""0"" offset=""415"" />
<slot kind=""0"" offset=""447"" />
<slot kind=""0"" offset=""539"" />
<slot kind=""temp"" />
<slot kind=""35"" offset=""23"" />
<slot kind=""35"" offset=""23"" ordinal=""1"" />
<slot kind=""35"" offset=""23"" ordinal=""2"" />
<slot kind=""35"" offset=""23"" ordinal=""3"" />
<slot kind=""35"" offset=""23"" ordinal=""4"" />
<slot kind=""35"" offset=""23"" ordinal=""5"" />
<slot kind=""35"" offset=""23"" ordinal=""6"" />
<slot kind=""35"" offset=""23"" ordinal=""7"" />
<slot kind=""35"" offset=""23"" ordinal=""8"" />
<slot kind=""35"" offset=""23"" ordinal=""9"" />
<slot kind=""35"" offset=""23"" ordinal=""10"" />
<slot kind=""35"" offset=""23"" ordinal=""11"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""24"" startColumn=""9"" endLine=""48"" endColumn=""11"" document=""1"" />
<entry offset=""0xb"" startLine=""24"" startColumn=""21"" endLine=""48"" endColumn=""10"" document=""1"" />
<entry offset=""0xc"" hidden=""true"" document=""1"" />
<entry offset=""0x1d"" hidden=""true"" document=""1"" />
<entry offset=""0x44"" hidden=""true"" document=""1"" />
<entry offset=""0x52"" hidden=""true"" document=""1"" />
<entry offset=""0x5b"" hidden=""true"" document=""1"" />
<entry offset=""0x92"" hidden=""true"" document=""1"" />
<entry offset=""0xbe"" hidden=""true"" document=""1"" />
<entry offset=""0xca"" hidden=""true"" document=""1"" />
<entry offset=""0xe1"" hidden=""true"" document=""1"" />
<entry offset=""0xf0"" hidden=""true"" document=""1"" />
<entry offset=""0x10e"" hidden=""true"" document=""1"" />
<entry offset=""0x11f"" hidden=""true"" document=""1"" />
<entry offset=""0x12f"" hidden=""true"" document=""1"" />
<entry offset=""0x13d"" hidden=""true"" document=""1"" />
<entry offset=""0x14b"" hidden=""true"" document=""1"" />
<entry offset=""0x14d"" startLine=""27"" startColumn=""19"" endLine=""27"" endColumn=""33"" document=""1"" />
<entry offset=""0x157"" hidden=""true"" document=""1"" />
<entry offset=""0x159"" startLine=""27"" startColumn=""37"" endLine=""27"" endColumn=""38"" document=""1"" />
<entry offset=""0x15e"" startLine=""30"" startColumn=""23"" endLine=""30"" endColumn=""24"" document=""1"" />
<entry offset=""0x163"" hidden=""true"" document=""1"" />
<entry offset=""0x165"" startLine=""33"" startColumn=""27"" endLine=""33"" endColumn=""28"" document=""1"" />
<entry offset=""0x16a"" startLine=""36"" startColumn=""20"" endLine=""36"" endColumn=""21"" document=""1"" />
<entry offset=""0x16f"" startLine=""39"" startColumn=""17"" endLine=""39"" endColumn=""25"" document=""1"" />
<entry offset=""0x176"" hidden=""true"" document=""1"" />
<entry offset=""0x17b"" startLine=""39"" startColumn=""17"" endLine=""39"" endColumn=""25"" document=""1"" />
<entry offset=""0x182"" hidden=""true"" document=""1"" />
<entry offset=""0x187"" startLine=""39"" startColumn=""29"" endLine=""39"" endColumn=""30"" document=""1"" />
<entry offset=""0x18c"" startLine=""40"" startColumn=""19"" endLine=""40"" endColumn=""20"" document=""1"" />
<entry offset=""0x191"" hidden=""true"" document=""1"" />
<entry offset=""0x193"" startLine=""41"" startColumn=""35"" endLine=""41"" endColumn=""36"" document=""1"" />
<entry offset=""0x198"" hidden=""true"" document=""1"" />
<entry offset=""0x19a"" startLine=""42"" startColumn=""28"" endLine=""42"" endColumn=""29"" document=""1"" />
<entry offset=""0x19f"" hidden=""true"" document=""1"" />
<entry offset=""0x1a1"" startLine=""45"" startColumn=""56"" endLine=""45"" endColumn=""57"" document=""1"" />
<entry offset=""0x1a7"" startLine=""47"" startColumn=""18"" endLine=""47"" endColumn=""20"" document=""1"" />
<entry offset=""0x1ad"" hidden=""true"" document=""1"" />
<entry offset=""0x1b0"" startLine=""24"" startColumn=""9"" endLine=""48"" endColumn=""11"" document=""1"" />
<entry offset=""0x1b1"" hidden=""true"" document=""1"" />
<entry offset=""0x1b4"" startLine=""49"" startColumn=""5"" endLine=""49"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1b5"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x1b5"" attributes=""0"" />
<scope startOffset=""0x14d"" endOffset=""0x15e"">
<local name=""x"" il_index=""1"" il_start=""0x14d"" il_end=""0x15e"" attributes=""0"" />
</scope>
<scope startOffset=""0x163"" endOffset=""0x16a"">
<local name=""y"" il_index=""2"" il_start=""0x163"" il_end=""0x16a"" attributes=""0"" />
<local name=""z"" il_index=""3"" il_start=""0x163"" il_end=""0x16a"" attributes=""0"" />
</scope>
<scope startOffset=""0x191"" endOffset=""0x198"">
<local name=""p"" il_index=""4"" il_start=""0x191"" il_end=""0x198"" attributes=""0"" />
<local name=""q"" il_index=""5"" il_start=""0x191"" il_end=""0x198"" attributes=""0"" />
</scope>
<scope startOffset=""0x198"" endOffset=""0x19f"">
<local name=""p"" il_index=""6"" il_start=""0x198"" il_end=""0x19f"" attributes=""0"" />
</scope>
<scope startOffset=""0x19f"" endOffset=""0x1a7"">
<local name=""z"" il_index=""7"" il_start=""0x19f"" il_end=""0x1a7"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")]
[Fact]
public void Patterns_IsPattern()
{
string source = WithWindowsLineBreaks(@"
class C
{
public void Deconstruct() { }
public void Deconstruct(out int x) { x = 1; }
public void Deconstruct(out int x, out object y) { x = 2; y = new C(); }
}
class D
{
public int P { get; set; }
public D Q { get; set; }
public C R { get; set; }
}
class Program
{
static object F() => new C();
static bool B() => true;
static int G(int x) => x;
static bool M()
{
object obj = F();
return
// declaration pattern
obj is int x ||
// discard pattern
obj is bool _ ||
// var pattern
obj is var (y, z1) ||
// constant pattern
obj is 4.0 ||
// positional patterns
obj is C() ||
obj is () ||
obj is C(int p1, C(int q)) ||
obj is C(x: int p2) ||
// property pattern
obj is D { P: 1, Q: D { P: 2 }, R: C(int z2) };
}
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp);
var verifier = CompileAndVerify(c, verify: Verification.Skipped);
verifier.VerifyIL("Program.M", sequencePoints: "Program.M", expectedIL: @"
{
// Code size 301 (0x12d)
.maxstack 3
.locals init (object V_0, //obj
int V_1, //x
object V_2, //y
object V_3, //z1
int V_4, //p1
int V_5, //q
int V_6, //p2
int V_7, //z2
System.Runtime.CompilerServices.ITuple V_8,
C V_9,
object V_10,
C V_11,
D V_12,
D V_13,
bool V_14)
-IL_0000: nop
-IL_0001: call ""object Program.F()""
IL_0006: stloc.0
-IL_0007: ldloc.0
IL_0008: isinst ""int""
IL_000d: brfalse.s IL_001b
IL_000f: ldloc.0
IL_0010: unbox.any ""int""
IL_0015: stloc.1
IL_0016: br IL_0125
IL_001b: ldloc.0
IL_001c: isinst ""bool""
IL_0021: brtrue IL_0125
IL_0026: ldloc.0
IL_0027: isinst ""System.Runtime.CompilerServices.ITuple""
IL_002c: stloc.s V_8
IL_002e: ldloc.s V_8
IL_0030: brfalse.s IL_0053
IL_0032: ldloc.s V_8
IL_0034: callvirt ""int System.Runtime.CompilerServices.ITuple.Length.get""
IL_0039: ldc.i4.2
IL_003a: bne.un.s IL_0053
IL_003c: ldloc.s V_8
IL_003e: ldc.i4.0
IL_003f: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get""
IL_0044: stloc.2
IL_0045: ldloc.s V_8
IL_0047: ldc.i4.1
IL_0048: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get""
IL_004d: stloc.3
IL_004e: br IL_0125
IL_0053: ldloc.0
IL_0054: isinst ""double""
IL_0059: brfalse.s IL_006f
IL_005b: ldloc.0
IL_005c: unbox.any ""double""
IL_0061: ldc.r8 4
IL_006a: beq IL_0125
IL_006f: ldloc.0
IL_0070: isinst ""C""
IL_0075: brtrue IL_0125
IL_007a: ldloc.0
IL_007b: isinst ""System.Runtime.CompilerServices.ITuple""
IL_0080: stloc.s V_8
IL_0082: ldloc.s V_8
IL_0084: brfalse.s IL_0092
IL_0086: ldloc.s V_8
IL_0088: callvirt ""int System.Runtime.CompilerServices.ITuple.Length.get""
IL_008d: brfalse IL_0125
IL_0092: ldloc.0
IL_0093: isinst ""C""
IL_0098: stloc.s V_9
IL_009a: ldloc.s V_9
IL_009c: brfalse.s IL_00c3
IL_009e: ldloc.s V_9
IL_00a0: ldloca.s V_4
IL_00a2: ldloca.s V_10
IL_00a4: callvirt ""void C.Deconstruct(out int, out object)""
IL_00a9: nop
IL_00aa: ldloc.s V_10
IL_00ac: isinst ""C""
IL_00b1: stloc.s V_11
IL_00b3: ldloc.s V_11
IL_00b5: brfalse.s IL_00c3
IL_00b7: ldloc.s V_11
IL_00b9: ldloca.s V_5
IL_00bb: callvirt ""void C.Deconstruct(out int)""
IL_00c0: nop
IL_00c1: br.s IL_0125
IL_00c3: ldloc.0
IL_00c4: isinst ""C""
IL_00c9: stloc.s V_11
IL_00cb: ldloc.s V_11
IL_00cd: brfalse.s IL_00db
IL_00cf: ldloc.s V_11
IL_00d1: ldloca.s V_6
IL_00d3: callvirt ""void C.Deconstruct(out int)""
IL_00d8: nop
IL_00d9: br.s IL_0125
IL_00db: ldloc.0
IL_00dc: isinst ""D""
IL_00e1: stloc.s V_12
IL_00e3: ldloc.s V_12
IL_00e5: brfalse.s IL_0122
IL_00e7: ldloc.s V_12
IL_00e9: callvirt ""int D.P.get""
IL_00ee: ldc.i4.1
IL_00ef: bne.un.s IL_0122
IL_00f1: ldloc.s V_12
IL_00f3: callvirt ""D D.Q.get""
IL_00f8: stloc.s V_13
IL_00fa: ldloc.s V_13
IL_00fc: brfalse.s IL_0122
IL_00fe: ldloc.s V_13
IL_0100: callvirt ""int D.P.get""
IL_0105: ldc.i4.2
IL_0106: bne.un.s IL_0122
IL_0108: ldloc.s V_12
IL_010a: callvirt ""C D.R.get""
IL_010f: stloc.s V_11
IL_0111: ldloc.s V_11
IL_0113: brfalse.s IL_0122
IL_0115: ldloc.s V_11
IL_0117: ldloca.s V_7
IL_0119: callvirt ""void C.Deconstruct(out int)""
IL_011e: nop
IL_011f: ldc.i4.1
IL_0120: br.s IL_0123
IL_0122: ldc.i4.0
IL_0123: br.s IL_0126
IL_0125: ldc.i4.1
IL_0126: stloc.s V_14
IL_0128: br.s IL_012a
-IL_012a: ldloc.s V_14
IL_012c: ret
}
");
verifier.VerifyPdb("Program.M", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""M"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Deconstruct"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""18"" />
<slot kind=""0"" offset=""106"" />
<slot kind=""0"" offset=""230"" />
<slot kind=""0"" offset=""233"" />
<slot kind=""0"" offset=""419"" />
<slot kind=""0"" offset=""429"" />
<slot kind=""0"" offset=""465"" />
<slot kind=""0"" offset=""561"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""26"" document=""1"" />
<entry offset=""0x7"" startLine=""25"" startColumn=""9"" endLine=""45"" endColumn=""60"" document=""1"" />
<entry offset=""0x12a"" startLine=""46"" startColumn=""5"" endLine=""46"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x12d"">
<local name=""obj"" il_index=""0"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
<local name=""x"" il_index=""1"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
<local name=""y"" il_index=""2"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
<local name=""z1"" il_index=""3"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
<local name=""p1"" il_index=""4"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
<local name=""q"" il_index=""5"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
<local name=""p2"" il_index=""6"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
<local name=""z2"" il_index=""7"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")]
[WorkItem(37232, "https://github.com/dotnet/roslyn/issues/37232")]
[WorkItem(37237, "https://github.com/dotnet/roslyn/issues/37237")]
[Fact]
public void Patterns_SwitchExpression_Closures()
{
string source = WithWindowsLineBreaks(@"
using System;
public class C
{
static int M()
{
return F() switch
{
1 => F() switch
{
C { P: int p, Q: C { P: int q } } => G(() => p + q),
_ => 10
},
2 => F() switch
{
C { P: int r } => G(() => r),
_ => 20
},
C { Q: int s } => G(() => s),
_ => 0
}
switch
{
var t when t > 0 => G(() => t),
_ => 0
};
}
object P { get; set; }
object Q { get; set; }
static object F() => null;
static int G(Func<int> f) => 0;
}
");
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var verifier = CompileAndVerify(c);
verifier.VerifyIL("C.M", sequencePoints: "C.M", source: source, expectedIL: @"
{
// Code size 472 (0x1d8)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
int V_1,
C.<>c__DisplayClass0_1 V_2, //CS$<>8__locals1
int V_3,
object V_4,
int V_5,
C V_6,
object V_7,
C.<>c__DisplayClass0_2 V_8, //CS$<>8__locals2
int V_9,
object V_10,
C V_11,
object V_12,
object V_13,
C V_14,
object V_15,
C.<>c__DisplayClass0_3 V_16, //CS$<>8__locals3
object V_17,
C V_18,
object V_19,
int V_20)
// sequence point: {
IL_0000: nop
// sequence point: <hidden>
IL_0001: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0006: stloc.0
// sequence point: <hidden>
IL_0007: newobj ""C.<>c__DisplayClass0_1..ctor()""
IL_000c: stloc.2
IL_000d: call ""object C.F()""
IL_0012: stloc.s V_4
IL_0014: ldc.i4.1
IL_0015: brtrue.s IL_0018
// sequence point: switch ... }
IL_0017: nop
// sequence point: <hidden>
IL_0018: ldloc.s V_4
IL_001a: isinst ""int""
IL_001f: brfalse.s IL_003e
IL_0021: ldloc.s V_4
IL_0023: unbox.any ""int""
IL_0028: stloc.s V_5
// sequence point: <hidden>
IL_002a: ldloc.s V_5
IL_002c: ldc.i4.1
IL_002d: beq.s IL_0075
IL_002f: br.s IL_0031
IL_0031: ldloc.s V_5
IL_0033: ldc.i4.2
IL_0034: beq IL_0116
IL_0039: br IL_0194
IL_003e: ldloc.s V_4
IL_0040: isinst ""C""
IL_0045: stloc.s V_6
IL_0047: ldloc.s V_6
IL_0049: brfalse IL_0194
IL_004e: ldloc.s V_6
IL_0050: callvirt ""object C.Q.get""
IL_0055: stloc.s V_7
// sequence point: <hidden>
IL_0057: ldloc.s V_7
IL_0059: isinst ""int""
IL_005e: brfalse IL_0194
IL_0063: ldloc.2
IL_0064: ldloc.s V_7
IL_0066: unbox.any ""int""
IL_006b: stfld ""int C.<>c__DisplayClass0_1.<s>5__3""
// sequence point: <hidden>
IL_0070: br IL_017e
// sequence point: <hidden>
IL_0075: newobj ""C.<>c__DisplayClass0_2..ctor()""
IL_007a: stloc.s V_8
IL_007c: call ""object C.F()""
IL_0081: stloc.s V_10
IL_0083: ldc.i4.1
IL_0084: brtrue.s IL_0087
// sequence point: switch ...
IL_0086: nop
// sequence point: <hidden>
IL_0087: ldloc.s V_10
IL_0089: isinst ""C""
IL_008e: stloc.s V_11
IL_0090: ldloc.s V_11
IL_0092: brfalse.s IL_0104
IL_0094: ldloc.s V_11
IL_0096: callvirt ""object C.P.get""
IL_009b: stloc.s V_12
// sequence point: <hidden>
IL_009d: ldloc.s V_12
IL_009f: isinst ""int""
IL_00a4: brfalse.s IL_0104
IL_00a6: ldloc.s V_8
IL_00a8: ldloc.s V_12
IL_00aa: unbox.any ""int""
IL_00af: stfld ""int C.<>c__DisplayClass0_2.<p>5__4""
// sequence point: <hidden>
IL_00b4: ldloc.s V_11
IL_00b6: callvirt ""object C.Q.get""
IL_00bb: stloc.s V_13
// sequence point: <hidden>
IL_00bd: ldloc.s V_13
IL_00bf: isinst ""C""
IL_00c4: stloc.s V_14
IL_00c6: ldloc.s V_14
IL_00c8: brfalse.s IL_0104
IL_00ca: ldloc.s V_14
IL_00cc: callvirt ""object C.P.get""
IL_00d1: stloc.s V_15
// sequence point: <hidden>
IL_00d3: ldloc.s V_15
IL_00d5: isinst ""int""
IL_00da: brfalse.s IL_0104
IL_00dc: ldloc.s V_8
IL_00de: ldloc.s V_15
IL_00e0: unbox.any ""int""
IL_00e5: stfld ""int C.<>c__DisplayClass0_2.<q>5__5""
// sequence point: <hidden>
IL_00ea: br.s IL_00ec
// sequence point: <hidden>
IL_00ec: br.s IL_00ee
// sequence point: G(() => p + q)
IL_00ee: ldloc.s V_8
IL_00f0: ldftn ""int C.<>c__DisplayClass0_2.<M>b__2()""
IL_00f6: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_00fb: call ""int C.G(System.Func<int>)""
IL_0100: stloc.s V_9
IL_0102: br.s IL_010a
// sequence point: 10
IL_0104: ldc.i4.s 10
IL_0106: stloc.s V_9
IL_0108: br.s IL_010a
// sequence point: <hidden>
IL_010a: ldc.i4.1
IL_010b: brtrue.s IL_010e
// sequence point: switch ... }
IL_010d: nop
// sequence point: F() switch ...
IL_010e: ldloc.s V_9
IL_0110: stloc.3
IL_0111: br IL_0198
// sequence point: <hidden>
IL_0116: newobj ""C.<>c__DisplayClass0_3..ctor()""
IL_011b: stloc.s V_16
IL_011d: call ""object C.F()""
IL_0122: stloc.s V_17
IL_0124: ldc.i4.1
IL_0125: brtrue.s IL_0128
// sequence point: switch ...
IL_0127: nop
// sequence point: <hidden>
IL_0128: ldloc.s V_17
IL_012a: isinst ""C""
IL_012f: stloc.s V_18
IL_0131: ldloc.s V_18
IL_0133: brfalse.s IL_016f
IL_0135: ldloc.s V_18
IL_0137: callvirt ""object C.P.get""
IL_013c: stloc.s V_19
// sequence point: <hidden>
IL_013e: ldloc.s V_19
IL_0140: isinst ""int""
IL_0145: brfalse.s IL_016f
IL_0147: ldloc.s V_16
IL_0149: ldloc.s V_19
IL_014b: unbox.any ""int""
IL_0150: stfld ""int C.<>c__DisplayClass0_3.<r>5__6""
// sequence point: <hidden>
IL_0155: br.s IL_0157
// sequence point: <hidden>
IL_0157: br.s IL_0159
// sequence point: G(() => r)
IL_0159: ldloc.s V_16
IL_015b: ldftn ""int C.<>c__DisplayClass0_3.<M>b__3()""
IL_0161: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_0166: call ""int C.G(System.Func<int>)""
IL_016b: stloc.s V_9
IL_016d: br.s IL_0175
// sequence point: 20
IL_016f: ldc.i4.s 20
IL_0171: stloc.s V_9
IL_0173: br.s IL_0175
// sequence point: <hidden>
IL_0175: ldc.i4.1
IL_0176: brtrue.s IL_0179
// sequence point: F() switch ...
IL_0178: nop
// sequence point: F() switch ...
IL_0179: ldloc.s V_9
IL_017b: stloc.3
IL_017c: br.s IL_0198
// sequence point: <hidden>
IL_017e: br.s IL_0180
// sequence point: G(() => s)
IL_0180: ldloc.2
IL_0181: ldftn ""int C.<>c__DisplayClass0_1.<M>b__1()""
IL_0187: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_018c: call ""int C.G(System.Func<int>)""
IL_0191: stloc.3
IL_0192: br.s IL_0198
// sequence point: 0
IL_0194: ldc.i4.0
IL_0195: stloc.3
IL_0196: br.s IL_0198
// sequence point: <hidden>
IL_0198: ldc.i4.1
IL_0199: brtrue.s IL_019c
// sequence point: return F() s ... };
IL_019b: nop
// sequence point: <hidden>
IL_019c: ldloc.0
IL_019d: ldloc.3
IL_019e: stfld ""int C.<>c__DisplayClass0_0.<t>5__2""
IL_01a3: ldc.i4.1
IL_01a4: brtrue.s IL_01a7
// sequence point: switch ... }
IL_01a6: nop
// sequence point: <hidden>
IL_01a7: br.s IL_01a9
// sequence point: when t > 0
IL_01a9: ldloc.0
IL_01aa: ldfld ""int C.<>c__DisplayClass0_0.<t>5__2""
IL_01af: ldc.i4.0
IL_01b0: bgt.s IL_01b4
// sequence point: <hidden>
IL_01b2: br.s IL_01c8
// sequence point: G(() => t)
IL_01b4: ldloc.0
IL_01b5: ldftn ""int C.<>c__DisplayClass0_0.<M>b__0()""
IL_01bb: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_01c0: call ""int C.G(System.Func<int>)""
IL_01c5: stloc.1
IL_01c6: br.s IL_01cc
// sequence point: 0
IL_01c8: ldc.i4.0
IL_01c9: stloc.1
IL_01ca: br.s IL_01cc
// sequence point: <hidden>
IL_01cc: ldc.i4.1
IL_01cd: brtrue.s IL_01d0
// sequence point: return F() s ... };
IL_01cf: nop
// sequence point: <hidden>
IL_01d0: ldloc.1
IL_01d1: stloc.s V_20
IL_01d3: br.s IL_01d5
// sequence point: }
IL_01d5: ldloc.s V_20
IL_01d7: ret
}
");
verifier.VerifyPdb("C.M", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""30"" offset=""11"" />
<slot kind=""temp"" />
<slot kind=""30"" offset=""22"" />
<slot kind=""temp"" />
<slot kind=""35"" offset=""22"" />
<slot kind=""35"" offset=""22"" ordinal=""1"" />
<slot kind=""35"" offset=""22"" ordinal=""2"" />
<slot kind=""35"" offset=""22"" ordinal=""3"" />
<slot kind=""30"" offset=""63"" />
<slot kind=""temp"" />
<slot kind=""35"" offset=""63"" />
<slot kind=""35"" offset=""63"" ordinal=""1"" />
<slot kind=""35"" offset=""63"" ordinal=""2"" />
<slot kind=""35"" offset=""63"" ordinal=""3"" />
<slot kind=""35"" offset=""63"" ordinal=""4"" />
<slot kind=""35"" offset=""63"" ordinal=""5"" />
<slot kind=""30"" offset=""238"" />
<slot kind=""35"" offset=""238"" />
<slot kind=""35"" offset=""238"" ordinal=""1"" />
<slot kind=""35"" offset=""238"" ordinal=""2"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""11"" />
<closure offset=""22"" />
<closure offset=""63"" />
<closure offset=""238"" />
<lambda offset=""511"" closure=""0"" />
<lambda offset=""407"" closure=""1"" />
<lambda offset=""157"" closure=""2"" />
<lambda offset=""313"" closure=""3"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" hidden=""true"" document=""1"" />
<entry offset=""0x17"" startLine=""7"" startColumn=""20"" endLine=""21"" endColumn=""10"" document=""1"" />
<entry offset=""0x18"" hidden=""true"" document=""1"" />
<entry offset=""0x2a"" hidden=""true"" document=""1"" />
<entry offset=""0x57"" hidden=""true"" document=""1"" />
<entry offset=""0x70"" hidden=""true"" document=""1"" />
<entry offset=""0x75"" hidden=""true"" document=""1"" />
<entry offset=""0x86"" startLine=""9"" startColumn=""22"" endLine=""13"" endColumn=""19"" document=""1"" />
<entry offset=""0x87"" hidden=""true"" document=""1"" />
<entry offset=""0x9d"" hidden=""true"" document=""1"" />
<entry offset=""0xb4"" hidden=""true"" document=""1"" />
<entry offset=""0xbd"" hidden=""true"" document=""1"" />
<entry offset=""0xd3"" hidden=""true"" document=""1"" />
<entry offset=""0xea"" hidden=""true"" document=""1"" />
<entry offset=""0xec"" hidden=""true"" document=""1"" />
<entry offset=""0xee"" startLine=""11"" startColumn=""59"" endLine=""11"" endColumn=""73"" document=""1"" />
<entry offset=""0x104"" startLine=""12"" startColumn=""27"" endLine=""12"" endColumn=""29"" document=""1"" />
<entry offset=""0x10a"" hidden=""true"" document=""1"" />
<entry offset=""0x10d"" startLine=""7"" startColumn=""20"" endLine=""21"" endColumn=""10"" document=""1"" />
<entry offset=""0x10e"" startLine=""9"" startColumn=""18"" endLine=""13"" endColumn=""19"" document=""1"" />
<entry offset=""0x116"" hidden=""true"" document=""1"" />
<entry offset=""0x127"" startLine=""14"" startColumn=""22"" endLine=""18"" endColumn=""19"" document=""1"" />
<entry offset=""0x128"" hidden=""true"" document=""1"" />
<entry offset=""0x13e"" hidden=""true"" document=""1"" />
<entry offset=""0x155"" hidden=""true"" document=""1"" />
<entry offset=""0x157"" hidden=""true"" document=""1"" />
<entry offset=""0x159"" startLine=""16"" startColumn=""40"" endLine=""16"" endColumn=""50"" document=""1"" />
<entry offset=""0x16f"" startLine=""17"" startColumn=""27"" endLine=""17"" endColumn=""29"" document=""1"" />
<entry offset=""0x175"" hidden=""true"" document=""1"" />
<entry offset=""0x178"" startLine=""9"" startColumn=""18"" endLine=""13"" endColumn=""19"" document=""1"" />
<entry offset=""0x179"" startLine=""14"" startColumn=""18"" endLine=""18"" endColumn=""19"" document=""1"" />
<entry offset=""0x17e"" hidden=""true"" document=""1"" />
<entry offset=""0x180"" startLine=""19"" startColumn=""31"" endLine=""19"" endColumn=""41"" document=""1"" />
<entry offset=""0x194"" startLine=""20"" startColumn=""18"" endLine=""20"" endColumn=""19"" document=""1"" />
<entry offset=""0x198"" hidden=""true"" document=""1"" />
<entry offset=""0x19b"" startLine=""7"" startColumn=""9"" endLine=""26"" endColumn=""11"" document=""1"" />
<entry offset=""0x19c"" hidden=""true"" document=""1"" />
<entry offset=""0x1a6"" startLine=""22"" startColumn=""9"" endLine=""26"" endColumn=""10"" document=""1"" />
<entry offset=""0x1a7"" hidden=""true"" document=""1"" />
<entry offset=""0x1a9"" startLine=""24"" startColumn=""19"" endLine=""24"" endColumn=""29"" document=""1"" />
<entry offset=""0x1b2"" hidden=""true"" document=""1"" />
<entry offset=""0x1b4"" startLine=""24"" startColumn=""33"" endLine=""24"" endColumn=""43"" document=""1"" />
<entry offset=""0x1c8"" startLine=""25"" startColumn=""18"" endLine=""25"" endColumn=""19"" document=""1"" />
<entry offset=""0x1cc"" hidden=""true"" document=""1"" />
<entry offset=""0x1cf"" startLine=""7"" startColumn=""9"" endLine=""26"" endColumn=""11"" document=""1"" />
<entry offset=""0x1d0"" hidden=""true"" document=""1"" />
<entry offset=""0x1d5"" startLine=""27"" startColumn=""5"" endLine=""27"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1d8"">
<namespace name=""System"" />
<scope startOffset=""0x1"" endOffset=""0x1d5"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x1"" il_end=""0x1d5"" attributes=""0"" />
<scope startOffset=""0x7"" endOffset=""0x1a3"">
<local name=""CS$<>8__locals1"" il_index=""2"" il_start=""0x7"" il_end=""0x1a3"" attributes=""0"" />
<scope startOffset=""0x75"" endOffset=""0x111"">
<local name=""CS$<>8__locals2"" il_index=""8"" il_start=""0x75"" il_end=""0x111"" attributes=""0"" />
</scope>
<scope startOffset=""0x116"" endOffset=""0x17c"">
<local name=""CS$<>8__locals3"" il_index=""16"" il_start=""0x116"" il_end=""0x17c"" attributes=""0"" />
</scope>
</scope>
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(50321, "https://github.com/dotnet/roslyn/issues/50321")]
[ConditionalFact(typeof(CoreClrOnly))]
public void NestedSwitchExpressions_Closures_01()
{
string source = WithWindowsLineBreaks(
@"using System;
class C
{
static int F(object o)
{
return o switch
{
int i => new Func<int>(() => i + i switch
{
1 => 2,
_ => 3
})(),
_ => 4
};
}
}");
var verifier = CompileAndVerify(source, options: TestOptions.DebugDll);
verifier.VerifyTypeIL("C",
@".class private auto ansi beforefieldinit C
extends [netstandard]System.Object
{
// Nested Types
.class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0'
extends [netstandard]System.Object
{
.custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
01 00 00 00
)
// Fields
.field public int32 '<i>5__2'
// Methods
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x20a1
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [netstandard]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method '<>c__DisplayClass0_0'::.ctor
.method assembly hidebysig
instance int32 '<F>b__0' () cil managed
{
// Method begins at RVA 0x20ac
// Code size 38 (0x26)
.maxstack 2
.locals init (
[0] int32,
[1] int32
)
IL_0000: ldarg.0
IL_0001: ldfld int32 C/'<>c__DisplayClass0_0'::'<i>5__2'
IL_0006: stloc.0
IL_0007: ldc.i4.1
IL_0008: brtrue.s IL_000b
IL_000a: nop
IL_000b: ldarg.0
IL_000c: ldfld int32 C/'<>c__DisplayClass0_0'::'<i>5__2'
IL_0011: ldc.i4.1
IL_0012: beq.s IL_0016
IL_0014: br.s IL_001a
IL_0016: ldc.i4.2
IL_0017: stloc.1
IL_0018: br.s IL_001e
IL_001a: ldc.i4.3
IL_001b: stloc.1
IL_001c: br.s IL_001e
IL_001e: ldc.i4.1
IL_001f: brtrue.s IL_0022
IL_0021: nop
IL_0022: ldloc.0
IL_0023: ldloc.1
IL_0024: add
IL_0025: ret
} // end of method '<>c__DisplayClass0_0'::'<F>b__0'
} // end of class <>c__DisplayClass0_0
// Methods
.method private hidebysig static
int32 F (
object o
) cil managed
{
// Method begins at RVA 0x2050
// Code size 69 (0x45)
.maxstack 2
.locals init (
[0] class C/'<>c__DisplayClass0_0',
[1] int32,
[2] int32
)
IL_0000: nop
IL_0001: newobj instance void C/'<>c__DisplayClass0_0'::.ctor()
IL_0006: stloc.0
IL_0007: ldc.i4.1
IL_0008: brtrue.s IL_000b
IL_000a: nop
IL_000b: ldarg.0
IL_000c: isinst [netstandard]System.Int32
IL_0011: brfalse.s IL_0037
IL_0013: ldloc.0
IL_0014: ldarg.0
IL_0015: unbox.any [netstandard]System.Int32
IL_001a: stfld int32 C/'<>c__DisplayClass0_0'::'<i>5__2'
IL_001f: br.s IL_0021
IL_0021: br.s IL_0023
IL_0023: ldloc.0
IL_0024: ldftn instance int32 C/'<>c__DisplayClass0_0'::'<F>b__0'()
IL_002a: newobj instance void class [netstandard]System.Func`1<int32>::.ctor(object, native int)
IL_002f: callvirt instance !0 class [netstandard]System.Func`1<int32>::Invoke()
IL_0034: stloc.1
IL_0035: br.s IL_003b
IL_0037: ldc.i4.4
IL_0038: stloc.1
IL_0039: br.s IL_003b
IL_003b: ldc.i4.1
IL_003c: brtrue.s IL_003f
IL_003e: nop
IL_003f: ldloc.1
IL_0040: stloc.2
IL_0041: br.s IL_0043
IL_0043: ldloc.2
IL_0044: ret
} // end of method C::F
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x20a1
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [netstandard]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method C::.ctor
} // end of class C
");
verifier.VerifyPdb(
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"" parameterNames=""o"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""30"" offset=""11"" />
<slot kind=""temp"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""11"" />
<lambda offset=""80"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" hidden=""true"" document=""1"" />
<entry offset=""0xa"" startLine=""6"" startColumn=""18"" endLine=""14"" endColumn=""10"" document=""1"" />
<entry offset=""0xb"" hidden=""true"" document=""1"" />
<entry offset=""0x1f"" hidden=""true"" document=""1"" />
<entry offset=""0x21"" hidden=""true"" document=""1"" />
<entry offset=""0x23"" startLine=""8"" startColumn=""22"" endLine=""12"" endColumn=""17"" document=""1"" />
<entry offset=""0x37"" startLine=""13"" startColumn=""18"" endLine=""13"" endColumn=""19"" document=""1"" />
<entry offset=""0x3b"" hidden=""true"" document=""1"" />
<entry offset=""0x3e"" startLine=""6"" startColumn=""9"" endLine=""14"" endColumn=""11"" document=""1"" />
<entry offset=""0x3f"" hidden=""true"" document=""1"" />
<entry offset=""0x43"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x45"">
<namespace name=""System"" />
<scope startOffset=""0x1"" endOffset=""0x43"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x1"" il_end=""0x43"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""C+<>c__DisplayClass0_0"" name=""<F>b__0"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" parameterNames=""o"" />
<encLocalSlotMap>
<slot kind=""28"" offset=""86"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""42"" endLine=""12"" endColumn=""14"" document=""1"" />
<entry offset=""0xa"" startLine=""8"" startColumn=""48"" endLine=""12"" endColumn=""14"" document=""1"" />
<entry offset=""0xb"" hidden=""true"" document=""1"" />
<entry offset=""0x16"" startLine=""10"" startColumn=""22"" endLine=""10"" endColumn=""23"" document=""1"" />
<entry offset=""0x1a"" startLine=""11"" startColumn=""22"" endLine=""11"" endColumn=""23"" document=""1"" />
<entry offset=""0x1e"" hidden=""true"" document=""1"" />
<entry offset=""0x21"" startLine=""8"" startColumn=""42"" endLine=""12"" endColumn=""14"" document=""1"" />
<entry offset=""0x22"" hidden=""true"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(50321, "https://github.com/dotnet/roslyn/issues/50321")]
[ConditionalFact(typeof(CoreClrOnly))]
public void NestedSwitchExpressions_Closures_02()
{
string source = WithWindowsLineBreaks(
@"using System;
class C
{
static string F(object o)
{
return o switch
{
int i => new Func<string>(() => ""1"" + i switch
{
1 => new Func<string>(() => ""2"" + i)(),
_ => ""3""
})(),
_ => ""4""
};
}
}");
var verifier = CompileAndVerify(source, options: TestOptions.DebugDll);
verifier.VerifyTypeIL("C",
@".class private auto ansi beforefieldinit C
extends [netstandard]System.Object
{
// Nested Types
.class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0'
extends [netstandard]System.Object
{
.custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
01 00 00 00
)
// Fields
.field public int32 '<i>5__2'
.field public class [netstandard]System.Func`1<string> '<>9__1'
// Methods
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x20a5
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [netstandard]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method '<>c__DisplayClass0_0'::.ctor
.method assembly hidebysig
instance string '<F>b__0' () cil managed
{
// Method begins at RVA 0x20b0
// Code size 78 (0x4e)
.maxstack 3
.locals init (
[0] string,
[1] class [netstandard]System.Func`1<string>
)
IL_0000: ldc.i4.1
IL_0001: brtrue.s IL_0004
IL_0003: nop
IL_0004: ldarg.0
IL_0005: ldfld int32 C/'<>c__DisplayClass0_0'::'<i>5__2'
IL_000a: ldc.i4.1
IL_000b: beq.s IL_000f
IL_000d: br.s IL_0036
IL_000f: ldarg.0
IL_0010: ldfld class [netstandard]System.Func`1<string> C/'<>c__DisplayClass0_0'::'<>9__1'
IL_0015: dup
IL_0016: brtrue.s IL_002e
IL_0018: pop
IL_0019: ldarg.0
IL_001a: ldarg.0
IL_001b: ldftn instance string C/'<>c__DisplayClass0_0'::'<F>b__1'()
IL_0021: newobj instance void class [netstandard]System.Func`1<string>::.ctor(object, native int)
IL_0026: dup
IL_0027: stloc.1
IL_0028: stfld class [netstandard]System.Func`1<string> C/'<>c__DisplayClass0_0'::'<>9__1'
IL_002d: ldloc.1
IL_002e: callvirt instance !0 class [netstandard]System.Func`1<string>::Invoke()
IL_0033: stloc.0
IL_0034: br.s IL_003e
IL_0036: ldstr ""3""
IL_003b: stloc.0
IL_003c: br.s IL_003e
IL_003e: ldc.i4.1
IL_003f: brtrue.s IL_0042
IL_0041: nop
IL_0042: ldstr ""1""
IL_0047: ldloc.0
IL_0048: call string [netstandard]System.String::Concat(string, string)
IL_004d: ret
} // end of method '<>c__DisplayClass0_0'::'<F>b__0'
.method assembly hidebysig
instance string '<F>b__1' () cil managed
{
// Method begins at RVA 0x210a
// Code size 22 (0x16)
.maxstack 8
IL_0000: ldstr ""2""
IL_0005: ldarg.0
IL_0006: ldflda int32 C/'<>c__DisplayClass0_0'::'<i>5__2'
IL_000b: call instance string [netstandard]System.Int32::ToString()
IL_0010: call string [netstandard]System.String::Concat(string, string)
IL_0015: ret
} // end of method '<>c__DisplayClass0_0'::'<F>b__1'
} // end of class <>c__DisplayClass0_0
// Methods
.method private hidebysig static
string F (
object o
) cil managed
{
// Method begins at RVA 0x2050
// Code size 73 (0x49)
.maxstack 2
.locals init (
[0] class C/'<>c__DisplayClass0_0',
[1] string,
[2] string
)
IL_0000: nop
IL_0001: newobj instance void C/'<>c__DisplayClass0_0'::.ctor()
IL_0006: stloc.0
IL_0007: ldc.i4.1
IL_0008: brtrue.s IL_000b
IL_000a: nop
IL_000b: ldarg.0
IL_000c: isinst [netstandard]System.Int32
IL_0011: brfalse.s IL_0037
IL_0013: ldloc.0
IL_0014: ldarg.0
IL_0015: unbox.any [netstandard]System.Int32
IL_001a: stfld int32 C/'<>c__DisplayClass0_0'::'<i>5__2'
IL_001f: br.s IL_0021
IL_0021: br.s IL_0023
IL_0023: ldloc.0
IL_0024: ldftn instance string C/'<>c__DisplayClass0_0'::'<F>b__0'()
IL_002a: newobj instance void class [netstandard]System.Func`1<string>::.ctor(object, native int)
IL_002f: callvirt instance !0 class [netstandard]System.Func`1<string>::Invoke()
IL_0034: stloc.1
IL_0035: br.s IL_003f
IL_0037: ldstr ""4""
IL_003c: stloc.1
IL_003d: br.s IL_003f
IL_003f: ldc.i4.1
IL_0040: brtrue.s IL_0043
IL_0042: nop
IL_0043: ldloc.1
IL_0044: stloc.2
IL_0045: br.s IL_0047
IL_0047: ldloc.2
IL_0048: ret
} // end of method C::F
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x20a5
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [netstandard]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method C::.ctor
} // end of class C
");
verifier.VerifyPdb(
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"" parameterNames=""o"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""30"" offset=""11"" />
<slot kind=""temp"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""11"" />
<lambda offset=""83"" closure=""0"" />
<lambda offset=""158"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" hidden=""true"" document=""1"" />
<entry offset=""0xa"" startLine=""6"" startColumn=""18"" endLine=""14"" endColumn=""10"" document=""1"" />
<entry offset=""0xb"" hidden=""true"" document=""1"" />
<entry offset=""0x1f"" hidden=""true"" document=""1"" />
<entry offset=""0x21"" hidden=""true"" document=""1"" />
<entry offset=""0x23"" startLine=""8"" startColumn=""22"" endLine=""12"" endColumn=""17"" document=""1"" />
<entry offset=""0x37"" startLine=""13"" startColumn=""18"" endLine=""13"" endColumn=""21"" document=""1"" />
<entry offset=""0x3f"" hidden=""true"" document=""1"" />
<entry offset=""0x42"" startLine=""6"" startColumn=""9"" endLine=""14"" endColumn=""11"" document=""1"" />
<entry offset=""0x43"" hidden=""true"" document=""1"" />
<entry offset=""0x47"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x49"">
<namespace name=""System"" />
<scope startOffset=""0x1"" endOffset=""0x47"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x1"" il_end=""0x47"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""C+<>c__DisplayClass0_0"" name=""<F>b__0"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" parameterNames=""o"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""45"" endLine=""12"" endColumn=""14"" document=""1"" />
<entry offset=""0x3"" startLine=""8"" startColumn=""53"" endLine=""12"" endColumn=""14"" document=""1"" />
<entry offset=""0x4"" hidden=""true"" document=""1"" />
<entry offset=""0xf"" startLine=""10"" startColumn=""22"" endLine=""10"" endColumn=""55"" document=""1"" />
<entry offset=""0x36"" startLine=""11"" startColumn=""22"" endLine=""11"" endColumn=""25"" document=""1"" />
<entry offset=""0x3e"" hidden=""true"" document=""1"" />
<entry offset=""0x41"" startLine=""8"" startColumn=""45"" endLine=""12"" endColumn=""14"" document=""1"" />
<entry offset=""0x42"" hidden=""true"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""C+<>c__DisplayClass0_0"" name=""<F>b__1"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" parameterNames=""o"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""45"" endLine=""10"" endColumn=""52"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(37261, "https://github.com/dotnet/roslyn/issues/37261")]
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SwitchExpression_MethodBody()
{
string source = @"
using System;
public class C
{
static int M() => F() switch
{
1 => 1,
C { P: int p, Q: C { P: int q } } => G(() => p + q),
_ => 0
};
object P { get; set; }
object Q { get; set; }
static object F() => null;
static int G(Func<int> f) => 0;
}
";
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var verifier = CompileAndVerify(c);
verifier.VerifyIL("C.M", sequencePoints: "C.M", source: source, expectedIL: @"
{
// Code size 171 (0xab)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
int V_1,
object V_2,
int V_3,
C V_4,
object V_5,
object V_6,
C V_7,
object V_8)
// sequence point: <hidden>
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: call ""object C.F()""
IL_000b: stloc.2
IL_000c: ldc.i4.1
IL_000d: brtrue.s IL_0010
// sequence point: switch ... }
IL_000f: nop
// sequence point: <hidden>
IL_0010: ldloc.2
IL_0011: isinst ""int""
IL_0016: brfalse.s IL_0025
IL_0018: ldloc.2
IL_0019: unbox.any ""int""
IL_001e: stloc.3
// sequence point: <hidden>
IL_001f: ldloc.3
IL_0020: ldc.i4.1
IL_0021: beq.s IL_0087
IL_0023: br.s IL_00a1
IL_0025: ldloc.2
IL_0026: isinst ""C""
IL_002b: stloc.s V_4
IL_002d: ldloc.s V_4
IL_002f: brfalse.s IL_00a1
IL_0031: ldloc.s V_4
IL_0033: callvirt ""object C.P.get""
IL_0038: stloc.s V_5
// sequence point: <hidden>
IL_003a: ldloc.s V_5
IL_003c: isinst ""int""
IL_0041: brfalse.s IL_00a1
IL_0043: ldloc.0
IL_0044: ldloc.s V_5
IL_0046: unbox.any ""int""
IL_004b: stfld ""int C.<>c__DisplayClass0_0.<p>5__2""
// sequence point: <hidden>
IL_0050: ldloc.s V_4
IL_0052: callvirt ""object C.Q.get""
IL_0057: stloc.s V_6
// sequence point: <hidden>
IL_0059: ldloc.s V_6
IL_005b: isinst ""C""
IL_0060: stloc.s V_7
IL_0062: ldloc.s V_7
IL_0064: brfalse.s IL_00a1
IL_0066: ldloc.s V_7
IL_0068: callvirt ""object C.P.get""
IL_006d: stloc.s V_8
// sequence point: <hidden>
IL_006f: ldloc.s V_8
IL_0071: isinst ""int""
IL_0076: brfalse.s IL_00a1
IL_0078: ldloc.0
IL_0079: ldloc.s V_8
IL_007b: unbox.any ""int""
IL_0080: stfld ""int C.<>c__DisplayClass0_0.<q>5__3""
// sequence point: <hidden>
IL_0085: br.s IL_008b
// sequence point: 1
IL_0087: ldc.i4.1
IL_0088: stloc.1
IL_0089: br.s IL_00a5
// sequence point: <hidden>
IL_008b: br.s IL_008d
// sequence point: G(() => p + q)
IL_008d: ldloc.0
IL_008e: ldftn ""int C.<>c__DisplayClass0_0.<M>b__0()""
IL_0094: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_0099: call ""int C.G(System.Func<int>)""
IL_009e: stloc.1
IL_009f: br.s IL_00a5
// sequence point: 0
IL_00a1: ldc.i4.0
IL_00a2: stloc.1
IL_00a3: br.s IL_00a5
// sequence point: <hidden>
IL_00a5: ldc.i4.1
IL_00a6: brtrue.s IL_00a9
// sequence point: F() switch ... }
IL_00a8: nop
// sequence point: <hidden>
IL_00a9: ldloc.1
IL_00aa: ret
}
");
verifier.VerifyPdb("C.M", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""30"" offset=""7"" />
<slot kind=""temp"" />
<slot kind=""35"" offset=""7"" />
<slot kind=""35"" offset=""7"" ordinal=""1"" />
<slot kind=""35"" offset=""7"" ordinal=""2"" />
<slot kind=""35"" offset=""7"" ordinal=""3"" />
<slot kind=""35"" offset=""7"" ordinal=""4"" />
<slot kind=""35"" offset=""7"" ordinal=""5"" />
<slot kind=""35"" offset=""7"" ordinal=""6"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""7"" />
<lambda offset=""92"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0xf"" startLine=""5"" startColumn=""27"" endLine=""10"" endColumn=""6"" document=""1"" />
<entry offset=""0x10"" hidden=""true"" document=""1"" />
<entry offset=""0x1f"" hidden=""true"" document=""1"" />
<entry offset=""0x3a"" hidden=""true"" document=""1"" />
<entry offset=""0x50"" hidden=""true"" document=""1"" />
<entry offset=""0x59"" hidden=""true"" document=""1"" />
<entry offset=""0x6f"" hidden=""true"" document=""1"" />
<entry offset=""0x85"" hidden=""true"" document=""1"" />
<entry offset=""0x87"" startLine=""7"" startColumn=""14"" endLine=""7"" endColumn=""15"" document=""1"" />
<entry offset=""0x8b"" hidden=""true"" document=""1"" />
<entry offset=""0x8d"" startLine=""8"" startColumn=""46"" endLine=""8"" endColumn=""60"" document=""1"" />
<entry offset=""0xa1"" startLine=""9"" startColumn=""14"" endLine=""9"" endColumn=""15"" document=""1"" />
<entry offset=""0xa5"" hidden=""true"" document=""1"" />
<entry offset=""0xa8"" startLine=""5"" startColumn=""23"" endLine=""10"" endColumn=""6"" document=""1"" />
<entry offset=""0xa9"" hidden=""true"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xab"">
<namespace name=""System"" />
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0xab"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(37261, "https://github.com/dotnet/roslyn/issues/37261")]
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SwitchExpression_MethodBody_02()
{
string source = @"
using System;
public class C
{
static Action M1(int x) => () => { _ = x; };
static Action M2(int x) => x switch { _ => () => { _ = x; } };
}
";
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var verifier = CompileAndVerify(c);
verifier.VerifyIL("C.M1", sequencePoints: "C.M1", source: source, expectedIL: @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0
// sequence point: <hidden>
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldarg.0
IL_0008: stfld ""int C.<>c__DisplayClass0_0.x""
// sequence point: () => { _ = x; }
IL_000d: ldloc.0
IL_000e: ldftn ""void C.<>c__DisplayClass0_0.<M1>b__0()""
IL_0014: newobj ""System.Action..ctor(object, System.IntPtr)""
IL_0019: ret
}
");
verifier.VerifyIL("C.M2", sequencePoints: "C.M2", source: source, expectedIL: @"
{
// Code size 40 (0x28)
.maxstack 2
.locals init (C.<>c__DisplayClass1_0 V_0, //CS$<>8__locals0
System.Action V_1)
// sequence point: <hidden>
IL_0000: newobj ""C.<>c__DisplayClass1_0..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldarg.0
IL_0008: stfld ""int C.<>c__DisplayClass1_0.x""
// sequence point: x switch { _ => () => { _ = x; } }
IL_000d: ldc.i4.1
IL_000e: brtrue.s IL_0011
// sequence point: switch { _ => () => { _ = x; } }
IL_0010: nop
// sequence point: <hidden>
IL_0011: br.s IL_0013
// sequence point: () => { _ = x; }
IL_0013: ldloc.0
IL_0014: ldftn ""void C.<>c__DisplayClass1_0.<M2>b__0()""
IL_001a: newobj ""System.Action..ctor(object, System.IntPtr)""
IL_001f: stloc.1
IL_0020: br.s IL_0022
// sequence point: <hidden>
IL_0022: ldc.i4.1
IL_0023: brtrue.s IL_0026
// sequence point: x switch { _ => () => { _ = x; } }
IL_0025: nop
// sequence point: <hidden>
IL_0026: ldloc.1
IL_0027: ret
}
");
verifier.VerifyPdb("C.M1", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M1"" parameterNames=""x"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""30"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""0"" />
<lambda offset=""9"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""5"" startColumn=""32"" endLine=""5"" endColumn=""48"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1a"">
<namespace name=""System"" />
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x1a"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
verifier.VerifyPdb("C.M2", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M2"" parameterNames=""x"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""M1"" parameterNames=""x"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""0"" />
<slot kind=""temp"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>1</methodOrdinal>
<closure offset=""0"" />
<lambda offset=""25"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0xd"" startLine=""6"" startColumn=""32"" endLine=""6"" endColumn=""66"" document=""1"" />
<entry offset=""0x10"" startLine=""6"" startColumn=""34"" endLine=""6"" endColumn=""66"" document=""1"" />
<entry offset=""0x11"" hidden=""true"" document=""1"" />
<entry offset=""0x13"" startLine=""6"" startColumn=""48"" endLine=""6"" endColumn=""64"" document=""1"" />
<entry offset=""0x22"" hidden=""true"" document=""1"" />
<entry offset=""0x25"" startLine=""6"" startColumn=""32"" endLine=""6"" endColumn=""66"" document=""1"" />
<entry offset=""0x26"" hidden=""true"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x28"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x28"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SyntaxOffset_OutVarInInitializers_SwitchExpression()
{
var source =
@"class C
{
static int G(out int x) => throw null;
static int F(System.Func<int> x) => throw null;
C() { }
int y1 = G(out var z) switch { _ => F(() => z) }; // line 7
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""-26"" />
<slot kind=""temp"" />
<slot kind=""35"" offset=""-26"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>2</methodOrdinal>
<closure offset=""-26"" />
<lambda offset=""-4"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x6"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""54"" document=""1"" />
<entry offset=""0x15"" startLine=""7"" startColumn=""27"" endLine=""7"" endColumn=""53"" document=""1"" />
<entry offset=""0x16"" hidden=""true"" document=""1"" />
<entry offset=""0x18"" startLine=""7"" startColumn=""41"" endLine=""7"" endColumn=""51"" document=""1"" />
<entry offset=""0x2c"" hidden=""true"" document=""1"" />
<entry offset=""0x2f"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""54"" document=""1"" />
<entry offset=""0x30"" hidden=""true"" document=""1"" />
<entry offset=""0x37"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""8"" document=""1"" />
<entry offset=""0x3e"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""10"" document=""1"" />
<entry offset=""0x3f"" startLine=""5"" startColumn=""11"" endLine=""5"" endColumn=""12"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x40"">
<scope startOffset=""0x0"" endOffset=""0x37"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x37"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(43468, "https://github.com/dotnet/roslyn/issues/43468")]
[Fact]
public void HiddenSequencePointAtSwitchExpressionFinalMergePoint()
{
var source =
@"class C
{
static int M(int x)
{
var y = x switch
{
1 => 2,
_ => 3,
};
return y;
}
}
";
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var verifier = CompileAndVerify(c);
verifier.VerifyIL("C.M", sequencePoints: "C.M", source: source, expectedIL: @"
{
// Code size 31 (0x1f)
.maxstack 2
.locals init (int V_0, //y
int V_1,
int V_2)
// sequence point: {
IL_0000: nop
// sequence point: var y = x sw ... };
IL_0001: ldc.i4.1
IL_0002: brtrue.s IL_0005
// sequence point: switch ... }
IL_0004: nop
// sequence point: <hidden>
IL_0005: ldarg.0
IL_0006: ldc.i4.1
IL_0007: beq.s IL_000b
IL_0009: br.s IL_000f
// sequence point: 2
IL_000b: ldc.i4.2
IL_000c: stloc.1
IL_000d: br.s IL_0013
// sequence point: 3
IL_000f: ldc.i4.3
IL_0010: stloc.1
IL_0011: br.s IL_0013
// sequence point: <hidden>
IL_0013: ldc.i4.1
IL_0014: brtrue.s IL_0017
// sequence point: var y = x sw ... };
IL_0016: nop
// sequence point: <hidden>
IL_0017: ldloc.1
IL_0018: stloc.0
// sequence point: return y;
IL_0019: ldloc.0
IL_001a: stloc.2
IL_001b: br.s IL_001d
// sequence point: }
IL_001d: ldloc.2
IL_001e: ret
}
");
}
[WorkItem(12378, "https://github.com/dotnet/roslyn/issues/12378")]
[WorkItem(13971, "https://github.com/dotnet/roslyn/issues/13971")]
[Fact]
public void Patterns_SwitchStatement_Constant()
{
string source = WithWindowsLineBreaks(
@"class Program
{
static void M(object o)
{
switch (o)
{
case 1 when o == null:
case 4:
case 2 when o == null:
break;
case 1 when o != null:
case 5:
case 3 when o != null:
break;
default:
break;
case 1:
break;
}
switch (o)
{
case 1:
break;
default:
break;
}
switch (o)
{
default:
break;
}
}
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
CompileAndVerify(c).VerifyIL(qualifiedMethodName: "Program.M", sequencePoints: "Program.M", source: source,
expectedIL: @"{
// Code size 123 (0x7b)
.maxstack 2
.locals init (object V_0,
int V_1,
object V_2,
object V_3,
int V_4,
object V_5,
object V_6,
object V_7)
// sequence point: {
IL_0000: nop
// sequence point: switch (o)
IL_0001: ldarg.0
IL_0002: stloc.2
// sequence point: <hidden>
IL_0003: ldloc.2
IL_0004: stloc.0
// sequence point: <hidden>
IL_0005: ldloc.0
IL_0006: isinst ""int""
IL_000b: brfalse.s IL_004a
IL_000d: ldloc.0
IL_000e: unbox.any ""int""
IL_0013: stloc.1
// sequence point: <hidden>
IL_0014: ldloc.1
IL_0015: ldc.i4.1
IL_0016: sub
IL_0017: switch (
IL_0032,
IL_0037,
IL_0043,
IL_003c,
IL_0048)
IL_0030: br.s IL_004a
// sequence point: when o == null
IL_0032: ldarg.0
IL_0033: brfalse.s IL_003c
// sequence point: <hidden>
IL_0035: br.s IL_003e
// sequence point: when o == null
IL_0037: ldarg.0
IL_0038: brfalse.s IL_003c
// sequence point: <hidden>
IL_003a: br.s IL_004a
// sequence point: break;
IL_003c: br.s IL_004e
// sequence point: when o != null
IL_003e: ldarg.0
IL_003f: brtrue.s IL_0048
// sequence point: <hidden>
IL_0041: br.s IL_004c
// sequence point: when o != null
IL_0043: ldarg.0
IL_0044: brtrue.s IL_0048
// sequence point: <hidden>
IL_0046: br.s IL_004a
// sequence point: break;
IL_0048: br.s IL_004e
// sequence point: break;
IL_004a: br.s IL_004e
// sequence point: break;
IL_004c: br.s IL_004e
// sequence point: switch (o)
IL_004e: ldarg.0
IL_004f: stloc.s V_5
// sequence point: <hidden>
IL_0051: ldloc.s V_5
IL_0053: stloc.3
// sequence point: <hidden>
IL_0054: ldloc.3
IL_0055: isinst ""int""
IL_005a: brfalse.s IL_006d
IL_005c: ldloc.3
IL_005d: unbox.any ""int""
IL_0062: stloc.s V_4
// sequence point: <hidden>
IL_0064: ldloc.s V_4
IL_0066: ldc.i4.1
IL_0067: beq.s IL_006b
IL_0069: br.s IL_006d
// sequence point: break;
IL_006b: br.s IL_006f
// sequence point: break;
IL_006d: br.s IL_006f
// sequence point: switch (o)
IL_006f: ldarg.0
IL_0070: stloc.s V_7
// sequence point: <hidden>
IL_0072: ldloc.s V_7
IL_0074: stloc.s V_6
// sequence point: <hidden>
IL_0076: br.s IL_0078
// sequence point: break;
IL_0078: br.s IL_007a
// sequence point: }
IL_007a: ret
}");
c.VerifyPdb(
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""M"" parameterNames=""o"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""35"" offset=""11"" />
<slot kind=""35"" offset=""11"" ordinal=""1"" />
<slot kind=""1"" offset=""11"" />
<slot kind=""35"" offset=""378"" />
<slot kind=""35"" offset=""378"" ordinal=""1"" />
<slot kind=""1"" offset=""378"" />
<slot kind=""35"" offset=""511"" />
<slot kind=""1"" offset=""511"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""19"" document=""1"" />
<entry offset=""0x3"" hidden=""true"" document=""1"" />
<entry offset=""0x5"" hidden=""true"" document=""1"" />
<entry offset=""0x14"" hidden=""true"" document=""1"" />
<entry offset=""0x32"" startLine=""7"" startColumn=""20"" endLine=""7"" endColumn=""34"" document=""1"" />
<entry offset=""0x35"" hidden=""true"" document=""1"" />
<entry offset=""0x37"" startLine=""9"" startColumn=""20"" endLine=""9"" endColumn=""34"" document=""1"" />
<entry offset=""0x3a"" hidden=""true"" document=""1"" />
<entry offset=""0x3c"" startLine=""10"" startColumn=""17"" endLine=""10"" endColumn=""23"" document=""1"" />
<entry offset=""0x3e"" startLine=""11"" startColumn=""20"" endLine=""11"" endColumn=""34"" document=""1"" />
<entry offset=""0x41"" hidden=""true"" document=""1"" />
<entry offset=""0x43"" startLine=""13"" startColumn=""20"" endLine=""13"" endColumn=""34"" document=""1"" />
<entry offset=""0x46"" hidden=""true"" document=""1"" />
<entry offset=""0x48"" startLine=""14"" startColumn=""17"" endLine=""14"" endColumn=""23"" document=""1"" />
<entry offset=""0x4a"" startLine=""16"" startColumn=""17"" endLine=""16"" endColumn=""23"" document=""1"" />
<entry offset=""0x4c"" startLine=""18"" startColumn=""17"" endLine=""18"" endColumn=""23"" document=""1"" />
<entry offset=""0x4e"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""19"" document=""1"" />
<entry offset=""0x51"" hidden=""true"" document=""1"" />
<entry offset=""0x54"" hidden=""true"" document=""1"" />
<entry offset=""0x64"" hidden=""true"" document=""1"" />
<entry offset=""0x6b"" startLine=""23"" startColumn=""17"" endLine=""23"" endColumn=""23"" document=""1"" />
<entry offset=""0x6d"" startLine=""25"" startColumn=""17"" endLine=""25"" endColumn=""23"" document=""1"" />
<entry offset=""0x6f"" startLine=""27"" startColumn=""9"" endLine=""27"" endColumn=""19"" document=""1"" />
<entry offset=""0x72"" hidden=""true"" document=""1"" />
<entry offset=""0x76"" hidden=""true"" document=""1"" />
<entry offset=""0x78"" startLine=""30"" startColumn=""17"" endLine=""30"" endColumn=""23"" document=""1"" />
<entry offset=""0x7a"" startLine=""32"" startColumn=""5"" endLine=""32"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")]
[Fact]
public void Patterns_SwitchStatement_Tuple()
{
string source = WithWindowsLineBreaks(@"
public class C
{
static int F(int i)
{
switch (G())
{
case (1, 2): return 3;
default: return 0;
};
}
static (object, object) G() => (2, 3);
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: s_valueTupleRefs);
var cv = CompileAndVerify(c);
cv.VerifyIL("C.F", @"
{
// Code size 80 (0x50)
.maxstack 2
.locals init (System.ValueTuple<object, object> V_0,
object V_1,
int V_2,
object V_3,
int V_4,
System.ValueTuple<object, object> V_5,
int V_6)
IL_0000: nop
IL_0001: call ""System.ValueTuple<object, object> C.G()""
IL_0006: stloc.s V_5
IL_0008: ldloc.s V_5
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: ldfld ""object System.ValueTuple<object, object>.Item1""
IL_0011: stloc.1
IL_0012: ldloc.1
IL_0013: isinst ""int""
IL_0018: brfalse.s IL_0048
IL_001a: ldloc.1
IL_001b: unbox.any ""int""
IL_0020: stloc.2
IL_0021: ldloc.2
IL_0022: ldc.i4.1
IL_0023: bne.un.s IL_0048
IL_0025: ldloc.0
IL_0026: ldfld ""object System.ValueTuple<object, object>.Item2""
IL_002b: stloc.3
IL_002c: ldloc.3
IL_002d: isinst ""int""
IL_0032: brfalse.s IL_0048
IL_0034: ldloc.3
IL_0035: unbox.any ""int""
IL_003a: stloc.s V_4
IL_003c: ldloc.s V_4
IL_003e: ldc.i4.2
IL_003f: beq.s IL_0043
IL_0041: br.s IL_0048
IL_0043: ldc.i4.3
IL_0044: stloc.s V_6
IL_0046: br.s IL_004d
IL_0048: ldc.i4.0
IL_0049: stloc.s V_6
IL_004b: br.s IL_004d
IL_004d: ldloc.s V_6
IL_004f: ret
}
");
c.VerifyPdb("C.F", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"" parameterNames=""i"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""35"" offset=""11"" />
<slot kind=""35"" offset=""11"" ordinal=""1"" />
<slot kind=""35"" offset=""11"" ordinal=""2"" />
<slot kind=""35"" offset=""11"" ordinal=""3"" />
<slot kind=""35"" offset=""11"" ordinal=""4"" />
<slot kind=""1"" offset=""11"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""21"" document=""1"" />
<entry offset=""0x8"" hidden=""true"" document=""1"" />
<entry offset=""0xb"" hidden=""true"" document=""1"" />
<entry offset=""0x12"" hidden=""true"" document=""1"" />
<entry offset=""0x21"" hidden=""true"" document=""1"" />
<entry offset=""0x2c"" hidden=""true"" document=""1"" />
<entry offset=""0x3c"" hidden=""true"" document=""1"" />
<entry offset=""0x43"" startLine=""8"" startColumn=""26"" endLine=""8"" endColumn=""35"" document=""1"" />
<entry offset=""0x48"" startLine=""9"" startColumn=""22"" endLine=""9"" endColumn=""31"" document=""1"" />
<entry offset=""0x4d"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
#endregion
#region Tuples
[Fact]
public void SyntaxOffset_TupleDeconstruction()
{
var source = @"class C { int F() { (int a, (_, int c)) = (1, (2, 3)); return a + c; } }";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: s_valueTupleRefs);
c.VerifyPdb("C.F", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""7"" />
<slot kind=""0"" offset=""18"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""19"" endLine=""1"" endColumn=""20"" document=""1"" />
<entry offset=""0x1"" startLine=""1"" startColumn=""21"" endLine=""1"" endColumn=""55"" document=""1"" />
<entry offset=""0x5"" startLine=""1"" startColumn=""56"" endLine=""1"" endColumn=""69"" document=""1"" />
<entry offset=""0xb"" startLine=""1"" startColumn=""70"" endLine=""1"" endColumn=""71"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xd"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0xd"" attributes=""0"" />
<local name=""c"" il_index=""1"" il_start=""0x0"" il_end=""0xd"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void TestDeconstruction()
{
var source = @"
public class C
{
public static (int, int) F() => (1, 2);
public static void Main()
{
int x, y;
(x, y) = F();
System.Console.WriteLine(x + y);
}
}
";
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C.Main", @"
{
// Code size 29 (0x1d)
.maxstack 2
.locals init (int V_0, //x
int V_1) //y
// sequence point: {
IL_0000: nop
// sequence point: (x, y) = F();
IL_0001: call ""System.ValueTuple<int, int> C.F()""
IL_0006: dup
IL_0007: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_000c: stloc.0
IL_000d: ldfld ""int System.ValueTuple<int, int>.Item2""
IL_0012: stloc.1
// sequence point: System.Console.WriteLine(x + y);
IL_0013: ldloc.0
IL_0014: ldloc.1
IL_0015: add
IL_0016: call ""void System.Console.WriteLine(int)""
IL_001b: nop
// sequence point: }
IL_001c: ret
}
", sequencePoints: "C.Main", source: source);
}
[Fact]
public void SyntaxOffset_TupleParenthesized()
{
var source = @"class C { int F() { (int, (int, int)) x = (1, (2, 3)); return x.Item1 + x.Item2.Item1 + x.Item2.Item2; } }";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: s_valueTupleRefs);
c.VerifyPdb("C.F", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""20"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""19"" endLine=""1"" endColumn=""20"" document=""1"" />
<entry offset=""0x1"" startLine=""1"" startColumn=""21"" endLine=""1"" endColumn=""55"" document=""1"" />
<entry offset=""0x10"" startLine=""1"" startColumn=""56"" endLine=""1"" endColumn=""103"" document=""1"" />
<entry offset=""0x31"" startLine=""1"" startColumn=""104"" endLine=""1"" endColumn=""105"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x33"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x33"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>"
);
}
[Fact]
public void SyntaxOffset_TupleVarDefined()
{
var source = @"class C { int F() { var x = (1, 2); return x.Item1 + x.Item2; } }";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: s_valueTupleRefs);
c.VerifyPdb("C.F", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""6"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""19"" endLine=""1"" endColumn=""20"" document=""1"" />
<entry offset=""0x1"" startLine=""1"" startColumn=""21"" endLine=""1"" endColumn=""36"" document=""1"" />
<entry offset=""0xa"" startLine=""1"" startColumn=""37"" endLine=""1"" endColumn=""62"" document=""1"" />
<entry offset=""0x1a"" startLine=""1"" startColumn=""63"" endLine=""1"" endColumn=""64"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1c"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void SyntaxOffset_TupleIgnoreDeconstructionIfVariableDeclared()
{
var source = @"class C { int F() { (int x, int y) a = (1, 2); return a.Item1 + a.Item2; } }";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: s_valueTupleRefs);
c.VerifyPdb("C.F", @"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<tupleElementNames>
<local elementNames=""|x|y"" slotIndex=""0"" localName=""a"" scopeStart=""0x0"" scopeEnd=""0x0"" />
</tupleElementNames>
<encLocalSlotMap>
<slot kind=""0"" offset=""17"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""19"" endLine=""1"" endColumn=""20"" document=""1"" />
<entry offset=""0x1"" startLine=""1"" startColumn=""21"" endLine=""1"" endColumn=""47"" document=""1"" />
<entry offset=""0x9"" startLine=""1"" startColumn=""48"" endLine=""1"" endColumn=""73"" document=""1"" />
<entry offset=""0x19"" startLine=""1"" startColumn=""74"" endLine=""1"" endColumn=""75"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1b"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x1b"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
#endregion
#region OutVar
[Fact]
public void SyntaxOffset_OutVarInConstructor()
{
var source = @"
class B
{
B(out int z) { z = 2; }
}
class C
{
int F = G(out var v1);
int P => G(out var v2);
C()
: base(out var v3)
{
G(out var v4);
}
int G(out int x)
{
x = 1;
return 2;
}
}
";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyDiagnostics(
// (9,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'C.G(out int)'
// int F = G(out var v1);
Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "G").WithArguments("C.G(out int)").WithLocation(9, 13),
// (13,7): error CS1729: 'object' does not contain a constructor that takes 1 arguments
// : base(out var v3)
Diagnostic(ErrorCode.ERR_BadCtorArgCount, "base").WithArguments("object", "1").WithLocation(13, 7));
}
[Fact]
public void SyntaxOffset_OutVarInMethod()
{
var source = @"class C { int G(out int x) { int z = 1; G(out var y); G(out var w); return x = y; } }";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.G", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""G"" parameterNames=""x"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""6"" />
<slot kind=""0"" offset=""23"" />
<slot kind=""0"" offset=""37"" />
<slot kind=""temp"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""28"" endLine=""1"" endColumn=""29"" document=""1"" />
<entry offset=""0x1"" startLine=""1"" startColumn=""30"" endLine=""1"" endColumn=""40"" document=""1"" />
<entry offset=""0x3"" startLine=""1"" startColumn=""41"" endLine=""1"" endColumn=""54"" document=""1"" />
<entry offset=""0xc"" startLine=""1"" startColumn=""55"" endLine=""1"" endColumn=""68"" document=""1"" />
<entry offset=""0x15"" startLine=""1"" startColumn=""69"" endLine=""1"" endColumn=""82"" document=""1"" />
<entry offset=""0x1f"" startLine=""1"" startColumn=""83"" endLine=""1"" endColumn=""84"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x22"">
<local name=""z"" il_index=""0"" il_start=""0x0"" il_end=""0x22"" attributes=""0"" />
<local name=""y"" il_index=""1"" il_start=""0x0"" il_end=""0x22"" attributes=""0"" />
<local name=""w"" il_index=""2"" il_start=""0x0"" il_end=""0x22"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInInitializers_01()
{
var source = WithWindowsLineBreaks(
@"
class C : A
{
int x = G(out var x);
int y {get;} = G(out var y);
C() : base(G(out var z))
{
}
static int G(out int x)
{
throw null;
}
}
class A
{
public A(int x) {}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""-36"" />
<slot kind=""0"" offset=""-22"" />
<slot kind=""0"" offset=""-3"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""26"" document=""1"" />
<entry offset=""0xd"" startLine=""5"" startColumn=""20"" endLine=""5"" endColumn=""32"" document=""1"" />
<entry offset=""0x1a"" startLine=""7"" startColumn=""11"" endLine=""7"" endColumn=""29"" document=""1"" />
<entry offset=""0x28"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
<entry offset=""0x29"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2a"">
<scope startOffset=""0x0"" endOffset=""0xd"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0xd"" attributes=""0"" />
</scope>
<scope startOffset=""0xd"" endOffset=""0x1a"">
<local name=""y"" il_index=""1"" il_start=""0xd"" il_end=""0x1a"" attributes=""0"" />
</scope>
<scope startOffset=""0x1a"" endOffset=""0x2a"">
<local name=""z"" il_index=""2"" il_start=""0x1a"" il_end=""0x2a"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInInitializers_02()
{
var source = WithWindowsLineBreaks(
@"
class C : A
{
C() : base(G(out var x))
{
int y = 1;
y++;
}
static int G(out int x)
{
throw null;
}
}
class A
{
public A(int x) {}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""-3"" />
<slot kind=""0"" offset=""16"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""11"" endLine=""4"" endColumn=""29"" document=""1"" />
<entry offset=""0xe"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0xf"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""19"" document=""1"" />
<entry offset=""0x11"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""13"" document=""1"" />
<entry offset=""0x15"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x16"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x16"" attributes=""0"" />
<scope startOffset=""0xe"" endOffset=""0x16"">
<local name=""y"" il_index=""1"" il_start=""0xe"" il_end=""0x16"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInInitializers_03()
{
var source = WithWindowsLineBreaks(
@"
class C : A
{
C() : base(G(out var x))
=> G(out var y);
static int G(out int x)
{
throw null;
}
}
class A
{
public A(int x) {}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""-3"" />
<slot kind=""0"" offset=""13"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""11"" endLine=""4"" endColumn=""29"" document=""1"" />
<entry offset=""0xe"" startLine=""5"" startColumn=""8"" endLine=""5"" endColumn=""20"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x17"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x17"" attributes=""0"" />
<scope startOffset=""0xe"" endOffset=""0x17"">
<local name=""y"" il_index=""1"" il_start=""0xe"" il_end=""0x17"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInInitializers_04()
{
var source = WithWindowsLineBreaks(
@"
class C
{
static int G(out int x)
{
throw null;
}
static int F(System.Func<int> x)
{
throw null;
}
C()
{
}
#line 2000
int y1 = G(out var z) + F(() => z);
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""-25"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>2</methodOrdinal>
<closure offset=""-25"" />
<lambda offset=""-2"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x6"" startLine=""2000"" startColumn=""5"" endLine=""2000"" endColumn=""40"" document=""1"" />
<entry offset=""0x29"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""8"" document=""1"" />
<entry offset=""0x30"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" />
<entry offset=""0x31"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x32"">
<scope startOffset=""0x0"" endOffset=""0x29"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x29"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c__DisplayClass2_0.<.ctor>b__0", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c__DisplayClass2_0"" name=""<.ctor>b__0"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""2000"" startColumn=""37"" endLine=""2000"" endColumn=""38"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInInitializers_05()
{
var source = WithWindowsLineBreaks(
@"
class C
{
static int G(out int x)
{
throw null;
}
static int F(System.Func<int> x)
{
throw null;
}
#line 2000
int y1 { get; } = G(out var z) + F(() => z);
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""-25"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>5</methodOrdinal>
<closure offset=""-25"" />
<lambda offset=""-2"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x6"" startLine=""2000"" startColumn=""23"" endLine=""2000"" endColumn=""48"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x31"">
<scope startOffset=""0x0"" endOffset=""0x29"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x29"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c__DisplayClass5_0.<.ctor>b__0", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c__DisplayClass5_0"" name=""<.ctor>b__0"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""2000"" startColumn=""46"" endLine=""2000"" endColumn=""47"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInInitializers_06()
{
var source = WithWindowsLineBreaks(
@"
class C
{
static int G(out int x)
{
throw null;
}
static int F(System.Func<int> x)
{
throw null;
}
#line 2000
int y1 = G(out var z) + F(() => z), y2 = G(out var u) + F(() => u);
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
var v = CompileAndVerify(c);
v.VerifyIL("C..ctor", sequencePoints: "C..ctor", expectedIL: @"
{
// Code size 90 (0x5a)
.maxstack 4
.locals init (C.<>c__DisplayClass4_0 V_0, //CS$<>8__locals0
C.<>c__DisplayClass4_1 V_1) //CS$<>8__locals1
~IL_0000: newobj ""C.<>c__DisplayClass4_0..ctor()""
IL_0005: stloc.0
-IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass4_0.z""
IL_000d: call ""int C.G(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass4_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.F(System.Func<int>)""
IL_0023: add
IL_0024: stfld ""int C.y1""
~IL_0029: newobj ""C.<>c__DisplayClass4_1..ctor()""
IL_002e: stloc.1
-IL_002f: ldarg.0
IL_0030: ldloc.1
IL_0031: ldflda ""int C.<>c__DisplayClass4_1.u""
IL_0036: call ""int C.G(out int)""
IL_003b: ldloc.1
IL_003c: ldftn ""int C.<>c__DisplayClass4_1.<.ctor>b__1()""
IL_0042: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_0047: call ""int C.F(System.Func<int>)""
IL_004c: add
IL_004d: stfld ""int C.y2""
IL_0052: ldarg.0
IL_0053: call ""object..ctor()""
IL_0058: nop
IL_0059: ret
}
");
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""-52"" />
<slot kind=""30"" offset=""-25"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>4</methodOrdinal>
<closure offset=""-52"" />
<closure offset=""-25"" />
<lambda offset=""-29"" closure=""0"" />
<lambda offset=""-2"" closure=""1"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x6"" startLine=""2000"" startColumn=""5"" endLine=""2000"" endColumn=""39"" document=""1"" />
<entry offset=""0x29"" hidden=""true"" document=""1"" />
<entry offset=""0x2f"" startLine=""2000"" startColumn=""41"" endLine=""2000"" endColumn=""71"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x5a"">
<scope startOffset=""0x0"" endOffset=""0x29"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x29"" attributes=""0"" />
</scope>
<scope startOffset=""0x29"" endOffset=""0x52"">
<local name=""CS$<>8__locals1"" il_index=""1"" il_start=""0x29"" il_end=""0x52"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c__DisplayClass4_0.<.ctor>b__0", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c__DisplayClass4_0"" name=""<.ctor>b__0"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""2000"" startColumn=""37"" endLine=""2000"" endColumn=""38"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c__DisplayClass4_1.<.ctor>b__1", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c__DisplayClass4_1"" name=""<.ctor>b__1"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""x"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""2000"" startColumn=""69"" endLine=""2000"" endColumn=""70"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInInitializers_07()
{
var source = WithWindowsLineBreaks(
@"
class C : A
{
#line 2000
C() : base(G(out var z)+ F(() => z))
{
}
static int G(out int x)
{
throw null;
}
static int F(System.Func<int> x)
{
throw null;
}
}
class A
{
public A(int x) {}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""30"" offset=""-1"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""-1"" />
<lambda offset=""-3"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x6"" startLine=""2000"" startColumn=""11"" endLine=""2000"" endColumn=""41"" document=""1"" />
<entry offset=""0x2a"" startLine=""2001"" startColumn=""5"" endLine=""2001"" endColumn=""6"" document=""1"" />
<entry offset=""0x2b"" startLine=""2002"" startColumn=""5"" endLine=""2002"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2c"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x2c"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c__DisplayClass0_0.<.ctor>b__0", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c__DisplayClass0_0"" name=""<.ctor>b__0"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""2000"" startColumn=""38"" endLine=""2000"" endColumn=""39"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInQuery_01()
{
var source = WithWindowsLineBreaks(
@"
using System.Linq;
class C
{
C()
{
var q = from a in new [] {1}
where
G(out var x1) > a
select a;
}
static int G(out int x)
{
throw null;
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<lambda offset=""88"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""8"" document=""1"" />
<entry offset=""0x7"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x8"" startLine=""8"" startColumn=""9"" endLine=""11"" endColumn=""26"" document=""1"" />
<entry offset=""0x37"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x38"">
<namespace name=""System.Linq"" />
<scope startOffset=""0x7"" endOffset=""0x38"">
<local name=""q"" il_index=""0"" il_start=""0x7"" il_end=""0x38"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c.<.ctor>b__0_0", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c"" name=""<.ctor>b__0_0"" parameterNames=""a"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
<encLocalSlotMap>
<slot kind=""0"" offset=""98"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""23"" endLine=""10"" endColumn=""40"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xb"">
<local name=""x1"" il_index=""0"" il_start=""0x0"" il_end=""0xb"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInQuery_02()
{
var source = WithWindowsLineBreaks(
@"
using System.Linq;
class C
{
C()
#line 2000
{
var q = from a in new [] {1}
where
G(out var x1) > F(() => x1)
select a;
}
static int G(out int x)
{
throw null;
}
static int F(System.Func<int> x)
{
throw null;
}
}
");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C..ctor", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""88"" />
<lambda offset=""88"" />
<lambda offset=""112"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""8"" document=""1"" />
<entry offset=""0x7"" startLine=""2000"" startColumn=""5"" endLine=""2000"" endColumn=""6"" document=""1"" />
<entry offset=""0x8"" startLine=""2001"" startColumn=""9"" endLine=""2004"" endColumn=""26"" document=""1"" />
<entry offset=""0x37"" startLine=""2005"" startColumn=""5"" endLine=""2005"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x38"">
<namespace name=""System.Linq"" />
<scope startOffset=""0x7"" endOffset=""0x38"">
<local name=""q"" il_index=""0"" il_start=""0x7"" il_end=""0x38"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c.<.ctor>b__0_0", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c"" name=""<.ctor>b__0_0"" parameterNames=""a"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""88"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x6"" startLine=""2003"" startColumn=""23"" endLine=""2003"" endColumn=""50"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x25"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x25"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
c.VerifyPdb("C+<>c__DisplayClass0_0.<.ctor>b__1", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C+<>c__DisplayClass0_0"" name=""<.ctor>b__1"">
<customDebugInfo>
<forward declaringType=""C"" methodName="".ctor"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""2003"" startColumn=""47"" endLine=""2003"" endColumn=""49"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SyntaxOffset_OutVarInSwitchExpression()
{
var source = @"class C { static object G() => N(out var x) switch { null => x switch {1 => 1, _ => 2 }, _ => 1 }; static object N(out int x) { x = 1; return null; } }";
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb("C.G", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""G"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
<slot kind=""temp"" />
<slot kind=""35"" offset=""16"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""1"" startColumn=""32"" endLine=""1"" endColumn=""99"" document=""1"" />
<entry offset=""0xb"" startLine=""1"" startColumn=""45"" endLine=""1"" endColumn=""99"" document=""1"" />
<entry offset=""0xc"" hidden=""true"" document=""1"" />
<entry offset=""0x11"" hidden=""true"" document=""1"" />
<entry offset=""0x14"" startLine=""1"" startColumn=""64"" endLine=""1"" endColumn=""89"" document=""1"" />
<entry offset=""0x15"" hidden=""true"" document=""1"" />
<entry offset=""0x1b"" startLine=""1"" startColumn=""78"" endLine=""1"" endColumn=""79"" document=""1"" />
<entry offset=""0x1f"" startLine=""1"" startColumn=""86"" endLine=""1"" endColumn=""87"" document=""1"" />
<entry offset=""0x23"" hidden=""true"" document=""1"" />
<entry offset=""0x26"" startLine=""1"" startColumn=""45"" endLine=""1"" endColumn=""99"" document=""1"" />
<entry offset=""0x27"" startLine=""1"" startColumn=""62"" endLine=""1"" endColumn=""89"" document=""1"" />
<entry offset=""0x2b"" startLine=""1"" startColumn=""96"" endLine=""1"" endColumn=""97"" document=""1"" />
<entry offset=""0x2f"" hidden=""true"" document=""1"" />
<entry offset=""0x32"" startLine=""1"" startColumn=""32"" endLine=""1"" endColumn=""99"" document=""1"" />
<entry offset=""0x33"" hidden=""true"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x3a"">
<local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x3a"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
#endregion
[WorkItem(4370, "https://github.com/dotnet/roslyn/issues/4370")]
[Fact]
public void HeadingHiddenSequencePointsPickUpDocumentFromVisibleSequencePoint()
{
var source = WithWindowsLineBreaks(
@"#line 1 ""C:\Async.cs""
#pragma checksum ""C:\Async.cs"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""DBEB2A067B2F0E0D678A002C587A2806056C3DCE""
using System.Threading.Tasks;
public class C
{
public async void M1()
{
}
}
");
var tree = SyntaxFactory.ParseSyntaxTree(source, encoding: Encoding.UTF8, path: "HIDDEN.cs");
var c = CSharpCompilation.Create("Compilation", new[] { tree }, new[] { MscorlibRef_v46 }, options: TestOptions.DebugDll.WithDebugPlusMode(true));
c.VerifyPdb(
@"<symbols>
<files>
<file id=""1"" name=""C:\Async.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""DB-EB-2A-06-7B-2F-0E-0D-67-8A-00-2C-58-7A-28-06-05-6C-3D-CE"" />
<file id=""2"" name=""HIDDEN.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""8A-92-EE-2F-D6-6F-C0-69-F4-A8-54-CB-11-BE-A3-06-76-2C-9C-98"" />
</files>
<methods>
<method containingType=""C"" name=""M1"">
<customDebugInfo>
<forwardIterator name=""<M1>d__0"" />
</customDebugInfo>
</method>
<method containingType=""C+<M1>d__0"" name=""MoveNext"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
<entry offset=""0xa"" hidden=""true"" document=""1"" />
<entry offset=""0x22"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x2a"" hidden=""true"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x37"">
<namespace name=""System.Threading.Tasks"" />
</scope>
<asyncInfo>
<catchHandler offset=""0xa"" />
<kickoffMethod declaringType=""C"" methodName=""M1"" />
</asyncInfo>
</method>
</methods>
</symbols>
", format: DebugInformationFormat.Pdb);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""HIDDEN.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""8A-92-EE-2F-D6-6F-C0-69-F4-A8-54-CB-11-BE-A3-06-76-2C-9C-98"" />
<file id=""2"" name=""C:\Async.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""DB-EB-2A-06-7B-2F-0E-0D-67-8A-00-2C-58-7A-28-06-05-6C-3D-CE"" />
</files>
<methods>
<method containingType=""C+<M1>d__0"" name=""MoveNext"">
<customDebugInfo>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""2"" />
<entry offset=""0x7"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""2"" />
<entry offset=""0xa"" hidden=""true"" document=""2"" />
<entry offset=""0x22"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""2"" />
<entry offset=""0x2a"" hidden=""true"" document=""2"" />
</sequencePoints>
<asyncInfo>
<catchHandler offset=""0xa"" />
<kickoffMethod declaringType=""C"" methodName=""M1"" />
</asyncInfo>
</method>
</methods>
</symbols>", format: DebugInformationFormat.PortablePdb);
}
[WorkItem(12923, "https://github.com/dotnet/roslyn/issues/12923")]
[Fact]
public void SequencePointsForConstructorWithHiddenInitializer()
{
string initializerSource = WithWindowsLineBreaks(@"
#line hidden
partial class C
{
int i = 42;
}
");
string constructorSource = WithWindowsLineBreaks(@"
partial class C
{
C()
{
}
}
");
var c = CreateCompilation(
new[] { Parse(initializerSource, "initializer.cs"), Parse(constructorSource, "constructor.cs") },
options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""constructor.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""EA-D6-0A-16-6C-6A-BC-C1-5D-98-0F-B7-4B-78-13-93-FB-C7-C2-5A"" />
<file id=""2"" name=""initializer.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""84-32-24-D7-FE-32-63-BA-41-D5-17-A2-D5-90-23-B8-12-3C-AF-D5"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x8"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""8"" document=""1"" />
<entry offset=""0xf"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x10"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>
", format: DebugInformationFormat.Pdb);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""initializer.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""84-32-24-D7-FE-32-63-BA-41-D5-17-A2-D5-90-23-B8-12-3C-AF-D5"" />
<file id=""2"" name=""constructor.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""EA-D6-0A-16-6C-6A-BC-C1-5D-98-0F-B7-4B-78-13-93-FB-C7-C2-5A"" />
</files>
<methods>
<method containingType=""C"" name="".ctor"">
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""2"" />
<entry offset=""0x8"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""8"" document=""2"" />
<entry offset=""0xf"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""2"" />
<entry offset=""0x10"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""2"" />
</sequencePoints>
</method>
</methods>
</symbols>", format: DebugInformationFormat.PortablePdb);
}
[WorkItem(14437, "https://github.com/dotnet/roslyn/issues/14437")]
[Fact]
public void LocalFunctionSequencePoints()
{
string source = WithWindowsLineBreaks(
@"class Program
{
static int Main(string[] args)
{ // 4
int Local1(string[] a)
=>
a.Length; // 7
int Local2(string[] a)
{ // 9
return a.Length; // 10
} // 11
return Local1(args) + Local2(args); // 12
} // 13
}");
var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(
@"<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""Program"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<lambda offset=""115"" />
<lambda offset=""202"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" />
<entry offset=""0x3"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""44"" document=""1"" />
<entry offset=""0x13"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""Program"" name=""<Main>g__Local1|0_0"" parameterNames=""a"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""13"" endLine=""7"" endColumn=""21"" document=""1"" />
</sequencePoints>
</method>
<method containingType=""Program"" name=""<Main>g__Local2|0_1"" parameterNames=""a"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" />
<encLocalSlotMap>
<slot kind=""21"" offset=""202"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""29"" document=""1"" />
<entry offset=""0x7"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void SwitchInAsyncMethod()
{
var source = @"
using System;
class Program
{
public static async void Test()
{
int i = 0;
switch (i)
{
case 1:
break;
}
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 89 (0x59)
.maxstack 2
.locals init (int V_0,
int V_1,
System.Exception V_2)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Test>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: int i = 0;
IL_0008: ldarg.0
IL_0009: ldc.i4.0
IL_000a: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: switch (i)
IL_000f: ldarg.0
IL_0010: ldarg.0
IL_0011: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_0016: stloc.1
// sequence point: <hidden>
IL_0017: ldloc.1
IL_0018: stfld ""int Program.<Test>d__0.<>s__2""
// sequence point: <hidden>
IL_001d: ldarg.0
IL_001e: ldfld ""int Program.<Test>d__0.<>s__2""
IL_0023: ldc.i4.1
IL_0024: beq.s IL_0028
IL_0026: br.s IL_002a
// sequence point: break;
IL_0028: br.s IL_002a
// sequence point: <hidden>
IL_002a: leave.s IL_0044
}
catch System.Exception
{
// async: catch handler, sequence point: <hidden>
IL_002c: stloc.2
IL_002d: ldarg.0
IL_002e: ldc.i4.s -2
IL_0030: stfld ""int Program.<Test>d__0.<>1__state""
IL_0035: ldarg.0
IL_0036: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_003b: ldloc.2
IL_003c: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)""
IL_0041: nop
IL_0042: leave.s IL_0058
}
// sequence point: }
IL_0044: ldarg.0
IL_0045: ldc.i4.s -2
IL_0047: stfld ""int Program.<Test>d__0.<>1__state""
// sequence point: <hidden>
IL_004c: ldarg.0
IL_004d: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_0052: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()""
IL_0057: nop
IL_0058: ret
}", sequencePoints: "Program+<Test>d__0.MoveNext", source: source);
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void WhileInAsyncMethod()
{
var source = @"
using System;
class Program
{
public static async void Test()
{
int i = 0;
while (i == 1)
Console.WriteLine();
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 83 (0x53)
.maxstack 2
.locals init (int V_0,
bool V_1,
System.Exception V_2)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Test>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: int i = 0;
IL_0008: ldarg.0
IL_0009: ldc.i4.0
IL_000a: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: <hidden>
IL_000f: br.s IL_0017
// sequence point: Console.WriteLine();
IL_0011: call ""void System.Console.WriteLine()""
IL_0016: nop
// sequence point: while (i == 1)
IL_0017: ldarg.0
IL_0018: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_001d: ldc.i4.1
IL_001e: ceq
IL_0020: stloc.1
// sequence point: <hidden>
IL_0021: ldloc.1
IL_0022: brtrue.s IL_0011
IL_0024: leave.s IL_003e
}
catch System.Exception
{
// async: catch handler, sequence point: <hidden>
IL_0026: stloc.2
IL_0027: ldarg.0
IL_0028: ldc.i4.s -2
IL_002a: stfld ""int Program.<Test>d__0.<>1__state""
IL_002f: ldarg.0
IL_0030: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_0035: ldloc.2
IL_0036: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)""
IL_003b: nop
IL_003c: leave.s IL_0052
}
// sequence point: }
IL_003e: ldarg.0
IL_003f: ldc.i4.s -2
IL_0041: stfld ""int Program.<Test>d__0.<>1__state""
// sequence point: <hidden>
IL_0046: ldarg.0
IL_0047: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_004c: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()""
IL_0051: nop
IL_0052: ret
}
", sequencePoints: "Program+<Test>d__0.MoveNext", source: source);
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ForInAsyncMethod()
{
var source = @"
using System;
class Program
{
public static async void Test()
{
for (int i = 0; i > 1; i--)
Console.WriteLine();
}
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 99 (0x63)
.maxstack 3
.locals init (int V_0,
int V_1,
bool V_2,
System.Exception V_3)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Test>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: int i = 0
IL_0008: ldarg.0
IL_0009: ldc.i4.0
IL_000a: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: <hidden>
IL_000f: br.s IL_0027
// sequence point: Console.WriteLine();
IL_0011: call ""void System.Console.WriteLine()""
IL_0016: nop
// sequence point: i--
IL_0017: ldarg.0
IL_0018: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_001d: stloc.1
IL_001e: ldarg.0
IL_001f: ldloc.1
IL_0020: ldc.i4.1
IL_0021: sub
IL_0022: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: i > 1
IL_0027: ldarg.0
IL_0028: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_002d: ldc.i4.1
IL_002e: cgt
IL_0030: stloc.2
// sequence point: <hidden>
IL_0031: ldloc.2
IL_0032: brtrue.s IL_0011
IL_0034: leave.s IL_004e
}
catch System.Exception
{
// async: catch handler, sequence point: <hidden>
IL_0036: stloc.3
IL_0037: ldarg.0
IL_0038: ldc.i4.s -2
IL_003a: stfld ""int Program.<Test>d__0.<>1__state""
IL_003f: ldarg.0
IL_0040: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_0045: ldloc.3
IL_0046: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)""
IL_004b: nop
IL_004c: leave.s IL_0062
}
// sequence point: }
IL_004e: ldarg.0
IL_004f: ldc.i4.s -2
IL_0051: stfld ""int Program.<Test>d__0.<>1__state""
// sequence point: <hidden>
IL_0056: ldarg.0
IL_0057: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_005c: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()""
IL_0061: nop
IL_0062: ret
}
", sequencePoints: "Program+<Test>d__0.MoveNext", source: source);
}
[Fact]
[WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")]
public void ForWithInnerLocalsInAsyncMethod()
{
var source = @"
using System;
class Program
{
public static async void Test()
{
for (int i = M(out var x); i > 1; i--)
Console.WriteLine();
}
public static int M(out int x) { x = 0; return 0; }
}
";
var v = CompileAndVerify(source, options: TestOptions.DebugDll);
v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 109 (0x6d)
.maxstack 3
.locals init (int V_0,
int V_1,
bool V_2,
System.Exception V_3)
// sequence point: <hidden>
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Test>d__0.<>1__state""
IL_0006: stloc.0
.try
{
// sequence point: {
IL_0007: nop
// sequence point: int i = M(out var x)
IL_0008: ldarg.0
IL_0009: ldarg.0
IL_000a: ldflda ""int Program.<Test>d__0.<x>5__2""
IL_000f: call ""int Program.M(out int)""
IL_0014: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: <hidden>
IL_0019: br.s IL_0031
// sequence point: Console.WriteLine();
IL_001b: call ""void System.Console.WriteLine()""
IL_0020: nop
// sequence point: i--
IL_0021: ldarg.0
IL_0022: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_0027: stloc.1
IL_0028: ldarg.0
IL_0029: ldloc.1
IL_002a: ldc.i4.1
IL_002b: sub
IL_002c: stfld ""int Program.<Test>d__0.<i>5__1""
// sequence point: i > 1
IL_0031: ldarg.0
IL_0032: ldfld ""int Program.<Test>d__0.<i>5__1""
IL_0037: ldc.i4.1
IL_0038: cgt
IL_003a: stloc.2
// sequence point: <hidden>
IL_003b: ldloc.2
IL_003c: brtrue.s IL_001b
IL_003e: leave.s IL_0058
}
catch System.Exception
{
// async: catch handler, sequence point: <hidden>
IL_0040: stloc.3
IL_0041: ldarg.0
IL_0042: ldc.i4.s -2
IL_0044: stfld ""int Program.<Test>d__0.<>1__state""
IL_0049: ldarg.0
IL_004a: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_004f: ldloc.3
IL_0050: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)""
IL_0055: nop
IL_0056: leave.s IL_006c
}
// sequence point: }
IL_0058: ldarg.0
IL_0059: ldc.i4.s -2
IL_005b: stfld ""int Program.<Test>d__0.<>1__state""
// sequence point: <hidden>
IL_0060: ldarg.0
IL_0061: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder""
IL_0066: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()""
IL_006b: nop
IL_006c: ret
}
", sequencePoints: "Program+<Test>d__0.MoveNext", source: source);
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
[WorkItem(23525, "https://github.com/dotnet/roslyn/issues/23525")]
public void InvalidCharacterInPdbPath()
{
using (var outStream = Temp.CreateFile().Open())
{
var compilation = CreateCompilation("");
var result = compilation.Emit(outStream, options: new EmitOptions(pdbFilePath: "test\\?.pdb", debugInformationFormat: DebugInformationFormat.Embedded));
// This is fine because EmitOptions just controls what is written into the PE file and it's
// valid for this to be an illegal file name (path map can easily create these).
Assert.True(result.Success);
}
}
[Fact]
[WorkItem(38954, "https://github.com/dotnet/roslyn/issues/38954")]
public void FilesOneWithNoMethodBody()
{
string source1 = WithWindowsLineBreaks(@"
using System;
class C
{
public static void Main()
{
Console.WriteLine();
}
}
");
string source2 = WithWindowsLineBreaks(@"
// no code
");
var tree1 = Parse(source1, "f:/build/goo.cs");
var tree2 = Parse(source2, "f:/build/nocode.cs");
var c = CreateCompilation(new[] { tree1, tree2 }, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""f:/build/goo.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""5D-7D-CF-1B-79-12-0E-0A-80-13-E0-98-7E-5C-AA-3B-63-D8-7E-4F"" />
<file id=""2"" name=""f:/build/nocode.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""8B-1D-3F-75-E0-A8-8F-90-B2-D3-52-CF-71-9B-17-29-3C-70-7A-42"" />
</files>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""29"" document=""1"" />
<entry offset=""0x7"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x8"">
<namespace name=""System"" />
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
[WorkItem(38954, "https://github.com/dotnet/roslyn/issues/38954")]
public void SingleFileWithNoMethodBody()
{
string source = WithWindowsLineBreaks(@"
// no code
");
var tree = Parse(source, "f:/build/nocode.cs");
var c = CreateCompilation(new[] { tree }, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<files>
<file id=""1"" name=""f:/build/nocode.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""8B-1D-3F-75-E0-A8-8F-90-B2-D3-52-CF-71-9B-17-29-3C-70-7A-42"" />
</files>
<methods />
</symbols>
");
}
}
}
| 1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Compilers/Core/Portable/NativePdbWriter/PdbWriter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Security.Cryptography;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.DiaSymReader;
using Roslyn.Utilities;
namespace Microsoft.Cci
{
internal sealed class PdbWriter : IDisposable
{
internal const uint Age = 1;
private readonly HashAlgorithmName _hashAlgorithmNameOpt;
private readonly string _fileName;
private readonly Func<ISymWriterMetadataProvider, SymUnmanagedWriter> _symWriterFactory;
private readonly Dictionary<DebugSourceDocument, int> _documentIndex;
private MetadataWriter _metadataWriter;
private SymUnmanagedWriter _symWriter;
private SymUnmanagedSequencePointsWriter _sequencePointsWriter;
// { INamespace or ITypeReference -> qualified name }
private readonly Dictionary<object, string> _qualifiedNameCache;
// in support of determinism
private bool IsDeterministic { get => _hashAlgorithmNameOpt.Name != null; }
public PdbWriter(string fileName, Func<ISymWriterMetadataProvider, SymUnmanagedWriter> symWriterFactory, HashAlgorithmName hashAlgorithmNameOpt)
{
_fileName = fileName;
_symWriterFactory = symWriterFactory;
_hashAlgorithmNameOpt = hashAlgorithmNameOpt;
_documentIndex = new Dictionary<DebugSourceDocument, int>();
_qualifiedNameCache = new Dictionary<object, string>(ReferenceEqualityComparer.Instance);
}
public void WriteTo(Stream stream)
{
_symWriter.WriteTo(stream);
}
public void Dispose()
{
_symWriter?.Dispose();
}
private CommonPEModuleBuilder Module => Context.Module;
private EmitContext Context => _metadataWriter.Context;
public void SerializeDebugInfo(IMethodBody methodBody, StandaloneSignatureHandle localSignatureHandleOpt, CustomDebugInfoWriter customDebugInfoWriter)
{
Debug.Assert(_metadataWriter != null);
// A state machine kickoff method doesn't have sequence points as it only contains generated code.
// We could avoid emitting debug info for it if the corresponding MoveNext method had no sequence points,
// but there is no real need for such optimization.
//
// Special case a hidden entry point (#line hidden applied) that would otherwise have no debug info.
// This is to accommodate for a requirement of Windows PDB writer that the entry point method must have some debug information.
bool isKickoffMethod = methodBody.StateMachineTypeName != null;
bool emitDebugInfo = isKickoffMethod || !methodBody.SequencePoints.IsEmpty ||
methodBody.MethodDefinition == (Context.Module.DebugEntryPoint ?? Context.Module.PEEntryPoint);
if (!emitDebugInfo)
{
return;
}
var methodHandle = (MethodDefinitionHandle)_metadataWriter.GetMethodHandle(methodBody.MethodDefinition);
int methodToken = MetadataTokens.GetToken(methodHandle);
OpenMethod(methodToken, methodBody.MethodDefinition);
var localScopes = methodBody.LocalScopes;
// Define locals, constants and namespaces in the outermost local scope (opened in OpenMethod):
if (localScopes.Length > 0)
{
this.DefineScopeLocals(localScopes[0], localSignatureHandleOpt);
}
if (!isKickoffMethod && methodBody.ImportScope != null)
{
IMethodDefinition forwardToMethod;
if (customDebugInfoWriter.ShouldForwardNamespaceScopes(Context, methodBody, methodHandle, out forwardToMethod))
{
if (forwardToMethod != null)
{
UsingNamespace("@" + MetadataTokens.GetToken(_metadataWriter.GetMethodHandle(forwardToMethod)), methodBody.MethodDefinition);
}
// otherwise, the forwarding is done via custom debug info
}
else
{
this.DefineNamespaceScopes(methodBody);
}
}
DefineLocalScopes(localScopes, localSignatureHandleOpt);
EmitSequencePoints(methodBody.SequencePoints);
if (methodBody.MoveNextBodyInfo is AsyncMoveNextBodyDebugInfo asyncMoveNextInfo)
{
_symWriter.SetAsyncInfo(
methodToken,
MetadataTokens.GetToken(_metadataWriter.GetMethodHandle(asyncMoveNextInfo.KickoffMethod)),
asyncMoveNextInfo.CatchHandlerOffset,
asyncMoveNextInfo.YieldOffsets.AsSpan(),
asyncMoveNextInfo.ResumeOffsets.AsSpan());
}
var compilationOptions = Context.Module.CommonCompilation.Options;
// We need to avoid emitting CDI DynamicLocals = 5 and EditAndContinueLocalSlotMap = 6 for files processed by WinMDExp until
// bug #1067635 is fixed and available in SDK.
bool suppressNewCustomDebugInfo = compilationOptions.OutputKind == OutputKind.WindowsRuntimeMetadata;
// delta doesn't need this information - we use information recorded by previous generation emit
bool emitEncInfo = compilationOptions.EnableEditAndContinue && _metadataWriter.IsFullMetadata;
bool emitExternNamespaces;
byte[] blob = customDebugInfoWriter.SerializeMethodDebugInfo(Context, methodBody, methodHandle, emitEncInfo, suppressNewCustomDebugInfo, out emitExternNamespaces);
if (blob != null)
{
_symWriter.DefineCustomMetadata(blob);
}
if (emitExternNamespaces)
{
DefineAssemblyReferenceAliases();
}
CloseMethod(methodBody.IL.Length);
}
private void DefineNamespaceScopes(IMethodBody methodBody)
{
var module = Module;
bool isVisualBasic = module.GenerateVisualBasicStylePdb;
IMethodDefinition method = methodBody.MethodDefinition;
var namespaceScopes = methodBody.ImportScope;
PooledHashSet<string> lazyDeclaredExternAliases = null;
if (!isVisualBasic)
{
for (var scope = namespaceScopes; scope != null; scope = scope.Parent)
{
foreach (var import in scope.GetUsedNamespaces())
{
if (import.TargetNamespaceOpt == null && import.TargetTypeOpt == null)
{
Debug.Assert(import.AliasOpt != null);
Debug.Assert(import.TargetAssemblyOpt == null);
if (lazyDeclaredExternAliases == null)
{
lazyDeclaredExternAliases = PooledHashSet<string>.GetInstance();
}
lazyDeclaredExternAliases.Add(import.AliasOpt);
}
}
}
}
// file and namespace level
for (IImportScope scope = namespaceScopes; scope != null; scope = scope.Parent)
{
foreach (UsedNamespaceOrType import in scope.GetUsedNamespaces())
{
var importString = TryEncodeImport(import, lazyDeclaredExternAliases, isProjectLevel: false);
if (importString != null)
{
UsingNamespace(importString, method);
}
}
}
lazyDeclaredExternAliases?.Free();
// project level
if (isVisualBasic)
{
string defaultNamespace = module.DefaultNamespace;
if (!string.IsNullOrEmpty(defaultNamespace))
{
// VB marks the default/root namespace with an asterisk
UsingNamespace("*" + defaultNamespace, module);
}
foreach (string assemblyName in module.LinkedAssembliesDebugInfo)
{
UsingNamespace("&" + assemblyName, module);
}
foreach (UsedNamespaceOrType import in module.GetImports())
{
var importString = TryEncodeImport(import, null, isProjectLevel: true);
if (importString != null)
{
UsingNamespace(importString, method);
}
}
// VB current namespace -- VB appends the namespace of the container without prefixes
UsingNamespace(GetOrCreateSerializedNamespaceName(method.ContainingNamespace), method);
}
}
private void DefineAssemblyReferenceAliases()
{
foreach (AssemblyReferenceAlias alias in Module.GetAssemblyReferenceAliases(Context))
{
UsingNamespace("Z" + alias.Name + " " + alias.Assembly.Identity.GetDisplayName(), Module);
}
}
private string TryEncodeImport(UsedNamespaceOrType import, HashSet<string> declaredExternAliasesOpt, bool isProjectLevel)
{
// NOTE: Dev12 has related cases "I" and "O" in EMITTER::ComputeDebugNamespace,
// but they were probably implementation details that do not affect Roslyn.
if (Module.GenerateVisualBasicStylePdb)
{
// VB doesn't support extern aliases
Debug.Assert(import.TargetAssemblyOpt == null);
Debug.Assert(declaredExternAliasesOpt == null);
if (import.TargetTypeOpt != null)
{
Debug.Assert(import.TargetNamespaceOpt == null);
Debug.Assert(import.TargetAssemblyOpt == null);
// Native compiler doesn't write imports with generic types to PDB.
if (import.TargetTypeOpt.IsTypeSpecification())
{
return null;
}
string typeName = GetOrCreateSerializedTypeName(import.TargetTypeOpt);
if (import.AliasOpt != null)
{
return (isProjectLevel ? "@PA:" : "@FA:") + import.AliasOpt + "=" + typeName;
}
else
{
return (isProjectLevel ? "@PT:" : "@FT:") + typeName;
}
}
if (import.TargetNamespaceOpt != null)
{
string namespaceName = GetOrCreateSerializedNamespaceName(import.TargetNamespaceOpt);
if (import.AliasOpt == null)
{
return (isProjectLevel ? "@P:" : "@F:") + namespaceName;
}
else
{
return (isProjectLevel ? "@PA:" : "@FA:") + import.AliasOpt + "=" + namespaceName;
}
}
Debug.Assert(import.AliasOpt != null);
Debug.Assert(import.TargetXmlNamespaceOpt != null);
return (isProjectLevel ? "@PX:" : "@FX:") + import.AliasOpt + "=" + import.TargetXmlNamespaceOpt;
}
Debug.Assert(import.TargetXmlNamespaceOpt == null);
if (import.TargetTypeOpt != null)
{
Debug.Assert(import.TargetNamespaceOpt == null);
Debug.Assert(import.TargetAssemblyOpt == null);
string typeName = GetOrCreateSerializedTypeName(import.TargetTypeOpt);
return (import.AliasOpt != null) ?
"A" + import.AliasOpt + " T" + typeName :
"T" + typeName;
}
if (import.TargetNamespaceOpt != null)
{
string namespaceName = GetOrCreateSerializedNamespaceName(import.TargetNamespaceOpt);
if (import.AliasOpt != null)
{
return (import.TargetAssemblyOpt != null) ?
"A" + import.AliasOpt + " E" + namespaceName + " " + GetAssemblyReferenceAlias(import.TargetAssemblyOpt, declaredExternAliasesOpt) :
"A" + import.AliasOpt + " U" + namespaceName;
}
else
{
return (import.TargetAssemblyOpt != null) ?
"E" + namespaceName + " " + GetAssemblyReferenceAlias(import.TargetAssemblyOpt, declaredExternAliasesOpt) :
"U" + namespaceName;
}
}
Debug.Assert(import.AliasOpt != null);
Debug.Assert(import.TargetAssemblyOpt == null);
return "X" + import.AliasOpt;
}
internal string GetOrCreateSerializedNamespaceName(INamespace @namespace)
{
string result;
if (!_qualifiedNameCache.TryGetValue(@namespace, out result))
{
result = TypeNameSerializer.BuildQualifiedNamespaceName(@namespace);
_qualifiedNameCache.Add(@namespace, result);
}
return result;
}
internal string GetOrCreateSerializedTypeName(ITypeReference typeReference)
{
string result;
if (!_qualifiedNameCache.TryGetValue(typeReference, out result))
{
if (Module.GenerateVisualBasicStylePdb)
{
result = SerializeVisualBasicImportTypeReference(typeReference);
}
else
{
result = typeReference.GetSerializedTypeName(Context);
}
_qualifiedNameCache.Add(typeReference, result);
}
return result;
}
private string SerializeVisualBasicImportTypeReference(ITypeReference typeReference)
{
Debug.Assert(!(typeReference is IArrayTypeReference));
Debug.Assert(!(typeReference is IPointerTypeReference));
Debug.Assert(!typeReference.IsTypeSpecification());
var result = PooledStringBuilder.GetInstance();
ArrayBuilder<string> nestedNamesReversed;
INestedTypeReference nestedType = typeReference.AsNestedTypeReference;
if (nestedType != null)
{
nestedNamesReversed = ArrayBuilder<string>.GetInstance();
while (nestedType != null)
{
nestedNamesReversed.Add(nestedType.Name);
typeReference = nestedType.GetContainingType(_metadataWriter.Context);
nestedType = typeReference.AsNestedTypeReference;
}
}
else
{
nestedNamesReversed = null;
}
INamespaceTypeReference namespaceType = typeReference.AsNamespaceTypeReference;
Debug.Assert(namespaceType != null);
string namespaceName = namespaceType.NamespaceName;
if (namespaceName.Length != 0)
{
result.Builder.Append(namespaceName);
result.Builder.Append('.');
}
result.Builder.Append(namespaceType.Name);
if (nestedNamesReversed != null)
{
for (int i = nestedNamesReversed.Count - 1; i >= 0; i--)
{
result.Builder.Append('.');
result.Builder.Append(nestedNamesReversed[i]);
}
nestedNamesReversed.Free();
}
return result.ToStringAndFree();
}
private string GetAssemblyReferenceAlias(IAssemblyReference assembly, HashSet<string> declaredExternAliases)
{
// no extern alias defined in scope at all -> error in compiler
Debug.Assert(declaredExternAliases != null);
var allAliases = _metadataWriter.Context.Module.GetAssemblyReferenceAliases(_metadataWriter.Context);
foreach (AssemblyReferenceAlias alias in allAliases)
{
// Multiple aliases may be given to an assembly reference.
// We find one that is in scope (was imported via extern alias directive).
// If multiple are in scope then use the first one.
// NOTE: Dev12 uses the one that appeared in source, whereas we use
// the first one that COULD have appeared in source. (DevDiv #913022)
// The reason we're not just using the alias from the syntax is that
// it is non-trivial to locate. In particular, since "." may be used in
// place of "::", determining whether the first identifier in the name is
// the alias requires binding. For example, "using A.B;" could refer to
// either "A::B" or "global::A.B".
if (assembly == alias.Assembly && declaredExternAliases.Contains(alias.Name))
{
return alias.Name;
}
}
// no alias defined in scope for given assembly -> error in compiler
throw ExceptionUtilities.Unreachable;
}
private void DefineLocalScopes(ImmutableArray<LocalScope> scopes, StandaloneSignatureHandle localSignatureHandleOpt)
{
// VB scope ranges are end-inclusive
bool endInclusive = this.Module.GenerateVisualBasicStylePdb;
// The order of OpenScope and CloseScope calls must follow the scope nesting.
var scopeStack = ArrayBuilder<LocalScope>.GetInstance();
for (int i = 1; i < scopes.Length; i++)
{
var currentScope = scopes[i];
// Close any scopes that have finished.
while (scopeStack.Count > 0)
{
LocalScope topScope = scopeStack.Last();
if (currentScope.StartOffset < topScope.StartOffset + topScope.Length)
{
break;
}
scopeStack.RemoveLast();
_symWriter.CloseScope(endInclusive ? topScope.EndOffset - 1 : topScope.EndOffset);
}
// Open this scope.
scopeStack.Add(currentScope);
_symWriter.OpenScope(currentScope.StartOffset);
DefineScopeLocals(currentScope, localSignatureHandleOpt);
}
// Close remaining scopes.
for (int i = scopeStack.Count - 1; i >= 0; i--)
{
LocalScope scope = scopeStack[i];
_symWriter.CloseScope(endInclusive ? scope.EndOffset - 1 : scope.EndOffset);
}
scopeStack.Free();
}
private void DefineScopeLocals(LocalScope currentScope, StandaloneSignatureHandle localSignatureHandleOpt)
{
foreach (ILocalDefinition scopeConstant in currentScope.Constants)
{
var signatureHandle = _metadataWriter.SerializeLocalConstantStandAloneSignature(scopeConstant);
if (!_metadataWriter.IsLocalNameTooLong(scopeConstant))
{
_symWriter.DefineLocalConstant(
scopeConstant.Name,
scopeConstant.CompileTimeValue.Value,
MetadataTokens.GetToken(signatureHandle));
}
}
foreach (ILocalDefinition scopeLocal in currentScope.Variables)
{
if (!_metadataWriter.IsLocalNameTooLong(scopeLocal))
{
Debug.Assert(scopeLocal.SlotIndex >= 0);
_symWriter.DefineLocalVariable(
scopeLocal.SlotIndex,
scopeLocal.Name,
(int)scopeLocal.PdbAttributes,
localSignatureHandleOpt.IsNil ? 0 : MetadataTokens.GetToken(localSignatureHandleOpt));
}
}
}
public void SetMetadataEmitter(MetadataWriter metadataWriter)
{
// Do not look for COM registered diasymreader when determinism is needed as it doesn't support it.
var options =
(IsDeterministic ? SymUnmanagedWriterCreationOptions.Deterministic : SymUnmanagedWriterCreationOptions.UseComRegistry) |
SymUnmanagedWriterCreationOptions.UseAlternativeLoadPath;
var metadataProvider = new SymWriterMetadataProvider(metadataWriter);
SymUnmanagedWriter symWriter;
try
{
symWriter = (_symWriterFactory != null) ? _symWriterFactory(metadataProvider) : SymUnmanagedWriterFactory.CreateWriter(metadataProvider, options);
}
catch (DllNotFoundException e)
{
throw new SymUnmanagedWriterException(e.Message);
}
catch (SymUnmanagedWriterException e) when (e.InnerException is NotSupportedException)
{
var message = IsDeterministic ? CodeAnalysisResources.SymWriterNotDeterministic : CodeAnalysisResources.SymWriterOlderVersionThanRequired;
throw new SymUnmanagedWriterException(string.Format(message, e.ImplementationModuleName));
}
_metadataWriter = metadataWriter;
_symWriter = symWriter;
_sequencePointsWriter = new SymUnmanagedSequencePointsWriter(symWriter, capacity: 64);
}
public BlobContentId GetContentId()
{
BlobContentId contentId;
if (IsDeterministic)
{
// Calculate hash of the stream content.
// Note: all bits of the signature currently stored in the PDB stream were initialized to 1 by InitializeDeterministic.
contentId = BlobContentId.FromHash(CryptographicHashProvider.ComputeHash(_hashAlgorithmNameOpt, _symWriter.GetUnderlyingData()));
_symWriter.UpdateSignature(contentId.Guid, contentId.Stamp, age: 1);
}
else
{
_symWriter.GetSignature(out Guid guid, out uint stamp, out int age);
Debug.Assert(age == Age);
contentId = new BlobContentId(guid, stamp);
}
// Once we calculate the content id we shall not write more data to the writer.
// Note that the underlying stream is accessible for reading even after the writer is disposed.
_symWriter.Dispose();
return contentId;
}
public void SetEntryPoint(int entryMethodToken)
{
_symWriter.SetEntryPoint(entryMethodToken);
}
private int GetDocumentIndex(DebugSourceDocument document)
{
if (_documentIndex.TryGetValue(document, out int documentIndex))
{
return documentIndex;
}
return AddDocumentIndex(document);
}
private int AddDocumentIndex(DebugSourceDocument document)
{
Guid algorithmId;
ReadOnlySpan<byte> checksum;
ReadOnlySpan<byte> embeddedSource;
DebugSourceInfo info = document.GetSourceInfo();
if (!info.Checksum.IsDefault)
{
algorithmId = info.ChecksumAlgorithmId;
checksum = info.Checksum.AsSpan();
}
else
{
algorithmId = default;
checksum = null;
}
if (!info.EmbeddedTextBlob.IsDefault)
{
embeddedSource = info.EmbeddedTextBlob.AsSpan();
}
else
{
embeddedSource = null;
}
int documentIndex = _symWriter.DefineDocument(
document.Location,
document.Language,
document.LanguageVendor,
document.DocumentType,
algorithmId,
checksum,
embeddedSource);
_documentIndex.Add(document, documentIndex);
return documentIndex;
}
private void OpenMethod(int methodToken, IMethodDefinition method)
{
_symWriter.OpenMethod(methodToken);
// open outermost scope:
_symWriter.OpenScope(startOffset: 0);
}
private void CloseMethod(int ilLength)
{
// close the root scope:
_symWriter.CloseScope(endOffset: ilLength);
_symWriter.CloseMethod();
}
private void UsingNamespace(string fullName, INamedEntity errorEntity)
{
if (!_metadataWriter.IsUsingStringTooLong(fullName, errorEntity))
{
_symWriter.UsingNamespace(fullName);
}
}
private void EmitSequencePoints(ImmutableArray<SequencePoint> sequencePoints)
{
int lastDocumentIndex = -1;
DebugSourceDocument lastDocument = null;
foreach (var sequencePoint in sequencePoints)
{
Debug.Assert(sequencePoint.Document != null);
var document = sequencePoint.Document;
int documentIndex;
if (lastDocument == document)
{
documentIndex = lastDocumentIndex;
}
else
{
lastDocument = document;
documentIndex = lastDocumentIndex = GetDocumentIndex(lastDocument);
}
_sequencePointsWriter.Add(
documentIndex,
sequencePoint.Offset,
sequencePoint.StartLine,
sequencePoint.StartColumn,
sequencePoint.EndLine,
sequencePoint.EndColumn);
}
_sequencePointsWriter.Flush();
}
[Conditional("DEBUG")]
// Used to catch cases where file2definitions contain nonwritable definitions early
// If left unfixed, such scenarios will lead to crashes if happen in winmdobj projects
public void AssertAllDefinitionsHaveTokens(MultiDictionary<DebugSourceDocument, DefinitionWithLocation> file2definitions)
{
foreach (var kvp in file2definitions)
{
foreach (var definition in kvp.Value)
{
EntityHandle handle = _metadataWriter.GetDefinitionHandle(definition.Definition);
Debug.Assert(!handle.IsNil);
}
}
}
// Note: only used for WinMD
public void WriteDefinitionLocations(MultiDictionary<DebugSourceDocument, DefinitionWithLocation> file2definitions)
{
// Only open and close the map if we have any mapping.
bool open = false;
foreach (var kvp in file2definitions)
{
foreach (var definition in kvp.Value)
{
if (!open)
{
_symWriter.OpenTokensToSourceSpansMap();
open = true;
}
int token = MetadataTokens.GetToken(_metadataWriter.GetDefinitionHandle(definition.Definition));
Debug.Assert(token != 0);
_symWriter.MapTokenToSourceSpan(
token,
GetDocumentIndex(kvp.Key),
definition.StartLine + 1,
definition.StartColumn + 1,
definition.EndLine + 1,
definition.EndColumn + 1);
}
}
if (open)
{
_symWriter.CloseTokensToSourceSpansMap();
}
}
public void EmbedSourceLink(Stream stream)
{
byte[] bytes;
try
{
bytes = stream.ReadAllBytes();
}
catch (Exception e)
{
throw new SymUnmanagedWriterException(e.Message, e);
}
try
{
_symWriter.SetSourceLinkData(bytes);
}
catch (SymUnmanagedWriterException e) when (e.InnerException is NotSupportedException)
{
throw new SymUnmanagedWriterException(string.Format(CodeAnalysisResources.SymWriterDoesNotSupportSourceLink, e.ImplementationModuleName));
}
}
/// <summary>
/// Write document entries for all debug documents that do not yet have an entry.
/// </summary>
/// <remarks>
/// This is done after serializing method debug info to ensure that we embed all requested
/// text even if there are no corresponding sequence points.
/// </remarks>
public void WriteRemainingDebugDocuments(IReadOnlyDictionary<string, DebugSourceDocument> documents)
{
foreach (var kvp in documents
.Where(kvp => !_documentIndex.ContainsKey(kvp.Value))
.OrderBy(kvp => kvp.Key))
{
AddDocumentIndex(kvp.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;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Security.Cryptography;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.DiaSymReader;
using Roslyn.Utilities;
namespace Microsoft.Cci
{
internal sealed class PdbWriter : IDisposable
{
internal const uint Age = 1;
private readonly HashAlgorithmName _hashAlgorithmNameOpt;
private readonly string _fileName;
private readonly Func<ISymWriterMetadataProvider, SymUnmanagedWriter> _symWriterFactory;
private readonly Dictionary<DebugSourceDocument, int> _documentIndex;
private MetadataWriter _metadataWriter;
private SymUnmanagedWriter _symWriter;
private SymUnmanagedSequencePointsWriter _sequencePointsWriter;
// { INamespace or ITypeReference -> qualified name }
private readonly Dictionary<object, string> _qualifiedNameCache;
// in support of determinism
private bool IsDeterministic { get => _hashAlgorithmNameOpt.Name != null; }
public PdbWriter(string fileName, Func<ISymWriterMetadataProvider, SymUnmanagedWriter> symWriterFactory, HashAlgorithmName hashAlgorithmNameOpt)
{
_fileName = fileName;
_symWriterFactory = symWriterFactory;
_hashAlgorithmNameOpt = hashAlgorithmNameOpt;
_documentIndex = new Dictionary<DebugSourceDocument, int>();
_qualifiedNameCache = new Dictionary<object, string>(ReferenceEqualityComparer.Instance);
}
public void WriteTo(Stream stream)
{
_symWriter.WriteTo(stream);
}
public void Dispose()
{
_symWriter?.Dispose();
}
private CommonPEModuleBuilder Module => Context.Module;
private EmitContext Context => _metadataWriter.Context;
public void SerializeDebugInfo(IMethodBody methodBody, StandaloneSignatureHandle localSignatureHandleOpt, CustomDebugInfoWriter customDebugInfoWriter)
{
Debug.Assert(_metadataWriter != null);
var methodHandle = (MethodDefinitionHandle)_metadataWriter.GetMethodHandle(methodBody.MethodDefinition);
// A state machine kickoff method doesn't have sequence points as it only contains generated code.
// We could avoid emitting debug info for it if the corresponding MoveNext method had no sequence points,
// but there is no real need for such optimization.
//
// Special case a hidden entry point (#line hidden applied) that would otherwise have no debug info.
// This is to accommodate for a requirement of Windows PDB writer that the entry point method must have some debug information.
bool isKickoffMethod = methodBody.StateMachineTypeName != null;
bool emitAllDebugInfo = isKickoffMethod || !methodBody.SequencePoints.IsEmpty ||
methodBody.MethodDefinition == (Context.Module.DebugEntryPoint ?? Context.Module.PEEntryPoint);
var compilationOptions = Context.Module.CommonCompilation.Options;
// We need to avoid emitting CDI DynamicLocals = 5 and EditAndContinueLocalSlotMap = 6 for files processed by WinMDExp until
// bug #1067635 is fixed and available in SDK.
bool suppressNewCustomDebugInfo = compilationOptions.OutputKind == OutputKind.WindowsRuntimeMetadata;
bool emitDynamicAndTupleInfo = emitAllDebugInfo && !suppressNewCustomDebugInfo;
// Emit EnC info for all methods even if they do not have sequence points.
// The information facilitates reusing lambdas and closures. The reuse is important for runtimes that can't add new members (e.g. Mono).
bool emitEncInfo = compilationOptions.EnableEditAndContinue && _metadataWriter.IsFullMetadata && !suppressNewCustomDebugInfo;
byte[] blob = customDebugInfoWriter.SerializeMethodDebugInfo(Context, methodBody, methodHandle, emitStateMachineInfo: emitAllDebugInfo, emitEncInfo, emitDynamicAndTupleInfo, out bool emitExternNamespaces);
if (!emitAllDebugInfo && blob.Length == 0)
{
return;
}
int methodToken = MetadataTokens.GetToken(methodHandle);
OpenMethod(methodToken, methodBody.MethodDefinition);
if (emitAllDebugInfo)
{
var localScopes = methodBody.LocalScopes;
// Define locals, constants and namespaces in the outermost local scope (opened in OpenMethod):
if (localScopes.Length > 0)
{
DefineScopeLocals(localScopes[0], localSignatureHandleOpt);
}
if (!isKickoffMethod && methodBody.ImportScope != null)
{
if (customDebugInfoWriter.ShouldForwardNamespaceScopes(Context, methodBody, methodHandle, out IMethodDefinition forwardToMethod))
{
if (forwardToMethod != null)
{
UsingNamespace("@" + MetadataTokens.GetToken(_metadataWriter.GetMethodHandle(forwardToMethod)), methodBody.MethodDefinition);
}
// otherwise, the forwarding is done via custom debug info
}
else
{
DefineNamespaceScopes(methodBody);
}
}
DefineLocalScopes(localScopes, localSignatureHandleOpt);
EmitSequencePoints(methodBody.SequencePoints);
if (methodBody.MoveNextBodyInfo is AsyncMoveNextBodyDebugInfo asyncMoveNextInfo)
{
_symWriter.SetAsyncInfo(
methodToken,
MetadataTokens.GetToken(_metadataWriter.GetMethodHandle(asyncMoveNextInfo.KickoffMethod)),
asyncMoveNextInfo.CatchHandlerOffset,
asyncMoveNextInfo.YieldOffsets.AsSpan(),
asyncMoveNextInfo.ResumeOffsets.AsSpan());
}
if (emitExternNamespaces)
{
DefineAssemblyReferenceAliases();
}
}
if (blob.Length > 0)
{
_symWriter.DefineCustomMetadata(blob);
}
CloseMethod(methodBody.IL.Length);
}
private void DefineNamespaceScopes(IMethodBody methodBody)
{
var module = Module;
bool isVisualBasic = module.GenerateVisualBasicStylePdb;
IMethodDefinition method = methodBody.MethodDefinition;
var namespaceScopes = methodBody.ImportScope;
PooledHashSet<string> lazyDeclaredExternAliases = null;
if (!isVisualBasic)
{
for (var scope = namespaceScopes; scope != null; scope = scope.Parent)
{
foreach (var import in scope.GetUsedNamespaces())
{
if (import.TargetNamespaceOpt == null && import.TargetTypeOpt == null)
{
Debug.Assert(import.AliasOpt != null);
Debug.Assert(import.TargetAssemblyOpt == null);
if (lazyDeclaredExternAliases == null)
{
lazyDeclaredExternAliases = PooledHashSet<string>.GetInstance();
}
lazyDeclaredExternAliases.Add(import.AliasOpt);
}
}
}
}
// file and namespace level
for (IImportScope scope = namespaceScopes; scope != null; scope = scope.Parent)
{
foreach (UsedNamespaceOrType import in scope.GetUsedNamespaces())
{
var importString = TryEncodeImport(import, lazyDeclaredExternAliases, isProjectLevel: false);
if (importString != null)
{
UsingNamespace(importString, method);
}
}
}
lazyDeclaredExternAliases?.Free();
// project level
if (isVisualBasic)
{
string defaultNamespace = module.DefaultNamespace;
if (!string.IsNullOrEmpty(defaultNamespace))
{
// VB marks the default/root namespace with an asterisk
UsingNamespace("*" + defaultNamespace, module);
}
foreach (string assemblyName in module.LinkedAssembliesDebugInfo)
{
UsingNamespace("&" + assemblyName, module);
}
foreach (UsedNamespaceOrType import in module.GetImports())
{
var importString = TryEncodeImport(import, null, isProjectLevel: true);
if (importString != null)
{
UsingNamespace(importString, method);
}
}
// VB current namespace -- VB appends the namespace of the container without prefixes
UsingNamespace(GetOrCreateSerializedNamespaceName(method.ContainingNamespace), method);
}
}
private void DefineAssemblyReferenceAliases()
{
foreach (AssemblyReferenceAlias alias in Module.GetAssemblyReferenceAliases(Context))
{
UsingNamespace("Z" + alias.Name + " " + alias.Assembly.Identity.GetDisplayName(), Module);
}
}
private string TryEncodeImport(UsedNamespaceOrType import, HashSet<string> declaredExternAliasesOpt, bool isProjectLevel)
{
// NOTE: Dev12 has related cases "I" and "O" in EMITTER::ComputeDebugNamespace,
// but they were probably implementation details that do not affect Roslyn.
if (Module.GenerateVisualBasicStylePdb)
{
// VB doesn't support extern aliases
Debug.Assert(import.TargetAssemblyOpt == null);
Debug.Assert(declaredExternAliasesOpt == null);
if (import.TargetTypeOpt != null)
{
Debug.Assert(import.TargetNamespaceOpt == null);
Debug.Assert(import.TargetAssemblyOpt == null);
// Native compiler doesn't write imports with generic types to PDB.
if (import.TargetTypeOpt.IsTypeSpecification())
{
return null;
}
string typeName = GetOrCreateSerializedTypeName(import.TargetTypeOpt);
if (import.AliasOpt != null)
{
return (isProjectLevel ? "@PA:" : "@FA:") + import.AliasOpt + "=" + typeName;
}
else
{
return (isProjectLevel ? "@PT:" : "@FT:") + typeName;
}
}
if (import.TargetNamespaceOpt != null)
{
string namespaceName = GetOrCreateSerializedNamespaceName(import.TargetNamespaceOpt);
if (import.AliasOpt == null)
{
return (isProjectLevel ? "@P:" : "@F:") + namespaceName;
}
else
{
return (isProjectLevel ? "@PA:" : "@FA:") + import.AliasOpt + "=" + namespaceName;
}
}
Debug.Assert(import.AliasOpt != null);
Debug.Assert(import.TargetXmlNamespaceOpt != null);
return (isProjectLevel ? "@PX:" : "@FX:") + import.AliasOpt + "=" + import.TargetXmlNamespaceOpt;
}
Debug.Assert(import.TargetXmlNamespaceOpt == null);
if (import.TargetTypeOpt != null)
{
Debug.Assert(import.TargetNamespaceOpt == null);
Debug.Assert(import.TargetAssemblyOpt == null);
string typeName = GetOrCreateSerializedTypeName(import.TargetTypeOpt);
return (import.AliasOpt != null) ?
"A" + import.AliasOpt + " T" + typeName :
"T" + typeName;
}
if (import.TargetNamespaceOpt != null)
{
string namespaceName = GetOrCreateSerializedNamespaceName(import.TargetNamespaceOpt);
if (import.AliasOpt != null)
{
return (import.TargetAssemblyOpt != null) ?
"A" + import.AliasOpt + " E" + namespaceName + " " + GetAssemblyReferenceAlias(import.TargetAssemblyOpt, declaredExternAliasesOpt) :
"A" + import.AliasOpt + " U" + namespaceName;
}
else
{
return (import.TargetAssemblyOpt != null) ?
"E" + namespaceName + " " + GetAssemblyReferenceAlias(import.TargetAssemblyOpt, declaredExternAliasesOpt) :
"U" + namespaceName;
}
}
Debug.Assert(import.AliasOpt != null);
Debug.Assert(import.TargetAssemblyOpt == null);
return "X" + import.AliasOpt;
}
internal string GetOrCreateSerializedNamespaceName(INamespace @namespace)
{
string result;
if (!_qualifiedNameCache.TryGetValue(@namespace, out result))
{
result = TypeNameSerializer.BuildQualifiedNamespaceName(@namespace);
_qualifiedNameCache.Add(@namespace, result);
}
return result;
}
internal string GetOrCreateSerializedTypeName(ITypeReference typeReference)
{
string result;
if (!_qualifiedNameCache.TryGetValue(typeReference, out result))
{
if (Module.GenerateVisualBasicStylePdb)
{
result = SerializeVisualBasicImportTypeReference(typeReference);
}
else
{
result = typeReference.GetSerializedTypeName(Context);
}
_qualifiedNameCache.Add(typeReference, result);
}
return result;
}
private string SerializeVisualBasicImportTypeReference(ITypeReference typeReference)
{
Debug.Assert(!(typeReference is IArrayTypeReference));
Debug.Assert(!(typeReference is IPointerTypeReference));
Debug.Assert(!typeReference.IsTypeSpecification());
var result = PooledStringBuilder.GetInstance();
ArrayBuilder<string> nestedNamesReversed;
INestedTypeReference nestedType = typeReference.AsNestedTypeReference;
if (nestedType != null)
{
nestedNamesReversed = ArrayBuilder<string>.GetInstance();
while (nestedType != null)
{
nestedNamesReversed.Add(nestedType.Name);
typeReference = nestedType.GetContainingType(_metadataWriter.Context);
nestedType = typeReference.AsNestedTypeReference;
}
}
else
{
nestedNamesReversed = null;
}
INamespaceTypeReference namespaceType = typeReference.AsNamespaceTypeReference;
Debug.Assert(namespaceType != null);
string namespaceName = namespaceType.NamespaceName;
if (namespaceName.Length != 0)
{
result.Builder.Append(namespaceName);
result.Builder.Append('.');
}
result.Builder.Append(namespaceType.Name);
if (nestedNamesReversed != null)
{
for (int i = nestedNamesReversed.Count - 1; i >= 0; i--)
{
result.Builder.Append('.');
result.Builder.Append(nestedNamesReversed[i]);
}
nestedNamesReversed.Free();
}
return result.ToStringAndFree();
}
private string GetAssemblyReferenceAlias(IAssemblyReference assembly, HashSet<string> declaredExternAliases)
{
// no extern alias defined in scope at all -> error in compiler
Debug.Assert(declaredExternAliases != null);
var allAliases = _metadataWriter.Context.Module.GetAssemblyReferenceAliases(_metadataWriter.Context);
foreach (AssemblyReferenceAlias alias in allAliases)
{
// Multiple aliases may be given to an assembly reference.
// We find one that is in scope (was imported via extern alias directive).
// If multiple are in scope then use the first one.
// NOTE: Dev12 uses the one that appeared in source, whereas we use
// the first one that COULD have appeared in source. (DevDiv #913022)
// The reason we're not just using the alias from the syntax is that
// it is non-trivial to locate. In particular, since "." may be used in
// place of "::", determining whether the first identifier in the name is
// the alias requires binding. For example, "using A.B;" could refer to
// either "A::B" or "global::A.B".
if (assembly == alias.Assembly && declaredExternAliases.Contains(alias.Name))
{
return alias.Name;
}
}
// no alias defined in scope for given assembly -> error in compiler
throw ExceptionUtilities.Unreachable;
}
private void DefineLocalScopes(ImmutableArray<LocalScope> scopes, StandaloneSignatureHandle localSignatureHandleOpt)
{
// VB scope ranges are end-inclusive
bool endInclusive = this.Module.GenerateVisualBasicStylePdb;
// The order of OpenScope and CloseScope calls must follow the scope nesting.
var scopeStack = ArrayBuilder<LocalScope>.GetInstance();
for (int i = 1; i < scopes.Length; i++)
{
var currentScope = scopes[i];
// Close any scopes that have finished.
while (scopeStack.Count > 0)
{
LocalScope topScope = scopeStack.Last();
if (currentScope.StartOffset < topScope.StartOffset + topScope.Length)
{
break;
}
scopeStack.RemoveLast();
_symWriter.CloseScope(endInclusive ? topScope.EndOffset - 1 : topScope.EndOffset);
}
// Open this scope.
scopeStack.Add(currentScope);
_symWriter.OpenScope(currentScope.StartOffset);
DefineScopeLocals(currentScope, localSignatureHandleOpt);
}
// Close remaining scopes.
for (int i = scopeStack.Count - 1; i >= 0; i--)
{
LocalScope scope = scopeStack[i];
_symWriter.CloseScope(endInclusive ? scope.EndOffset - 1 : scope.EndOffset);
}
scopeStack.Free();
}
private void DefineScopeLocals(LocalScope currentScope, StandaloneSignatureHandle localSignatureHandleOpt)
{
foreach (ILocalDefinition scopeConstant in currentScope.Constants)
{
var signatureHandle = _metadataWriter.SerializeLocalConstantStandAloneSignature(scopeConstant);
if (!_metadataWriter.IsLocalNameTooLong(scopeConstant))
{
_symWriter.DefineLocalConstant(
scopeConstant.Name,
scopeConstant.CompileTimeValue.Value,
MetadataTokens.GetToken(signatureHandle));
}
}
foreach (ILocalDefinition scopeLocal in currentScope.Variables)
{
if (!_metadataWriter.IsLocalNameTooLong(scopeLocal))
{
Debug.Assert(scopeLocal.SlotIndex >= 0);
_symWriter.DefineLocalVariable(
scopeLocal.SlotIndex,
scopeLocal.Name,
(int)scopeLocal.PdbAttributes,
localSignatureHandleOpt.IsNil ? 0 : MetadataTokens.GetToken(localSignatureHandleOpt));
}
}
}
public void SetMetadataEmitter(MetadataWriter metadataWriter)
{
// Do not look for COM registered diasymreader when determinism is needed as it doesn't support it.
var options =
(IsDeterministic ? SymUnmanagedWriterCreationOptions.Deterministic : SymUnmanagedWriterCreationOptions.UseComRegistry) |
SymUnmanagedWriterCreationOptions.UseAlternativeLoadPath;
var metadataProvider = new SymWriterMetadataProvider(metadataWriter);
SymUnmanagedWriter symWriter;
try
{
symWriter = (_symWriterFactory != null) ? _symWriterFactory(metadataProvider) : SymUnmanagedWriterFactory.CreateWriter(metadataProvider, options);
}
catch (DllNotFoundException e)
{
throw new SymUnmanagedWriterException(e.Message);
}
catch (SymUnmanagedWriterException e) when (e.InnerException is NotSupportedException)
{
var message = IsDeterministic ? CodeAnalysisResources.SymWriterNotDeterministic : CodeAnalysisResources.SymWriterOlderVersionThanRequired;
throw new SymUnmanagedWriterException(string.Format(message, e.ImplementationModuleName));
}
_metadataWriter = metadataWriter;
_symWriter = symWriter;
_sequencePointsWriter = new SymUnmanagedSequencePointsWriter(symWriter, capacity: 64);
}
public BlobContentId GetContentId()
{
BlobContentId contentId;
if (IsDeterministic)
{
// Calculate hash of the stream content.
// Note: all bits of the signature currently stored in the PDB stream were initialized to 1 by InitializeDeterministic.
contentId = BlobContentId.FromHash(CryptographicHashProvider.ComputeHash(_hashAlgorithmNameOpt, _symWriter.GetUnderlyingData()));
_symWriter.UpdateSignature(contentId.Guid, contentId.Stamp, age: 1);
}
else
{
_symWriter.GetSignature(out Guid guid, out uint stamp, out int age);
Debug.Assert(age == Age);
contentId = new BlobContentId(guid, stamp);
}
// Once we calculate the content id we shall not write more data to the writer.
// Note that the underlying stream is accessible for reading even after the writer is disposed.
_symWriter.Dispose();
return contentId;
}
public void SetEntryPoint(int entryMethodToken)
{
_symWriter.SetEntryPoint(entryMethodToken);
}
private int GetDocumentIndex(DebugSourceDocument document)
{
if (_documentIndex.TryGetValue(document, out int documentIndex))
{
return documentIndex;
}
return AddDocumentIndex(document);
}
private int AddDocumentIndex(DebugSourceDocument document)
{
Guid algorithmId;
ReadOnlySpan<byte> checksum;
ReadOnlySpan<byte> embeddedSource;
DebugSourceInfo info = document.GetSourceInfo();
if (!info.Checksum.IsDefault)
{
algorithmId = info.ChecksumAlgorithmId;
checksum = info.Checksum.AsSpan();
}
else
{
algorithmId = default;
checksum = null;
}
if (!info.EmbeddedTextBlob.IsDefault)
{
embeddedSource = info.EmbeddedTextBlob.AsSpan();
}
else
{
embeddedSource = null;
}
int documentIndex = _symWriter.DefineDocument(
document.Location,
document.Language,
document.LanguageVendor,
document.DocumentType,
algorithmId,
checksum,
embeddedSource);
_documentIndex.Add(document, documentIndex);
return documentIndex;
}
private void OpenMethod(int methodToken, IMethodDefinition method)
{
_symWriter.OpenMethod(methodToken);
// open outermost scope:
_symWriter.OpenScope(startOffset: 0);
}
private void CloseMethod(int ilLength)
{
// close the root scope:
_symWriter.CloseScope(endOffset: ilLength);
_symWriter.CloseMethod();
}
private void UsingNamespace(string fullName, INamedEntity errorEntity)
{
if (!_metadataWriter.IsUsingStringTooLong(fullName, errorEntity))
{
_symWriter.UsingNamespace(fullName);
}
}
private void EmitSequencePoints(ImmutableArray<SequencePoint> sequencePoints)
{
int lastDocumentIndex = -1;
DebugSourceDocument lastDocument = null;
foreach (var sequencePoint in sequencePoints)
{
Debug.Assert(sequencePoint.Document != null);
var document = sequencePoint.Document;
int documentIndex;
if (lastDocument == document)
{
documentIndex = lastDocumentIndex;
}
else
{
lastDocument = document;
documentIndex = lastDocumentIndex = GetDocumentIndex(lastDocument);
}
_sequencePointsWriter.Add(
documentIndex,
sequencePoint.Offset,
sequencePoint.StartLine,
sequencePoint.StartColumn,
sequencePoint.EndLine,
sequencePoint.EndColumn);
}
_sequencePointsWriter.Flush();
}
[Conditional("DEBUG")]
// Used to catch cases where file2definitions contain nonwritable definitions early
// If left unfixed, such scenarios will lead to crashes if happen in winmdobj projects
public void AssertAllDefinitionsHaveTokens(MultiDictionary<DebugSourceDocument, DefinitionWithLocation> file2definitions)
{
foreach (var kvp in file2definitions)
{
foreach (var definition in kvp.Value)
{
EntityHandle handle = _metadataWriter.GetDefinitionHandle(definition.Definition);
Debug.Assert(!handle.IsNil);
}
}
}
// Note: only used for WinMD
public void WriteDefinitionLocations(MultiDictionary<DebugSourceDocument, DefinitionWithLocation> file2definitions)
{
// Only open and close the map if we have any mapping.
bool open = false;
foreach (var kvp in file2definitions)
{
foreach (var definition in kvp.Value)
{
if (!open)
{
_symWriter.OpenTokensToSourceSpansMap();
open = true;
}
int token = MetadataTokens.GetToken(_metadataWriter.GetDefinitionHandle(definition.Definition));
Debug.Assert(token != 0);
_symWriter.MapTokenToSourceSpan(
token,
GetDocumentIndex(kvp.Key),
definition.StartLine + 1,
definition.StartColumn + 1,
definition.EndLine + 1,
definition.EndColumn + 1);
}
}
if (open)
{
_symWriter.CloseTokensToSourceSpansMap();
}
}
public void EmbedSourceLink(Stream stream)
{
byte[] bytes;
try
{
bytes = stream.ReadAllBytes();
}
catch (Exception e)
{
throw new SymUnmanagedWriterException(e.Message, e);
}
try
{
_symWriter.SetSourceLinkData(bytes);
}
catch (SymUnmanagedWriterException e) when (e.InnerException is NotSupportedException)
{
throw new SymUnmanagedWriterException(string.Format(CodeAnalysisResources.SymWriterDoesNotSupportSourceLink, e.ImplementationModuleName));
}
}
/// <summary>
/// Write document entries for all debug documents that do not yet have an entry.
/// </summary>
/// <remarks>
/// This is done after serializing method debug info to ensure that we embed all requested
/// text even if there are no corresponding sequence points.
/// </remarks>
public void WriteRemainingDebugDocuments(IReadOnlyDictionary<string, DebugSourceDocument> documents)
{
foreach (var kvp in documents
.Where(kvp => !_documentIndex.ContainsKey(kvp.Value))
.OrderBy(kvp => kvp.Key))
{
AddDocumentIndex(kvp.Value);
}
}
}
}
| 1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Compilers/Core/Portable/PEWriter/CustomDebugInfoWriter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Diagnostics;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.Cci
{
internal sealed class CustomDebugInfoWriter
{
private MethodDefinitionHandle _methodWithModuleInfo;
private IMethodBody _methodBodyWithModuleInfo;
private MethodDefinitionHandle _previousMethodWithUsingInfo;
private IMethodBody _previousMethodBodyWithUsingInfo;
private readonly PdbWriter _pdbWriter;
public CustomDebugInfoWriter(PdbWriter pdbWriter)
{
Debug.Assert(pdbWriter != null);
_pdbWriter = pdbWriter;
}
/// <summary>
/// Returns true if the namespace scope for this method should be forwarded to another method.
/// Returns non-null <paramref name="forwardToMethod"/> if the forwarding should be done directly via UsingNamespace,
/// null if the forwarding is done via custom debug info.
/// </summary>
public bool ShouldForwardNamespaceScopes(EmitContext context, IMethodBody methodBody, MethodDefinitionHandle methodHandle, out IMethodDefinition forwardToMethod)
{
if (ShouldForwardToPreviousMethodWithUsingInfo(context, methodBody))
{
// SerializeNamespaceScopeMetadata will do the actual forwarding in case this is a CSharp method.
// VB on the other hand adds a "@methodtoken" to the scopes instead.
if (context.Module.GenerateVisualBasicStylePdb)
{
forwardToMethod = _previousMethodBodyWithUsingInfo.MethodDefinition;
}
else
{
forwardToMethod = null;
}
return true;
}
_previousMethodBodyWithUsingInfo = methodBody;
_previousMethodWithUsingInfo = methodHandle;
forwardToMethod = null;
return false;
}
public byte[] SerializeMethodDebugInfo(EmitContext context, IMethodBody methodBody, MethodDefinitionHandle methodHandle, bool emitEncInfo, bool suppressNewCustomDebugInfo, out bool emitExternNamespaces)
{
emitExternNamespaces = false;
// CONSIDER: this may not be the same "first" method as in Dev10, but
// it shouldn't matter since all methods will still forward to a method
// containing the appropriate information.
if (_methodBodyWithModuleInfo == null)
{
// This module level information could go on every method (and does in
// the edit-and-continue case), but - as an optimization - we'll just
// put it on the first method we happen to encounter and then put a
// reference to the first method's token in every other method (so they
// can find the information).
if (context.Module.GetAssemblyReferenceAliases(context).Any())
{
_methodWithModuleInfo = methodHandle;
_methodBodyWithModuleInfo = methodBody;
emitExternNamespaces = true;
}
}
var pooledBuilder = PooledBlobBuilder.GetInstance();
var encoder = new CustomDebugInfoEncoder(pooledBuilder);
if (methodBody.StateMachineTypeName != null)
{
encoder.AddStateMachineTypeName(methodBody.StateMachineTypeName);
}
else
{
SerializeNamespaceScopeMetadata(ref encoder, context, methodBody);
encoder.AddStateMachineHoistedLocalScopes(methodBody.StateMachineHoistedLocalScopes);
}
if (!suppressNewCustomDebugInfo)
{
SerializeDynamicLocalInfo(ref encoder, methodBody);
SerializeTupleElementNames(ref encoder, methodBody);
if (emitEncInfo)
{
var encMethodInfo = MetadataWriter.GetEncMethodDebugInfo(methodBody);
SerializeCustomDebugInformation(ref encoder, encMethodInfo);
}
}
byte[] result = encoder.ToArray();
pooledBuilder.Free();
return result;
}
// internal for testing
internal static void SerializeCustomDebugInformation(ref CustomDebugInfoEncoder encoder, EditAndContinueMethodDebugInformation debugInfo)
{
// PERF: note that we pass debugInfo as explicit parameter
// that is intentional to avoid capturing debugInfo as that
// would result in a lot of delegate allocations here that are otherwise can be avoided.
if (!debugInfo.LocalSlots.IsDefaultOrEmpty)
{
encoder.AddRecord(
CustomDebugInfoKind.EditAndContinueLocalSlotMap,
debugInfo,
(info, builder) => info.SerializeLocalSlots(builder));
}
if (!debugInfo.Lambdas.IsDefaultOrEmpty)
{
encoder.AddRecord(
CustomDebugInfoKind.EditAndContinueLambdaMap,
debugInfo,
(info, builder) => info.SerializeLambdaMap(builder));
}
}
private static ArrayBuilder<T> GetLocalInfoToSerialize<T>(
IMethodBody methodBody,
Func<ILocalDefinition, bool> filter,
Func<LocalScope, ILocalDefinition, T> getInfo)
{
ArrayBuilder<T> builder = null;
foreach (var currentScope in methodBody.LocalScopes)
{
foreach (var local in currentScope.Variables)
{
Debug.Assert(local.SlotIndex >= 0);
if (filter(local))
{
if (builder == null)
{
builder = ArrayBuilder<T>.GetInstance();
}
builder.Add(getInfo(default(LocalScope), local));
}
}
foreach (var localConstant in currentScope.Constants)
{
Debug.Assert(localConstant.SlotIndex < 0);
if (filter(localConstant))
{
if (builder == null)
{
builder = ArrayBuilder<T>.GetInstance();
}
builder.Add(getInfo(currentScope, localConstant));
}
}
}
return builder;
}
private static void SerializeDynamicLocalInfo(ref CustomDebugInfoEncoder encoder, IMethodBody methodBody)
{
if (!methodBody.HasDynamicLocalVariables)
{
return;
}
byte[] GetDynamicFlags(ILocalDefinition local)
{
var dynamicTransformFlags = local.DynamicTransformFlags;
var flags = new byte[CustomDebugInfoEncoder.DynamicAttributeSize];
for (int k = 0; k < dynamicTransformFlags.Length; k++)
{
if (dynamicTransformFlags[k])
{
flags[k] = 1;
}
}
return flags;
}
var dynamicLocals = GetLocalInfoToSerialize(
methodBody,
local =>
{
var dynamicTransformFlags = local.DynamicTransformFlags;
return !dynamicTransformFlags.IsEmpty &&
dynamicTransformFlags.Length <= CustomDebugInfoEncoder.DynamicAttributeSize &&
local.Name.Length < CustomDebugInfoEncoder.IdentifierSize;
},
(scope, local) => (local.Name, GetDynamicFlags(local), local.DynamicTransformFlags.Length, (local.SlotIndex < 0) ? 0 : local.SlotIndex));
if (dynamicLocals == null)
{
return;
}
encoder.AddDynamicLocals(dynamicLocals);
dynamicLocals.Free();
}
private static void SerializeTupleElementNames(ref CustomDebugInfoEncoder encoder, IMethodBody methodBody)
{
var locals = GetLocalInfoToSerialize(
methodBody,
local => !local.TupleElementNames.IsEmpty,
(scope, local) => (local.Name, local.SlotIndex, scope.StartOffset, scope.EndOffset, local.TupleElementNames));
if (locals == null)
{
return;
}
encoder.AddTupleElementNames(locals);
locals.Free();
}
private void SerializeNamespaceScopeMetadata(ref CustomDebugInfoEncoder encoder, EmitContext context, IMethodBody methodBody)
{
if (context.Module.GenerateVisualBasicStylePdb)
{
return;
}
if (ShouldForwardToPreviousMethodWithUsingInfo(context, methodBody))
{
Debug.Assert(!ReferenceEquals(_previousMethodBodyWithUsingInfo, methodBody));
encoder.AddForwardMethodInfo(_previousMethodWithUsingInfo);
return;
}
var usingCounts = ArrayBuilder<int>.GetInstance();
for (IImportScope scope = methodBody.ImportScope; scope != null; scope = scope.Parent)
{
usingCounts.Add(scope.GetUsedNamespaces().Length);
}
encoder.AddUsingGroups(usingCounts);
usingCounts.Free();
if (_methodBodyWithModuleInfo != null && !ReferenceEquals(_methodBodyWithModuleInfo, methodBody))
{
encoder.AddForwardModuleInfo(_methodWithModuleInfo);
}
}
private bool ShouldForwardToPreviousMethodWithUsingInfo(EmitContext context, IMethodBody methodBody)
{
if (_previousMethodBodyWithUsingInfo == null ||
ReferenceEquals(_previousMethodBodyWithUsingInfo, methodBody))
{
return false;
}
// VB includes method namespace in namespace scopes:
if (context.Module.GenerateVisualBasicStylePdb)
{
if (_pdbWriter.GetOrCreateSerializedNamespaceName(_previousMethodBodyWithUsingInfo.MethodDefinition.ContainingNamespace) !=
_pdbWriter.GetOrCreateSerializedNamespaceName(methodBody.MethodDefinition.ContainingNamespace))
{
return false;
}
}
var previousScopes = _previousMethodBodyWithUsingInfo.ImportScope;
// methods share the same import scope (common case for methods declared in the same file)
if (methodBody.ImportScope == previousScopes)
{
return true;
}
// If methods are in different files they don't share the same scopes,
// but the imports might be the same nevertheless.
// Note: not comparing project-level imports since those are the same for all method bodies.
var s1 = methodBody.ImportScope;
var s2 = previousScopes;
while (s1 != null && s2 != null)
{
if (!s1.GetUsedNamespaces().SequenceEqual(s2.GetUsedNamespaces()))
{
return false;
}
s1 = s1.Parent;
s2 = s2.Parent;
}
return s1 == s2;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Diagnostics;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.Cci
{
internal sealed class CustomDebugInfoWriter
{
private MethodDefinitionHandle _methodWithModuleInfo;
private IMethodBody _methodBodyWithModuleInfo;
private MethodDefinitionHandle _previousMethodWithUsingInfo;
private IMethodBody _previousMethodBodyWithUsingInfo;
private readonly PdbWriter _pdbWriter;
public CustomDebugInfoWriter(PdbWriter pdbWriter)
{
Debug.Assert(pdbWriter != null);
_pdbWriter = pdbWriter;
}
/// <summary>
/// Returns true if the namespace scope for this method should be forwarded to another method.
/// Returns non-null <paramref name="forwardToMethod"/> if the forwarding should be done directly via UsingNamespace,
/// null if the forwarding is done via custom debug info.
/// </summary>
public bool ShouldForwardNamespaceScopes(EmitContext context, IMethodBody methodBody, MethodDefinitionHandle methodHandle, out IMethodDefinition forwardToMethod)
{
if (ShouldForwardToPreviousMethodWithUsingInfo(context, methodBody))
{
// SerializeNamespaceScopeMetadata will do the actual forwarding in case this is a CSharp method.
// VB on the other hand adds a "@methodtoken" to the scopes instead.
if (context.Module.GenerateVisualBasicStylePdb)
{
forwardToMethod = _previousMethodBodyWithUsingInfo.MethodDefinition;
}
else
{
forwardToMethod = null;
}
return true;
}
_previousMethodBodyWithUsingInfo = methodBody;
_previousMethodWithUsingInfo = methodHandle;
forwardToMethod = null;
return false;
}
public byte[] SerializeMethodDebugInfo(
EmitContext context,
IMethodBody methodBody,
MethodDefinitionHandle methodHandle,
bool emitStateMachineInfo,
bool emitEncInfo,
bool emitDynamicAndTupleInfo,
out bool emitExternNamespaces)
{
emitExternNamespaces = false;
// CONSIDER: this may not be the same "first" method as in Dev10, but
// it shouldn't matter since all methods will still forward to a method
// containing the appropriate information.
if (_methodBodyWithModuleInfo == null)
{
// This module level information could go on every method (and does in
// the edit-and-continue case), but - as an optimization - we'll just
// put it on the first method we happen to encounter and then put a
// reference to the first method's token in every other method (so they
// can find the information).
if (context.Module.GetAssemblyReferenceAliases(context).Any())
{
_methodWithModuleInfo = methodHandle;
_methodBodyWithModuleInfo = methodBody;
emitExternNamespaces = true;
}
}
var pooledBuilder = PooledBlobBuilder.GetInstance();
var encoder = new CustomDebugInfoEncoder(pooledBuilder);
if (emitStateMachineInfo)
{
if (methodBody.StateMachineTypeName != null)
{
encoder.AddStateMachineTypeName(methodBody.StateMachineTypeName);
}
else
{
SerializeNamespaceScopeMetadata(ref encoder, context, methodBody);
encoder.AddStateMachineHoistedLocalScopes(methodBody.StateMachineHoistedLocalScopes);
}
}
if (emitDynamicAndTupleInfo)
{
SerializeDynamicLocalInfo(ref encoder, methodBody);
SerializeTupleElementNames(ref encoder, methodBody);
}
if (emitEncInfo)
{
var encMethodInfo = MetadataWriter.GetEncMethodDebugInfo(methodBody);
SerializeCustomDebugInformation(ref encoder, encMethodInfo);
}
byte[] result = encoder.ToArray() ?? Array.Empty<byte>();
pooledBuilder.Free();
return result;
}
// internal for testing
internal static void SerializeCustomDebugInformation(ref CustomDebugInfoEncoder encoder, EditAndContinueMethodDebugInformation debugInfo)
{
// PERF: note that we pass debugInfo as explicit parameter
// that is intentional to avoid capturing debugInfo as that
// would result in a lot of delegate allocations here that are otherwise can be avoided.
if (!debugInfo.LocalSlots.IsDefaultOrEmpty)
{
encoder.AddRecord(
CustomDebugInfoKind.EditAndContinueLocalSlotMap,
debugInfo,
(info, builder) => info.SerializeLocalSlots(builder));
}
if (!debugInfo.Lambdas.IsDefaultOrEmpty)
{
encoder.AddRecord(
CustomDebugInfoKind.EditAndContinueLambdaMap,
debugInfo,
(info, builder) => info.SerializeLambdaMap(builder));
}
}
private static ArrayBuilder<T> GetLocalInfoToSerialize<T>(
IMethodBody methodBody,
Func<ILocalDefinition, bool> filter,
Func<LocalScope, ILocalDefinition, T> getInfo)
{
ArrayBuilder<T> builder = null;
foreach (var currentScope in methodBody.LocalScopes)
{
foreach (var local in currentScope.Variables)
{
Debug.Assert(local.SlotIndex >= 0);
if (filter(local))
{
if (builder == null)
{
builder = ArrayBuilder<T>.GetInstance();
}
builder.Add(getInfo(default(LocalScope), local));
}
}
foreach (var localConstant in currentScope.Constants)
{
Debug.Assert(localConstant.SlotIndex < 0);
if (filter(localConstant))
{
if (builder == null)
{
builder = ArrayBuilder<T>.GetInstance();
}
builder.Add(getInfo(currentScope, localConstant));
}
}
}
return builder;
}
private static void SerializeDynamicLocalInfo(ref CustomDebugInfoEncoder encoder, IMethodBody methodBody)
{
if (!methodBody.HasDynamicLocalVariables)
{
return;
}
byte[] GetDynamicFlags(ILocalDefinition local)
{
var dynamicTransformFlags = local.DynamicTransformFlags;
var flags = new byte[CustomDebugInfoEncoder.DynamicAttributeSize];
for (int k = 0; k < dynamicTransformFlags.Length; k++)
{
if (dynamicTransformFlags[k])
{
flags[k] = 1;
}
}
return flags;
}
var dynamicLocals = GetLocalInfoToSerialize(
methodBody,
local =>
{
var dynamicTransformFlags = local.DynamicTransformFlags;
return !dynamicTransformFlags.IsEmpty &&
dynamicTransformFlags.Length <= CustomDebugInfoEncoder.DynamicAttributeSize &&
local.Name.Length < CustomDebugInfoEncoder.IdentifierSize;
},
(scope, local) => (local.Name, GetDynamicFlags(local), local.DynamicTransformFlags.Length, (local.SlotIndex < 0) ? 0 : local.SlotIndex));
if (dynamicLocals == null)
{
return;
}
encoder.AddDynamicLocals(dynamicLocals);
dynamicLocals.Free();
}
private static void SerializeTupleElementNames(ref CustomDebugInfoEncoder encoder, IMethodBody methodBody)
{
var locals = GetLocalInfoToSerialize(
methodBody,
local => !local.TupleElementNames.IsEmpty,
(scope, local) => (local.Name, local.SlotIndex, scope.StartOffset, scope.EndOffset, local.TupleElementNames));
if (locals == null)
{
return;
}
encoder.AddTupleElementNames(locals);
locals.Free();
}
private void SerializeNamespaceScopeMetadata(ref CustomDebugInfoEncoder encoder, EmitContext context, IMethodBody methodBody)
{
if (context.Module.GenerateVisualBasicStylePdb)
{
return;
}
if (ShouldForwardToPreviousMethodWithUsingInfo(context, methodBody))
{
Debug.Assert(!ReferenceEquals(_previousMethodBodyWithUsingInfo, methodBody));
encoder.AddForwardMethodInfo(_previousMethodWithUsingInfo);
return;
}
var usingCounts = ArrayBuilder<int>.GetInstance();
for (IImportScope scope = methodBody.ImportScope; scope != null; scope = scope.Parent)
{
usingCounts.Add(scope.GetUsedNamespaces().Length);
}
encoder.AddUsingGroups(usingCounts);
usingCounts.Free();
if (_methodBodyWithModuleInfo != null && !ReferenceEquals(_methodBodyWithModuleInfo, methodBody))
{
encoder.AddForwardModuleInfo(_methodWithModuleInfo);
}
}
private bool ShouldForwardToPreviousMethodWithUsingInfo(EmitContext context, IMethodBody methodBody)
{
if (_previousMethodBodyWithUsingInfo == null ||
ReferenceEquals(_previousMethodBodyWithUsingInfo, methodBody))
{
return false;
}
// VB includes method namespace in namespace scopes:
if (context.Module.GenerateVisualBasicStylePdb)
{
if (_pdbWriter.GetOrCreateSerializedNamespaceName(_previousMethodBodyWithUsingInfo.MethodDefinition.ContainingNamespace) !=
_pdbWriter.GetOrCreateSerializedNamespaceName(methodBody.MethodDefinition.ContainingNamespace))
{
return false;
}
}
var previousScopes = _previousMethodBodyWithUsingInfo.ImportScope;
// methods share the same import scope (common case for methods declared in the same file)
if (methodBody.ImportScope == previousScopes)
{
return true;
}
// If methods are in different files they don't share the same scopes,
// but the imports might be the same nevertheless.
// Note: not comparing project-level imports since those are the same for all method bodies.
var s1 = methodBody.ImportScope;
var s2 = previousScopes;
while (s1 != null && s2 != null)
{
if (!s1.GetUsedNamespaces().SequenceEqual(s2.GetUsedNamespaces()))
{
return false;
}
s1 = s1.Parent;
s2 = s2.Parent;
}
return s1 == s2;
}
}
}
| 1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Compilers/Core/Portable/PEWriter/MetadataWriter.PortablePdb.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.DiaSymReader;
using Roslyn.Utilities;
namespace Microsoft.Cci
{
internal partial class MetadataWriter
{
/// <summary>
/// Import scopes are associated with binders (in C#) and thus multiple instances might be created for a single set of imports.
/// We consider scopes with the same parent and the same imports the same.
/// Internal for testing.
/// </summary>
internal sealed class ImportScopeEqualityComparer : IEqualityComparer<IImportScope>
{
public static readonly ImportScopeEqualityComparer Instance = new ImportScopeEqualityComparer();
public bool Equals(IImportScope x, IImportScope y)
{
return (object)x == y ||
x != null && y != null && Equals(x.Parent, y.Parent) && x.GetUsedNamespaces().SequenceEqual(y.GetUsedNamespaces());
}
public int GetHashCode(IImportScope obj)
{
return Hash.Combine(Hash.CombineValues(obj.GetUsedNamespaces()), obj.Parent != null ? GetHashCode(obj.Parent) : 0);
}
}
private readonly Dictionary<DebugSourceDocument, DocumentHandle> _documentIndex = new Dictionary<DebugSourceDocument, DocumentHandle>();
private readonly Dictionary<IImportScope, ImportScopeHandle> _scopeIndex = new Dictionary<IImportScope, ImportScopeHandle>(ImportScopeEqualityComparer.Instance);
private void SerializeMethodDebugInfo(IMethodBody bodyOpt, int methodRid, int aggregateMethodRid, StandaloneSignatureHandle localSignatureHandleOpt, ref LocalVariableHandle lastLocalVariableHandle, ref LocalConstantHandle lastLocalConstantHandle)
{
if (bodyOpt == null)
{
_debugMetadataOpt.AddMethodDebugInformation(default(DocumentHandle), default(BlobHandle));
return;
}
bool isKickoffMethod = bodyOpt.StateMachineTypeName != null;
bool emitDebugInfo = isKickoffMethod || !bodyOpt.SequencePoints.IsEmpty;
if (!emitDebugInfo)
{
_debugMetadataOpt.AddMethodDebugInformation(default(DocumentHandle), default(BlobHandle));
return;
}
var methodHandle = MetadataTokens.MethodDefinitionHandle(methodRid);
var bodyImportScope = bodyOpt.ImportScope;
var importScopeHandle = (bodyImportScope != null) ? GetImportScopeIndex(bodyImportScope, _scopeIndex) : default(ImportScopeHandle);
// documents & sequence points:
DocumentHandle singleDocumentHandle;
BlobHandle sequencePointsBlob = SerializeSequencePoints(localSignatureHandleOpt, bodyOpt.SequencePoints, _documentIndex, out singleDocumentHandle);
_debugMetadataOpt.AddMethodDebugInformation(document: singleDocumentHandle, sequencePoints: sequencePointsBlob);
// Unlike native PDB we don't emit an empty root scope.
// scopes are already ordered by StartOffset ascending then by EndOffset descending (the longest scope first).
if (bodyOpt.LocalScopes.Length == 0)
{
// TODO: the compiler should produce a scope for each debuggable method
_debugMetadataOpt.AddLocalScope(
method: methodHandle,
importScope: importScopeHandle,
variableList: NextHandle(lastLocalVariableHandle),
constantList: NextHandle(lastLocalConstantHandle),
startOffset: 0,
length: bodyOpt.IL.Length);
}
else
{
foreach (LocalScope scope in bodyOpt.LocalScopes)
{
_debugMetadataOpt.AddLocalScope(
method: methodHandle,
importScope: importScopeHandle,
variableList: NextHandle(lastLocalVariableHandle),
constantList: NextHandle(lastLocalConstantHandle),
startOffset: scope.StartOffset,
length: scope.Length);
foreach (ILocalDefinition local in scope.Variables)
{
Debug.Assert(local.SlotIndex >= 0);
lastLocalVariableHandle = _debugMetadataOpt.AddLocalVariable(
attributes: local.PdbAttributes,
index: local.SlotIndex,
name: _debugMetadataOpt.GetOrAddString(local.Name));
SerializeLocalInfo(local, lastLocalVariableHandle);
}
foreach (ILocalDefinition constant in scope.Constants)
{
var mdConstant = constant.CompileTimeValue;
Debug.Assert(mdConstant != null);
lastLocalConstantHandle = _debugMetadataOpt.AddLocalConstant(
name: _debugMetadataOpt.GetOrAddString(constant.Name),
signature: SerializeLocalConstantSignature(constant));
SerializeLocalInfo(constant, lastLocalConstantHandle);
}
}
}
var moveNextBodyInfo = bodyOpt.MoveNextBodyInfo;
if (moveNextBodyInfo != null)
{
_debugMetadataOpt.AddStateMachineMethod(
moveNextMethod: methodHandle,
kickoffMethod: GetMethodDefinitionHandle(moveNextBodyInfo.KickoffMethod));
if (moveNextBodyInfo is AsyncMoveNextBodyDebugInfo asyncInfo)
{
SerializeAsyncMethodSteppingInfo(asyncInfo, methodHandle, aggregateMethodRid);
}
}
SerializeStateMachineLocalScopes(bodyOpt, methodHandle);
// delta doesn't need this information - we use information recorded by previous generation emit
if (Context.Module.CommonCompilation.Options.EnableEditAndContinue && IsFullMetadata)
{
SerializeEncMethodDebugInformation(bodyOpt, methodHandle);
}
}
private static LocalVariableHandle NextHandle(LocalVariableHandle handle) =>
MetadataTokens.LocalVariableHandle(MetadataTokens.GetRowNumber(handle) + 1);
private static LocalConstantHandle NextHandle(LocalConstantHandle handle) =>
MetadataTokens.LocalConstantHandle(MetadataTokens.GetRowNumber(handle) + 1);
private BlobHandle SerializeLocalConstantSignature(ILocalDefinition localConstant)
{
var builder = new BlobBuilder();
// TODO: BlobEncoder.LocalConstantSignature
// CustomMod*
var encoder = new CustomModifiersEncoder(builder);
SerializeCustomModifiers(encoder, localConstant.CustomModifiers);
var type = localConstant.Type;
var typeCode = type.TypeCode;
object value = localConstant.CompileTimeValue.Value;
// PrimitiveConstant or EnumConstant
if (value is decimal)
{
builder.WriteByte((byte)SignatureTypeKind.ValueType);
builder.WriteCompressedInteger(CodedIndex.TypeDefOrRefOrSpec(GetTypeHandle(type)));
builder.WriteDecimal((decimal)value);
}
else if (value is DateTime)
{
builder.WriteByte((byte)SignatureTypeKind.ValueType);
builder.WriteCompressedInteger(CodedIndex.TypeDefOrRefOrSpec(GetTypeHandle(type)));
builder.WriteDateTime((DateTime)value);
}
else if (typeCode == PrimitiveTypeCode.String)
{
builder.WriteByte((byte)ConstantTypeCode.String);
if (value == null)
{
builder.WriteByte(0xff);
}
else
{
builder.WriteUTF16((string)value);
}
}
else if (value != null)
{
// TypeCode
builder.WriteByte((byte)GetConstantTypeCode(value));
// Value
builder.WriteConstant(value);
// EnumType
if (type.IsEnum)
{
builder.WriteCompressedInteger(CodedIndex.TypeDefOrRefOrSpec(GetTypeHandle(type)));
}
}
else if (this.module.IsPlatformType(type, PlatformType.SystemObject))
{
builder.WriteByte((byte)SignatureTypeCode.Object);
}
else
{
builder.WriteByte((byte)(type.IsValueType ? SignatureTypeKind.ValueType : SignatureTypeKind.Class));
builder.WriteCompressedInteger(CodedIndex.TypeDefOrRefOrSpec(GetTypeHandle(type)));
}
return _debugMetadataOpt.GetOrAddBlob(builder);
}
private static SignatureTypeCode GetConstantTypeCode(object value)
{
if (value == null)
{
// The encoding of Type for the nullref value for FieldInit is ELEMENT_TYPE_CLASS with a Value of a zero.
return (SignatureTypeCode)SignatureTypeKind.Class;
}
Debug.Assert(!value.GetType().GetTypeInfo().IsEnum);
// Perf: Note that JIT optimizes each expression val.GetType() == typeof(T) to a single register comparison.
// Also the checks are sorted by commonality of the checked types.
if (value.GetType() == typeof(int))
{
return SignatureTypeCode.Int32;
}
if (value.GetType() == typeof(string))
{
return SignatureTypeCode.String;
}
if (value.GetType() == typeof(bool))
{
return SignatureTypeCode.Boolean;
}
if (value.GetType() == typeof(char))
{
return SignatureTypeCode.Char;
}
if (value.GetType() == typeof(byte))
{
return SignatureTypeCode.Byte;
}
if (value.GetType() == typeof(long))
{
return SignatureTypeCode.Int64;
}
if (value.GetType() == typeof(double))
{
return SignatureTypeCode.Double;
}
if (value.GetType() == typeof(short))
{
return SignatureTypeCode.Int16;
}
if (value.GetType() == typeof(ushort))
{
return SignatureTypeCode.UInt16;
}
if (value.GetType() == typeof(uint))
{
return SignatureTypeCode.UInt32;
}
if (value.GetType() == typeof(sbyte))
{
return SignatureTypeCode.SByte;
}
if (value.GetType() == typeof(ulong))
{
return SignatureTypeCode.UInt64;
}
if (value.GetType() == typeof(float))
{
return SignatureTypeCode.Single;
}
throw ExceptionUtilities.Unreachable;
}
#region ImportScope
private static readonly ImportScopeHandle ModuleImportScopeHandle = MetadataTokens.ImportScopeHandle(1);
private void SerializeImport(BlobBuilder writer, AssemblyReferenceAlias alias)
{
// <import> ::= AliasAssemblyReference <alias> <target-assembly>
writer.WriteByte((byte)ImportDefinitionKind.AliasAssemblyReference);
writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(alias.Name)));
writer.WriteCompressedInteger(MetadataTokens.GetRowNumber(GetOrAddAssemblyReferenceHandle(alias.Assembly)));
}
private void SerializeImport(BlobBuilder writer, UsedNamespaceOrType import)
{
if (import.TargetXmlNamespaceOpt != null)
{
Debug.Assert(import.TargetNamespaceOpt == null);
Debug.Assert(import.TargetAssemblyOpt == null);
Debug.Assert(import.TargetTypeOpt == null);
// <import> ::= ImportXmlNamespace <alias> <target-namespace>
writer.WriteByte((byte)ImportDefinitionKind.ImportXmlNamespace);
writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(import.AliasOpt)));
writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(import.TargetXmlNamespaceOpt)));
}
else if (import.TargetTypeOpt != null)
{
Debug.Assert(import.TargetNamespaceOpt == null);
Debug.Assert(import.TargetAssemblyOpt == null);
if (import.AliasOpt != null)
{
// <import> ::= AliasType <alias> <target-type>
writer.WriteByte((byte)ImportDefinitionKind.AliasType);
writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(import.AliasOpt)));
}
else
{
// <import> ::= ImportType <target-type>
writer.WriteByte((byte)ImportDefinitionKind.ImportType);
}
writer.WriteCompressedInteger(CodedIndex.TypeDefOrRefOrSpec(GetTypeHandle(import.TargetTypeOpt))); // TODO: index in release build
}
else if (import.TargetNamespaceOpt != null)
{
if (import.TargetAssemblyOpt != null)
{
if (import.AliasOpt != null)
{
// <import> ::= AliasAssemblyNamespace <alias> <target-assembly> <target-namespace>
writer.WriteByte((byte)ImportDefinitionKind.AliasAssemblyNamespace);
writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(import.AliasOpt)));
}
else
{
// <import> ::= ImportAssemblyNamespace <target-assembly> <target-namespace>
writer.WriteByte((byte)ImportDefinitionKind.ImportAssemblyNamespace);
}
writer.WriteCompressedInteger(MetadataTokens.GetRowNumber(GetAssemblyReferenceHandle(import.TargetAssemblyOpt)));
}
else
{
if (import.AliasOpt != null)
{
// <import> ::= AliasNamespace <alias> <target-namespace>
writer.WriteByte((byte)ImportDefinitionKind.AliasNamespace);
writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(import.AliasOpt)));
}
else
{
// <import> ::= ImportNamespace <target-namespace>
writer.WriteByte((byte)ImportDefinitionKind.ImportNamespace);
}
}
// TODO: cache?
string namespaceName = TypeNameSerializer.BuildQualifiedNamespaceName(import.TargetNamespaceOpt);
writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(namespaceName)));
}
else
{
// <import> ::= ImportReferenceAlias <alias>
Debug.Assert(import.AliasOpt != null);
Debug.Assert(import.TargetAssemblyOpt == null);
writer.WriteByte((byte)ImportDefinitionKind.ImportAssemblyReferenceAlias);
writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(import.AliasOpt)));
}
}
private void DefineModuleImportScope()
{
// module-level import scope:
var writer = new BlobBuilder();
SerializeModuleDefaultNamespace();
foreach (AssemblyReferenceAlias alias in module.GetAssemblyReferenceAliases(Context))
{
SerializeImport(writer, alias);
}
foreach (UsedNamespaceOrType import in module.GetImports())
{
SerializeImport(writer, import);
}
var rid = _debugMetadataOpt.AddImportScope(
parentScope: default(ImportScopeHandle),
imports: _debugMetadataOpt.GetOrAddBlob(writer));
Debug.Assert(rid == ModuleImportScopeHandle);
}
private ImportScopeHandle GetImportScopeIndex(IImportScope scope, Dictionary<IImportScope, ImportScopeHandle> scopeIndex)
{
ImportScopeHandle scopeHandle;
if (scopeIndex.TryGetValue(scope, out scopeHandle))
{
// scope is already indexed:
return scopeHandle;
}
var parent = scope.Parent;
var parentScopeHandle = (parent != null) ? GetImportScopeIndex(scope.Parent, scopeIndex) : ModuleImportScopeHandle;
var result = _debugMetadataOpt.AddImportScope(
parentScope: parentScopeHandle,
imports: SerializeImportsBlob(scope));
scopeIndex.Add(scope, result);
return result;
}
private BlobHandle SerializeImportsBlob(IImportScope scope)
{
var writer = new BlobBuilder();
foreach (UsedNamespaceOrType import in scope.GetUsedNamespaces())
{
SerializeImport(writer, import);
}
return _debugMetadataOpt.GetOrAddBlob(writer);
}
private void SerializeModuleDefaultNamespace()
{
// C#: DefaultNamespace is null.
// VB: DefaultNamespace is non-null.
if (module.DefaultNamespace == null)
{
return;
}
_debugMetadataOpt.AddCustomDebugInformation(
parent: EntityHandle.ModuleDefinition,
kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.DefaultNamespace),
value: _debugMetadataOpt.GetOrAddBlobUTF8(module.DefaultNamespace));
}
#endregion
#region Locals
private void SerializeLocalInfo(ILocalDefinition local, EntityHandle parent)
{
var dynamicFlags = local.DynamicTransformFlags;
if (!dynamicFlags.IsEmpty)
{
var value = SerializeBitVector(dynamicFlags);
_debugMetadataOpt.AddCustomDebugInformation(
parent: parent,
kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.DynamicLocalVariables),
value: _debugMetadataOpt.GetOrAddBlob(value));
}
var tupleElementNames = local.TupleElementNames;
if (!tupleElementNames.IsEmpty)
{
var builder = new BlobBuilder();
SerializeTupleElementNames(builder, tupleElementNames);
_debugMetadataOpt.AddCustomDebugInformation(
parent: parent,
kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.TupleElementNames),
value: _debugMetadataOpt.GetOrAddBlob(builder));
}
}
private static ImmutableArray<byte> SerializeBitVector(ImmutableArray<bool> vector)
{
var builder = ArrayBuilder<byte>.GetInstance();
int b = 0;
int shift = 0;
for (int i = 0; i < vector.Length; i++)
{
if (vector[i])
{
b |= 1 << shift;
}
if (shift == 7)
{
builder.Add((byte)b);
b = 0;
shift = 0;
}
else
{
shift++;
}
}
if (b != 0)
{
builder.Add((byte)b);
}
else
{
// trim trailing zeros:
int lastNonZero = builder.Count - 1;
while (builder[lastNonZero] == 0)
{
lastNonZero--;
}
builder.Clip(lastNonZero + 1);
}
return builder.ToImmutableAndFree();
}
private static void SerializeTupleElementNames(BlobBuilder builder, ImmutableArray<string> names)
{
foreach (var name in names)
{
WriteUtf8String(builder, name ?? string.Empty);
}
}
/// <summary>
/// Write string as UTF8 with null terminator.
/// </summary>
private static void WriteUtf8String(BlobBuilder builder, string str)
{
builder.WriteUTF8(str);
builder.WriteByte(0);
}
#endregion
#region State Machines
private void SerializeAsyncMethodSteppingInfo(AsyncMoveNextBodyDebugInfo asyncInfo, MethodDefinitionHandle moveNextMethod, int aggregateMethodDefRid)
{
Debug.Assert(asyncInfo.ResumeOffsets.Length == asyncInfo.YieldOffsets.Length);
Debug.Assert(asyncInfo.CatchHandlerOffset >= -1);
var writer = new BlobBuilder();
writer.WriteUInt32((uint)((long)asyncInfo.CatchHandlerOffset + 1));
for (int i = 0; i < asyncInfo.ResumeOffsets.Length; i++)
{
writer.WriteUInt32((uint)asyncInfo.YieldOffsets[i]);
writer.WriteUInt32((uint)asyncInfo.ResumeOffsets[i]);
writer.WriteCompressedInteger(aggregateMethodDefRid);
}
_debugMetadataOpt.AddCustomDebugInformation(
parent: moveNextMethod,
kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.AsyncMethodSteppingInformationBlob),
value: _debugMetadataOpt.GetOrAddBlob(writer));
}
private void SerializeStateMachineLocalScopes(IMethodBody methodBody, MethodDefinitionHandle method)
{
var scopes = methodBody.StateMachineHoistedLocalScopes;
if (scopes.IsDefaultOrEmpty)
{
return;
}
var writer = new BlobBuilder();
foreach (var scope in scopes)
{
writer.WriteUInt32((uint)scope.StartOffset);
writer.WriteUInt32((uint)scope.Length);
}
_debugMetadataOpt.AddCustomDebugInformation(
parent: method,
kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.StateMachineHoistedLocalScopes),
value: _debugMetadataOpt.GetOrAddBlob(writer));
}
#endregion
#region Sequence Points
private BlobHandle SerializeSequencePoints(
StandaloneSignatureHandle localSignatureHandleOpt,
ImmutableArray<SequencePoint> sequencePoints,
Dictionary<DebugSourceDocument, DocumentHandle> documentIndex,
out DocumentHandle singleDocumentHandle)
{
if (sequencePoints.Length == 0)
{
singleDocumentHandle = default(DocumentHandle);
return default(BlobHandle);
}
var writer = new BlobBuilder();
int previousNonHiddenStartLine = -1;
int previousNonHiddenStartColumn = -1;
// header:
writer.WriteCompressedInteger(MetadataTokens.GetRowNumber(localSignatureHandleOpt));
var previousDocument = TryGetSingleDocument(sequencePoints);
singleDocumentHandle = (previousDocument != null) ? GetOrAddDocument(previousDocument, documentIndex) : default(DocumentHandle);
for (int i = 0; i < sequencePoints.Length; i++)
{
var currentDocument = sequencePoints[i].Document;
if (previousDocument != currentDocument)
{
var documentHandle = GetOrAddDocument(currentDocument, documentIndex);
// optional document in header or document record:
if (previousDocument != null)
{
writer.WriteCompressedInteger(0);
}
writer.WriteCompressedInteger(MetadataTokens.GetRowNumber(documentHandle));
previousDocument = currentDocument;
}
// delta IL offset:
if (i > 0)
{
writer.WriteCompressedInteger(sequencePoints[i].Offset - sequencePoints[i - 1].Offset);
}
else
{
writer.WriteCompressedInteger(sequencePoints[i].Offset);
}
if (sequencePoints[i].IsHidden)
{
writer.WriteInt16(0);
continue;
}
// Delta Lines & Columns:
SerializeDeltaLinesAndColumns(writer, sequencePoints[i]);
// delta Start Lines & Columns:
if (previousNonHiddenStartLine < 0)
{
Debug.Assert(previousNonHiddenStartColumn < 0);
writer.WriteCompressedInteger(sequencePoints[i].StartLine);
writer.WriteCompressedInteger(sequencePoints[i].StartColumn);
}
else
{
writer.WriteCompressedSignedInteger(sequencePoints[i].StartLine - previousNonHiddenStartLine);
writer.WriteCompressedSignedInteger(sequencePoints[i].StartColumn - previousNonHiddenStartColumn);
}
previousNonHiddenStartLine = sequencePoints[i].StartLine;
previousNonHiddenStartColumn = sequencePoints[i].StartColumn;
}
return _debugMetadataOpt.GetOrAddBlob(writer);
}
private static DebugSourceDocument TryGetSingleDocument(ImmutableArray<SequencePoint> sequencePoints)
{
DebugSourceDocument singleDocument = sequencePoints[0].Document;
for (int i = 1; i < sequencePoints.Length; i++)
{
if (sequencePoints[i].Document != singleDocument)
{
return null;
}
}
return singleDocument;
}
private void SerializeDeltaLinesAndColumns(BlobBuilder writer, SequencePoint sequencePoint)
{
int deltaLines = sequencePoint.EndLine - sequencePoint.StartLine;
int deltaColumns = sequencePoint.EndColumn - sequencePoint.StartColumn;
// only hidden sequence points have zero width
Debug.Assert(deltaLines != 0 || deltaColumns != 0 || sequencePoint.IsHidden);
writer.WriteCompressedInteger(deltaLines);
if (deltaLines == 0)
{
writer.WriteCompressedInteger(deltaColumns);
}
else
{
writer.WriteCompressedSignedInteger(deltaColumns);
}
}
#endregion
#region Documents
private DocumentHandle GetOrAddDocument(DebugSourceDocument document, Dictionary<DebugSourceDocument, DocumentHandle> index)
{
if (index.TryGetValue(document, out var documentHandle))
{
return documentHandle;
}
return AddDocument(document, index);
}
private DocumentHandle AddDocument(DebugSourceDocument document, Dictionary<DebugSourceDocument, DocumentHandle> index)
{
DocumentHandle documentHandle;
DebugSourceInfo info = document.GetSourceInfo();
var name = document.Location;
if (_usingNonSourceDocumentNameEnumerator)
{
var result = _nonSourceDocumentNameEnumerator.MoveNext();
Debug.Assert(result);
name = _nonSourceDocumentNameEnumerator.Current;
}
documentHandle = _debugMetadataOpt.AddDocument(
name: _debugMetadataOpt.GetOrAddDocumentName(name),
hashAlgorithm: info.Checksum.IsDefault ? default(GuidHandle) : _debugMetadataOpt.GetOrAddGuid(info.ChecksumAlgorithmId),
hash: info.Checksum.IsDefault ? default(BlobHandle) : _debugMetadataOpt.GetOrAddBlob(info.Checksum),
language: _debugMetadataOpt.GetOrAddGuid(document.Language));
index.Add(document, documentHandle);
if (info.EmbeddedTextBlob != null)
{
_debugMetadataOpt.AddCustomDebugInformation(
parent: documentHandle,
kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.EmbeddedSource),
value: _debugMetadataOpt.GetOrAddBlob(info.EmbeddedTextBlob));
}
return documentHandle;
}
/// <summary>
/// Add document entries for all debug documents that do not yet have an entry.
/// </summary>
/// <remarks>
/// This is done after serializing method debug info to ensure that we embed all requested
/// text even if there are no corresponding sequence points.
/// </remarks>
public void AddRemainingDebugDocuments(IReadOnlyDictionary<string, DebugSourceDocument> documents)
{
foreach (var kvp in documents
.Where(kvp => !_documentIndex.ContainsKey(kvp.Value))
.OrderBy(kvp => kvp.Key))
{
AddDocument(kvp.Value, _documentIndex);
}
}
#endregion
#region Edit and Continue
private void SerializeEncMethodDebugInformation(IMethodBody methodBody, MethodDefinitionHandle method)
{
var encInfo = GetEncMethodDebugInfo(methodBody);
if (!encInfo.LocalSlots.IsDefaultOrEmpty)
{
var writer = new BlobBuilder();
encInfo.SerializeLocalSlots(writer);
_debugMetadataOpt.AddCustomDebugInformation(
parent: method,
kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.EncLocalSlotMap),
value: _debugMetadataOpt.GetOrAddBlob(writer));
}
if (!encInfo.Lambdas.IsDefaultOrEmpty)
{
var writer = new BlobBuilder();
encInfo.SerializeLambdaMap(writer);
_debugMetadataOpt.AddCustomDebugInformation(
parent: method,
kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.EncLambdaAndClosureMap),
value: _debugMetadataOpt.GetOrAddBlob(writer));
}
}
#endregion
private void EmbedSourceLink(Stream stream)
{
byte[] bytes;
try
{
bytes = stream.ReadAllBytes();
}
catch (Exception e) when (!(e is OperationCanceledException))
{
throw new SymUnmanagedWriterException(e.Message, e);
}
_debugMetadataOpt.AddCustomDebugInformation(
parent: EntityHandle.ModuleDefinition,
kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.SourceLink),
value: _debugMetadataOpt.GetOrAddBlob(bytes));
}
///<summary>The version of the compilation options schema to be written to the PDB.</summary>
private const int CompilationOptionsSchemaVersion = 2;
/// <summary>
/// Capture the set of compilation options to allow a compilation
/// to be reconstructed from the pdb
/// </summary>
private void EmbedCompilationOptions(CommonPEModuleBuilder module)
{
var builder = new BlobBuilder();
if (this.Context.RebuildData is { } rebuildData)
{
var reader = rebuildData.OptionsBlobReader;
builder.WriteBytes(reader.ReadBytes(reader.RemainingBytes));
}
else
{
var compilerVersion = typeof(Compilation).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;
WriteValue(CompilationOptionNames.CompilationOptionsVersion, CompilationOptionsSchemaVersion.ToString());
WriteValue(CompilationOptionNames.CompilerVersion, compilerVersion);
WriteValue(CompilationOptionNames.Language, module.CommonCompilation.Options.Language);
WriteValue(CompilationOptionNames.SourceFileCount, module.CommonCompilation.SyntaxTrees.Count().ToString());
WriteValue(CompilationOptionNames.OutputKind, module.OutputKind.ToString());
if (module.EmitOptions.FallbackSourceFileEncoding != null)
{
WriteValue(CompilationOptionNames.FallbackEncoding, module.EmitOptions.FallbackSourceFileEncoding.WebName);
}
if (module.EmitOptions.DefaultSourceFileEncoding != null)
{
WriteValue(CompilationOptionNames.DefaultEncoding, module.EmitOptions.DefaultSourceFileEncoding.WebName);
}
int portabilityPolicy = 0;
if (module.CommonCompilation.Options.AssemblyIdentityComparer is DesktopAssemblyIdentityComparer identityComparer)
{
portabilityPolicy |= identityComparer.PortabilityPolicy.SuppressSilverlightLibraryAssembliesPortability ? 0b1 : 0;
portabilityPolicy |= identityComparer.PortabilityPolicy.SuppressSilverlightPlatformAssembliesPortability ? 0b10 : 0;
}
if (portabilityPolicy != 0)
{
WriteValue(CompilationOptionNames.PortabilityPolicy, portabilityPolicy.ToString());
}
var optimizationLevel = module.CommonCompilation.Options.OptimizationLevel;
var debugPlusMode = module.CommonCompilation.Options.DebugPlusMode;
if ((optimizationLevel, debugPlusMode) != OptimizationLevelFacts.DefaultValues)
{
WriteValue(CompilationOptionNames.Optimization, optimizationLevel.ToPdbSerializedString(debugPlusMode));
}
var platform = module.CommonCompilation.Options.Platform;
WriteValue(CompilationOptionNames.Platform, platform.ToString());
var runtimeVersion = typeof(object).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
WriteValue(CompilationOptionNames.RuntimeVersion, runtimeVersion);
module.CommonCompilation.SerializePdbEmbeddedCompilationOptions(builder);
}
_debugMetadataOpt.AddCustomDebugInformation(
parent: EntityHandle.ModuleDefinition,
kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.CompilationOptions),
value: _debugMetadataOpt.GetOrAddBlob(builder));
void WriteValue(string key, string value)
{
builder.WriteUTF8(key);
builder.WriteByte(0);
builder.WriteUTF8(value);
builder.WriteByte(0);
}
}
/// <summary>
/// Writes information about metadata references to the pdb so the same
/// reference can be found on sourcelink to create the compilation again
/// </summary>
private void EmbedMetadataReferenceInformation(CommonPEModuleBuilder module)
{
var builder = new BlobBuilder();
// Order of information
// File name (null terminated string): A.exe
// Extern Alias (null terminated string): a1,a2,a3
// MetadataImageKind (byte)
// EmbedInteropTypes (boolean)
// COFF header Timestamp field (4 byte int)
// COFF header SizeOfImage field (4 byte int)
// MVID (Guid, 24 bytes)
var referenceManager = module.CommonCompilation.GetBoundReferenceManager();
foreach (var pair in referenceManager.GetReferencedAssemblyAliases())
{
if (referenceManager.GetMetadataReference(pair.AssemblySymbol) is PortableExecutableReference { FilePath: { } } portableReference)
{
var fileName = PathUtilities.GetFileName(portableReference.FilePath);
var peReader = pair.AssemblySymbol.GetISymbol() is IAssemblySymbol assemblySymbol
? assemblySymbol.GetMetadata().GetAssembly().ManifestModule.PEReaderOpt
: null;
// Don't write before checking that we can get a peReader for the metadata reference
if (peReader is null)
continue;
// Write file name first
builder.WriteUTF8(fileName);
// Make sure to add null terminator
builder.WriteByte(0);
// Extern alias
if (pair.Aliases.Length > 0)
builder.WriteUTF8(string.Join(",", pair.Aliases.OrderBy(StringComparer.Ordinal)));
// Always null terminate the extern alias list
builder.WriteByte(0);
byte kindAndEmbedInteropTypes = (byte)(portableReference.Properties.EmbedInteropTypes
? 0b10
: 0b0);
kindAndEmbedInteropTypes |= portableReference.Properties.Kind switch
{
MetadataImageKind.Assembly => 1,
MetadataImageKind.Module => 0,
_ => throw ExceptionUtilities.UnexpectedValue(portableReference.Properties.Kind)
};
builder.WriteByte(kindAndEmbedInteropTypes);
builder.WriteInt32(peReader.PEHeaders.CoffHeader.TimeDateStamp);
builder.WriteInt32(peReader.PEHeaders.PEHeader.SizeOfImage);
var metadataReader = peReader.GetMetadataReader();
var moduleDefinition = metadataReader.GetModuleDefinition();
builder.WriteGuid(metadataReader.GetGuid(moduleDefinition.Mvid));
}
}
_debugMetadataOpt.AddCustomDebugInformation(
parent: EntityHandle.ModuleDefinition,
kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.CompilationMetadataReferences),
value: _debugMetadataOpt.GetOrAddBlob(builder));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.DiaSymReader;
using Roslyn.Utilities;
namespace Microsoft.Cci
{
internal partial class MetadataWriter
{
/// <summary>
/// Import scopes are associated with binders (in C#) and thus multiple instances might be created for a single set of imports.
/// We consider scopes with the same parent and the same imports the same.
/// Internal for testing.
/// </summary>
internal sealed class ImportScopeEqualityComparer : IEqualityComparer<IImportScope>
{
public static readonly ImportScopeEqualityComparer Instance = new ImportScopeEqualityComparer();
public bool Equals(IImportScope x, IImportScope y)
{
return (object)x == y ||
x != null && y != null && Equals(x.Parent, y.Parent) && x.GetUsedNamespaces().SequenceEqual(y.GetUsedNamespaces());
}
public int GetHashCode(IImportScope obj)
{
return Hash.Combine(Hash.CombineValues(obj.GetUsedNamespaces()), obj.Parent != null ? GetHashCode(obj.Parent) : 0);
}
}
private readonly Dictionary<DebugSourceDocument, DocumentHandle> _documentIndex = new Dictionary<DebugSourceDocument, DocumentHandle>();
private readonly Dictionary<IImportScope, ImportScopeHandle> _scopeIndex = new Dictionary<IImportScope, ImportScopeHandle>(ImportScopeEqualityComparer.Instance);
private void SerializeMethodDebugInfo(IMethodBody bodyOpt, int methodRid, int aggregateMethodRid, StandaloneSignatureHandle localSignatureHandleOpt, ref LocalVariableHandle lastLocalVariableHandle, ref LocalConstantHandle lastLocalConstantHandle)
{
if (bodyOpt == null)
{
_debugMetadataOpt.AddMethodDebugInformation(document: default, sequencePoints: default);
return;
}
bool isKickoffMethod = bodyOpt.StateMachineTypeName != null;
bool emitAllDebugInfo = isKickoffMethod || !bodyOpt.SequencePoints.IsEmpty;
var methodHandle = MetadataTokens.MethodDefinitionHandle(methodRid);
// documents & sequence points:
BlobHandle sequencePointsBlob = SerializeSequencePoints(localSignatureHandleOpt, bodyOpt.SequencePoints, _documentIndex, out var singleDocumentHandle);
_debugMetadataOpt.AddMethodDebugInformation(document: singleDocumentHandle, sequencePoints: sequencePointsBlob);
if (emitAllDebugInfo)
{
var bodyImportScope = bodyOpt.ImportScope;
var importScopeHandle = (bodyImportScope != null) ? GetImportScopeIndex(bodyImportScope, _scopeIndex) : default;
// Unlike native PDB we don't emit an empty root scope.
// scopes are already ordered by StartOffset ascending then by EndOffset descending (the longest scope first).
if (bodyOpt.LocalScopes.Length == 0)
{
// TODO: the compiler should produce a scope for each debuggable method rather then adding one here
_debugMetadataOpt.AddLocalScope(
method: methodHandle,
importScope: importScopeHandle,
variableList: NextHandle(lastLocalVariableHandle),
constantList: NextHandle(lastLocalConstantHandle),
startOffset: 0,
length: bodyOpt.IL.Length);
}
else
{
foreach (LocalScope scope in bodyOpt.LocalScopes)
{
_debugMetadataOpt.AddLocalScope(
method: methodHandle,
importScope: importScopeHandle,
variableList: NextHandle(lastLocalVariableHandle),
constantList: NextHandle(lastLocalConstantHandle),
startOffset: scope.StartOffset,
length: scope.Length);
foreach (ILocalDefinition local in scope.Variables)
{
Debug.Assert(local.SlotIndex >= 0);
lastLocalVariableHandle = _debugMetadataOpt.AddLocalVariable(
attributes: local.PdbAttributes,
index: local.SlotIndex,
name: _debugMetadataOpt.GetOrAddString(local.Name));
SerializeLocalInfo(local, lastLocalVariableHandle);
}
foreach (ILocalDefinition constant in scope.Constants)
{
var mdConstant = constant.CompileTimeValue;
Debug.Assert(mdConstant != null);
lastLocalConstantHandle = _debugMetadataOpt.AddLocalConstant(
name: _debugMetadataOpt.GetOrAddString(constant.Name),
signature: SerializeLocalConstantSignature(constant));
SerializeLocalInfo(constant, lastLocalConstantHandle);
}
}
}
var moveNextBodyInfo = bodyOpt.MoveNextBodyInfo;
if (moveNextBodyInfo != null)
{
_debugMetadataOpt.AddStateMachineMethod(
moveNextMethod: methodHandle,
kickoffMethod: GetMethodDefinitionHandle(moveNextBodyInfo.KickoffMethod));
if (moveNextBodyInfo is AsyncMoveNextBodyDebugInfo asyncInfo)
{
SerializeAsyncMethodSteppingInfo(asyncInfo, methodHandle, aggregateMethodRid);
}
}
SerializeStateMachineLocalScopes(bodyOpt, methodHandle);
}
// Emit EnC info for all methods even if they do not have sequence points.
// The information facilitates reusing lambdas and closures. The reuse is important for runtimes that can't add new members (e.g. Mono).
// EnC delta doesn't need this information - we use information recorded by previous generation emit.
if (Context.Module.CommonCompilation.Options.EnableEditAndContinue && IsFullMetadata)
{
SerializeEncMethodDebugInformation(bodyOpt, methodHandle);
}
}
private static LocalVariableHandle NextHandle(LocalVariableHandle handle) =>
MetadataTokens.LocalVariableHandle(MetadataTokens.GetRowNumber(handle) + 1);
private static LocalConstantHandle NextHandle(LocalConstantHandle handle) =>
MetadataTokens.LocalConstantHandle(MetadataTokens.GetRowNumber(handle) + 1);
private BlobHandle SerializeLocalConstantSignature(ILocalDefinition localConstant)
{
var builder = new BlobBuilder();
// TODO: BlobEncoder.LocalConstantSignature
// CustomMod*
var encoder = new CustomModifiersEncoder(builder);
SerializeCustomModifiers(encoder, localConstant.CustomModifiers);
var type = localConstant.Type;
var typeCode = type.TypeCode;
object value = localConstant.CompileTimeValue.Value;
// PrimitiveConstant or EnumConstant
if (value is decimal)
{
builder.WriteByte((byte)SignatureTypeKind.ValueType);
builder.WriteCompressedInteger(CodedIndex.TypeDefOrRefOrSpec(GetTypeHandle(type)));
builder.WriteDecimal((decimal)value);
}
else if (value is DateTime)
{
builder.WriteByte((byte)SignatureTypeKind.ValueType);
builder.WriteCompressedInteger(CodedIndex.TypeDefOrRefOrSpec(GetTypeHandle(type)));
builder.WriteDateTime((DateTime)value);
}
else if (typeCode == PrimitiveTypeCode.String)
{
builder.WriteByte((byte)ConstantTypeCode.String);
if (value == null)
{
builder.WriteByte(0xff);
}
else
{
builder.WriteUTF16((string)value);
}
}
else if (value != null)
{
// TypeCode
builder.WriteByte((byte)GetConstantTypeCode(value));
// Value
builder.WriteConstant(value);
// EnumType
if (type.IsEnum)
{
builder.WriteCompressedInteger(CodedIndex.TypeDefOrRefOrSpec(GetTypeHandle(type)));
}
}
else if (this.module.IsPlatformType(type, PlatformType.SystemObject))
{
builder.WriteByte((byte)SignatureTypeCode.Object);
}
else
{
builder.WriteByte((byte)(type.IsValueType ? SignatureTypeKind.ValueType : SignatureTypeKind.Class));
builder.WriteCompressedInteger(CodedIndex.TypeDefOrRefOrSpec(GetTypeHandle(type)));
}
return _debugMetadataOpt.GetOrAddBlob(builder);
}
private static SignatureTypeCode GetConstantTypeCode(object value)
{
if (value == null)
{
// The encoding of Type for the nullref value for FieldInit is ELEMENT_TYPE_CLASS with a Value of a zero.
return (SignatureTypeCode)SignatureTypeKind.Class;
}
Debug.Assert(!value.GetType().GetTypeInfo().IsEnum);
// Perf: Note that JIT optimizes each expression val.GetType() == typeof(T) to a single register comparison.
// Also the checks are sorted by commonality of the checked types.
if (value.GetType() == typeof(int))
{
return SignatureTypeCode.Int32;
}
if (value.GetType() == typeof(string))
{
return SignatureTypeCode.String;
}
if (value.GetType() == typeof(bool))
{
return SignatureTypeCode.Boolean;
}
if (value.GetType() == typeof(char))
{
return SignatureTypeCode.Char;
}
if (value.GetType() == typeof(byte))
{
return SignatureTypeCode.Byte;
}
if (value.GetType() == typeof(long))
{
return SignatureTypeCode.Int64;
}
if (value.GetType() == typeof(double))
{
return SignatureTypeCode.Double;
}
if (value.GetType() == typeof(short))
{
return SignatureTypeCode.Int16;
}
if (value.GetType() == typeof(ushort))
{
return SignatureTypeCode.UInt16;
}
if (value.GetType() == typeof(uint))
{
return SignatureTypeCode.UInt32;
}
if (value.GetType() == typeof(sbyte))
{
return SignatureTypeCode.SByte;
}
if (value.GetType() == typeof(ulong))
{
return SignatureTypeCode.UInt64;
}
if (value.GetType() == typeof(float))
{
return SignatureTypeCode.Single;
}
throw ExceptionUtilities.Unreachable;
}
#region ImportScope
private static readonly ImportScopeHandle ModuleImportScopeHandle = MetadataTokens.ImportScopeHandle(1);
private void SerializeImport(BlobBuilder writer, AssemblyReferenceAlias alias)
{
// <import> ::= AliasAssemblyReference <alias> <target-assembly>
writer.WriteByte((byte)ImportDefinitionKind.AliasAssemblyReference);
writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(alias.Name)));
writer.WriteCompressedInteger(MetadataTokens.GetRowNumber(GetOrAddAssemblyReferenceHandle(alias.Assembly)));
}
private void SerializeImport(BlobBuilder writer, UsedNamespaceOrType import)
{
if (import.TargetXmlNamespaceOpt != null)
{
Debug.Assert(import.TargetNamespaceOpt == null);
Debug.Assert(import.TargetAssemblyOpt == null);
Debug.Assert(import.TargetTypeOpt == null);
// <import> ::= ImportXmlNamespace <alias> <target-namespace>
writer.WriteByte((byte)ImportDefinitionKind.ImportXmlNamespace);
writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(import.AliasOpt)));
writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(import.TargetXmlNamespaceOpt)));
}
else if (import.TargetTypeOpt != null)
{
Debug.Assert(import.TargetNamespaceOpt == null);
Debug.Assert(import.TargetAssemblyOpt == null);
if (import.AliasOpt != null)
{
// <import> ::= AliasType <alias> <target-type>
writer.WriteByte((byte)ImportDefinitionKind.AliasType);
writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(import.AliasOpt)));
}
else
{
// <import> ::= ImportType <target-type>
writer.WriteByte((byte)ImportDefinitionKind.ImportType);
}
writer.WriteCompressedInteger(CodedIndex.TypeDefOrRefOrSpec(GetTypeHandle(import.TargetTypeOpt))); // TODO: index in release build
}
else if (import.TargetNamespaceOpt != null)
{
if (import.TargetAssemblyOpt != null)
{
if (import.AliasOpt != null)
{
// <import> ::= AliasAssemblyNamespace <alias> <target-assembly> <target-namespace>
writer.WriteByte((byte)ImportDefinitionKind.AliasAssemblyNamespace);
writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(import.AliasOpt)));
}
else
{
// <import> ::= ImportAssemblyNamespace <target-assembly> <target-namespace>
writer.WriteByte((byte)ImportDefinitionKind.ImportAssemblyNamespace);
}
writer.WriteCompressedInteger(MetadataTokens.GetRowNumber(GetAssemblyReferenceHandle(import.TargetAssemblyOpt)));
}
else
{
if (import.AliasOpt != null)
{
// <import> ::= AliasNamespace <alias> <target-namespace>
writer.WriteByte((byte)ImportDefinitionKind.AliasNamespace);
writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(import.AliasOpt)));
}
else
{
// <import> ::= ImportNamespace <target-namespace>
writer.WriteByte((byte)ImportDefinitionKind.ImportNamespace);
}
}
// TODO: cache?
string namespaceName = TypeNameSerializer.BuildQualifiedNamespaceName(import.TargetNamespaceOpt);
writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(namespaceName)));
}
else
{
// <import> ::= ImportReferenceAlias <alias>
Debug.Assert(import.AliasOpt != null);
Debug.Assert(import.TargetAssemblyOpt == null);
writer.WriteByte((byte)ImportDefinitionKind.ImportAssemblyReferenceAlias);
writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(import.AliasOpt)));
}
}
private void DefineModuleImportScope()
{
// module-level import scope:
var writer = new BlobBuilder();
SerializeModuleDefaultNamespace();
foreach (AssemblyReferenceAlias alias in module.GetAssemblyReferenceAliases(Context))
{
SerializeImport(writer, alias);
}
foreach (UsedNamespaceOrType import in module.GetImports())
{
SerializeImport(writer, import);
}
var rid = _debugMetadataOpt.AddImportScope(
parentScope: default(ImportScopeHandle),
imports: _debugMetadataOpt.GetOrAddBlob(writer));
Debug.Assert(rid == ModuleImportScopeHandle);
}
private ImportScopeHandle GetImportScopeIndex(IImportScope scope, Dictionary<IImportScope, ImportScopeHandle> scopeIndex)
{
ImportScopeHandle scopeHandle;
if (scopeIndex.TryGetValue(scope, out scopeHandle))
{
// scope is already indexed:
return scopeHandle;
}
var parent = scope.Parent;
var parentScopeHandle = (parent != null) ? GetImportScopeIndex(scope.Parent, scopeIndex) : ModuleImportScopeHandle;
var result = _debugMetadataOpt.AddImportScope(
parentScope: parentScopeHandle,
imports: SerializeImportsBlob(scope));
scopeIndex.Add(scope, result);
return result;
}
private BlobHandle SerializeImportsBlob(IImportScope scope)
{
var writer = new BlobBuilder();
foreach (UsedNamespaceOrType import in scope.GetUsedNamespaces())
{
SerializeImport(writer, import);
}
return _debugMetadataOpt.GetOrAddBlob(writer);
}
private void SerializeModuleDefaultNamespace()
{
// C#: DefaultNamespace is null.
// VB: DefaultNamespace is non-null.
if (module.DefaultNamespace == null)
{
return;
}
_debugMetadataOpt.AddCustomDebugInformation(
parent: EntityHandle.ModuleDefinition,
kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.DefaultNamespace),
value: _debugMetadataOpt.GetOrAddBlobUTF8(module.DefaultNamespace));
}
#endregion
#region Locals
private void SerializeLocalInfo(ILocalDefinition local, EntityHandle parent)
{
var dynamicFlags = local.DynamicTransformFlags;
if (!dynamicFlags.IsEmpty)
{
var value = SerializeBitVector(dynamicFlags);
_debugMetadataOpt.AddCustomDebugInformation(
parent: parent,
kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.DynamicLocalVariables),
value: _debugMetadataOpt.GetOrAddBlob(value));
}
var tupleElementNames = local.TupleElementNames;
if (!tupleElementNames.IsEmpty)
{
var builder = new BlobBuilder();
SerializeTupleElementNames(builder, tupleElementNames);
_debugMetadataOpt.AddCustomDebugInformation(
parent: parent,
kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.TupleElementNames),
value: _debugMetadataOpt.GetOrAddBlob(builder));
}
}
private static ImmutableArray<byte> SerializeBitVector(ImmutableArray<bool> vector)
{
var builder = ArrayBuilder<byte>.GetInstance();
int b = 0;
int shift = 0;
for (int i = 0; i < vector.Length; i++)
{
if (vector[i])
{
b |= 1 << shift;
}
if (shift == 7)
{
builder.Add((byte)b);
b = 0;
shift = 0;
}
else
{
shift++;
}
}
if (b != 0)
{
builder.Add((byte)b);
}
else
{
// trim trailing zeros:
int lastNonZero = builder.Count - 1;
while (builder[lastNonZero] == 0)
{
lastNonZero--;
}
builder.Clip(lastNonZero + 1);
}
return builder.ToImmutableAndFree();
}
private static void SerializeTupleElementNames(BlobBuilder builder, ImmutableArray<string> names)
{
foreach (var name in names)
{
WriteUtf8String(builder, name ?? string.Empty);
}
}
/// <summary>
/// Write string as UTF8 with null terminator.
/// </summary>
private static void WriteUtf8String(BlobBuilder builder, string str)
{
builder.WriteUTF8(str);
builder.WriteByte(0);
}
#endregion
#region State Machines
private void SerializeAsyncMethodSteppingInfo(AsyncMoveNextBodyDebugInfo asyncInfo, MethodDefinitionHandle moveNextMethod, int aggregateMethodDefRid)
{
Debug.Assert(asyncInfo.ResumeOffsets.Length == asyncInfo.YieldOffsets.Length);
Debug.Assert(asyncInfo.CatchHandlerOffset >= -1);
var writer = new BlobBuilder();
writer.WriteUInt32((uint)((long)asyncInfo.CatchHandlerOffset + 1));
for (int i = 0; i < asyncInfo.ResumeOffsets.Length; i++)
{
writer.WriteUInt32((uint)asyncInfo.YieldOffsets[i]);
writer.WriteUInt32((uint)asyncInfo.ResumeOffsets[i]);
writer.WriteCompressedInteger(aggregateMethodDefRid);
}
_debugMetadataOpt.AddCustomDebugInformation(
parent: moveNextMethod,
kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.AsyncMethodSteppingInformationBlob),
value: _debugMetadataOpt.GetOrAddBlob(writer));
}
private void SerializeStateMachineLocalScopes(IMethodBody methodBody, MethodDefinitionHandle method)
{
var scopes = methodBody.StateMachineHoistedLocalScopes;
if (scopes.IsDefaultOrEmpty)
{
return;
}
var writer = new BlobBuilder();
foreach (var scope in scopes)
{
writer.WriteUInt32((uint)scope.StartOffset);
writer.WriteUInt32((uint)scope.Length);
}
_debugMetadataOpt.AddCustomDebugInformation(
parent: method,
kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.StateMachineHoistedLocalScopes),
value: _debugMetadataOpt.GetOrAddBlob(writer));
}
#endregion
#region Sequence Points
private BlobHandle SerializeSequencePoints(
StandaloneSignatureHandle localSignatureHandleOpt,
ImmutableArray<SequencePoint> sequencePoints,
Dictionary<DebugSourceDocument, DocumentHandle> documentIndex,
out DocumentHandle singleDocumentHandle)
{
if (sequencePoints.Length == 0)
{
singleDocumentHandle = default(DocumentHandle);
return default(BlobHandle);
}
var writer = new BlobBuilder();
int previousNonHiddenStartLine = -1;
int previousNonHiddenStartColumn = -1;
// header:
writer.WriteCompressedInteger(MetadataTokens.GetRowNumber(localSignatureHandleOpt));
var previousDocument = TryGetSingleDocument(sequencePoints);
singleDocumentHandle = (previousDocument != null) ? GetOrAddDocument(previousDocument, documentIndex) : default(DocumentHandle);
for (int i = 0; i < sequencePoints.Length; i++)
{
var currentDocument = sequencePoints[i].Document;
if (previousDocument != currentDocument)
{
var documentHandle = GetOrAddDocument(currentDocument, documentIndex);
// optional document in header or document record:
if (previousDocument != null)
{
writer.WriteCompressedInteger(0);
}
writer.WriteCompressedInteger(MetadataTokens.GetRowNumber(documentHandle));
previousDocument = currentDocument;
}
// delta IL offset:
if (i > 0)
{
writer.WriteCompressedInteger(sequencePoints[i].Offset - sequencePoints[i - 1].Offset);
}
else
{
writer.WriteCompressedInteger(sequencePoints[i].Offset);
}
if (sequencePoints[i].IsHidden)
{
writer.WriteInt16(0);
continue;
}
// Delta Lines & Columns:
SerializeDeltaLinesAndColumns(writer, sequencePoints[i]);
// delta Start Lines & Columns:
if (previousNonHiddenStartLine < 0)
{
Debug.Assert(previousNonHiddenStartColumn < 0);
writer.WriteCompressedInteger(sequencePoints[i].StartLine);
writer.WriteCompressedInteger(sequencePoints[i].StartColumn);
}
else
{
writer.WriteCompressedSignedInteger(sequencePoints[i].StartLine - previousNonHiddenStartLine);
writer.WriteCompressedSignedInteger(sequencePoints[i].StartColumn - previousNonHiddenStartColumn);
}
previousNonHiddenStartLine = sequencePoints[i].StartLine;
previousNonHiddenStartColumn = sequencePoints[i].StartColumn;
}
return _debugMetadataOpt.GetOrAddBlob(writer);
}
private static DebugSourceDocument TryGetSingleDocument(ImmutableArray<SequencePoint> sequencePoints)
{
DebugSourceDocument singleDocument = sequencePoints[0].Document;
for (int i = 1; i < sequencePoints.Length; i++)
{
if (sequencePoints[i].Document != singleDocument)
{
return null;
}
}
return singleDocument;
}
private void SerializeDeltaLinesAndColumns(BlobBuilder writer, SequencePoint sequencePoint)
{
int deltaLines = sequencePoint.EndLine - sequencePoint.StartLine;
int deltaColumns = sequencePoint.EndColumn - sequencePoint.StartColumn;
// only hidden sequence points have zero width
Debug.Assert(deltaLines != 0 || deltaColumns != 0 || sequencePoint.IsHidden);
writer.WriteCompressedInteger(deltaLines);
if (deltaLines == 0)
{
writer.WriteCompressedInteger(deltaColumns);
}
else
{
writer.WriteCompressedSignedInteger(deltaColumns);
}
}
#endregion
#region Documents
private DocumentHandle GetOrAddDocument(DebugSourceDocument document, Dictionary<DebugSourceDocument, DocumentHandle> index)
{
if (index.TryGetValue(document, out var documentHandle))
{
return documentHandle;
}
return AddDocument(document, index);
}
private DocumentHandle AddDocument(DebugSourceDocument document, Dictionary<DebugSourceDocument, DocumentHandle> index)
{
DocumentHandle documentHandle;
DebugSourceInfo info = document.GetSourceInfo();
var name = document.Location;
if (_usingNonSourceDocumentNameEnumerator)
{
var result = _nonSourceDocumentNameEnumerator.MoveNext();
Debug.Assert(result);
name = _nonSourceDocumentNameEnumerator.Current;
}
documentHandle = _debugMetadataOpt.AddDocument(
name: _debugMetadataOpt.GetOrAddDocumentName(name),
hashAlgorithm: info.Checksum.IsDefault ? default(GuidHandle) : _debugMetadataOpt.GetOrAddGuid(info.ChecksumAlgorithmId),
hash: info.Checksum.IsDefault ? default(BlobHandle) : _debugMetadataOpt.GetOrAddBlob(info.Checksum),
language: _debugMetadataOpt.GetOrAddGuid(document.Language));
index.Add(document, documentHandle);
if (info.EmbeddedTextBlob != null)
{
_debugMetadataOpt.AddCustomDebugInformation(
parent: documentHandle,
kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.EmbeddedSource),
value: _debugMetadataOpt.GetOrAddBlob(info.EmbeddedTextBlob));
}
return documentHandle;
}
/// <summary>
/// Add document entries for all debug documents that do not yet have an entry.
/// </summary>
/// <remarks>
/// This is done after serializing method debug info to ensure that we embed all requested
/// text even if there are no corresponding sequence points.
/// </remarks>
public void AddRemainingDebugDocuments(IReadOnlyDictionary<string, DebugSourceDocument> documents)
{
foreach (var kvp in documents
.Where(kvp => !_documentIndex.ContainsKey(kvp.Value))
.OrderBy(kvp => kvp.Key))
{
AddDocument(kvp.Value, _documentIndex);
}
}
#endregion
#region Edit and Continue
private void SerializeEncMethodDebugInformation(IMethodBody methodBody, MethodDefinitionHandle method)
{
var encInfo = GetEncMethodDebugInfo(methodBody);
if (!encInfo.LocalSlots.IsDefaultOrEmpty)
{
var writer = new BlobBuilder();
encInfo.SerializeLocalSlots(writer);
_debugMetadataOpt.AddCustomDebugInformation(
parent: method,
kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.EncLocalSlotMap),
value: _debugMetadataOpt.GetOrAddBlob(writer));
}
if (!encInfo.Lambdas.IsDefaultOrEmpty)
{
var writer = new BlobBuilder();
encInfo.SerializeLambdaMap(writer);
_debugMetadataOpt.AddCustomDebugInformation(
parent: method,
kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.EncLambdaAndClosureMap),
value: _debugMetadataOpt.GetOrAddBlob(writer));
}
}
#endregion
private void EmbedSourceLink(Stream stream)
{
byte[] bytes;
try
{
bytes = stream.ReadAllBytes();
}
catch (Exception e) when (!(e is OperationCanceledException))
{
throw new SymUnmanagedWriterException(e.Message, e);
}
_debugMetadataOpt.AddCustomDebugInformation(
parent: EntityHandle.ModuleDefinition,
kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.SourceLink),
value: _debugMetadataOpt.GetOrAddBlob(bytes));
}
///<summary>The version of the compilation options schema to be written to the PDB.</summary>
private const int CompilationOptionsSchemaVersion = 2;
/// <summary>
/// Capture the set of compilation options to allow a compilation
/// to be reconstructed from the pdb
/// </summary>
private void EmbedCompilationOptions(CommonPEModuleBuilder module)
{
var builder = new BlobBuilder();
if (this.Context.RebuildData is { } rebuildData)
{
var reader = rebuildData.OptionsBlobReader;
builder.WriteBytes(reader.ReadBytes(reader.RemainingBytes));
}
else
{
var compilerVersion = typeof(Compilation).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;
WriteValue(CompilationOptionNames.CompilationOptionsVersion, CompilationOptionsSchemaVersion.ToString());
WriteValue(CompilationOptionNames.CompilerVersion, compilerVersion);
WriteValue(CompilationOptionNames.Language, module.CommonCompilation.Options.Language);
WriteValue(CompilationOptionNames.SourceFileCount, module.CommonCompilation.SyntaxTrees.Count().ToString());
WriteValue(CompilationOptionNames.OutputKind, module.OutputKind.ToString());
if (module.EmitOptions.FallbackSourceFileEncoding != null)
{
WriteValue(CompilationOptionNames.FallbackEncoding, module.EmitOptions.FallbackSourceFileEncoding.WebName);
}
if (module.EmitOptions.DefaultSourceFileEncoding != null)
{
WriteValue(CompilationOptionNames.DefaultEncoding, module.EmitOptions.DefaultSourceFileEncoding.WebName);
}
int portabilityPolicy = 0;
if (module.CommonCompilation.Options.AssemblyIdentityComparer is DesktopAssemblyIdentityComparer identityComparer)
{
portabilityPolicy |= identityComparer.PortabilityPolicy.SuppressSilverlightLibraryAssembliesPortability ? 0b1 : 0;
portabilityPolicy |= identityComparer.PortabilityPolicy.SuppressSilverlightPlatformAssembliesPortability ? 0b10 : 0;
}
if (portabilityPolicy != 0)
{
WriteValue(CompilationOptionNames.PortabilityPolicy, portabilityPolicy.ToString());
}
var optimizationLevel = module.CommonCompilation.Options.OptimizationLevel;
var debugPlusMode = module.CommonCompilation.Options.DebugPlusMode;
if ((optimizationLevel, debugPlusMode) != OptimizationLevelFacts.DefaultValues)
{
WriteValue(CompilationOptionNames.Optimization, optimizationLevel.ToPdbSerializedString(debugPlusMode));
}
var platform = module.CommonCompilation.Options.Platform;
WriteValue(CompilationOptionNames.Platform, platform.ToString());
var runtimeVersion = typeof(object).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
WriteValue(CompilationOptionNames.RuntimeVersion, runtimeVersion);
module.CommonCompilation.SerializePdbEmbeddedCompilationOptions(builder);
}
_debugMetadataOpt.AddCustomDebugInformation(
parent: EntityHandle.ModuleDefinition,
kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.CompilationOptions),
value: _debugMetadataOpt.GetOrAddBlob(builder));
void WriteValue(string key, string value)
{
builder.WriteUTF8(key);
builder.WriteByte(0);
builder.WriteUTF8(value);
builder.WriteByte(0);
}
}
/// <summary>
/// Writes information about metadata references to the pdb so the same
/// reference can be found on sourcelink to create the compilation again
/// </summary>
private void EmbedMetadataReferenceInformation(CommonPEModuleBuilder module)
{
var builder = new BlobBuilder();
// Order of information
// File name (null terminated string): A.exe
// Extern Alias (null terminated string): a1,a2,a3
// MetadataImageKind (byte)
// EmbedInteropTypes (boolean)
// COFF header Timestamp field (4 byte int)
// COFF header SizeOfImage field (4 byte int)
// MVID (Guid, 24 bytes)
var referenceManager = module.CommonCompilation.GetBoundReferenceManager();
foreach (var pair in referenceManager.GetReferencedAssemblyAliases())
{
if (referenceManager.GetMetadataReference(pair.AssemblySymbol) is PortableExecutableReference { FilePath: { } } portableReference)
{
var fileName = PathUtilities.GetFileName(portableReference.FilePath);
var peReader = pair.AssemblySymbol.GetISymbol() is IAssemblySymbol assemblySymbol
? assemblySymbol.GetMetadata().GetAssembly().ManifestModule.PEReaderOpt
: null;
// Don't write before checking that we can get a peReader for the metadata reference
if (peReader is null)
continue;
// Write file name first
builder.WriteUTF8(fileName);
// Make sure to add null terminator
builder.WriteByte(0);
// Extern alias
if (pair.Aliases.Length > 0)
builder.WriteUTF8(string.Join(",", pair.Aliases.OrderBy(StringComparer.Ordinal)));
// Always null terminate the extern alias list
builder.WriteByte(0);
byte kindAndEmbedInteropTypes = (byte)(portableReference.Properties.EmbedInteropTypes
? 0b10
: 0b0);
kindAndEmbedInteropTypes |= portableReference.Properties.Kind switch
{
MetadataImageKind.Assembly => 1,
MetadataImageKind.Module => 0,
_ => throw ExceptionUtilities.UnexpectedValue(portableReference.Properties.Kind)
};
builder.WriteByte(kindAndEmbedInteropTypes);
builder.WriteInt32(peReader.PEHeaders.CoffHeader.TimeDateStamp);
builder.WriteInt32(peReader.PEHeaders.PEHeader.SizeOfImage);
var metadataReader = peReader.GetMetadataReader();
var moduleDefinition = metadataReader.GetModuleDefinition();
builder.WriteGuid(metadataReader.GetGuid(moduleDefinition.Mvid));
}
}
_debugMetadataOpt.AddCustomDebugInformation(
parent: EntityHandle.ModuleDefinition,
kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.CompilationMetadataReferences),
value: _debugMetadataOpt.GetOrAddBlob(builder));
}
}
}
| 1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Compilers/VisualBasic/Test/Emit/PDB/PDBExternalSourceDirectiveTests.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.Emit
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB
Public Class PDBExternalSourceDirectiveTests
Inherits BasicTestBase
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
<WorkItem(50611, "https://github.com/dotnet/roslyn/issues/50611")>
Public Sub TwoMethodsOnlyOneWithMapping()
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
Option Infer Off
Option Explicit Off
Imports System
Imports System.Collections.Generic
Class C1
Public Shared Sub FooInvisible()
dim str as string = "World!"
Console.WriteLine("Hello " & str)
End Sub
Public Shared Sub Main()
Console.WriteLine("Hello World")
#ExternalSource("C:\abc\def.vb", 23)
Console.WriteLine("Hello World")
#End ExternalSource
Console.WriteLine("Hello World")
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe)
' Care about the fact that there is no file reference to a.vb
' Care about the fact that C1.FooInvisible doesn't include any sequence points
compilation.VerifyPdb(
<symbols>
<files>
<file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="70-82-DD-9A-57-B3-BE-57-7E-E8-B4-AE-B8-1E-1B-75-38-9D-13-C9"/>
<file id="2" name="C:\abc\def.vb" language="VB"/>
</files>
<entryPoint declaringType="C1" methodName="Main"/>
<methods>
<method containingType="C1" name="Main">
<sequencePoints>
<entry offset="0x0" hidden="true" document="2"/>
<entry offset="0x1" hidden="true" document="2"/>
<entry offset="0xc" startLine="23" startColumn="9" endLine="23" endColumn="41" document="2"/>
<entry offset="0x17" hidden="true" document="2"/>
<entry offset="0x22" hidden="true" document="2"/>
</sequencePoints>
</method>
</methods>
</symbols>, format:=DebugInformationFormat.PortablePdb)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
<WorkItem(50611, "https://github.com/dotnet/roslyn/issues/50611")>
Public Sub TwoMethodsOnlyOneWithMultipleMappingsAndRewriting()
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
Option Infer Off
Option Explicit Off
Imports System
Imports System.Collections.Generic
Class C1
Public Shared Sub FooInvisible()
dim str as string = "World!"
Console.WriteLine("Hello " & str)
End Sub
Public Shared Sub Main()
Console.WriteLine("Hello World")
#ExternalSource("C:\abc\def.vb", 23)
Console.WriteLine("Hello World")
Console.WriteLine("Hello World")
#End ExternalSource
#ExternalSource("C:\abc\def2.vb", 42)
' check that there are normal and hidden sequence points with mapping present
' because a for each will be rewritten
for each i in new Integer() {1, 2, 3}
Console.WriteLine(i)
next i
#End ExternalSource
Console.WriteLine("Hello World")
' hidden sequence points of rewritten statements will survive *iiks*.
for each i in new Integer() {1, 2, 3}
Console.WriteLine(i)
next i
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe)
' Care about the fact that C1.FooInvisible doesn't include any sequence points
' Care about the fact that there is no file reference to a.vb
compilation.VerifyPdb(
<symbols>
<files>
<file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="DB-A9-94-EF-BC-DF-10-C9-60-0F-C0-C4-9F-E4-77-F9-37-CF-E1-CE"/>
<file id="2" name="C:\abc\def.vb" language="VB"/>
<file id="3" name="C:\abc\def2.vb" language="VB"/>
</files>
<entryPoint declaringType="C1" methodName="Main"/>
<methods>
<method containingType="C1" name="Main">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="0" offset="372"/>
<slot kind="6" offset="363"/>
<slot kind="8" offset="363"/>
<slot kind="1" offset="363"/>
<slot kind="6" offset="606"/>
<slot kind="8" offset="606"/>
<slot kind="1" offset="606"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" hidden="true" document="2"/>
<entry offset="0x1" hidden="true" document="2"/>
<entry offset="0xc" startLine="23" startColumn="9" endLine="23" endColumn="41" document="2"/>
<entry offset="0x17" startLine="24" startColumn="9" endLine="24" endColumn="41" document="2"/>
<entry offset="0x22" startLine="44" startColumn="9" endLine="44" endColumn="46" document="3"/>
<entry offset="0x36" hidden="true" document="3"/>
<entry offset="0x41" startLine="45" startColumn="13" endLine="45" endColumn="33" document="3"/>
<entry offset="0x4d" startLine="46" startColumn="9" endLine="46" endColumn="15" document="3"/>
<entry offset="0x4e" hidden="true" document="3"/>
<entry offset="0x52" hidden="true" document="3"/>
<entry offset="0x59" hidden="true" document="3"/>
<entry offset="0x5c" hidden="true" document="3"/>
<entry offset="0x67" hidden="true" document="3"/>
<entry offset="0x7d" hidden="true" document="3"/>
<entry offset="0x8a" hidden="true" document="3"/>
<entry offset="0x96" hidden="true" document="3"/>
<entry offset="0x97" hidden="true" document="3"/>
<entry offset="0x9d" hidden="true" document="3"/>
<entry offset="0xa7" hidden="true" document="3"/>
<entry offset="0xab" hidden="true" document="3"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0xac">
<local name="i" il_index="0" il_start="0x0" il_end="0xac" attributes="0"/>
</scope>
</method>
</methods>
</symbols>, format:=DebugInformationFormat.PortablePdb)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub EmptyExternalSourceWillBeIgnored()
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
Option Infer Off
Option Explicit Off
Imports System
Imports System.Collections.Generic
Class C1
Public Shared Sub FooInvisible()
dim str as string = "World!"
Console.WriteLine("Hello " & str)
End Sub
Public Shared Sub Main()
Console.WriteLine("Hello World")
#ExternalSource("C:\abc\def.vb", 23)
#End ExternalSource
Console.WriteLine("Hello World")
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe)
compilation.VerifyPdb(
<symbols>
<files>
<file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="EE-47-B3-F6-59-FA-0D-E8-DF-B2-26-6A-7D-82-D3-52-3E-0C-36-E1"/>
</files>
<entryPoint declaringType="C1" methodName="Main"/>
<methods>
<method containingType="C1" name="FooInvisible">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="0" offset="4"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" startLine="9" startColumn="5" endLine="9" endColumn="37" document="1"/>
<entry offset="0x1" startLine="10" startColumn="13" endLine="10" endColumn="37" document="1"/>
<entry offset="0x7" startLine="11" startColumn="9" endLine="11" endColumn="42" document="1"/>
<entry offset="0x18" startLine="12" startColumn="5" endLine="12" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x19">
<namespace name="System" importlevel="file"/>
<namespace name="System.Collections.Generic" importlevel="file"/>
<currentnamespace name=""/>
<local name="str" il_index="0" il_start="0x0" il_end="0x19" attributes="0"/>
</scope>
</method>
<method containingType="C1" name="Main">
<sequencePoints>
<entry offset="0x0" startLine="14" startColumn="5" endLine="14" endColumn="29" document="1"/>
<entry offset="0x1" startLine="15" startColumn="9" endLine="15" endColumn="41" document="1"/>
<entry offset="0xc" startLine="20" startColumn="9" endLine="20" endColumn="41" document="1"/>
<entry offset="0x17" startLine="21" startColumn="5" endLine="21" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x18">
<importsforward declaringType="C1" methodName="FooInvisible"/>
</scope>
</method>
</methods>
</symbols>)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub MultipleEmptyExternalSourceWillBeIgnored()
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
Option Infer Off
Option Explicit Off
Imports System
Imports System.Collections.Generic
Class C1
Public Shared Sub FooInvisible()
dim str as string = "World!"
Console.WriteLine("Hello " & str)
End Sub
Public Shared Sub Main()
#ExternalSource("C:\abc\def.vb", 21)
#End ExternalSource
Console.WriteLine("Hello World")
#ExternalSource("C:\abc\def.vb", 22)
#End ExternalSource
Console.WriteLine("Hello World")
#ExternalSource("C:\abc\def.vb", 23)
#End ExternalSource
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe)
compilation.VerifyPdb(
<symbols>
<files>
<file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="B9-85-76-74-1E-E7-27-25-F7-8A-CB-A2-B1-9C-A4-CD-FD-49-8C-B7"/>
</files>
<entryPoint declaringType="C1" methodName="Main"/>
<methods>
<method containingType="C1" name="FooInvisible">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="0" offset="4"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" startLine="9" startColumn="5" endLine="9" endColumn="37" document="1"/>
<entry offset="0x1" startLine="10" startColumn="13" endLine="10" endColumn="37" document="1"/>
<entry offset="0x7" startLine="11" startColumn="9" endLine="11" endColumn="42" document="1"/>
<entry offset="0x18" startLine="12" startColumn="5" endLine="12" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x19">
<namespace name="System" importlevel="file"/>
<namespace name="System.Collections.Generic" importlevel="file"/>
<currentnamespace name=""/>
<local name="str" il_index="0" il_start="0x0" il_end="0x19" attributes="0"/>
</scope>
</method>
<method containingType="C1" name="Main">
<sequencePoints>
<entry offset="0x0" startLine="14" startColumn="5" endLine="14" endColumn="29" document="1"/>
<entry offset="0x1" startLine="18" startColumn="9" endLine="18" endColumn="41" document="1"/>
<entry offset="0xc" startLine="23" startColumn="9" endLine="23" endColumn="41" document="1"/>
<entry offset="0x17" startLine="27" startColumn="5" endLine="27" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x18">
<importsforward declaringType="C1" methodName="FooInvisible"/>
</scope>
</method>
</methods>
</symbols>)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub MultipleEmptyExternalSourceWithNonEmptyExternalSource()
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
Option Infer Off
Option Explicit Off
Imports System
Imports System.Collections.Generic
Class C1
Public Shared Sub FooInvisible()
dim str as string = "World!"
Console.WriteLine("Hello " & str)
End Sub
Public Shared Sub Main()
#ExternalSource("C:\abc\def.vb", 21)
#End ExternalSource
Console.WriteLine("Hello World")
#ExternalSource("C:\abc\def.vb", 22)
#End ExternalSource
Console.WriteLine("Hello World")
#ExternalSource("C:\abc\def.vb", 23)
' boo!
#End ExternalSource
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe)
' Care about the fact that there are no sequence points or referenced files
compilation.VerifyPdb(
<symbols>
<files>
<file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="B6-80-9E-65-43-38-00-C1-35-7F-AE-D0-60-F2-24-44-A8-11-C2-63"/>
</files>
<entryPoint declaringType="C1" methodName="Main"/>
<methods>
<method containingType="C1" name="Main" format="windows">
<scope startOffset="0x0" endOffset="0x18">
<namespace name="System" importlevel="file"/>
<namespace name="System.Collections.Generic" importlevel="file"/>
<currentnamespace name=""/>
</scope>
</method>
</methods>
</symbols>, ' Since the CDI is not emitted to Portable PDB it won't be present in the converted Windows PDB.
options:=PdbValidationOptions.SkipConversionValidation)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub MultipleEmptyExternalSourceWithNonEmptyExternalSourceFollowedByEmptyExternalSource()
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
Option Infer Off
Option Explicit Off
Imports System
Imports System.Collections.Generic
Class C1
Public Shared Sub FooInvisible()
dim str as string = "World!"
Console.WriteLine("Hello " & str)
End Sub
Public Shared Sub Main()
#ExternalSource("C:\abc\def.vb", 21)
#End ExternalSource
Console.WriteLine("Hello World")
#ExternalSource("C:\abc\def.vb", 22)
#End ExternalSource
Console.WriteLine("Hello World")
#ExternalSource("C:\abc\def.vb", 23)
#End ExternalSource
Console.WriteLine("Hello World")
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe)
' Care about the fact that C1.FooInvisible and C1.Main include no sequence points
' Care about the fact that no files are referenced
compilation.VerifyPdb(
<symbols>
<files>
<file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="73-05-84-40-AC-E0-15-63-CC-FE-BD-9A-99-23-AA-BD-24-40-24-44"/>
</files>
<entryPoint declaringType="C1" methodName="Main"/>
<methods>
<method containingType="C1" name="Main" format="windows">
<scope startOffset="0x0" endOffset="0x23">
<namespace name="System" importlevel="file"/>
<namespace name="System.Collections.Generic" importlevel="file"/>
<currentnamespace name=""/>
</scope>
</method>
</methods>
</symbols>, options:=PdbValidationOptions.SkipConversionValidation)
' When converting from Portable to Windows the PDB writer doesn't create an entry for the Main method
' and thus there Is no entry point record either.
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
<WorkItem(50611, "https://github.com/dotnet/roslyn/issues/50611")>
Public Sub TestPartialClassFieldInitializersWithExternalSource()
Dim source =
<compilation>
<file name="C:\Abc\ACTUAL.vb">
#ExternalSource("C:\abc\def1.vb", 41)
Option strict on
imports system
partial Class C1
public f1 as integer = 23
#End ExternalSource
#ExternalSource("C:\abc\def1.vb", 10)
Public sub DumpFields()
Console.WriteLine(f1)
Console.WriteLine(f2)
End Sub
#End ExternalSource
#ExternalSource("C:\abc\def1.vb", 1)
Public shared Sub Main(args() as string)
Dim c as new C1
c.DumpFields()
End sub
#End ExternalSource
End Class
Class InActual
public f1 as integer = 23
end Class
#ExternalChecksum("C:\abc\def2.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "1234")
#ExternalChecksum("BOGUS.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "1234")
#ExternalChecksum("C:\Abc\ACTUAL.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "6789")
</file>
<file name="b.vb">
Option strict on
imports system
partial Class C1
#ExternalSource("C:\abc\def2.vb", 23)
' more lines to see a different span in the sequence points ...
public f2 as integer = 42
#End ExternalSource
#ExternalChecksum("BOGUS.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "1234")
#ExternalChecksum("C:\Abc\ACTUAL.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "6789")
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe)
' Care about the fact that InActual.ctor includes no sequence points
' Care about the fact that there is no file reference to ACTUAL.vb
compilation.VerifyPdb(
<symbols>
<files>
<file id="1" name="C:\Abc\ACTUAL.vb" language="VB" checksumAlgorithm="SHA1" checksum="27-52-E9-85-5A-AC-31-05-A5-6F-70-40-55-3A-9C-43-D2-07-0D-4B"/>
<file id="2" name="b.vb" language="VB" checksumAlgorithm="SHA1" checksum="7F-D8-35-3F-B4-08-17-37-3E-37-30-26-2A-3F-0C-20-6F-48-2A-7A"/>
<file id="3" name="C:\abc\def1.vb" language="VB"/>
<file id="4" name="C:\abc\def2.vb" language="VB" checksumAlgorithm="406ea660-64cf-4c82-b6f0-42d48172a799" checksum="12-34"/>
<file id="5" name="BOGUS.vb" language="VB" checksumAlgorithm="406ea660-64cf-4c82-b6f0-42d48172a799" checksum="12-34"/>
</files>
<entryPoint declaringType="C1" methodName="Main" parameterNames="args"/>
<methods>
<method containingType="C1" name=".ctor">
<sequencePoints>
<entry offset="0x0" hidden="true" document="3"/>
<entry offset="0x7" startLine="46" startColumn="12" endLine="46" endColumn="30" document="3"/>
<entry offset="0xf" startLine="27" startColumn="36" endLine="27" endColumn="54" document="4"/>
</sequencePoints>
</method>
<method containingType="C1" name="DumpFields">
<sequencePoints>
<entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="28" document="3"/>
<entry offset="0x1" startLine="11" startColumn="9" endLine="11" endColumn="30" document="3"/>
<entry offset="0xd" startLine="12" startColumn="9" endLine="12" endColumn="30" document="3"/>
<entry offset="0x19" startLine="13" startColumn="5" endLine="13" endColumn="12" document="3"/>
</sequencePoints>
</method>
<method containingType="C1" name="Main" parameterNames="args">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="0" offset="4"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" startLine="1" startColumn="5" endLine="1" endColumn="45" document="3"/>
<entry offset="0x1" startLine="2" startColumn="13" endLine="2" endColumn="24" document="3"/>
<entry offset="0x7" startLine="3" startColumn="9" endLine="3" endColumn="23" document="3"/>
<entry offset="0xe" startLine="4" startColumn="5" endLine="4" endColumn="12" document="3"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0xf">
<local name="c" il_index="0" il_start="0x0" il_end="0xf" attributes="0"/>
</scope>
</method>
</methods>
</symbols>, format:=DebugInformationFormat.PortablePdb)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub IllegalExternalSourceUsageShouldNotAssert_1()
Dim source =
<compilation>
<file name="a.vb">
Option strict on
public Class C1
#ExternalSource("bar1.vb", 41)
#ExternalSource("bar1.vb", 41)
public shared sub main()
End sub
#End ExternalSource
#End ExternalSource
boo
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
source,
TestOptions.ReleaseExe).VerifyDiagnostics(Diagnostic(ERRID.ERR_NestedExternalSource, "#ExternalSource(""bar1.vb"", 41)"),
Diagnostic(ERRID.ERR_EndExternalSource, "#End ExternalSource"))
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub IllegalExternalSourceUsageShouldNotAssert_2()
Dim source =
<compilation>
<file name="a.vb">
Option strict on
public Class C1
#End ExternalSource
#End ExternalSource
public shared sub main()
End sub
boo
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
source,
TestOptions.ReleaseExe).VerifyDiagnostics(Diagnostic(ERRID.ERR_EndExternalSource, "#End ExternalSource"),
Diagnostic(ERRID.ERR_EndExternalSource, "#End ExternalSource"),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "boo"))
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub IllegalExternalSourceUsageShouldNotAssert_3()
Dim source =
<compilation>
<file name="a.vb">
Option strict on
public Class C1
#End ExternalSource
#ExternalSource("bar1.vb", 23)
public shared sub main()
End sub
boo
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
source,
TestOptions.ReleaseExe).VerifyDiagnostics(Diagnostic(ERRID.ERR_EndExternalSource, "#End ExternalSource"),
Diagnostic(ERRID.ERR_ExpectedEndExternalSource, "#ExternalSource(""bar1.vb"", 23)"),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "boo"))
End Sub
<WorkItem(545302, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545302")>
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub IllegalExternalSourceUsageShouldNotAssert_4()
Dim source =
<compilation>
<file name="a.vb">
Module Program
Sub Main()
#ExternalSource ("bar1.vb", 23)
#ExternalSource ("bar1.vb", 23)
System.Console.WriteLine("boo")
#End ExternalSource
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
source,
TestOptions.ReleaseExe).VerifyDiagnostics(Diagnostic(ERRID.ERR_NestedExternalSource, "#ExternalSource (""bar1.vb"", 23)"))
End Sub
<WorkItem(545307, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545307")>
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub OverflowLineNumbers()
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Imports System.Collections.Generic
Module Program
Public Sub Main()
Console.WriteLine("Hello World")
#ExternalSource("C:\abc\def.vb", 0)
Console.WriteLine("Hello World")
#End ExternalSource
#ExternalSource("C:\abc\def.vb", 1)
Console.WriteLine("Hello World")
#End ExternalSource
#ExternalSource("C:\abc\def.vb", 2147483647)
Console.WriteLine("Hello World")
#End ExternalSource
#ExternalSource("C:\abc\def.vb", 2147483648)
Console.WriteLine("Hello World")
#End ExternalSource
#ExternalSource("C:\abc\def.vb", 2147483649)
Console.WriteLine("Hello World")
#End ExternalSource
#ExternalSource("C:\abc\def.vb", &hfeefed)
Console.WriteLine("Hello World")
#End ExternalSource
Console.WriteLine("Hello World")
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe)
' Care about the fact that there is no document reference to a.vb
compilation.VerifyPdb(
<symbols>
<files>
<file id="1" name="C:\abc\def.vb" language="VB"/>
<file id="2" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="D2-FF-05-F8-B7-A2-25-B0-96-D9-97-2F-05-F8-F0-B5-81-8D-98-1D"/>
</files>
<entryPoint declaringType="Program" methodName="Main"/>
<methods>
<method containingType="Program" name="Main">
<sequencePoints>
<entry offset="0x0" hidden="true" document="1"/>
<entry offset="0x1" hidden="true" document="1"/>
<entry offset="0xc" startLine="0" startColumn="9" endLine="0" endColumn="41" document="1"/>
<entry offset="0x17" startLine="1" startColumn="9" endLine="1" endColumn="41" document="1"/>
<entry offset="0x22" startLine="16777215" startColumn="9" endLine="16777215" endColumn="41" document="1"/>
<entry offset="0x2d" startLine="16777215" startColumn="9" endLine="16777215" endColumn="41" document="1"/>
<entry offset="0x38" startLine="16777215" startColumn="9" endLine="16777215" endColumn="41" document="1"/>
<entry offset="0x43" startLine="16707565" startColumn="9" endLine="16707565" endColumn="41" document="1"/>
<entry offset="0x4e" hidden="true" document="1"/>
<entry offset="0x59" hidden="true" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x5a">
<namespace name="System" importlevel="file"/>
<namespace name="System.Collections.Generic" importlevel="file"/>
<currentnamespace name=""/>
</scope>
</method>
</methods>
</symbols>, format:=DebugInformationFormat.Pdb)
End Sub
<WorkItem(846584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/846584")>
<WorkItem(50611, "https://github.com/dotnet/roslyn/issues/50611")>
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub RelativePathForExternalSource()
Dim source =
<compilation>
<file name="C:\Folder1\Folder2\Test1.vb">
#ExternalChecksum("..\Test2.vb","{406ea660-64cf-4c82-b6f0-42d48172a799}","DB788882721B2B27C90579D5FE2A0418")
Class Test1
Sub Main()
#ExternalSource("..\Test2.vb",4)
Main()
#End ExternalSource
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
source,
TestOptions.DebugDll.WithSourceReferenceResolver(SourceFileResolver.Default))
' Care about the fact that there is no document reference to C:\Folder1\Folder2\Test1.vb
compilation.VerifyPdb(
<symbols>
<files>
<file id="1" name="C:\Folder1\Folder2\Test1.vb" language="VB" checksumAlgorithm="SHA1" checksum="B9-49-3D-62-89-9B-B2-2F-B6-72-90-A1-2D-01-11-89-B4-C2-83-B4"/>
<file id="2" name="C:\Folder1\Test2.vb" language="VB" checksumAlgorithm="406ea660-64cf-4c82-b6f0-42d48172a799" checksum="DB-78-88-82-72-1B-2B-27-C9-05-79-D5-FE-2A-04-18"/>
</files>
<methods>
<method containingType="Test1" name="Main">
<sequencePoints>
<entry offset="0x0" hidden="true" document="2"/>
<entry offset="0x1" startLine="4" startColumn="2" endLine="4" endColumn="8" document="2"/>
<entry offset="0x8" hidden="true" document="2"/>
</sequencePoints>
</method>
</methods>
</symbols>, format:=DebugInformationFormat.PortablePdb)
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.Emit
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB
Public Class PDBExternalSourceDirectiveTests
Inherits BasicTestBase
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
<WorkItem(50611, "https://github.com/dotnet/roslyn/issues/50611")>
Public Sub TwoMethodsOnlyOneWithMapping()
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
Option Infer Off
Option Explicit Off
Imports System
Imports System.Collections.Generic
Class C1
Public Shared Sub FooInvisible()
dim str as string = "World!"
Console.WriteLine("Hello " & str)
End Sub
Public Shared Sub Main()
Console.WriteLine("Hello World")
#ExternalSource("C:\abc\def.vb", 23)
Console.WriteLine("Hello World")
#End ExternalSource
Console.WriteLine("Hello World")
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe)
' Care about the fact that there is no file reference to a.vb
' Care about the fact that C1.FooInvisible doesn't include any sequence points
compilation.VerifyPdb(
<symbols>
<files>
<file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="70-82-DD-9A-57-B3-BE-57-7E-E8-B4-AE-B8-1E-1B-75-38-9D-13-C9"/>
<file id="2" name="C:\abc\def.vb" language="VB"/>
</files>
<entryPoint declaringType="C1" methodName="Main"/>
<methods>
<method containingType="C1" name="FooInvisible">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="0" offset="4"/>
</encLocalSlotMap>
</customDebugInfo>
</method>
<method containingType="C1" name="Main">
<sequencePoints>
<entry offset="0x0" hidden="true" document="2"/>
<entry offset="0x1" hidden="true" document="2"/>
<entry offset="0xc" startLine="23" startColumn="9" endLine="23" endColumn="41" document="2"/>
<entry offset="0x17" hidden="true" document="2"/>
<entry offset="0x22" hidden="true" document="2"/>
</sequencePoints>
</method>
</methods>
</symbols>, format:=DebugInformationFormat.PortablePdb)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
<WorkItem(50611, "https://github.com/dotnet/roslyn/issues/50611")>
Public Sub TwoMethodsOnlyOneWithMultipleMappingsAndRewriting()
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
Option Infer Off
Option Explicit Off
Imports System
Imports System.Collections.Generic
Class C1
Public Shared Sub FooInvisible()
dim str as string = "World!"
Console.WriteLine("Hello " & str)
End Sub
Public Shared Sub Main()
Console.WriteLine("Hello World")
#ExternalSource("C:\abc\def.vb", 23)
Console.WriteLine("Hello World")
Console.WriteLine("Hello World")
#End ExternalSource
#ExternalSource("C:\abc\def2.vb", 42)
' check that there are normal and hidden sequence points with mapping present
' because a for each will be rewritten
for each i in new Integer() {1, 2, 3}
Console.WriteLine(i)
next i
#End ExternalSource
Console.WriteLine("Hello World")
' hidden sequence points of rewritten statements will survive *iiks*.
for each i in new Integer() {1, 2, 3}
Console.WriteLine(i)
next i
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe)
' Care about the fact that C1.FooInvisible doesn't include any sequence points
' Care about the fact that there is no file reference to a.vb
compilation.VerifyPdb(
<symbols>
<files>
<file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="DB-A9-94-EF-BC-DF-10-C9-60-0F-C0-C4-9F-E4-77-F9-37-CF-E1-CE"/>
<file id="2" name="C:\abc\def.vb" language="VB"/>
<file id="3" name="C:\abc\def2.vb" language="VB"/>
</files>
<entryPoint declaringType="C1" methodName="Main"/>
<methods>
<method containingType="C1" name="FooInvisible">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="0" offset="4"/>
</encLocalSlotMap>
</customDebugInfo>
</method>
<method containingType="C1" name="Main">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="0" offset="372"/>
<slot kind="6" offset="363"/>
<slot kind="8" offset="363"/>
<slot kind="1" offset="363"/>
<slot kind="6" offset="606"/>
<slot kind="8" offset="606"/>
<slot kind="1" offset="606"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" hidden="true" document="2"/>
<entry offset="0x1" hidden="true" document="2"/>
<entry offset="0xc" startLine="23" startColumn="9" endLine="23" endColumn="41" document="2"/>
<entry offset="0x17" startLine="24" startColumn="9" endLine="24" endColumn="41" document="2"/>
<entry offset="0x22" startLine="44" startColumn="9" endLine="44" endColumn="46" document="3"/>
<entry offset="0x36" hidden="true" document="3"/>
<entry offset="0x41" startLine="45" startColumn="13" endLine="45" endColumn="33" document="3"/>
<entry offset="0x4d" startLine="46" startColumn="9" endLine="46" endColumn="15" document="3"/>
<entry offset="0x4e" hidden="true" document="3"/>
<entry offset="0x52" hidden="true" document="3"/>
<entry offset="0x59" hidden="true" document="3"/>
<entry offset="0x5c" hidden="true" document="3"/>
<entry offset="0x67" hidden="true" document="3"/>
<entry offset="0x7d" hidden="true" document="3"/>
<entry offset="0x8a" hidden="true" document="3"/>
<entry offset="0x96" hidden="true" document="3"/>
<entry offset="0x97" hidden="true" document="3"/>
<entry offset="0x9d" hidden="true" document="3"/>
<entry offset="0xa7" hidden="true" document="3"/>
<entry offset="0xab" hidden="true" document="3"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0xac">
<local name="i" il_index="0" il_start="0x0" il_end="0xac" attributes="0"/>
</scope>
</method>
</methods>
</symbols>, format:=DebugInformationFormat.PortablePdb)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub EmptyExternalSourceWillBeIgnored()
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
Option Infer Off
Option Explicit Off
Imports System
Imports System.Collections.Generic
Class C1
Public Shared Sub FooInvisible()
dim str as string = "World!"
Console.WriteLine("Hello " & str)
End Sub
Public Shared Sub Main()
Console.WriteLine("Hello World")
#ExternalSource("C:\abc\def.vb", 23)
#End ExternalSource
Console.WriteLine("Hello World")
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe)
compilation.VerifyPdb(
<symbols>
<files>
<file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="EE-47-B3-F6-59-FA-0D-E8-DF-B2-26-6A-7D-82-D3-52-3E-0C-36-E1"/>
</files>
<entryPoint declaringType="C1" methodName="Main"/>
<methods>
<method containingType="C1" name="FooInvisible">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="0" offset="4"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" startLine="9" startColumn="5" endLine="9" endColumn="37" document="1"/>
<entry offset="0x1" startLine="10" startColumn="13" endLine="10" endColumn="37" document="1"/>
<entry offset="0x7" startLine="11" startColumn="9" endLine="11" endColumn="42" document="1"/>
<entry offset="0x18" startLine="12" startColumn="5" endLine="12" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x19">
<namespace name="System" importlevel="file"/>
<namespace name="System.Collections.Generic" importlevel="file"/>
<currentnamespace name=""/>
<local name="str" il_index="0" il_start="0x0" il_end="0x19" attributes="0"/>
</scope>
</method>
<method containingType="C1" name="Main">
<sequencePoints>
<entry offset="0x0" startLine="14" startColumn="5" endLine="14" endColumn="29" document="1"/>
<entry offset="0x1" startLine="15" startColumn="9" endLine="15" endColumn="41" document="1"/>
<entry offset="0xc" startLine="20" startColumn="9" endLine="20" endColumn="41" document="1"/>
<entry offset="0x17" startLine="21" startColumn="5" endLine="21" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x18">
<importsforward declaringType="C1" methodName="FooInvisible"/>
</scope>
</method>
</methods>
</symbols>)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub MultipleEmptyExternalSourceWillBeIgnored()
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
Option Infer Off
Option Explicit Off
Imports System
Imports System.Collections.Generic
Class C1
Public Shared Sub FooInvisible()
dim str as string = "World!"
Console.WriteLine("Hello " & str)
End Sub
Public Shared Sub Main()
#ExternalSource("C:\abc\def.vb", 21)
#End ExternalSource
Console.WriteLine("Hello World")
#ExternalSource("C:\abc\def.vb", 22)
#End ExternalSource
Console.WriteLine("Hello World")
#ExternalSource("C:\abc\def.vb", 23)
#End ExternalSource
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe)
compilation.VerifyPdb(
<symbols>
<files>
<file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="B9-85-76-74-1E-E7-27-25-F7-8A-CB-A2-B1-9C-A4-CD-FD-49-8C-B7"/>
</files>
<entryPoint declaringType="C1" methodName="Main"/>
<methods>
<method containingType="C1" name="FooInvisible">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="0" offset="4"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" startLine="9" startColumn="5" endLine="9" endColumn="37" document="1"/>
<entry offset="0x1" startLine="10" startColumn="13" endLine="10" endColumn="37" document="1"/>
<entry offset="0x7" startLine="11" startColumn="9" endLine="11" endColumn="42" document="1"/>
<entry offset="0x18" startLine="12" startColumn="5" endLine="12" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x19">
<namespace name="System" importlevel="file"/>
<namespace name="System.Collections.Generic" importlevel="file"/>
<currentnamespace name=""/>
<local name="str" il_index="0" il_start="0x0" il_end="0x19" attributes="0"/>
</scope>
</method>
<method containingType="C1" name="Main">
<sequencePoints>
<entry offset="0x0" startLine="14" startColumn="5" endLine="14" endColumn="29" document="1"/>
<entry offset="0x1" startLine="18" startColumn="9" endLine="18" endColumn="41" document="1"/>
<entry offset="0xc" startLine="23" startColumn="9" endLine="23" endColumn="41" document="1"/>
<entry offset="0x17" startLine="27" startColumn="5" endLine="27" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x18">
<importsforward declaringType="C1" methodName="FooInvisible"/>
</scope>
</method>
</methods>
</symbols>)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub MultipleEmptyExternalSourceWithNonEmptyExternalSource()
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
Option Infer Off
Option Explicit Off
Imports System
Imports System.Collections.Generic
Class C1
Public Shared Sub FooInvisible()
dim str as string = "World!"
Console.WriteLine("Hello " & str)
End Sub
Public Shared Sub Main()
#ExternalSource("C:\abc\def.vb", 21)
#End ExternalSource
Console.WriteLine("Hello World")
#ExternalSource("C:\abc\def.vb", 22)
#End ExternalSource
Console.WriteLine("Hello World")
#ExternalSource("C:\abc\def.vb", 23)
' boo!
#End ExternalSource
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe)
' Care about the fact that there are no sequence points or referenced files
compilation.VerifyPdb(
<symbols>
<files>
<file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="B6-80-9E-65-43-38-00-C1-35-7F-AE-D0-60-F2-24-44-A8-11-C2-63"/>
</files>
<entryPoint declaringType="C1" methodName="Main"/>
<methods>
<method containingType="C1" name="FooInvisible">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="0" offset="4"/>
</encLocalSlotMap>
</customDebugInfo>
</method>
<method containingType="C1" name="Main" format="windows">
<scope startOffset="0x0" endOffset="0x18">
<namespace name="System" importlevel="file"/>
<namespace name="System.Collections.Generic" importlevel="file"/>
<currentnamespace name=""/>
</scope>
</method>
</methods>
</symbols>, ' Since the CDI is not emitted to Portable PDB it won't be present in the converted Windows PDB.
options:=PdbValidationOptions.SkipConversionValidation)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub MultipleEmptyExternalSourceWithNonEmptyExternalSourceFollowedByEmptyExternalSource()
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
Option Infer Off
Option Explicit Off
Imports System
Imports System.Collections.Generic
Class C1
Public Shared Sub FooInvisible()
dim str as string = "World!"
Console.WriteLine("Hello " & str)
End Sub
Public Shared Sub Main()
#ExternalSource("C:\abc\def.vb", 21)
#End ExternalSource
Console.WriteLine("Hello World")
#ExternalSource("C:\abc\def.vb", 22)
#End ExternalSource
Console.WriteLine("Hello World")
#ExternalSource("C:\abc\def.vb", 23)
#End ExternalSource
Console.WriteLine("Hello World")
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe)
' Care about the fact that C1.FooInvisible and C1.Main include no sequence points
' Care about the fact that no files are referenced
compilation.VerifyPdb(
<symbols>
<files>
<file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="73-05-84-40-AC-E0-15-63-CC-FE-BD-9A-99-23-AA-BD-24-40-24-44"/>
</files>
<entryPoint declaringType="C1" methodName="Main"/>
<methods>
<method containingType="C1" name="FooInvisible">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="0" offset="4"/>
</encLocalSlotMap>
</customDebugInfo>
</method>
<method containingType="C1" name="Main" format="windows">
<scope startOffset="0x0" endOffset="0x23">
<namespace name="System" importlevel="file"/>
<namespace name="System.Collections.Generic" importlevel="file"/>
<currentnamespace name=""/>
</scope>
</method>
</methods>
</symbols>, options:=PdbValidationOptions.SkipConversionValidation)
' When converting from Portable to Windows the PDB writer doesn't create an entry for the Main method
' and thus there Is no entry point record either.
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
<WorkItem(50611, "https://github.com/dotnet/roslyn/issues/50611")>
Public Sub TestPartialClassFieldInitializersWithExternalSource()
Dim source =
<compilation>
<file name="C:\Abc\ACTUAL.vb">
#ExternalSource("C:\abc\def1.vb", 41)
Option strict on
imports system
partial Class C1
public f1 as integer = 23
#End ExternalSource
#ExternalSource("C:\abc\def1.vb", 10)
Public sub DumpFields()
Console.WriteLine(f1)
Console.WriteLine(f2)
End Sub
#End ExternalSource
#ExternalSource("C:\abc\def1.vb", 1)
Public shared Sub Main(args() as string)
Dim c as new C1
c.DumpFields()
End sub
#End ExternalSource
End Class
Class InActual
public f1 as integer = 23
end Class
#ExternalChecksum("C:\abc\def2.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "1234")
#ExternalChecksum("BOGUS.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "1234")
#ExternalChecksum("C:\Abc\ACTUAL.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "6789")
</file>
<file name="b.vb">
Option strict on
imports system
partial Class C1
#ExternalSource("C:\abc\def2.vb", 23)
' more lines to see a different span in the sequence points ...
public f2 as integer = 42
#End ExternalSource
#ExternalChecksum("BOGUS.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "1234")
#ExternalChecksum("C:\Abc\ACTUAL.vb", "{406EA660-64CF-4C82-B6F0-42D48172A799}", "6789")
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe)
' Care about the fact that InActual.ctor includes no sequence points
' Care about the fact that there is no file reference to ACTUAL.vb
compilation.VerifyPdb(
<symbols>
<files>
<file id="1" name="C:\Abc\ACTUAL.vb" language="VB" checksumAlgorithm="SHA1" checksum="27-52-E9-85-5A-AC-31-05-A5-6F-70-40-55-3A-9C-43-D2-07-0D-4B"/>
<file id="2" name="b.vb" language="VB" checksumAlgorithm="SHA1" checksum="7F-D8-35-3F-B4-08-17-37-3E-37-30-26-2A-3F-0C-20-6F-48-2A-7A"/>
<file id="3" name="C:\abc\def1.vb" language="VB"/>
<file id="4" name="C:\abc\def2.vb" language="VB" checksumAlgorithm="406ea660-64cf-4c82-b6f0-42d48172a799" checksum="12-34"/>
<file id="5" name="BOGUS.vb" language="VB" checksumAlgorithm="406ea660-64cf-4c82-b6f0-42d48172a799" checksum="12-34"/>
</files>
<entryPoint declaringType="C1" methodName="Main" parameterNames="args"/>
<methods>
<method containingType="C1" name=".ctor">
<sequencePoints>
<entry offset="0x0" hidden="true" document="3"/>
<entry offset="0x7" startLine="46" startColumn="12" endLine="46" endColumn="30" document="3"/>
<entry offset="0xf" startLine="27" startColumn="36" endLine="27" endColumn="54" document="4"/>
</sequencePoints>
</method>
<method containingType="C1" name="DumpFields">
<sequencePoints>
<entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="28" document="3"/>
<entry offset="0x1" startLine="11" startColumn="9" endLine="11" endColumn="30" document="3"/>
<entry offset="0xd" startLine="12" startColumn="9" endLine="12" endColumn="30" document="3"/>
<entry offset="0x19" startLine="13" startColumn="5" endLine="13" endColumn="12" document="3"/>
</sequencePoints>
</method>
<method containingType="C1" name="Main" parameterNames="args">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="0" offset="4"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" startLine="1" startColumn="5" endLine="1" endColumn="45" document="3"/>
<entry offset="0x1" startLine="2" startColumn="13" endLine="2" endColumn="24" document="3"/>
<entry offset="0x7" startLine="3" startColumn="9" endLine="3" endColumn="23" document="3"/>
<entry offset="0xe" startLine="4" startColumn="5" endLine="4" endColumn="12" document="3"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0xf">
<local name="c" il_index="0" il_start="0x0" il_end="0xf" attributes="0"/>
</scope>
</method>
</methods>
</symbols>, format:=DebugInformationFormat.PortablePdb)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub IllegalExternalSourceUsageShouldNotAssert_1()
Dim source =
<compilation>
<file name="a.vb">
Option strict on
public Class C1
#ExternalSource("bar1.vb", 41)
#ExternalSource("bar1.vb", 41)
public shared sub main()
End sub
#End ExternalSource
#End ExternalSource
boo
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
source,
TestOptions.ReleaseExe).VerifyDiagnostics(Diagnostic(ERRID.ERR_NestedExternalSource, "#ExternalSource(""bar1.vb"", 41)"),
Diagnostic(ERRID.ERR_EndExternalSource, "#End ExternalSource"))
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub IllegalExternalSourceUsageShouldNotAssert_2()
Dim source =
<compilation>
<file name="a.vb">
Option strict on
public Class C1
#End ExternalSource
#End ExternalSource
public shared sub main()
End sub
boo
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
source,
TestOptions.ReleaseExe).VerifyDiagnostics(Diagnostic(ERRID.ERR_EndExternalSource, "#End ExternalSource"),
Diagnostic(ERRID.ERR_EndExternalSource, "#End ExternalSource"),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "boo"))
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub IllegalExternalSourceUsageShouldNotAssert_3()
Dim source =
<compilation>
<file name="a.vb">
Option strict on
public Class C1
#End ExternalSource
#ExternalSource("bar1.vb", 23)
public shared sub main()
End sub
boo
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
source,
TestOptions.ReleaseExe).VerifyDiagnostics(Diagnostic(ERRID.ERR_EndExternalSource, "#End ExternalSource"),
Diagnostic(ERRID.ERR_ExpectedEndExternalSource, "#ExternalSource(""bar1.vb"", 23)"),
Diagnostic(ERRID.ERR_ExpectedDeclaration, "boo"))
End Sub
<WorkItem(545302, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545302")>
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub IllegalExternalSourceUsageShouldNotAssert_4()
Dim source =
<compilation>
<file name="a.vb">
Module Program
Sub Main()
#ExternalSource ("bar1.vb", 23)
#ExternalSource ("bar1.vb", 23)
System.Console.WriteLine("boo")
#End ExternalSource
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
source,
TestOptions.ReleaseExe).VerifyDiagnostics(Diagnostic(ERRID.ERR_NestedExternalSource, "#ExternalSource (""bar1.vb"", 23)"))
End Sub
<WorkItem(545307, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545307")>
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub OverflowLineNumbers()
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Imports System.Collections.Generic
Module Program
Public Sub Main()
Console.WriteLine("Hello World")
#ExternalSource("C:\abc\def.vb", 0)
Console.WriteLine("Hello World")
#End ExternalSource
#ExternalSource("C:\abc\def.vb", 1)
Console.WriteLine("Hello World")
#End ExternalSource
#ExternalSource("C:\abc\def.vb", 2147483647)
Console.WriteLine("Hello World")
#End ExternalSource
#ExternalSource("C:\abc\def.vb", 2147483648)
Console.WriteLine("Hello World")
#End ExternalSource
#ExternalSource("C:\abc\def.vb", 2147483649)
Console.WriteLine("Hello World")
#End ExternalSource
#ExternalSource("C:\abc\def.vb", &hfeefed)
Console.WriteLine("Hello World")
#End ExternalSource
Console.WriteLine("Hello World")
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe)
' Care about the fact that there is no document reference to a.vb
compilation.VerifyPdb(
<symbols>
<files>
<file id="1" name="C:\abc\def.vb" language="VB"/>
<file id="2" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="D2-FF-05-F8-B7-A2-25-B0-96-D9-97-2F-05-F8-F0-B5-81-8D-98-1D"/>
</files>
<entryPoint declaringType="Program" methodName="Main"/>
<methods>
<method containingType="Program" name="Main">
<sequencePoints>
<entry offset="0x0" hidden="true" document="1"/>
<entry offset="0x1" hidden="true" document="1"/>
<entry offset="0xc" startLine="0" startColumn="9" endLine="0" endColumn="41" document="1"/>
<entry offset="0x17" startLine="1" startColumn="9" endLine="1" endColumn="41" document="1"/>
<entry offset="0x22" startLine="16777215" startColumn="9" endLine="16777215" endColumn="41" document="1"/>
<entry offset="0x2d" startLine="16777215" startColumn="9" endLine="16777215" endColumn="41" document="1"/>
<entry offset="0x38" startLine="16777215" startColumn="9" endLine="16777215" endColumn="41" document="1"/>
<entry offset="0x43" startLine="16707565" startColumn="9" endLine="16707565" endColumn="41" document="1"/>
<entry offset="0x4e" hidden="true" document="1"/>
<entry offset="0x59" hidden="true" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x5a">
<namespace name="System" importlevel="file"/>
<namespace name="System.Collections.Generic" importlevel="file"/>
<currentnamespace name=""/>
</scope>
</method>
</methods>
</symbols>, format:=DebugInformationFormat.Pdb)
End Sub
<WorkItem(846584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/846584")>
<WorkItem(50611, "https://github.com/dotnet/roslyn/issues/50611")>
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub RelativePathForExternalSource()
Dim source =
<compilation>
<file name="C:\Folder1\Folder2\Test1.vb">
#ExternalChecksum("..\Test2.vb","{406ea660-64cf-4c82-b6f0-42d48172a799}","DB788882721B2B27C90579D5FE2A0418")
Class Test1
Sub Main()
#ExternalSource("..\Test2.vb",4)
Main()
#End ExternalSource
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
source,
TestOptions.DebugDll.WithSourceReferenceResolver(SourceFileResolver.Default))
' Care about the fact that there is no document reference to C:\Folder1\Folder2\Test1.vb
compilation.VerifyPdb(
<symbols>
<files>
<file id="1" name="C:\Folder1\Folder2\Test1.vb" language="VB" checksumAlgorithm="SHA1" checksum="B9-49-3D-62-89-9B-B2-2F-B6-72-90-A1-2D-01-11-89-B4-C2-83-B4"/>
<file id="2" name="C:\Folder1\Test2.vb" language="VB" checksumAlgorithm="406ea660-64cf-4c82-b6f0-42d48172a799" checksum="DB-78-88-82-72-1B-2B-27-C9-05-79-D5-FE-2A-04-18"/>
</files>
<methods>
<method containingType="Test1" name="Main">
<sequencePoints>
<entry offset="0x0" hidden="true" document="2"/>
<entry offset="0x1" startLine="4" startColumn="2" endLine="4" endColumn="8" document="2"/>
<entry offset="0x8" hidden="true" document="2"/>
</sequencePoints>
</method>
</methods>
</symbols>, format:=DebugInformationFormat.PortablePdb)
End Sub
End Class
End Namespace
| 1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Analyzers/VisualBasic/Tests/UseNullPropagation/UseNullPropagationTests.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.CodeFixes
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics
Imports Microsoft.CodeAnalysis.VisualBasic.UseNullPropagation
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.UseNullPropagation
Partial Public Class UseNullPropagationTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider)
Return (New VisualBasicUseNullPropagationDiagnosticAnalyzer(),
New VisualBasicUseNullPropagationCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestLeft_Equals() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (o Is Nothing, Nothing, o.ToString())
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.ToString()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestMissingInVB12() As Task
Await TestMissingAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (o Is Nothing, Nothing, o.ToString())
End Sub
End Class", New TestParameters(VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestRight_Equals() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (Nothing Is o, Nothing, o.ToString()
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.ToString()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestLeft_NotEquals() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (o IsNot Nothing, o.ToString(), Nothing)
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.ToString()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableType() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Dim f As Integer?
Sub M(C c)
Dim v = [||]If (c IsNot Nothing, c.f, Nothing)
End Sub
End Class",
"
Imports System
Class C
Dim f As Integer?
Sub M(C c)
Dim v = c?.f
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndObjectCast() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Dim f As Integer?
Sub M(C c)
Dim v = [||]If (DirectCast(c, Object) IsNot Nothing, c.f, Nothing)
End Sub
End Class",
"
Imports System
Class C
Dim f As Integer?
Sub M(C c)
Dim v = c?.f
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestRight_NotEquals() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (Nothing IsNot o, o.ToString(), Nothing)
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.ToString()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestIndexer() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (o Is Nothing, Nothing, o(0))
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?(0)
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestConditionalAccess() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (o Is Nothing, Nothing, o.B?.C)
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.B?.C
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestMemberAccess() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (o Is Nothing, Nothing, o.B)
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.B
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestMissingOnSimpleMatch() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (o Is Nothing, Nothing, o)
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestParenthesizedCondition() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If ((o Is Nothing), Nothing, o.ToString())
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.ToString()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestFixAll1() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v1 = {|FixAllInDocument:If|} (o Is Nothing, Nothing, o.ToString())
Dim v2 = If (o IsNot Nothing, o.ToString(), Nothing)
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v1 = o?.ToString()
Dim v2 = o?.ToString()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestFixAll2() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
void M(object o1, object o2)
Dim v1 = {|FixAllInDocument:If|} (o1 Is Nothing, Nothing, o1.ToString(If(o2 Is Nothing, Nothing, o2.ToString()))
End Sub
End Class",
"
Imports System
Class C
void M(object o1, object o2)
Dim v1 = o1?.ToString(o2?.ToString())
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestNullable1() As Task
Await TestMissingAsync(
"
Imports System
Class C
Function M(o As String) As Integer?
return [||]If (o Is Nothing, Nothing, o.Length)
End Function
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestNullable2() As Task
Await TestMissingAsync(
"
Imports System
Class C
Sub M(o As String)
Dim x = [||]If (o Is Nothing, Nothing, o.Length)
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndReferenceEquals1() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (ReferenceEquals(o, Nothing), Nothing, o.ToString())
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.ToString()
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndReferenceEquals2() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (ReferenceEquals(Nothing, o), Nothing, o.ToString())
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.ToString()
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndReferenceEqualsOtherValue1() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object, other as Object)
Dim v = [||]If (ReferenceEquals(o, other), Nothing, o.ToString())
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndReferenceEqualsOtherValue2() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object, other as Object)
Dim v = [||]If (ReferenceEquals(other, o), Nothing, o.ToString())
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndReferenceEqualsWithObject1() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (Object.ReferenceEquals(o, Nothing), Nothing, o.ToString())
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.ToString()
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndReferenceEqualsWithObject2() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (Object.ReferenceEquals(Nothing, o), Nothing, o.ToString())
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.ToString()
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndReferenceEqualsOtherValueWithObject1() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object, other as Object)
Dim v = [||]If (Object.ReferenceEquals(o, other), Nothing, o.ToString())
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndReferenceEqualsOtherValueWithObject2() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object, other as Object)
Dim v = [||]If (Object.ReferenceEquals(other, o), Nothing, o.ToString())
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndReferenceEqualsWithOmittedArgument1() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (Object.ReferenceEquals(o, ), Nothing, o.ToString())
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndReferenceEqualsWithOmittedArgument2() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (Object.ReferenceEquals(, Nothing), Nothing, o.ToString())
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndLogicalNotReferenceEquals1() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (Not ReferenceEquals(o, Nothing), o.ToString(), Nothing)
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.ToString()
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndLogicalNotReferenceEquals2() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (Not ReferenceEquals(Nothing, o), o.ToString(), Nothing)
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.ToString()
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndLogicalNotReferenceEqualsOtherValue1() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object, other as Object)
Dim v = [||]If (Not ReferenceEquals(o, other), o.ToString(), Nothing)
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndLogicalNotReferenceEqualsOtherValue2() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object, other as Object)
Dim v = [||]If (Not ReferenceEquals(other, o), o.ToString(), Nothing)
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndLogicalNotReferenceEqualsWithObject1() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (Not Object.ReferenceEquals(o, Nothing), o.ToString(), Nothing)
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.ToString()
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndLogicalNotReferenceEqualsWithObject2() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (Not Object.ReferenceEquals(Nothing, o), o.ToString(), Nothing)
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.ToString()
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndLogicalNotReferenceEqualsOtherValueWithObject1() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object, other as Object)
Dim v = [||]If (Not Object.ReferenceEquals(o, other), o.ToString(), Nothing)
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndLogicalNotReferenceEqualsOtherValueWithObject2() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object, other as Object)
Dim v = [||]If (Not Object.ReferenceEquals(other, o), o.ToString(), Nothing)
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestEqualsWithLogicalNot() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (Not (o Is Nothing), o.ToString(), Nothing)
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.ToString()
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestNotEqualsWithLogicalNot() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (Not (o IsNot Nothing), Nothing, o.ToString())
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.ToString()
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestEqualsOtherValueWithLogicalNot() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object, other as Object)
Dim v = [||]If (Not (o Is other), o.ToString(), Nothing)
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestNotEqualsOtherValueWithLogicalNot() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object, other as Object)
Dim v = [||]If (Not (o IsNot other), Nothing, o.ToString())
End Sub
End Class")
End Function
<WorkItem(33992, "https://github.com/dotnet/roslyn/issues/33992")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestExpressionTree1() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Imports System.Linq
Public Class Class1
Public Sub Foo()
Dim q = From item In Enumerable.Empty(Of (x As Integer?, y As Integer?)?)().AsQueryable()
Select [||]If(item Is Nothing, Nothing, item.Value.x)
End Sub
End Class")
End Function
<WorkItem(33992, "https://github.com/dotnet/roslyn/issues/33992")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestExpressionTree2() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Imports System.Linq
Public Class Class1
Public Sub Foo()
Dim q = From item In Enumerable.Empty(Of (x As Integer?, y As Integer?)?)().AsQueryable()
Where [||]If(item Is Nothing, Nothing, item.Value.x) > 0
Select item
End Sub
End Class")
End Function
<WorkItem(33992, "https://github.com/dotnet/roslyn/issues/33992")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestExpressionTree3() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Imports System.Linq
Public Class Class1
Public Sub Foo()
Dim q = From item In Enumerable.Empty(Of (x As Integer?, y As Integer?)?)().AsQueryable()
Let x = [||]If(item Is Nothing, Nothing, item.Value.x)
Select x
End Sub
End Class")
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.CodeFixes
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics
Imports Microsoft.CodeAnalysis.VisualBasic.UseNullPropagation
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.UseNullPropagation
Partial Public Class UseNullPropagationTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider)
Return (New VisualBasicUseNullPropagationDiagnosticAnalyzer(),
New VisualBasicUseNullPropagationCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestLeft_Equals() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (o Is Nothing, Nothing, o.ToString())
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.ToString()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestMissingInVB12() As Task
Await TestMissingAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (o Is Nothing, Nothing, o.ToString())
End Sub
End Class", New TestParameters(VisualBasicParseOptions.Default.WithLanguageVersion(LanguageVersion.VisualBasic12)))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestRight_Equals() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (Nothing Is o, Nothing, o.ToString()
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.ToString()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestLeft_NotEquals() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (o IsNot Nothing, o.ToString(), Nothing)
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.ToString()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableType() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Dim f As Integer?
Sub M(C c)
Dim v = [||]If (c IsNot Nothing, c.f, Nothing)
End Sub
End Class",
"
Imports System
Class C
Dim f As Integer?
Sub M(C c)
Dim v = c?.f
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndObjectCast() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Dim f As Integer?
Sub M(C c)
Dim v = [||]If (DirectCast(c, Object) IsNot Nothing, c.f, Nothing)
End Sub
End Class",
"
Imports System
Class C
Dim f As Integer?
Sub M(C c)
Dim v = c?.f
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestRight_NotEquals() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (Nothing IsNot o, o.ToString(), Nothing)
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.ToString()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestIndexer() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (o Is Nothing, Nothing, o(0))
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?(0)
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestConditionalAccess() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (o Is Nothing, Nothing, o.B?.C)
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.B?.C
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestMemberAccess() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (o Is Nothing, Nothing, o.B)
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.B
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestMissingOnSimpleMatch() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (o Is Nothing, Nothing, o)
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestParenthesizedCondition() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If ((o Is Nothing), Nothing, o.ToString())
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.ToString()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestFixAll1() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v1 = {|FixAllInDocument:If|} (o Is Nothing, Nothing, o.ToString())
Dim v2 = If (o IsNot Nothing, o.ToString(), Nothing)
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v1 = o?.ToString()
Dim v2 = o?.ToString()
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestFixAll2() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
void M(object o1, object o2)
Dim v1 = {|FixAllInDocument:If|} (o1 Is Nothing, Nothing, o1.ToString(If(o2 Is Nothing, Nothing, o2.ToString()))
End Sub
End Class",
"
Imports System
Class C
void M(object o1, object o2)
Dim v1 = o1?.ToString(o2?.ToString())
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestNullable1() As Task
Await TestMissingAsync(
"
Imports System
Class C
Function M(o As String) As Integer?
return [||]If (o Is Nothing, Nothing, o.Length)
End Function
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestNullable2() As Task
Await TestMissingAsync(
"
Imports System
Class C
Sub M(o As String)
Dim x = [||]If (o Is Nothing, Nothing, o.Length)
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndReferenceEquals1() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (ReferenceEquals(o, Nothing), Nothing, o.ToString())
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.ToString()
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndReferenceEquals2() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (ReferenceEquals(Nothing, o), Nothing, o.ToString())
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.ToString()
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndReferenceEqualsOtherValue1() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object, other as Object)
Dim v = [||]If (ReferenceEquals(o, other), Nothing, o.ToString())
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndReferenceEqualsOtherValue2() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object, other as Object)
Dim v = [||]If (ReferenceEquals(other, o), Nothing, o.ToString())
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndReferenceEqualsWithObject1() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (Object.ReferenceEquals(o, Nothing), Nothing, o.ToString())
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.ToString()
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndReferenceEqualsWithObject2() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (Object.ReferenceEquals(Nothing, o), Nothing, o.ToString())
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.ToString()
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndReferenceEqualsOtherValueWithObject1() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object, other as Object)
Dim v = [||]If (Object.ReferenceEquals(o, other), Nothing, o.ToString())
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndReferenceEqualsOtherValueWithObject2() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object, other as Object)
Dim v = [||]If (Object.ReferenceEquals(other, o), Nothing, o.ToString())
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndReferenceEqualsWithOmittedArgument1() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (Object.ReferenceEquals(o, ), Nothing, o.ToString())
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndReferenceEqualsWithOmittedArgument2() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (Object.ReferenceEquals(, Nothing), Nothing, o.ToString())
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndLogicalNotReferenceEquals1() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (Not ReferenceEquals(o, Nothing), o.ToString(), Nothing)
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.ToString()
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndLogicalNotReferenceEquals2() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (Not ReferenceEquals(Nothing, o), o.ToString(), Nothing)
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.ToString()
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndLogicalNotReferenceEqualsOtherValue1() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object, other as Object)
Dim v = [||]If (Not ReferenceEquals(o, other), o.ToString(), Nothing)
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndLogicalNotReferenceEqualsOtherValue2() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object, other as Object)
Dim v = [||]If (Not ReferenceEquals(other, o), o.ToString(), Nothing)
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndLogicalNotReferenceEqualsWithObject1() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (Not Object.ReferenceEquals(o, Nothing), o.ToString(), Nothing)
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.ToString()
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndLogicalNotReferenceEqualsWithObject2() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (Not Object.ReferenceEquals(Nothing, o), o.ToString(), Nothing)
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.ToString()
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndLogicalNotReferenceEqualsOtherValueWithObject1() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object, other as Object)
Dim v = [||]If (Not Object.ReferenceEquals(o, other), o.ToString(), Nothing)
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestWithNullableTypeAndLogicalNotReferenceEqualsOtherValueWithObject2() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object, other as Object)
Dim v = [||]If (Not Object.ReferenceEquals(other, o), o.ToString(), Nothing)
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestEqualsWithLogicalNot() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (Not (o Is Nothing), o.ToString(), Nothing)
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.ToString()
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestNotEqualsWithLogicalNot() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object)
Dim v = [||]If (Not (o IsNot Nothing), Nothing, o.ToString())
End Sub
End Class",
"
Imports System
Class C
Sub M(o As Object)
Dim v = o?.ToString()
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestEqualsOtherValueWithLogicalNot() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object, other as Object)
Dim v = [||]If (Not (o Is other), o.ToString(), Nothing)
End Sub
End Class")
End Function
<WorkItem(23043, "https://github.com/dotnet/roslyn/issues/23043")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestNotEqualsOtherValueWithLogicalNot() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Class C
Sub M(o As Object, other as Object)
Dim v = [||]If (Not (o IsNot other), Nothing, o.ToString())
End Sub
End Class")
End Function
<WorkItem(33992, "https://github.com/dotnet/roslyn/issues/33992")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestExpressionTree1() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Imports System.Linq
Public Class Class1
Public Sub Foo()
Dim q = From item In Enumerable.Empty(Of (x As Integer?, y As Integer?)?)().AsQueryable()
Select [||]If(item Is Nothing, Nothing, item.Value.x)
End Sub
End Class")
End Function
<WorkItem(33992, "https://github.com/dotnet/roslyn/issues/33992")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestExpressionTree2() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Imports System.Linq
Public Class Class1
Public Sub Foo()
Dim q = From item In Enumerable.Empty(Of (x As Integer?, y As Integer?)?)().AsQueryable()
Where [||]If(item Is Nothing, Nothing, item.Value.x) > 0
Select item
End Sub
End Class")
End Function
<WorkItem(33992, "https://github.com/dotnet/roslyn/issues/33992")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)>
Public Async Function TestExpressionTree3() As Task
Await TestMissingInRegularAndScriptAsync(
"
Imports System
Imports System.Linq
Public Class Class1
Public Sub Foo()
Dim q = From item In Enumerable.Empty(Of (x As Integer?, y As Integer?)?)().AsQueryable()
Let x = [||]If(item Is Nothing, Nothing, item.Value.x)
Select x
End Sub
End Class")
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/EditorFeatures/VisualBasicTest/Diagnostics/GenerateVariable/GenerateVariableTests.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.CodeFixes
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.VisualBasic.GenerateVariable
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.GenerateVariable
Public Class GenerateVariableTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider)
Return (Nothing, New VisualBasicGenerateVariableCodeFixProvider())
End Function
Protected Overrides Function MassageActions(actions As ImmutableArray(Of CodeAction)) As ImmutableArray(Of CodeAction)
Return FlattenActions(actions)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateSimpleProperty() As Threading.Tasks.Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Goo([|Bar|])
End Sub
End Module",
"Module Program
Public Property Bar As Object
Sub Main(args As String())
Goo(Bar)
End Sub
End Module")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateSimpleField() As Threading.Tasks.Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Goo([|Bar|])
End Sub
End Module",
"Module Program
Private Bar As Object
Sub Main(args As String())
Goo(Bar)
End Sub
End Module",
index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateReadOnlyField() As Threading.Tasks.Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Goo([|Bar|])
End Sub
End Module",
"Module Program
Private ReadOnly Bar As Object
Sub Main(args As String())
Goo(Bar)
End Sub
End Module",
index:=2)
End Function
<WorkItem(539692, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539692")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateFromAssignment() As Threading.Tasks.Task
Await TestInRegularAndScriptAsync(
"Class C
Shared Sub M
[|Goo|] = 3
End Sub
End Class",
"Class C
Private Shared Goo As Integer
Shared Sub M
Goo = 3
End Sub
End Class",
index:=1)
End Function
<WorkItem(539694, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539694")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateReadOnlyProperty() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Dim i As IGoo
Main(i.[|Blah|])
End Sub
End Module
Interface IGoo
End Interface",
"Module Program
Sub Main(args As String())
Dim i As IGoo
Main(i.Blah)
End Sub
End Module
Interface IGoo
ReadOnly Property Blah As String()
End Interface")
End Function
<WorkItem(539694, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539694")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateReadWriteProperty() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Dim i As IGoo
Main(i.[|Blah|])
End Sub
End Module
Interface IGoo
End Interface",
"Module Program
Sub Main(args As String())
Dim i As IGoo
Main(i.Blah)
End Sub
End Module
Interface IGoo
Property Blah As String()
End Interface",
index:=1)
End Function
<WorkItem(539695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539695")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateProtectedSharedFieldIntoBase() As Threading.Tasks.Task
Await TestInRegularAndScriptAsync(
"Class Base
End Class
Class Derived
Inherits Base
Shared Sub Main
Dim a = Base.[|Goo|]
End Sub
End Class",
"Class Base
Protected Shared Goo As Object
End Class
Class Derived
Inherits Base
Shared Sub Main
Dim a = Base.Goo
End Sub
End Class",
index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestNotOfferedForSharedAccessOffInterface() As Task
Await TestMissingInRegularAndScriptAsync(
"Interface IGoo
End Interface
Class Program
Sub Main
IGoo.[|Bar|] = 3
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateFriendAccessibilityForField() As Threading.Tasks.Task
Await TestInRegularAndScriptAsync(
"Class A
End Class
Class B
Sub Main
Dim x = A.[|Goo|]
End Sub
End Class",
"Class A
Friend Shared Goo As Object
End Class
Class B
Sub Main
Dim x = A.Goo
End Sub
End Class",
index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyOnInterface1() As Threading.Tasks.Task
Await TestInRegularAndScriptAsync(
"Interface IGoo
End Interface
Class C
Sub Main
Dim goo As IGoo
Dim b = goo.[|Bar|]
End Sub
End Class",
"Interface IGoo
ReadOnly Property Bar As Object
End Interface
Class C
Sub Main
Dim goo As IGoo
Dim b = goo.Bar
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyOnInterface2() As Threading.Tasks.Task
Await TestInRegularAndScriptAsync(
"Interface IGoo
End Interface
Class C
Sub Main
Dim goo As IGoo
Dim b = goo.[|Bar|]
End Sub
End Class",
"Interface IGoo
Property Bar As Object
End Interface
Class C
Sub Main
Dim goo As IGoo
Dim b = goo.Bar
End Sub
End Class", index:=1)
End Function
<WorkItem(539796, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539796")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyIntoModule() As Threading.Tasks.Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
End Sub
End Module
Class C
Sub M()
Program.[|P|] = 10
End Sub
End Class",
"Module Program
Public Property P As Integer
Sub Main(args As String())
End Sub
End Module
Class C
Sub M()
Program.P = 10
End Sub
End Class")
End Function
<WorkItem(539796, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539796")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestFieldPropertyIntoModule() As Threading.Tasks.Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
End Sub
End Module
Class C
Sub M()
[|Program.P|] = 10
End Sub
End Class",
"Module Program
Friend P As Integer
Sub Main(args As String())
End Sub
End Module
Class C
Sub M()
Program.P = 10
End Sub
End Class",
index:=1)
End Function
<WorkItem(539848, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539848")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestOnLeftOfMemberAccess() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
[|HERE|].ToString()
End Sub
End Module",
"Module Program
Private HERE As Object
Sub Main(args As String())
HERE.ToString()
End Sub
End Module",
index:=1)
End Function
<WorkItem(539725, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539725")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestMissingWhenInterfacePropertyAlreadyExists() As Task
Await TestMissingInRegularAndScriptAsync(
"Interface IGoo
Property Blah As String()
End Interface
Module Program
Sub Main(args As String())
Dim goo As IGoo
Main(goo.[|Blah|])
End Sub
End Module")
End Function
<WorkItem(540013, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540013")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestMissingInAddressOf() As Task
Await TestMissingInRegularAndScriptAsync(
"Delegate Sub D(x As Integer)
Class C
Public Sub Goo()
Dim x As D = New D(AddressOf [|Method|])
End Sub
End Class")
End Function
<WorkItem(540578, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540578")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestInferProperReturnType() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Function Fun() As Integer
Return [|P|]
End Function
End Module",
"Module Program
Public Property P As Integer
Function Fun() As Integer
Return P
End Function
End Module")
End Function
<WorkItem(540576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540576")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestAssignment() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Dim x As Integer
x = [|P|]
End Sub
End Module",
"Module Program
Public Property P As Integer
Sub Main(args As String())
Dim x As Integer
x = P
End Sub
End Module")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateFromSharedMethod() As Task
Await TestInRegularAndScriptAsync(
"Class GenPropTest
Public Shared Sub Main()
[|genStaticUnqualified|] = """"
End Sub
End Class",
"Class GenPropTest
Private Shared genStaticUnqualified As String
Public Shared Sub Main()
genStaticUnqualified = """"
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateSharedField() As Task
Await TestInRegularAndScriptAsync(
"Class GenPropTest
Public Sub Main()
GenPropTest.[|genStaticUnqualified|] = """"
End Sub
End Class",
"Class GenPropTest
Private Shared genStaticUnqualified As String
Public Sub Main()
GenPropTest.genStaticUnqualified = """"
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateInstanceFieldOffMe() As Task
Await TestInRegularAndScriptAsync(
"Class GenPropTest
Public Sub Main()
Me.[|field|] = """"
End Sub
End Class",
"Class GenPropTest
Private field As String
Public Sub Main()
Me.field = """"
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestSimpleInstanceField() As Task
Await TestInRegularAndScriptAsync(
"Class GenPropTest
Public Sub Main()
[|field|] = """"
End Sub
End Class",
"Class GenPropTest
Private field As String
Public Sub Main()
field = """"
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestFieldOnByRefParam() As Task
Await TestInRegularAndScriptAsync(
"Class A
End Class
Class B
Public Sub Goo(ByRef d As Integer)
End Sub
Public Sub Bar()
Dim s As New A()
Goo(s.[|field|])
End Sub
End Class",
"Class A
Friend field As Integer
End Class
Class B
Public Sub Goo(ByRef d As Integer)
End Sub
Public Sub Bar()
Dim s As New A()
Goo(s.field)
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateFieldInByRefProperty() As Task
Await TestInRegularAndScriptAsync(
"Class A
End Class
Class B
Public Sub Goo(ByRef d As Integer)
End Sub
Public Sub Bar()
Dim s As New A()
Goo(s.[|field|])
End Sub
End Class",
"Class A
Friend field As Integer
End Class
Class B
Public Sub Goo(ByRef d As Integer)
End Sub
Public Sub Bar()
Dim s As New A()
Goo(s.field)
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyInByRefProperty() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class A
End Class
Class B
Public Sub Goo(ByRef d As Integer)
End Sub
Public Sub Bar()
Dim s As New A()
Goo(s.[|field|])
End Sub
End Class",
"
Imports System
Class A
Public ReadOnly Property field As Integer
Get
Throw New NotImplementedException()
End Get
End Property
End Class
Class B
Public Sub Goo(ByRef d As Integer)
End Sub
Public Sub Bar()
Dim s As New A()
Goo(s.field)
End Sub
End Class", index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateFieldIsFirstWithLowerCase() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
[|field|] = 5
End Sub
End Module",
"Module Program
Private field As Integer
Sub Main(args As String())
field = 5
End Sub
End Module")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyIsFirstWithUpperCase() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
[|Field|] = 5
End Sub
End Module",
"Module Program
Public Property Field As Integer
Sub Main(args As String())
Field = 5
End Sub
End Module")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestNestedTypesAndInference() As Task
Await TestInRegularAndScriptAsync(
"Imports System.Collections.Generic
Class A
Sub Main()
Dim field As List(Of C) = B.[|C|]
End Sub
End Class
Class B
End Class
Class C
End Class",
"Imports System.Collections.Generic
Class A
Sub Main()
Dim field As List(Of C) = B.C
End Sub
End Class
Class B
Public Shared Property C As List(Of C)
End Class
Class C
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestTypeInferenceWithGenerics1() As Task
Await TestInRegularAndScriptAsync(
"Class A
Sub Main()
[|field|] = New C(Of B)
End Sub
End Class
Class B
End Class
Class C(Of T)
End Class",
"Class A
Private field As C(Of B)
Sub Main()
field = New C(Of B)
End Sub
End Class
Class B
End Class
Class C(Of T)
End Class")
End Function
<WorkItem(540693, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540693")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestErrorType() As Task
Await TestInRegularAndScriptAsync(
"Class A
Sub Main()
Dim field As List(Of C) = B.[|C|]
End Sub
End Class
Class B
End Class
Class C(Of B)
End Class",
"Class A
Sub Main()
Dim field As List(Of C) = B.C
End Sub
End Class
Class B
Public Shared Property C As List
End Class
Class C(Of B)
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestTypeParameter() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Class A
Sub Goo(Of T)
[|z|] = GetType(T)
End Sub
End Class",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Class A
Private z As Type
Sub Goo(Of T)
z = GetType(T)
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestInterfaceProperty() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Class A
Implements IGoo
Public Property X As Integer Implements [|IGoo.X|]
Sub Bar()
End Sub
End Class
Interface IGoo
End Interface",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Class A
Implements IGoo
Public Property X As Integer Implements IGoo.X
Sub Bar()
End Sub
End Class
Interface IGoo
Property X As Integer
End Interface")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateEscapedKeywords() As Task
Await TestInRegularAndScriptAsync(
"Class [Class]
Private Sub Method(i As Integer)
[|[Enum]|] = 5
End Sub
End Class",
"Class [Class]
Public Property [Enum] As Integer
Private Sub Method(i As Integer)
[Enum] = 5
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateEscapedKeywords2() As Task
Await TestInRegularAndScriptAsync(
"Class [Class]
Private Sub Method(i As Integer)
[|[Enum]|] = 5
End Sub
End Class",
"Class [Class]
Private [Enum] As Integer
Private Sub Method(i As Integer)
[Enum] = 5
End Sub
End Class",
index:=1)
End Function
<WorkItem(528229, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528229")>
<WpfFact(Skip:="528229"), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestRefLambda() As Task
Await TestInRegularAndScriptAsync(
"Class [Class]
Private Sub Method()
[|test|] = Function(ByRef x As Integer) InlineAssignHelper(x, 10)
End Sub
Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, value As T) As T
target = value
Return value
End Function
End Class",
"Class [Class]
Private test As Object
Private Sub Method()
test = Function(ByRef x As Integer) InlineAssignHelper(x, 10)
End Sub
Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, value As T) As T
target = value
Return value
End Function
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestPropertyParameters1() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Class A
Implements IGoo
Public Property Item1(i As Integer) As String Implements [|IGoo.Item1|]
Get
Throw New NotImplementedException()
End Get
Set(value As String)
Throw New NotImplementedException()
End Set
End Property
Sub Bar()
End Sub
End Class
Interface IGoo
' Default Property Item(i As Integer) As String
End Interface",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Class A
Implements IGoo
Public Property Item1(i As Integer) As String Implements IGoo.Item1
Get
Throw New NotImplementedException()
End Get
Set(value As String)
Throw New NotImplementedException()
End Set
End Property
Sub Bar()
End Sub
End Class
Interface IGoo
Property Item1(i As Integer) As String
' Default Property Item(i As Integer) As String
End Interface")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestPropertyParameters2() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Class A
Implements IGoo
Public Property Item1(i As Integer) As String Implements [|IGoo.Item1|]
Get
Throw New NotImplementedException()
End Get
Set(value As String)
Throw New NotImplementedException()
End Set
End Property
Sub Bar()
End Sub
End Class
Interface IGoo
' Default Property Item(i As Integer) As String
End Interface",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Class A
Implements IGoo
Public Property Item1(i As Integer) As String Implements IGoo.Item1
Get
Throw New NotImplementedException()
End Get
Set(value As String)
Throw New NotImplementedException()
End Set
End Property
Sub Bar()
End Sub
End Class
Interface IGoo
Property Item1(i As Integer) As String
' Default Property Item(i As Integer) As String
End Interface")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestDefaultProperty1() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Class A
Implements IGoo
Default Public Property Item(i As Integer) As String Implements [|IGoo.Item|]
Get
Throw New NotImplementedException()
End Get
Set(value As String)
Throw New NotImplementedException()
End Set
End Property
Sub Bar()
End Sub
End Class
Interface IGoo
' Default Property Item(i As Integer) As String
End Interface",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Class A
Implements IGoo
Default Public Property Item(i As Integer) As String Implements IGoo.Item
Get
Throw New NotImplementedException()
End Get
Set(value As String)
Throw New NotImplementedException()
End Set
End Property
Sub Bar()
End Sub
End Class
Interface IGoo
Default Property Item(i As Integer) As String
' Default Property Item(i As Integer) As String
End Interface")
End Function
<WorkItem(540703, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540703")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestDefaultProperty2() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Class A
Implements IGoo
Default Public Property Item(i As Integer) As String Implements [|IGoo.Item|]
Get
Throw New NotImplementedException()
End Get
Set(value As String)
Throw New NotImplementedException()
End Set
End Property
Sub Bar()
End Sub
End Class
Interface IGoo
' Default Property Item(i As Integer) As String
End Interface",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Class A
Implements IGoo
Default Public Property Item(i As Integer) As String Implements IGoo.Item
Get
Throw New NotImplementedException()
End Get
Set(value As String)
Throw New NotImplementedException()
End Set
End Property
Sub Bar()
End Sub
End Class
Interface IGoo
Default Property Item(i As Integer) As String
' Default Property Item(i As Integer) As String
End Interface")
End Function
<WorkItem(540737, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540737")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestErrorInGenericType() As Task
Await TestInRegularAndScriptAsync(
"Imports System.Collections.Generic
Class A
Sub Main()
Dim field As List(Of C) = B.[|C|]
End Sub
End Class
Class B
End Class
Class C(Of T)
End Class",
"Imports System.Collections.Generic
Class A
Sub Main()
Dim field As List(Of C) = B.C
End Sub
End Class
Class B
Public Shared Property C As List(Of C)
End Class
Class C(Of T)
End Class")
End Function
<WorkItem(542241, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542241")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestFieldWithAnonymousTypeType() As Threading.Tasks.Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
[|a|] = New With {.a = ., .b = 1}
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Private a As Object
Sub Main(args As String())
a = New With {.a = ., .b = 1}
End Sub
End Module")
End Function
<WorkItem(542395, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542395")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestUnqualifiedModuleMethod1() As Task
Await TestAsync(
"Imports System.Runtime.CompilerServices
Module StringExtensions
Public Sub Print(ByVal aString As String)
Console.WriteLine(aString)
End Sub
End Module
Module M
Sub Main()
Print([|s|])
End Sub
End Module",
"Imports System.Runtime.CompilerServices
Module StringExtensions
Public Sub Print(ByVal aString As String)
Console.WriteLine(aString)
End Sub
End Module
Module M
Private s As String
Sub Main()
Print(s)
End Sub
End Module",
parseOptions:=Nothing) ' TODO (tomat): Modules nested in Script class not supported yet
End Function
<WorkItem(542395, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542395")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestUnqualifiedModuleMethod2() As Task
Await TestAsync(
"Imports System.Runtime.CompilerServices
Module StringExtensions
<Extension()>
Public Sub Print(ByVal aString As String)
Console.WriteLine(aString)
End Sub
End Module
Module M
Sub Main()
Print([|s|])
End Sub
End Module",
"Imports System.Runtime.CompilerServices
Module StringExtensions
<Extension()>
Public Sub Print(ByVal aString As String)
Console.WriteLine(aString)
End Sub
End Module
Module M
Private s As String
Sub Main()
Print(s)
End Sub
End Module",
parseOptions:=Nothing) ' TODO (tomat): Modules nested in Script class not supported yet)
End Function
<WorkItem(542942, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542942")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestInsideLambda() As Task
Await TestInRegularAndScriptAsync(
"Module P
Sub M()
Dim t As System.Action = Sub()
[|P.Goo|] = 5
End Sub
End Sub
End Module",
"Module P
Public Property Goo As Integer
Sub M()
Dim t As System.Action = Sub()
P.Goo = 5
End Sub
End Sub
End Module")
End Function
<WorkItem(544632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544632")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestMissingOnForEachExpression() As Task
Await TestMissingInRegularAndScriptAsync(
<Text>
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Public Sub Linq103()
Dim categories As String() = {"Beverages", "Condiments", "Vegetables", "Dairy Products", "Seafood"}
Dim productList = GetProductList()
Dim categorizedProducts = From cat In categories
Group Join prod In productList On cat Equals prod.Category
Into Products = Group
Select Category = cat, Products
For Each v In categorizedProducts
Console.WriteLine(v.Category & ":")
For Each p In v.[|Products|]
Console.WriteLine(" " & p.ProductName)
Next
Next
End Sub
End Module
</Text>.Value)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestLeftOfBinaryExpression() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Main([|a|] + b)
End Sub
End Module",
"Module Program
Private a As Integer
Sub Main(args As String())
Main(a + b)
End Sub
End Module")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestRightOfBinaryExpression() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Main(a + [|b|])
End Sub
End Module",
"Module Program
Private b As Integer
Sub Main(args As String())
Main(a + b)
End Sub
End Module")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateLocal() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Goo([|bar|])
End Sub
End Module",
"Module Program
Private bar As Object
Sub Main(args As String())
Goo(bar)
End Sub
End Module")
End Function
<WorkItem(809542, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/809542")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateLocalBeforeComment() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Module Program
Sub Main
#If True
' Banner Line 1
' Banner Line 2
Integer.TryParse(""123"", [|local|])
#End If
End Sub
End Module",
"Imports System
Module Program
Sub Main
#If True
Dim local As Integer = Nothing
' Banner Line 1
' Banner Line 2
Integer.TryParse(""123"", local)
#End If
End Sub
End Module", index:=2)
End Function
<WorkItem(809542, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/809542")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateLocalAfterComment() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Module Program
Sub Main
#If True
' Banner Line 1
' Banner Line 2
Integer.TryParse(""123"", [|local|])
#End If
End Sub
End Module",
"Imports System
Module Program
Sub Main
#If True
' Banner Line 1
' Banner Line 2
Dim local As Integer = Nothing
Integer.TryParse(""123"", local)
#End If
End Sub
End Module", index:=2)
End Function
<WorkItem(545218, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545218")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestTypeForLocal() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
goo([|xyz|])
End Sub
Sub goo(x As Integer)
End Sub
End Module",
"Module Program
Sub Main(args As String())
Dim xyz As Integer = Nothing
goo(xyz)
End Sub
Sub goo(x As Integer)
End Sub
End Module",
index:=3)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestInSelect() As Task
Await TestInRegularAndScriptAsync(
"Imports System.Linq
Module Program
Sub Main(args As String())
Dim q = From a In args
Select [|v|]
End Sub
End Module",
"Imports System.Linq
Module Program
Private v As Object
Sub Main(args As String())
Dim q = From a In args
Select v
End Sub
End Module")
End Function
<WorkItem(545400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545400")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateLocalInIfPart() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main()
If ([|a|] Mod b <> 0) Then
End If
End Sub
End Module",
"Module Program
Sub Main()
Dim a As Object = Nothing
If (a Mod b <> 0) Then
End If
End Sub
End Module",
index:=3)
End Function
<WorkItem(545672, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545672")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestCrashOnAggregateSelect() As Task
Await TestMissingInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Dim q2 = From j In {1} Select j Aggregate i In {1}
Select [|i|] Into Count(), Sum(i) Select Count, Sum, j
End Sub
End Module")
End Function
<WorkItem(546753, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546753")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestAddressOf() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
[|d|] = AddressOf test
End Sub
Public Function test() As String
Return ""hello""
End Function
End Module",
"Imports System
Module Program
Private d As Func(Of String)
Sub Main(args As String())
d = AddressOf test
End Sub
Public Function test() As String
Return ""hello""
End Function
End Module")
End Function
<WorkItem(530756, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530756")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestMissingOnDictionaryAccess1() As Task
Await TestMissingInRegularAndScriptAsync(
"Imports System.Collections
Module Program
Sub Goo()
Dim x = New Hashtable![|Goo|]!Bar
End Sub
End Module")
End Function
<WorkItem(530756, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530756")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestMissingOnDictionaryAccess2() As Task
Await TestMissingInRegularAndScriptAsync(
"Imports System.Collections
Module Program
Sub Goo()
Dim x = New Hashtable!Goo![|Bar|]
End Sub
End Module")
End Function
<WorkItem(530756, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530756")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestMissingOnDictionaryAccess3() As Task
Await TestMissingInRegularAndScriptAsync(
"Imports System.Collections
Module Program
Sub Goo()
Dim x = New Hashtable![|Goo!Bar|]
End Sub
End Module")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestFormattingInGenerateVariable() As Task
Await TestInRegularAndScriptAsync(
<Text>Module Program
Sub Main()
If ([|a|] Mod b <> 0) Then
End If
End Sub
End Module</Text>.Value.Replace(vbLf, vbCrLf),
<Text>Module Program
Public Property a As Object
Sub Main()
If (a Mod b <> 0) Then
End If
End Sub
End Module</Text>.Value.Replace(vbLf, vbCrLf),
index:=2)
End Function
<WorkItem(666189, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/666189")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyInScript() As Task
Await TestAsync(
<Text>Dim x As Integer
x = [|Goo|]</Text>.Value.Replace(vbLf, vbCrLf),
<Text>Dim x As Integer
Public Property Goo As Integer
x = Goo</Text>.Value.Replace(vbLf, vbCrLf),
parseOptions:=New VisualBasicParseOptions(kind:=SourceCodeKind.Script))
End Function
<WorkItem(666189, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/666189")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateFieldInScript() As Task
Await TestAsync(
<Text>Dim x As Integer
x = [|Goo|]</Text>.Value.Replace(vbLf, vbCrLf),
<Text>Dim x As Integer
Private Goo As Integer
x = Goo</Text>.Value.Replace(vbLf, vbCrLf),
parseOptions:=New VisualBasicParseOptions(kind:=SourceCodeKind.Script),
index:=1)
End Function
<WorkItem(977580, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/977580")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestWithThrow() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class A
Public Sub B()
Throw [|MyExp|]
End Sub
End Class",
"Imports System
Public Class A
Private MyExp As Exception
Public Sub B()
Throw MyExp
End Sub
End Class", index:=1)
End Function
<WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestInsideNameOfProperty() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Sub M()
Dim x = NameOf([|Z|])
End Sub
End Class",
"Imports System
Class C
Public Property Z As Object
Sub M()
Dim x = NameOf(Z)
End Sub
End Class")
End Function
<WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestInsideNameOfField() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Sub M()
Dim x = NameOf([|Z|])
End Sub
End Class",
"Imports System
Class C
Private Z As Object
Sub M()
Dim x = NameOf(Z)
End Sub
End Class", index:=1)
End Function
<WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestInsideNameOfReadonlyField() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Sub M()
Dim x = NameOf([|Z|])
End Sub
End Class",
"Imports System
Class C
Private ReadOnly Z As Object
Sub M()
Dim x = NameOf(Z)
End Sub
End Class", index:=2)
End Function
<WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestInsideNameOfLocal() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Sub M()
Dim x = NameOf([|Z|])
End Sub
End Class",
"Imports System
Class C
Sub M()
Dim Z As Object = Nothing
Dim x = NameOf(Z)
End Sub
End Class", index:=3)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessProperty() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As C = a?[|.B|]
End Sub
End Class",
"Public Class C
Public Property B As C
Sub Main(a As C)
Dim x As C = a?.B
End Sub
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessProperty2() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x = a?[|.B|]
End Sub
End Class",
"Public Class C
Public Property B As Object
Sub Main(a As C)
Dim x = a?.B
End Sub
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessProperty3() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As Integer? = a?[|.B|]
End Sub
End Class",
"Public Class C
Public Property B As Integer
Sub Main(a As C)
Dim x As Integer? = a?.B
End Sub
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessProperty4() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As C? = a?[|.B|]
End Sub
End Class",
"Public Class C
Public Property B As C
Sub Main(a As C)
Dim x As C? = a?.B
End Sub
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessField() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As C = a?[|.B|]
End Sub
End Class",
"Public Class C
Private B As C
Sub Main(a As C)
Dim x As C = a?.B
End Sub
End Class",
index:=1)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessField2() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x = a?[|.B|]
End Sub
End Class",
"Public Class C
Private B As Object
Sub Main(a As C)
Dim x = a?.B
End Sub
End Class",
index:=1)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessField3() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As Integer? = a?[|.B|]
End Sub
End Class",
"Public Class C
Private B As Integer
Sub Main(a As C)
Dim x As Integer? = a?.B
End Sub
End Class",
index:=1)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessField4() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As C? = a?[|.B|]
End Sub
End Class",
"Public Class C
Private B As C
Sub Main(a As C)
Dim x As C? = a?.B
End Sub
End Class",
index:=1)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessReadOnlyField() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As C = a?[|.B|]
End Sub
End Class",
"Public Class C
Private ReadOnly B As C
Sub Main(a As C)
Dim x As C = a?.B
End Sub
End Class",
index:=2)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessReadOnlyField2() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x = a?[|.B|]
End Sub
End Class",
"Public Class C
Private ReadOnly B As Object
Sub Main(a As C)
Dim x = a?.B
End Sub
End Class",
index:=2)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessReadOnlyField3() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As Integer? = a?[|.B|]
End Sub
End Class",
"Public Class C
Private ReadOnly B As Integer
Sub Main(a As C)
Dim x As Integer? = a?.B
End Sub
End Class",
index:=2)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessReadOnlyField4() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As C? = a?[|.B|]
End Sub
End Class",
"Public Class C
Private ReadOnly B As C
Sub Main(a As C)
Dim x As C? = a?.B
End Sub
End Class",
index:=2)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessPropertyInsideReferencedClass() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x As C = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As C = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Public Property Z As C
End Class
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessPropertyInsideReferencedClass2() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Public Property Z As Integer
End Class
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessPropertyInsideReferencedClass3() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer? = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer? = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Public Property Z As Integer
End Class
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessPropertyInsideReferencedClass4() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Public Property Z As Object
End Class
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessFieldInsideReferencedClass() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x As C = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As C = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Friend Z As C
End Class
End Class",
index:=1)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessFieldInsideReferencedClass2() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Friend Z As Integer
End Class
End Class",
index:=1)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessFieldInsideReferencedClass3() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer? = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer? = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Friend Z As Integer
End Class
End Class",
index:=1)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessFieldInsideReferencedClass4() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Friend Z As Object
End Class
End Class",
index:=1)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessReadOnlyFieldInsideReferencedClass() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x As C = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As C = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Friend ReadOnly Z As C
End Class
End Class",
index:=2)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessReadOnlyFieldInsideReferencedClass2() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Friend ReadOnly Z As Integer
End Class
End Class",
index:=2)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessReadOnlyFieldInsideReferencedClass3() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer? = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer? = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Friend ReadOnly Z As Integer
End Class
End Class",
index:=2)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessReadOnlyFieldInsideReferencedClass4() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Friend ReadOnly Z As Object
End Class
End Class",
index:=2)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyInPropertyInitializer() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Property a As Integer = [|y|]
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Private y As Integer
Property a As Integer = y
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateFieldInPropertyInitializer() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Property a As Integer = [|y|]
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Private ReadOnly y As Integer
Property a As Integer = y
End Module",
index:=1)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateReadonlyFieldInPropertyInitializer() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Property a As Integer = [|y|]
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Property a As Integer = y
Public Property y As Integer
End Module",
index:=2)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyInObjectInitializer1() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Dim x As New Customer With {.[|Name|] = ""blah""}
End Sub
End Module
Friend Class Customer
End Class",
"Module Program
Sub Main(args As String())
Dim x As New Customer With {.Name = ""blah""}
End Sub
End Module
Friend Class Customer
Public Property Name As String
End Class")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyInObjectInitializer2() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Dim x As New Customer With {.Name = ""blah"", .[|Age|] = blah}
End Sub
End Module
Friend Class Customer
Public Property Name As String
End Class",
"Module Program
Sub Main(args As String())
Dim x As New Customer With {.Name = ""blah"", .Age = blah}
End Sub
End Module
Friend Class Customer
Public Property Name As String
Public Property Age As Object
End Class")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyInObjectInitializer3() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Dim x As New Customer With {.Name = [|name|]}
End Sub
End Module
Friend Class Customer
End Class",
"Module Program
Public Property name As Object
Sub Main(args As String())
Dim x As New Customer With {.Name = name}
End Sub
End Module
Friend Class Customer
End Class",
index:=2)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateFieldInObjectInitializer1() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Dim x As New Customer With {.[|Name|] = ""blah""}
End Sub
End Module
Friend Class Customer
End Class",
"Module Program
Sub Main(args As String())
Dim x As New Customer With {.Name = ""blah""}
End Sub
End Module
Friend Class Customer
Friend Name As String
End Class",
index:=1)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateFieldInObjectInitializer2() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Dim x As New Customer With {.[|Name|] = name}
End Sub
End Module
Friend Class Customer
End Class",
"Module Program
Sub Main(args As String())
Dim x As New Customer With {.Name = name}
End Sub
End Module
Friend Class Customer
Friend Name As Object
End Class",
index:=1)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateFieldInObjectInitializer3() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Dim x As New Customer With {.Name = [|name|]}
End Sub
End Module
Friend Class Customer
End Class",
"Module Program
Private name As Object
Sub Main(args As String())
Dim x As New Customer With {.Name = name}
End Sub
End Module
Friend Class Customer
End Class")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestInvalidObjectInitializer() As Task
Await TestMissingInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Dim x As New Customer With { [|Name|] = ""blkah""}
End Sub
End Module
Friend Class Customer
End Class")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestOnlyPropertyAndFieldOfferedForObjectInitializer() As Task
Await TestActionCountAsync(
"Module Program
Sub Main(args As String())
Dim x As New Customer With {.[|Name|] = ""blah""}
End Sub
End Module
Friend Class Customer
End Class",
2)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateLocalInObjectInitializerValue() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Dim x As New Customer With {.Name = [|blah|]}
End Sub
End Module
Friend Class Customer
End Class",
"Module Program
Sub Main(args As String())
Dim blah As Object = Nothing
Dim x As New Customer With {.Name = blah}
End Sub
End Module
Friend Class Customer
End Class",
index:=3)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyInTypeOf() As Task
Await TestInRegularAndScriptAsync(
"Module C
Sub Test()
If TypeOf [|B|] Is String Then
End If
End Sub
End Module",
"Module C
Public Property B As String
Sub Test()
If TypeOf B Is String Then
End If
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateFieldInTypeOf() As Task
Await TestInRegularAndScriptAsync(
"Module C
Sub Test()
If TypeOf [|B|] Is String Then
End If
End Sub
End Module",
"Module C
Private B As String
Sub Test()
If TypeOf B Is String Then
End If
End Sub
End Module",
index:=1)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateReadOnlyFieldInTypeOf() As Task
Await TestInRegularAndScriptAsync(
"Module C
Sub Test()
If TypeOf [|B|] Is String Then
End If
End Sub
End Module",
"Module C
Private ReadOnly B As String
Sub Test()
If TypeOf B Is String Then
End If
End Sub
End Module",
index:=2)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateLocalInTypeOf() As Task
Await TestInRegularAndScriptAsync(
"Module C
Sub Test()
If TypeOf [|B|] Is String Then
End If
End Sub
End Module",
"Module C
Sub Test()
Dim B As String = Nothing
If TypeOf B Is String Then
End If
End Sub
End Module",
index:=3)
End Function
<WorkItem(1130960, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1130960")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGeneratePropertyInTypeOfIsNot() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub M()
If TypeOf [|Prop|] IsNot TypeOfIsNotDerived Then
End If
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Public Property Prop As TypeOfIsNotDerived
Sub M()
If TypeOf Prop IsNot TypeOfIsNotDerived Then
End If
End Sub
End Module")
End Function
<WorkItem(1130960, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1130960")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateFieldInTypeOfIsNot() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub M()
If TypeOf [|Prop|] IsNot TypeOfIsNotDerived Then
End If
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Private Prop As TypeOfIsNotDerived
Sub M()
If TypeOf Prop IsNot TypeOfIsNotDerived Then
End If
End Sub
End Module",
index:=1)
End Function
<WorkItem(1130960, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1130960")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateReadOnlyFieldInTypeOfIsNot() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub M()
If TypeOf [|Prop|] IsNot TypeOfIsNotDerived Then
End If
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Private ReadOnly Prop As TypeOfIsNotDerived
Sub M()
If TypeOf Prop IsNot TypeOfIsNotDerived Then
End If
End Sub
End Module",
index:=2)
End Function
<WorkItem(1130960, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1130960")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateLocalInTypeOfIsNot() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub M()
If TypeOf [|Prop|] IsNot TypeOfIsNotDerived Then
End If
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub M()
Dim Prop As TypeOfIsNotDerived = Nothing
If TypeOf Prop IsNot TypeOfIsNotDerived Then
End If
End Sub
End Module",
index:=3)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateVariableFromLambda() As Task
Await TestInRegularAndScriptAsync(
"Class [Class]
Private Sub Method(i As Integer)
[|goo|] = Function()
Return 2
End Function
End Sub
End Class",
"Imports System
Class [Class]
Private goo As Func(Of Integer)
Private Sub Method(i As Integer)
goo = Function()
Return 2
End Function
End Sub
End Class")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateVariableFromLambda2() As Task
Await TestInRegularAndScriptAsync(
"Class [Class]
Private Sub Method(i As Integer)
[|goo|] = Function()
Return 2
End Function
End Sub
End Class",
"Imports System
Class [Class]
Public Property goo As Func(Of Integer)
Private Sub Method(i As Integer)
goo = Function()
Return 2
End Function
End Sub
End Class",
index:=1)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateVariableFromLambda3() As Task
Await TestInRegularAndScriptAsync(
"Class [Class]
Private Sub Method(i As Integer)
[|goo|] = Function()
Return 2
End Function
End Sub
End Class",
"Class [Class]
Private Sub Method(i As Integer)
Dim goo As System.Func(Of Integer)
goo = Function()
Return 2
End Function
End Sub
End Class",
index:=2)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TupleRead() As Task
Await TestInRegularAndScriptAsync(
"Class [Class]
Private Sub Method(i As (Integer, String))
Method([|tuple|])
End Sub
End Class",
"Class [Class]
Private tuple As (Integer, String)
Private Sub Method(i As (Integer, String))
Method(tuple)
End Sub
End Class")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TupleWithOneNameRead() As Task
Await TestInRegularAndScriptAsync(
"Class [Class]
Private Sub Method(i As (a As Integer, String))
Method([|tuple|])
End Sub
End Class",
"Class [Class]
Private tuple As (a As Integer, String)
Private Sub Method(i As (a As Integer, String))
Method(tuple)
End Sub
End Class")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TupleWrite() As Task
Await TestInRegularAndScriptAsync(
"Class [Class]
Private Sub Method()
[|tuple|] = (1, ""hello"")
End Sub
End Class",
"Class [Class]
Private tuple As (Integer, String)
Private Sub Method()
tuple = (1, ""hello"")
End Sub
End Class")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TupleWithOneNameWrite() As Task
Await TestInRegularAndScriptAsync(
"Class [Class]
Private Sub Method()
[|tuple|] = (a:=1, ""hello"")
End Sub
End Class",
"Class [Class]
Private tuple As (a As Integer, String)
Private Sub Method()
tuple = (a:=1, ""hello"")
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestPreferReadOnlyIfAfterReadOnlyAssignment() As Task
Await TestInRegularAndScriptAsync(
"class C
private readonly _goo as integer
public sub new()
_goo = 0
[|_bar|] = 1
end sub
end class",
"class C
private readonly _goo as integer
Private ReadOnly _bar As Integer
public sub new()
_goo = 0
_bar = 1
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestPreferReadOnlyIfBeforeReadOnlyAssignment() As Task
Await TestInRegularAndScriptAsync(
"class C
private readonly _goo as integer
public sub new()
[|_bar|] = 1
_goo = 0
end sub
end class",
"class C
Private ReadOnly _bar As Integer
private readonly _goo as integer
public sub new()
_bar = 1
_goo = 0
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestPlaceFieldBasedOnSurroundingStatements() As Task
Await TestInRegularAndScriptAsync(
"class Class
private _goo as integer
private _quux as integer
public sub new()
_goo = 0
[|_bar|] = 1
_quux = 2
end sub
end class",
"class Class
private _goo as integer
Private _bar As Integer
private _quux as integer
public sub new()
_goo = 0
_bar = 1
_quux = 2
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestPlacePropertyBasedOnSurroundingStatements() As Task
Await TestInRegularAndScriptAsync(
"class Class
public readonly property Goo as integer
public readonly property Quux as integer
public sub new()
Goo = 0
[|Bar|] = 1
Quux = 2
end sub
end class",
"class Class
public readonly property Goo as integer
Public ReadOnly Property Bar As Integer
public readonly property Quux as integer
public sub new()
Goo = 0
Bar = 1
Quux = 2
end sub
end class")
End Function
<WorkItem(18988, "https://github.com/dotnet/roslyn/issues/18988")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function GroupNonReadonlyFieldsTogether() As Task
Await TestInRegularAndScriptAsync(
"
class C
public isDisposed as boolean
public readonly x as integer
public readonly m as integer
public sub new()
me.[|y|] = 0
end sub
end class",
"
class C
public isDisposed as boolean
Private y As Integer
public readonly x as integer
public readonly m as integer
public sub new()
me.y = 0
end sub
end class")
End Function
<WorkItem(18988, "https://github.com/dotnet/roslyn/issues/18988")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function GroupReadonlyFieldsTogether() As Task
Await TestInRegularAndScriptAsync("
class C
public readonly x as integer
public readonly m as integer
public isDisposed as boolean
public sub new()
me.[|y|] = 0
end sub
end class",
"
class C
public readonly x as integer
public readonly m as integer
Private ReadOnly y As Integer
public isDisposed as boolean
public sub new()
me.y = 0
end sub
end class", index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateSimplePropertyInSyncLock() As Threading.Tasks.Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
SyncLock [|Bar|]
End SyncLock
End Sub
End Module",
"Module Program
Public Property Bar As Object
Sub Main(args As String())
SyncLock Bar
End SyncLock
End Sub
End Module")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateSimpleFieldInSyncLock() As Threading.Tasks.Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
SyncLock [|Bar|]
End SyncLock
End Sub
End Module",
"Module Program
Private Bar As Object
Sub Main(args As String())
SyncLock Bar
End SyncLock
End Sub
End Module",
index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateReadOnlyFieldInSyncLock() As Threading.Tasks.Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
SyncLock [|Bar|]
End SyncLock
End Sub
End Module",
"Module Program
Private ReadOnly Bar As Object
Sub Main(args As String())
SyncLock Bar
End SyncLock
End Sub
End Module",
index:=2)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestAddParameter() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Goo([|bar|])
End Sub
End Module",
"Module Program
Sub Main(args As String(), bar As Object)
Goo(bar)
End Sub
End Module",
index:=4)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestAddParameterDoesntAddToOverride() As Task
Await TestInRegularAndScriptAsync(
"Class Base
Public Overridable Sub Method(args As String())
End Sub
End Class
Class Program
Public Overrides Sub Main(args As String())
Goo([|bar|])
End Sub
End Class",
"Class Base
Public Overridable Sub Method(args As String())
End Sub
End Class
Class Program
Public Overrides Sub Main(args As String(), bar As Object)
Goo(bar)
End Sub
End Class",
index:=4)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestAddParameterAndOverridesAddsToOverrides() As Task
Await TestInRegularAndScriptAsync(
"Class Base
Public Overridable Sub Method(args As String())
End Sub
End Class
Class Program
Inherits Base
Public Overrides Sub Method(args As String())
Goo([|bar|])
End Sub
End Class",
"Class Base
Public Overridable Sub Method(args As String(), bar As Object)
End Sub
End Class
Class Program
Inherits Base
Public Overrides Sub Method(args As String(), bar As Object)
Goo(bar)
End Sub
End Class",
index:=5)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestAddParameterIsOfCorrectType() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Goo([|bar|])
End Sub
Sub Goo(arg As Integer)
End Sub
End Module",
"Module Program
Sub Main(args As String(), bar As Integer)
Goo(bar)
End Sub
Sub Goo(arg As Integer)
End Sub
End Module",
index:=4)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestAddParameterAndOverridesIsOfCorrectType() As Task
Await TestInRegularAndScriptAsync(
"Class Base
Public Overridable Sub Method(args As String())
End Sub
End Class
Class Program
Inherits Base
Public Overrides Sub Method(args As String())
Goo([|bar|])
End Sub
Sub Goo(arg As Integer)
End Sub
End Class",
"Class Base
Public Overridable Sub Method(args As String(), bar As Integer)
End Sub
End Class
Class Program
Inherits Base
Public Overrides Sub Method(args As String(), bar As Integer)
Goo(bar)
End Sub
Sub Goo(arg As Integer)
End Sub
End Class",
index:=5)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestAddParameterAndOverridesNotOfferedToNonOverride1() As Task
Await TestActionCountAsync(
"Module Program
Sub Main(args As String())
Goo([|bar|])
End Sub
End Module",
count:=5)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestAddParameterAndOverridesNotOfferedToNonOverride2() As Task
Await TestActionCountAsync(
"Class Base
Public Overridable Sub Method(args As String())
End Sub
End Class
Class Program
Inherits Base
Public Sub Method(args As String())
Goo([|bar|])
End Sub
Sub Goo(arg As Integer)
End Sub
End Class",
count:=5)
End Function
<WorkItem(45367, "https://github.com/dotnet/roslyn/issues/45367")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestCrashInNamespace() As Task
Await TestMissingInRegularAndScriptAsync(
"Namespace ConsoleApp5
Friend Sub New(errNum As Integer, offset As Integer, message As String)
MyBase.New(message)
Me.[|Error|] = errNum
End Sub
End Namespace")
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.CodeFixes
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.VisualBasic.GenerateVariable
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.GenerateVariable
Public Class GenerateVariableTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider)
Return (Nothing, New VisualBasicGenerateVariableCodeFixProvider())
End Function
Protected Overrides Function MassageActions(actions As ImmutableArray(Of CodeAction)) As ImmutableArray(Of CodeAction)
Return FlattenActions(actions)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateSimpleProperty() As Threading.Tasks.Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Goo([|Bar|])
End Sub
End Module",
"Module Program
Public Property Bar As Object
Sub Main(args As String())
Goo(Bar)
End Sub
End Module")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateSimpleField() As Threading.Tasks.Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Goo([|Bar|])
End Sub
End Module",
"Module Program
Private Bar As Object
Sub Main(args As String())
Goo(Bar)
End Sub
End Module",
index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateReadOnlyField() As Threading.Tasks.Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Goo([|Bar|])
End Sub
End Module",
"Module Program
Private ReadOnly Bar As Object
Sub Main(args As String())
Goo(Bar)
End Sub
End Module",
index:=2)
End Function
<WorkItem(539692, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539692")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateFromAssignment() As Threading.Tasks.Task
Await TestInRegularAndScriptAsync(
"Class C
Shared Sub M
[|Goo|] = 3
End Sub
End Class",
"Class C
Private Shared Goo As Integer
Shared Sub M
Goo = 3
End Sub
End Class",
index:=1)
End Function
<WorkItem(539694, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539694")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateReadOnlyProperty() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Dim i As IGoo
Main(i.[|Blah|])
End Sub
End Module
Interface IGoo
End Interface",
"Module Program
Sub Main(args As String())
Dim i As IGoo
Main(i.Blah)
End Sub
End Module
Interface IGoo
ReadOnly Property Blah As String()
End Interface")
End Function
<WorkItem(539694, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539694")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateReadWriteProperty() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Dim i As IGoo
Main(i.[|Blah|])
End Sub
End Module
Interface IGoo
End Interface",
"Module Program
Sub Main(args As String())
Dim i As IGoo
Main(i.Blah)
End Sub
End Module
Interface IGoo
Property Blah As String()
End Interface",
index:=1)
End Function
<WorkItem(539695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539695")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateProtectedSharedFieldIntoBase() As Threading.Tasks.Task
Await TestInRegularAndScriptAsync(
"Class Base
End Class
Class Derived
Inherits Base
Shared Sub Main
Dim a = Base.[|Goo|]
End Sub
End Class",
"Class Base
Protected Shared Goo As Object
End Class
Class Derived
Inherits Base
Shared Sub Main
Dim a = Base.Goo
End Sub
End Class",
index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestNotOfferedForSharedAccessOffInterface() As Task
Await TestMissingInRegularAndScriptAsync(
"Interface IGoo
End Interface
Class Program
Sub Main
IGoo.[|Bar|] = 3
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateFriendAccessibilityForField() As Threading.Tasks.Task
Await TestInRegularAndScriptAsync(
"Class A
End Class
Class B
Sub Main
Dim x = A.[|Goo|]
End Sub
End Class",
"Class A
Friend Shared Goo As Object
End Class
Class B
Sub Main
Dim x = A.Goo
End Sub
End Class",
index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyOnInterface1() As Threading.Tasks.Task
Await TestInRegularAndScriptAsync(
"Interface IGoo
End Interface
Class C
Sub Main
Dim goo As IGoo
Dim b = goo.[|Bar|]
End Sub
End Class",
"Interface IGoo
ReadOnly Property Bar As Object
End Interface
Class C
Sub Main
Dim goo As IGoo
Dim b = goo.Bar
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyOnInterface2() As Threading.Tasks.Task
Await TestInRegularAndScriptAsync(
"Interface IGoo
End Interface
Class C
Sub Main
Dim goo As IGoo
Dim b = goo.[|Bar|]
End Sub
End Class",
"Interface IGoo
Property Bar As Object
End Interface
Class C
Sub Main
Dim goo As IGoo
Dim b = goo.Bar
End Sub
End Class", index:=1)
End Function
<WorkItem(539796, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539796")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyIntoModule() As Threading.Tasks.Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
End Sub
End Module
Class C
Sub M()
Program.[|P|] = 10
End Sub
End Class",
"Module Program
Public Property P As Integer
Sub Main(args As String())
End Sub
End Module
Class C
Sub M()
Program.P = 10
End Sub
End Class")
End Function
<WorkItem(539796, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539796")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestFieldPropertyIntoModule() As Threading.Tasks.Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
End Sub
End Module
Class C
Sub M()
[|Program.P|] = 10
End Sub
End Class",
"Module Program
Friend P As Integer
Sub Main(args As String())
End Sub
End Module
Class C
Sub M()
Program.P = 10
End Sub
End Class",
index:=1)
End Function
<WorkItem(539848, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539848")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestOnLeftOfMemberAccess() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
[|HERE|].ToString()
End Sub
End Module",
"Module Program
Private HERE As Object
Sub Main(args As String())
HERE.ToString()
End Sub
End Module",
index:=1)
End Function
<WorkItem(539725, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539725")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestMissingWhenInterfacePropertyAlreadyExists() As Task
Await TestMissingInRegularAndScriptAsync(
"Interface IGoo
Property Blah As String()
End Interface
Module Program
Sub Main(args As String())
Dim goo As IGoo
Main(goo.[|Blah|])
End Sub
End Module")
End Function
<WorkItem(540013, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540013")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestMissingInAddressOf() As Task
Await TestMissingInRegularAndScriptAsync(
"Delegate Sub D(x As Integer)
Class C
Public Sub Goo()
Dim x As D = New D(AddressOf [|Method|])
End Sub
End Class")
End Function
<WorkItem(540578, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540578")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestInferProperReturnType() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Function Fun() As Integer
Return [|P|]
End Function
End Module",
"Module Program
Public Property P As Integer
Function Fun() As Integer
Return P
End Function
End Module")
End Function
<WorkItem(540576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540576")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestAssignment() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Dim x As Integer
x = [|P|]
End Sub
End Module",
"Module Program
Public Property P As Integer
Sub Main(args As String())
Dim x As Integer
x = P
End Sub
End Module")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateFromSharedMethod() As Task
Await TestInRegularAndScriptAsync(
"Class GenPropTest
Public Shared Sub Main()
[|genStaticUnqualified|] = """"
End Sub
End Class",
"Class GenPropTest
Private Shared genStaticUnqualified As String
Public Shared Sub Main()
genStaticUnqualified = """"
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateSharedField() As Task
Await TestInRegularAndScriptAsync(
"Class GenPropTest
Public Sub Main()
GenPropTest.[|genStaticUnqualified|] = """"
End Sub
End Class",
"Class GenPropTest
Private Shared genStaticUnqualified As String
Public Sub Main()
GenPropTest.genStaticUnqualified = """"
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateInstanceFieldOffMe() As Task
Await TestInRegularAndScriptAsync(
"Class GenPropTest
Public Sub Main()
Me.[|field|] = """"
End Sub
End Class",
"Class GenPropTest
Private field As String
Public Sub Main()
Me.field = """"
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestSimpleInstanceField() As Task
Await TestInRegularAndScriptAsync(
"Class GenPropTest
Public Sub Main()
[|field|] = """"
End Sub
End Class",
"Class GenPropTest
Private field As String
Public Sub Main()
field = """"
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestFieldOnByRefParam() As Task
Await TestInRegularAndScriptAsync(
"Class A
End Class
Class B
Public Sub Goo(ByRef d As Integer)
End Sub
Public Sub Bar()
Dim s As New A()
Goo(s.[|field|])
End Sub
End Class",
"Class A
Friend field As Integer
End Class
Class B
Public Sub Goo(ByRef d As Integer)
End Sub
Public Sub Bar()
Dim s As New A()
Goo(s.field)
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateFieldInByRefProperty() As Task
Await TestInRegularAndScriptAsync(
"Class A
End Class
Class B
Public Sub Goo(ByRef d As Integer)
End Sub
Public Sub Bar()
Dim s As New A()
Goo(s.[|field|])
End Sub
End Class",
"Class A
Friend field As Integer
End Class
Class B
Public Sub Goo(ByRef d As Integer)
End Sub
Public Sub Bar()
Dim s As New A()
Goo(s.field)
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyInByRefProperty() As Task
Await TestInRegularAndScriptAsync(
"
Imports System
Class A
End Class
Class B
Public Sub Goo(ByRef d As Integer)
End Sub
Public Sub Bar()
Dim s As New A()
Goo(s.[|field|])
End Sub
End Class",
"
Imports System
Class A
Public ReadOnly Property field As Integer
Get
Throw New NotImplementedException()
End Get
End Property
End Class
Class B
Public Sub Goo(ByRef d As Integer)
End Sub
Public Sub Bar()
Dim s As New A()
Goo(s.field)
End Sub
End Class", index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateFieldIsFirstWithLowerCase() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
[|field|] = 5
End Sub
End Module",
"Module Program
Private field As Integer
Sub Main(args As String())
field = 5
End Sub
End Module")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyIsFirstWithUpperCase() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
[|Field|] = 5
End Sub
End Module",
"Module Program
Public Property Field As Integer
Sub Main(args As String())
Field = 5
End Sub
End Module")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestNestedTypesAndInference() As Task
Await TestInRegularAndScriptAsync(
"Imports System.Collections.Generic
Class A
Sub Main()
Dim field As List(Of C) = B.[|C|]
End Sub
End Class
Class B
End Class
Class C
End Class",
"Imports System.Collections.Generic
Class A
Sub Main()
Dim field As List(Of C) = B.C
End Sub
End Class
Class B
Public Shared Property C As List(Of C)
End Class
Class C
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestTypeInferenceWithGenerics1() As Task
Await TestInRegularAndScriptAsync(
"Class A
Sub Main()
[|field|] = New C(Of B)
End Sub
End Class
Class B
End Class
Class C(Of T)
End Class",
"Class A
Private field As C(Of B)
Sub Main()
field = New C(Of B)
End Sub
End Class
Class B
End Class
Class C(Of T)
End Class")
End Function
<WorkItem(540693, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540693")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestErrorType() As Task
Await TestInRegularAndScriptAsync(
"Class A
Sub Main()
Dim field As List(Of C) = B.[|C|]
End Sub
End Class
Class B
End Class
Class C(Of B)
End Class",
"Class A
Sub Main()
Dim field As List(Of C) = B.C
End Sub
End Class
Class B
Public Shared Property C As List
End Class
Class C(Of B)
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestTypeParameter() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Class A
Sub Goo(Of T)
[|z|] = GetType(T)
End Sub
End Class",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Class A
Private z As Type
Sub Goo(Of T)
z = GetType(T)
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestInterfaceProperty() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Class A
Implements IGoo
Public Property X As Integer Implements [|IGoo.X|]
Sub Bar()
End Sub
End Class
Interface IGoo
End Interface",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Class A
Implements IGoo
Public Property X As Integer Implements IGoo.X
Sub Bar()
End Sub
End Class
Interface IGoo
Property X As Integer
End Interface")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateEscapedKeywords() As Task
Await TestInRegularAndScriptAsync(
"Class [Class]
Private Sub Method(i As Integer)
[|[Enum]|] = 5
End Sub
End Class",
"Class [Class]
Public Property [Enum] As Integer
Private Sub Method(i As Integer)
[Enum] = 5
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateEscapedKeywords2() As Task
Await TestInRegularAndScriptAsync(
"Class [Class]
Private Sub Method(i As Integer)
[|[Enum]|] = 5
End Sub
End Class",
"Class [Class]
Private [Enum] As Integer
Private Sub Method(i As Integer)
[Enum] = 5
End Sub
End Class",
index:=1)
End Function
<WorkItem(528229, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528229")>
<WpfFact(Skip:="528229"), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestRefLambda() As Task
Await TestInRegularAndScriptAsync(
"Class [Class]
Private Sub Method()
[|test|] = Function(ByRef x As Integer) InlineAssignHelper(x, 10)
End Sub
Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, value As T) As T
target = value
Return value
End Function
End Class",
"Class [Class]
Private test As Object
Private Sub Method()
test = Function(ByRef x As Integer) InlineAssignHelper(x, 10)
End Sub
Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, value As T) As T
target = value
Return value
End Function
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestPropertyParameters1() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Class A
Implements IGoo
Public Property Item1(i As Integer) As String Implements [|IGoo.Item1|]
Get
Throw New NotImplementedException()
End Get
Set(value As String)
Throw New NotImplementedException()
End Set
End Property
Sub Bar()
End Sub
End Class
Interface IGoo
' Default Property Item(i As Integer) As String
End Interface",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Class A
Implements IGoo
Public Property Item1(i As Integer) As String Implements IGoo.Item1
Get
Throw New NotImplementedException()
End Get
Set(value As String)
Throw New NotImplementedException()
End Set
End Property
Sub Bar()
End Sub
End Class
Interface IGoo
Property Item1(i As Integer) As String
' Default Property Item(i As Integer) As String
End Interface")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestPropertyParameters2() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Class A
Implements IGoo
Public Property Item1(i As Integer) As String Implements [|IGoo.Item1|]
Get
Throw New NotImplementedException()
End Get
Set(value As String)
Throw New NotImplementedException()
End Set
End Property
Sub Bar()
End Sub
End Class
Interface IGoo
' Default Property Item(i As Integer) As String
End Interface",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Class A
Implements IGoo
Public Property Item1(i As Integer) As String Implements IGoo.Item1
Get
Throw New NotImplementedException()
End Get
Set(value As String)
Throw New NotImplementedException()
End Set
End Property
Sub Bar()
End Sub
End Class
Interface IGoo
Property Item1(i As Integer) As String
' Default Property Item(i As Integer) As String
End Interface")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestDefaultProperty1() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Class A
Implements IGoo
Default Public Property Item(i As Integer) As String Implements [|IGoo.Item|]
Get
Throw New NotImplementedException()
End Get
Set(value As String)
Throw New NotImplementedException()
End Set
End Property
Sub Bar()
End Sub
End Class
Interface IGoo
' Default Property Item(i As Integer) As String
End Interface",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Class A
Implements IGoo
Default Public Property Item(i As Integer) As String Implements IGoo.Item
Get
Throw New NotImplementedException()
End Get
Set(value As String)
Throw New NotImplementedException()
End Set
End Property
Sub Bar()
End Sub
End Class
Interface IGoo
Default Property Item(i As Integer) As String
' Default Property Item(i As Integer) As String
End Interface")
End Function
<WorkItem(540703, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540703")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestDefaultProperty2() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Class A
Implements IGoo
Default Public Property Item(i As Integer) As String Implements [|IGoo.Item|]
Get
Throw New NotImplementedException()
End Get
Set(value As String)
Throw New NotImplementedException()
End Set
End Property
Sub Bar()
End Sub
End Class
Interface IGoo
' Default Property Item(i As Integer) As String
End Interface",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Class A
Implements IGoo
Default Public Property Item(i As Integer) As String Implements IGoo.Item
Get
Throw New NotImplementedException()
End Get
Set(value As String)
Throw New NotImplementedException()
End Set
End Property
Sub Bar()
End Sub
End Class
Interface IGoo
Default Property Item(i As Integer) As String
' Default Property Item(i As Integer) As String
End Interface")
End Function
<WorkItem(540737, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540737")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestErrorInGenericType() As Task
Await TestInRegularAndScriptAsync(
"Imports System.Collections.Generic
Class A
Sub Main()
Dim field As List(Of C) = B.[|C|]
End Sub
End Class
Class B
End Class
Class C(Of T)
End Class",
"Imports System.Collections.Generic
Class A
Sub Main()
Dim field As List(Of C) = B.C
End Sub
End Class
Class B
Public Shared Property C As List(Of C)
End Class
Class C(Of T)
End Class")
End Function
<WorkItem(542241, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542241")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestFieldWithAnonymousTypeType() As Threading.Tasks.Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
[|a|] = New With {.a = ., .b = 1}
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Private a As Object
Sub Main(args As String())
a = New With {.a = ., .b = 1}
End Sub
End Module")
End Function
<WorkItem(542395, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542395")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestUnqualifiedModuleMethod1() As Task
Await TestAsync(
"Imports System.Runtime.CompilerServices
Module StringExtensions
Public Sub Print(ByVal aString As String)
Console.WriteLine(aString)
End Sub
End Module
Module M
Sub Main()
Print([|s|])
End Sub
End Module",
"Imports System.Runtime.CompilerServices
Module StringExtensions
Public Sub Print(ByVal aString As String)
Console.WriteLine(aString)
End Sub
End Module
Module M
Private s As String
Sub Main()
Print(s)
End Sub
End Module",
parseOptions:=Nothing) ' TODO (tomat): Modules nested in Script class not supported yet
End Function
<WorkItem(542395, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542395")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestUnqualifiedModuleMethod2() As Task
Await TestAsync(
"Imports System.Runtime.CompilerServices
Module StringExtensions
<Extension()>
Public Sub Print(ByVal aString As String)
Console.WriteLine(aString)
End Sub
End Module
Module M
Sub Main()
Print([|s|])
End Sub
End Module",
"Imports System.Runtime.CompilerServices
Module StringExtensions
<Extension()>
Public Sub Print(ByVal aString As String)
Console.WriteLine(aString)
End Sub
End Module
Module M
Private s As String
Sub Main()
Print(s)
End Sub
End Module",
parseOptions:=Nothing) ' TODO (tomat): Modules nested in Script class not supported yet)
End Function
<WorkItem(542942, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542942")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestInsideLambda() As Task
Await TestInRegularAndScriptAsync(
"Module P
Sub M()
Dim t As System.Action = Sub()
[|P.Goo|] = 5
End Sub
End Sub
End Module",
"Module P
Public Property Goo As Integer
Sub M()
Dim t As System.Action = Sub()
P.Goo = 5
End Sub
End Sub
End Module")
End Function
<WorkItem(544632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544632")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestMissingOnForEachExpression() As Task
Await TestMissingInRegularAndScriptAsync(
<Text>
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Public Sub Linq103()
Dim categories As String() = {"Beverages", "Condiments", "Vegetables", "Dairy Products", "Seafood"}
Dim productList = GetProductList()
Dim categorizedProducts = From cat In categories
Group Join prod In productList On cat Equals prod.Category
Into Products = Group
Select Category = cat, Products
For Each v In categorizedProducts
Console.WriteLine(v.Category & ":")
For Each p In v.[|Products|]
Console.WriteLine(" " & p.ProductName)
Next
Next
End Sub
End Module
</Text>.Value)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestLeftOfBinaryExpression() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Main([|a|] + b)
End Sub
End Module",
"Module Program
Private a As Integer
Sub Main(args As String())
Main(a + b)
End Sub
End Module")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestRightOfBinaryExpression() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Main(a + [|b|])
End Sub
End Module",
"Module Program
Private b As Integer
Sub Main(args As String())
Main(a + b)
End Sub
End Module")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateLocal() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Goo([|bar|])
End Sub
End Module",
"Module Program
Private bar As Object
Sub Main(args As String())
Goo(bar)
End Sub
End Module")
End Function
<WorkItem(809542, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/809542")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateLocalBeforeComment() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Module Program
Sub Main
#If True
' Banner Line 1
' Banner Line 2
Integer.TryParse(""123"", [|local|])
#End If
End Sub
End Module",
"Imports System
Module Program
Sub Main
#If True
Dim local As Integer = Nothing
' Banner Line 1
' Banner Line 2
Integer.TryParse(""123"", local)
#End If
End Sub
End Module", index:=2)
End Function
<WorkItem(809542, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/809542")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateLocalAfterComment() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Module Program
Sub Main
#If True
' Banner Line 1
' Banner Line 2
Integer.TryParse(""123"", [|local|])
#End If
End Sub
End Module",
"Imports System
Module Program
Sub Main
#If True
' Banner Line 1
' Banner Line 2
Dim local As Integer = Nothing
Integer.TryParse(""123"", local)
#End If
End Sub
End Module", index:=2)
End Function
<WorkItem(545218, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545218")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestTypeForLocal() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
goo([|xyz|])
End Sub
Sub goo(x As Integer)
End Sub
End Module",
"Module Program
Sub Main(args As String())
Dim xyz As Integer = Nothing
goo(xyz)
End Sub
Sub goo(x As Integer)
End Sub
End Module",
index:=3)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestInSelect() As Task
Await TestInRegularAndScriptAsync(
"Imports System.Linq
Module Program
Sub Main(args As String())
Dim q = From a In args
Select [|v|]
End Sub
End Module",
"Imports System.Linq
Module Program
Private v As Object
Sub Main(args As String())
Dim q = From a In args
Select v
End Sub
End Module")
End Function
<WorkItem(545400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545400")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateLocalInIfPart() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main()
If ([|a|] Mod b <> 0) Then
End If
End Sub
End Module",
"Module Program
Sub Main()
Dim a As Object = Nothing
If (a Mod b <> 0) Then
End If
End Sub
End Module",
index:=3)
End Function
<WorkItem(545672, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545672")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestCrashOnAggregateSelect() As Task
Await TestMissingInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Dim q2 = From j In {1} Select j Aggregate i In {1}
Select [|i|] Into Count(), Sum(i) Select Count, Sum, j
End Sub
End Module")
End Function
<WorkItem(546753, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546753")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestAddressOf() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
[|d|] = AddressOf test
End Sub
Public Function test() As String
Return ""hello""
End Function
End Module",
"Imports System
Module Program
Private d As Func(Of String)
Sub Main(args As String())
d = AddressOf test
End Sub
Public Function test() As String
Return ""hello""
End Function
End Module")
End Function
<WorkItem(530756, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530756")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestMissingOnDictionaryAccess1() As Task
Await TestMissingInRegularAndScriptAsync(
"Imports System.Collections
Module Program
Sub Goo()
Dim x = New Hashtable![|Goo|]!Bar
End Sub
End Module")
End Function
<WorkItem(530756, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530756")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestMissingOnDictionaryAccess2() As Task
Await TestMissingInRegularAndScriptAsync(
"Imports System.Collections
Module Program
Sub Goo()
Dim x = New Hashtable!Goo![|Bar|]
End Sub
End Module")
End Function
<WorkItem(530756, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530756")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestMissingOnDictionaryAccess3() As Task
Await TestMissingInRegularAndScriptAsync(
"Imports System.Collections
Module Program
Sub Goo()
Dim x = New Hashtable![|Goo!Bar|]
End Sub
End Module")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestFormattingInGenerateVariable() As Task
Await TestInRegularAndScriptAsync(
<Text>Module Program
Sub Main()
If ([|a|] Mod b <> 0) Then
End If
End Sub
End Module</Text>.Value.Replace(vbLf, vbCrLf),
<Text>Module Program
Public Property a As Object
Sub Main()
If (a Mod b <> 0) Then
End If
End Sub
End Module</Text>.Value.Replace(vbLf, vbCrLf),
index:=2)
End Function
<WorkItem(666189, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/666189")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyInScript() As Task
Await TestAsync(
<Text>Dim x As Integer
x = [|Goo|]</Text>.Value.Replace(vbLf, vbCrLf),
<Text>Dim x As Integer
Public Property Goo As Integer
x = Goo</Text>.Value.Replace(vbLf, vbCrLf),
parseOptions:=New VisualBasicParseOptions(kind:=SourceCodeKind.Script))
End Function
<WorkItem(666189, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/666189")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateFieldInScript() As Task
Await TestAsync(
<Text>Dim x As Integer
x = [|Goo|]</Text>.Value.Replace(vbLf, vbCrLf),
<Text>Dim x As Integer
Private Goo As Integer
x = Goo</Text>.Value.Replace(vbLf, vbCrLf),
parseOptions:=New VisualBasicParseOptions(kind:=SourceCodeKind.Script),
index:=1)
End Function
<WorkItem(977580, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/977580")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestWithThrow() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class A
Public Sub B()
Throw [|MyExp|]
End Sub
End Class",
"Imports System
Public Class A
Private MyExp As Exception
Public Sub B()
Throw MyExp
End Sub
End Class", index:=1)
End Function
<WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestInsideNameOfProperty() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Sub M()
Dim x = NameOf([|Z|])
End Sub
End Class",
"Imports System
Class C
Public Property Z As Object
Sub M()
Dim x = NameOf(Z)
End Sub
End Class")
End Function
<WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestInsideNameOfField() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Sub M()
Dim x = NameOf([|Z|])
End Sub
End Class",
"Imports System
Class C
Private Z As Object
Sub M()
Dim x = NameOf(Z)
End Sub
End Class", index:=1)
End Function
<WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestInsideNameOfReadonlyField() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Sub M()
Dim x = NameOf([|Z|])
End Sub
End Class",
"Imports System
Class C
Private ReadOnly Z As Object
Sub M()
Dim x = NameOf(Z)
End Sub
End Class", index:=2)
End Function
<WorkItem(1032176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032176")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestInsideNameOfLocal() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Sub M()
Dim x = NameOf([|Z|])
End Sub
End Class",
"Imports System
Class C
Sub M()
Dim Z As Object = Nothing
Dim x = NameOf(Z)
End Sub
End Class", index:=3)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessProperty() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As C = a?[|.B|]
End Sub
End Class",
"Public Class C
Public Property B As C
Sub Main(a As C)
Dim x As C = a?.B
End Sub
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessProperty2() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x = a?[|.B|]
End Sub
End Class",
"Public Class C
Public Property B As Object
Sub Main(a As C)
Dim x = a?.B
End Sub
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessProperty3() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As Integer? = a?[|.B|]
End Sub
End Class",
"Public Class C
Public Property B As Integer
Sub Main(a As C)
Dim x As Integer? = a?.B
End Sub
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessProperty4() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As C? = a?[|.B|]
End Sub
End Class",
"Public Class C
Public Property B As C
Sub Main(a As C)
Dim x As C? = a?.B
End Sub
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessField() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As C = a?[|.B|]
End Sub
End Class",
"Public Class C
Private B As C
Sub Main(a As C)
Dim x As C = a?.B
End Sub
End Class",
index:=1)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessField2() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x = a?[|.B|]
End Sub
End Class",
"Public Class C
Private B As Object
Sub Main(a As C)
Dim x = a?.B
End Sub
End Class",
index:=1)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessField3() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As Integer? = a?[|.B|]
End Sub
End Class",
"Public Class C
Private B As Integer
Sub Main(a As C)
Dim x As Integer? = a?.B
End Sub
End Class",
index:=1)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessField4() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As C? = a?[|.B|]
End Sub
End Class",
"Public Class C
Private B As C
Sub Main(a As C)
Dim x As C? = a?.B
End Sub
End Class",
index:=1)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessReadOnlyField() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As C = a?[|.B|]
End Sub
End Class",
"Public Class C
Private ReadOnly B As C
Sub Main(a As C)
Dim x As C = a?.B
End Sub
End Class",
index:=2)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessReadOnlyField2() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x = a?[|.B|]
End Sub
End Class",
"Public Class C
Private ReadOnly B As Object
Sub Main(a As C)
Dim x = a?.B
End Sub
End Class",
index:=2)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessReadOnlyField3() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As Integer? = a?[|.B|]
End Sub
End Class",
"Public Class C
Private ReadOnly B As Integer
Sub Main(a As C)
Dim x As Integer? = a?.B
End Sub
End Class",
index:=2)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessReadOnlyField4() As Task
Await TestInRegularAndScriptAsync(
"Public Class C
Sub Main(a As C)
Dim x As C? = a?[|.B|]
End Sub
End Class",
"Public Class C
Private ReadOnly B As C
Sub Main(a As C)
Dim x As C? = a?.B
End Sub
End Class",
index:=2)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessPropertyInsideReferencedClass() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x As C = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As C = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Public Property Z As C
End Class
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessPropertyInsideReferencedClass2() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Public Property Z As Integer
End Class
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessPropertyInsideReferencedClass3() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer? = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer? = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Public Property Z As Integer
End Class
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessPropertyInsideReferencedClass4() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Public Property Z As Object
End Class
End Class")
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessFieldInsideReferencedClass() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x As C = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As C = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Friend Z As C
End Class
End Class",
index:=1)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessFieldInsideReferencedClass2() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Friend Z As Integer
End Class
End Class",
index:=1)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessFieldInsideReferencedClass3() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer? = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer? = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Friend Z As Integer
End Class
End Class",
index:=1)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessFieldInsideReferencedClass4() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Friend Z As Object
End Class
End Class",
index:=1)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessReadOnlyFieldInsideReferencedClass() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x As C = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As C = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Friend ReadOnly Z As C
End Class
End Class",
index:=2)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessReadOnlyFieldInsideReferencedClass2() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Friend ReadOnly Z As Integer
End Class
End Class",
index:=2)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessReadOnlyFieldInsideReferencedClass3() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer? = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x As Integer? = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Friend ReadOnly Z As Integer
End Class
End Class",
index:=2)
End Function
<WorkItem(1064815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064815")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestConditionalAccessReadOnlyFieldInsideReferencedClass4() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Public Class C
Sub Main(a As C)
Dim x = a?[|.B.Z|]
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
End Class
End Class",
"Imports System
Public Class C
Sub Main(a As C)
Dim x = a?.B.Z
End Sub
Private Function B() As D
Throw New NotImplementedException()
End Function
Private Class D
Friend ReadOnly Z As Object
End Class
End Class",
index:=2)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyInPropertyInitializer() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Property a As Integer = [|y|]
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Private y As Integer
Property a As Integer = y
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateFieldInPropertyInitializer() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Property a As Integer = [|y|]
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Private ReadOnly y As Integer
Property a As Integer = y
End Module",
index:=1)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateReadonlyFieldInPropertyInitializer() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Property a As Integer = [|y|]
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Property a As Integer = y
Public Property y As Integer
End Module",
index:=2)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyInObjectInitializer1() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Dim x As New Customer With {.[|Name|] = ""blah""}
End Sub
End Module
Friend Class Customer
End Class",
"Module Program
Sub Main(args As String())
Dim x As New Customer With {.Name = ""blah""}
End Sub
End Module
Friend Class Customer
Public Property Name As String
End Class")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyInObjectInitializer2() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Dim x As New Customer With {.Name = ""blah"", .[|Age|] = blah}
End Sub
End Module
Friend Class Customer
Public Property Name As String
End Class",
"Module Program
Sub Main(args As String())
Dim x As New Customer With {.Name = ""blah"", .Age = blah}
End Sub
End Module
Friend Class Customer
Public Property Name As String
Public Property Age As Object
End Class")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyInObjectInitializer3() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Dim x As New Customer With {.Name = [|name|]}
End Sub
End Module
Friend Class Customer
End Class",
"Module Program
Public Property name As Object
Sub Main(args As String())
Dim x As New Customer With {.Name = name}
End Sub
End Module
Friend Class Customer
End Class",
index:=2)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateFieldInObjectInitializer1() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Dim x As New Customer With {.[|Name|] = ""blah""}
End Sub
End Module
Friend Class Customer
End Class",
"Module Program
Sub Main(args As String())
Dim x As New Customer With {.Name = ""blah""}
End Sub
End Module
Friend Class Customer
Friend Name As String
End Class",
index:=1)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateFieldInObjectInitializer2() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Dim x As New Customer With {.[|Name|] = name}
End Sub
End Module
Friend Class Customer
End Class",
"Module Program
Sub Main(args As String())
Dim x As New Customer With {.Name = name}
End Sub
End Module
Friend Class Customer
Friend Name As Object
End Class",
index:=1)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateFieldInObjectInitializer3() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Dim x As New Customer With {.Name = [|name|]}
End Sub
End Module
Friend Class Customer
End Class",
"Module Program
Private name As Object
Sub Main(args As String())
Dim x As New Customer With {.Name = name}
End Sub
End Module
Friend Class Customer
End Class")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestInvalidObjectInitializer() As Task
Await TestMissingInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Dim x As New Customer With { [|Name|] = ""blkah""}
End Sub
End Module
Friend Class Customer
End Class")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestOnlyPropertyAndFieldOfferedForObjectInitializer() As Task
Await TestActionCountAsync(
"Module Program
Sub Main(args As String())
Dim x As New Customer With {.[|Name|] = ""blah""}
End Sub
End Module
Friend Class Customer
End Class",
2)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateLocalInObjectInitializerValue() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Dim x As New Customer With {.Name = [|blah|]}
End Sub
End Module
Friend Class Customer
End Class",
"Module Program
Sub Main(args As String())
Dim blah As Object = Nothing
Dim x As New Customer With {.Name = blah}
End Sub
End Module
Friend Class Customer
End Class",
index:=3)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGeneratePropertyInTypeOf() As Task
Await TestInRegularAndScriptAsync(
"Module C
Sub Test()
If TypeOf [|B|] Is String Then
End If
End Sub
End Module",
"Module C
Public Property B As String
Sub Test()
If TypeOf B Is String Then
End If
End Sub
End Module")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateFieldInTypeOf() As Task
Await TestInRegularAndScriptAsync(
"Module C
Sub Test()
If TypeOf [|B|] Is String Then
End If
End Sub
End Module",
"Module C
Private B As String
Sub Test()
If TypeOf B Is String Then
End If
End Sub
End Module",
index:=1)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateReadOnlyFieldInTypeOf() As Task
Await TestInRegularAndScriptAsync(
"Module C
Sub Test()
If TypeOf [|B|] Is String Then
End If
End Sub
End Module",
"Module C
Private ReadOnly B As String
Sub Test()
If TypeOf B Is String Then
End If
End Sub
End Module",
index:=2)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateLocalInTypeOf() As Task
Await TestInRegularAndScriptAsync(
"Module C
Sub Test()
If TypeOf [|B|] Is String Then
End If
End Sub
End Module",
"Module C
Sub Test()
Dim B As String = Nothing
If TypeOf B Is String Then
End If
End Sub
End Module",
index:=3)
End Function
<WorkItem(1130960, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1130960")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)>
Public Async Function TestGeneratePropertyInTypeOfIsNot() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub M()
If TypeOf [|Prop|] IsNot TypeOfIsNotDerived Then
End If
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Public Property Prop As TypeOfIsNotDerived
Sub M()
If TypeOf Prop IsNot TypeOfIsNotDerived Then
End If
End Sub
End Module")
End Function
<WorkItem(1130960, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1130960")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateFieldInTypeOfIsNot() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub M()
If TypeOf [|Prop|] IsNot TypeOfIsNotDerived Then
End If
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Private Prop As TypeOfIsNotDerived
Sub M()
If TypeOf Prop IsNot TypeOfIsNotDerived Then
End If
End Sub
End Module",
index:=1)
End Function
<WorkItem(1130960, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1130960")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateReadOnlyFieldInTypeOfIsNot() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub M()
If TypeOf [|Prop|] IsNot TypeOfIsNotDerived Then
End If
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Private ReadOnly Prop As TypeOfIsNotDerived
Sub M()
If TypeOf Prop IsNot TypeOfIsNotDerived Then
End If
End Sub
End Module",
index:=2)
End Function
<WorkItem(1130960, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1130960")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateLocalInTypeOfIsNot() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub M()
If TypeOf [|Prop|] IsNot TypeOfIsNotDerived Then
End If
End Sub
End Module",
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub M()
Dim Prop As TypeOfIsNotDerived = Nothing
If TypeOf Prop IsNot TypeOfIsNotDerived Then
End If
End Sub
End Module",
index:=3)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateVariableFromLambda() As Task
Await TestInRegularAndScriptAsync(
"Class [Class]
Private Sub Method(i As Integer)
[|goo|] = Function()
Return 2
End Function
End Sub
End Class",
"Imports System
Class [Class]
Private goo As Func(Of Integer)
Private Sub Method(i As Integer)
goo = Function()
Return 2
End Function
End Sub
End Class")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateVariableFromLambda2() As Task
Await TestInRegularAndScriptAsync(
"Class [Class]
Private Sub Method(i As Integer)
[|goo|] = Function()
Return 2
End Function
End Sub
End Class",
"Imports System
Class [Class]
Public Property goo As Func(Of Integer)
Private Sub Method(i As Integer)
goo = Function()
Return 2
End Function
End Sub
End Class",
index:=1)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateVariableFromLambda3() As Task
Await TestInRegularAndScriptAsync(
"Class [Class]
Private Sub Method(i As Integer)
[|goo|] = Function()
Return 2
End Function
End Sub
End Class",
"Class [Class]
Private Sub Method(i As Integer)
Dim goo As System.Func(Of Integer)
goo = Function()
Return 2
End Function
End Sub
End Class",
index:=2)
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TupleRead() As Task
Await TestInRegularAndScriptAsync(
"Class [Class]
Private Sub Method(i As (Integer, String))
Method([|tuple|])
End Sub
End Class",
"Class [Class]
Private tuple As (Integer, String)
Private Sub Method(i As (Integer, String))
Method(tuple)
End Sub
End Class")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TupleWithOneNameRead() As Task
Await TestInRegularAndScriptAsync(
"Class [Class]
Private Sub Method(i As (a As Integer, String))
Method([|tuple|])
End Sub
End Class",
"Class [Class]
Private tuple As (a As Integer, String)
Private Sub Method(i As (a As Integer, String))
Method(tuple)
End Sub
End Class")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TupleWrite() As Task
Await TestInRegularAndScriptAsync(
"Class [Class]
Private Sub Method()
[|tuple|] = (1, ""hello"")
End Sub
End Class",
"Class [Class]
Private tuple As (Integer, String)
Private Sub Method()
tuple = (1, ""hello"")
End Sub
End Class")
End Function
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TupleWithOneNameWrite() As Task
Await TestInRegularAndScriptAsync(
"Class [Class]
Private Sub Method()
[|tuple|] = (a:=1, ""hello"")
End Sub
End Class",
"Class [Class]
Private tuple As (a As Integer, String)
Private Sub Method()
tuple = (a:=1, ""hello"")
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestPreferReadOnlyIfAfterReadOnlyAssignment() As Task
Await TestInRegularAndScriptAsync(
"class C
private readonly _goo as integer
public sub new()
_goo = 0
[|_bar|] = 1
end sub
end class",
"class C
private readonly _goo as integer
Private ReadOnly _bar As Integer
public sub new()
_goo = 0
_bar = 1
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestPreferReadOnlyIfBeforeReadOnlyAssignment() As Task
Await TestInRegularAndScriptAsync(
"class C
private readonly _goo as integer
public sub new()
[|_bar|] = 1
_goo = 0
end sub
end class",
"class C
Private ReadOnly _bar As Integer
private readonly _goo as integer
public sub new()
_bar = 1
_goo = 0
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestPlaceFieldBasedOnSurroundingStatements() As Task
Await TestInRegularAndScriptAsync(
"class Class
private _goo as integer
private _quux as integer
public sub new()
_goo = 0
[|_bar|] = 1
_quux = 2
end sub
end class",
"class Class
private _goo as integer
Private _bar As Integer
private _quux as integer
public sub new()
_goo = 0
_bar = 1
_quux = 2
end sub
end class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestPlacePropertyBasedOnSurroundingStatements() As Task
Await TestInRegularAndScriptAsync(
"class Class
public readonly property Goo as integer
public readonly property Quux as integer
public sub new()
Goo = 0
[|Bar|] = 1
Quux = 2
end sub
end class",
"class Class
public readonly property Goo as integer
Public ReadOnly Property Bar As Integer
public readonly property Quux as integer
public sub new()
Goo = 0
Bar = 1
Quux = 2
end sub
end class")
End Function
<WorkItem(18988, "https://github.com/dotnet/roslyn/issues/18988")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function GroupNonReadonlyFieldsTogether() As Task
Await TestInRegularAndScriptAsync(
"
class C
public isDisposed as boolean
public readonly x as integer
public readonly m as integer
public sub new()
me.[|y|] = 0
end sub
end class",
"
class C
public isDisposed as boolean
Private y As Integer
public readonly x as integer
public readonly m as integer
public sub new()
me.y = 0
end sub
end class")
End Function
<WorkItem(18988, "https://github.com/dotnet/roslyn/issues/18988")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function GroupReadonlyFieldsTogether() As Task
Await TestInRegularAndScriptAsync("
class C
public readonly x as integer
public readonly m as integer
public isDisposed as boolean
public sub new()
me.[|y|] = 0
end sub
end class",
"
class C
public readonly x as integer
public readonly m as integer
Private ReadOnly y As Integer
public isDisposed as boolean
public sub new()
me.y = 0
end sub
end class", index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateSimplePropertyInSyncLock() As Threading.Tasks.Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
SyncLock [|Bar|]
End SyncLock
End Sub
End Module",
"Module Program
Public Property Bar As Object
Sub Main(args As String())
SyncLock Bar
End SyncLock
End Sub
End Module")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateSimpleFieldInSyncLock() As Threading.Tasks.Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
SyncLock [|Bar|]
End SyncLock
End Sub
End Module",
"Module Program
Private Bar As Object
Sub Main(args As String())
SyncLock Bar
End SyncLock
End Sub
End Module",
index:=1)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestGenerateReadOnlyFieldInSyncLock() As Threading.Tasks.Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
SyncLock [|Bar|]
End SyncLock
End Sub
End Module",
"Module Program
Private ReadOnly Bar As Object
Sub Main(args As String())
SyncLock Bar
End SyncLock
End Sub
End Module",
index:=2)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestAddParameter() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Goo([|bar|])
End Sub
End Module",
"Module Program
Sub Main(args As String(), bar As Object)
Goo(bar)
End Sub
End Module",
index:=4)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestAddParameterDoesntAddToOverride() As Task
Await TestInRegularAndScriptAsync(
"Class Base
Public Overridable Sub Method(args As String())
End Sub
End Class
Class Program
Public Overrides Sub Main(args As String())
Goo([|bar|])
End Sub
End Class",
"Class Base
Public Overridable Sub Method(args As String())
End Sub
End Class
Class Program
Public Overrides Sub Main(args As String(), bar As Object)
Goo(bar)
End Sub
End Class",
index:=4)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestAddParameterAndOverridesAddsToOverrides() As Task
Await TestInRegularAndScriptAsync(
"Class Base
Public Overridable Sub Method(args As String())
End Sub
End Class
Class Program
Inherits Base
Public Overrides Sub Method(args As String())
Goo([|bar|])
End Sub
End Class",
"Class Base
Public Overridable Sub Method(args As String(), bar As Object)
End Sub
End Class
Class Program
Inherits Base
Public Overrides Sub Method(args As String(), bar As Object)
Goo(bar)
End Sub
End Class",
index:=5)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestAddParameterIsOfCorrectType() As Task
Await TestInRegularAndScriptAsync(
"Module Program
Sub Main(args As String())
Goo([|bar|])
End Sub
Sub Goo(arg As Integer)
End Sub
End Module",
"Module Program
Sub Main(args As String(), bar As Integer)
Goo(bar)
End Sub
Sub Goo(arg As Integer)
End Sub
End Module",
index:=4)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestAddParameterAndOverridesIsOfCorrectType() As Task
Await TestInRegularAndScriptAsync(
"Class Base
Public Overridable Sub Method(args As String())
End Sub
End Class
Class Program
Inherits Base
Public Overrides Sub Method(args As String())
Goo([|bar|])
End Sub
Sub Goo(arg As Integer)
End Sub
End Class",
"Class Base
Public Overridable Sub Method(args As String(), bar As Integer)
End Sub
End Class
Class Program
Inherits Base
Public Overrides Sub Method(args As String(), bar As Integer)
Goo(bar)
End Sub
Sub Goo(arg As Integer)
End Sub
End Class",
index:=5)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestAddParameterAndOverridesNotOfferedToNonOverride1() As Task
Await TestActionCountAsync(
"Module Program
Sub Main(args As String())
Goo([|bar|])
End Sub
End Module",
count:=5)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestAddParameterAndOverridesNotOfferedToNonOverride2() As Task
Await TestActionCountAsync(
"Class Base
Public Overridable Sub Method(args As String())
End Sub
End Class
Class Program
Inherits Base
Public Sub Method(args As String())
Goo([|bar|])
End Sub
Sub Goo(arg As Integer)
End Sub
End Class",
count:=5)
End Function
<WorkItem(45367, "https://github.com/dotnet/roslyn/issues/45367")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateVariable)>
Public Async Function TestCrashInNamespace() As Task
Await TestMissingInRegularAndScriptAsync(
"Namespace ConsoleApp5
Friend Sub New(errNum As Integer, offset As Integer, message As String)
MyBase.New(message)
Me.[|Error|] = errNum
End Sub
End Namespace")
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Workspaces/Core/Portable/Storage/CloudCache/ICloudCacheStorageServiceFactory.cs | // Licensed to the .NET Foundation under one or more 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.Storage.CloudCache
{
internal interface ICloudCacheStorageServiceFactory : IWorkspaceService
{
AbstractPersistentStorageService Create(IPersistentStorageLocationService locationService);
}
}
| // Licensed to the .NET Foundation under one or more 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.Storage.CloudCache
{
internal interface ICloudCacheStorageServiceFactory : IWorkspaceService
{
AbstractPersistentStorageService Create(IPersistentStorageLocationService locationService);
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Compilers/VisualBasic/Portable/Scanner/XmlDocComments.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
'-----------------------------------------------------------------------------
' Contains scanner functionality related to XmlDoc comments
'-----------------------------------------------------------------------------
Option Compare Binary
Option Strict On
Imports Microsoft.CodeAnalysis.Syntax.InternalSyntax
Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts
Imports CoreInternalSyntax = Microsoft.CodeAnalysis.Syntax.InternalSyntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax
Partial Friend Class Scanner
Private _IsScanningXmlDoc As Boolean = False
Friend Property IsScanningXmlDoc As Boolean
Get
Return _IsScanningXmlDoc
End Get
Private Set(value As Boolean)
_IsScanningXmlDoc = value
End Set
End Property
''' <remarks>See description in TryScanXmlDocComment(...)</remarks>
Private _endOfXmlInsteadOfLastDocCommentLineBreak As Boolean
' bug 903247. First line should be treated in a special way.
Private _isStartingFirstXmlDocLine As Boolean = False
Private _doNotRequireXmlDocCommentPrefix As Boolean = False
Private ReadOnly Property ShouldReportXmlError As Boolean
Get
Return Not Me._IsScanningXmlDoc OrElse
Me._options.DocumentationMode = DocumentationMode.Diagnose
End Get
End Property
''' <summary>
''' This method is only to be used for parsing Cref and Name attributes as stand-alone entities
''' </summary>
Friend Sub ForceScanningXmlDocMode()
Me.IsScanningXmlDoc = True
Me._isStartingFirstXmlDocLine = False
Me._doNotRequireXmlDocCommentPrefix = True
End Sub
Private Function TryScanXmlDocComment(tList As SyntaxListBuilder) As Boolean
Debug.Assert(IsAtNewLine)
' leading whitespace until we see ''' should be regular whitespace
If CanGet() AndAlso IsWhitespace(Peek()) Then
Dim ws = ScanWhitespace()
tList.Add(ws)
End If
' SAVE the lookahead state and clear current token
#If DEBUG Then
Dim origPosition = _lineBufferOffset
#End If
Dim restorePoint = CreateRestorePoint()
' since we do not have lookahead tokens, this just
' resets current token to _lineBufferOffset
Me.GetNextTokenInState(ScannerState.Content)
Dim currentNonterminal = Me.GetCurrentSyntaxNode()
Dim docCommentSyntax = TryCast(currentNonterminal, DocumentationCommentTriviaSyntax)
' if we are lucky to get whole doc comment, we can just reuse it.
If docCommentSyntax IsNot Nothing Then
Me.MoveToNextSyntaxNodeInTrivia()
Else
Dim parser As New Parser(Me)
Me.IsScanningXmlDoc = True
Me._isStartingFirstXmlDocLine = True
' NOTE: Documentation comment syntax trivia must have at least one child xml node, because
' all the ['''] trivia are created as leading trivia for appropriate tokens.
' This means that we have to create at least one XmlText having trailing
' EOL to represent an empty documentation comment: ['''<eol>]
'
' The problem with this approach is that in presence of some errors (like
' not closed XML tags) we create missing tokens needed to represent the nodes
' *after* that last <eol> of the doc comment trivia, that means all the locations
' of created diagnostics will land on the first character of the next line
' after documentation comment
'
' To workaround this we parse XML nodes in two phases:
' - in the first phase we detect the last DocCommentLineBreak and create
' end-of-xml token instead; this should force all diagnostics to be
' reported on the next token location;
' - in the second phase we continue parsing XML nodes but don't create
' end-of-xml token which should just result in parsing one single node
' of XmlText type containing EOL;
' Then we merge the results and create resulting DocumentationCommentTrivia
' The first phase
Me._endOfXmlInsteadOfLastDocCommentLineBreak = True
Dim nodes = parser.ParseXmlContent(ScannerState.Content)
' The second phase
Me._endOfXmlInsteadOfLastDocCommentLineBreak = False
If nodes.Count = 0 AndAlso parser.CurrentToken.Kind = SyntaxKind.EndOfXmlToken Then
' This must be an empty documentation comment, we need to reset scanner so
' that the doc comment exterior trivia ([''']) lands on the final XmlNode
ResetLineBufferOffset()
restorePoint.RestoreTokens(includeLookAhead:=False)
Me._isStartingFirstXmlDocLine = True
End If
nodes = parser.ParseRestOfDocCommentContent(nodes)
Me.IsScanningXmlDoc = False
Debug.Assert(nodes.Any)
Debug.Assert(nodes(0).FullWidth > 0, "should at least get {'''EoL} ")
' restore _currentToken and lookahead,
' but keep offset and PP state
ResetLineBufferOffset()
docCommentSyntax = SyntaxFactory.DocumentationCommentTrivia(nodes)
If Me.Options.DocumentationMode < DocumentationMode.Diagnose Then
' All diagnostics coming from documentation comment are ignored
docCommentSyntax.ClearFlags(GreenNode.NodeFlags.ContainsDiagnostics)
End If
End If
' RESTORE lookahead state and current token if there were any
restorePoint.RestoreTokens(includeLookAhead:=True)
#If DEBUG Then
Debug.Assert(Me._lineBufferOffset = origPosition + docCommentSyntax.FullWidth OrElse
Me._endOfTerminatorTrivia = origPosition + docCommentSyntax.FullWidth)
#End If
tList.Add(docCommentSyntax)
Return True
End Function
' lexes (ws)'''
Private Function TrySkipXmlDocMarker(ByRef len As Integer) As Boolean
Dim Here = len
While CanGet(Here)
Dim c = Peek(Here)
If IsWhitespace(c) Then
Here += 1
Else
Exit While
End If
End While
If StartsXmlDoc(Here) Then
len = Here + 3
Return True
Else
Return False
End If
End Function
' scans (ws)'''
Private Function ScanXmlDocTrivia() As VisualBasicSyntaxNode
Debug.Assert(IsAtNewLine() OrElse _isStartingFirstXmlDocLine)
Dim len = 0
If TrySkipXmlDocMarker(len) Then
Return MakeDocumentationCommentExteriorTrivia(GetText(len))
Else
Return Nothing
End If
End Function
''' <summary>
''' Returns False if trivia ends line.
''' </summary>
Private Function ScanXmlTriviaInXmlDoc(c As Char, triviaList As SyntaxListBuilder(Of VisualBasicSyntaxNode)) As Boolean
Debug.Assert(IsScanningXmlDoc)
Debug.Assert(c = CARRIAGE_RETURN OrElse c = LINE_FEED OrElse c = " "c OrElse c = CHARACTER_TABULATION)
Dim len = 0
Do
If c = " "c OrElse c = CHARACTER_TABULATION Then
len += 1
ElseIf IsNewLine(c) Then
If len > 0 Then
triviaList.Add(MakeWhiteSpaceTrivia(GetText(len)))
len = 0
End If
' Only consume the end of line if the XML doc
' comment continues on the following line.
Dim offsets = CreateOffsetRestorePoint()
Dim endOfLineTrivia = ScanNewlineAsTrivia(c)
Dim ws = GetXmlWhitespaceLength(0)
If TrySkipXmlDocMarker(ws) Then
triviaList.Add(endOfLineTrivia)
triviaList.Add(MakeDocumentationCommentExteriorTrivia(GetText(ws)))
Else
offsets.Restore()
Return False
End If
Else
Exit Do
End If
c = Peek(len)
Loop
If len > 0 Then
triviaList.Add(MakeWhiteSpaceTrivia(GetText(len)))
End If
Return True
End Function
Private Function ScanXmlContentInXmlDoc() As SyntaxToken
Debug.Assert(IsScanningXmlDoc)
' // [14] CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*)
Dim precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) = Nothing
If IsAtNewLine() OrElse _isStartingFirstXmlDocLine Then
Dim xDocTrivia = ScanXmlDocTrivia()
_isStartingFirstXmlDocLine = False ' no longer starting
If xDocTrivia Is Nothing Then
Return MakeEofToken() ' XmlDoc lines must start with XmlDocTrivia
End If
precedingTrivia = New CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)(xDocTrivia)
End If
Dim Here As Integer = 0
Dim scratch = GetScratch()
While CanGet(Here)
Dim c As Char = Peek(Here)
Select Case (c)
Case CARRIAGE_RETURN, LINE_FEED
If Here <> 0 Then
Return XmlMakeTextLiteralToken(precedingTrivia, Here, scratch)
End If
Here = SkipLineBreak(c, Here)
If _endOfXmlInsteadOfLastDocCommentLineBreak Then
Dim tempHere As Integer = Here
If Not TrySkipXmlDocMarker(tempHere) Then
' NOTE: we need to reset the buffer so that precedingTrivia
' lands on the next token
ResetLineBufferOffset()
Return SyntaxFactory.Token(Nothing, SyntaxKind.EndOfXmlToken, Nothing, String.Empty)
End If
End If
' line breaks in Doc comments are separate tokens.
Return MakeDocCommentLineBreakToken(precedingTrivia, Here)
Case " "c, CHARACTER_TABULATION
scratch.Append(c)
Here += 1
Case "&"c
If Here <> 0 Then
Return XmlMakeTextLiteralToken(precedingTrivia, Here, scratch)
End If
Return ScanXmlReference(precedingTrivia)
Case "<"c
If Here <> 0 Then
Return XmlMakeTextLiteralToken(precedingTrivia, Here, scratch)
End If
Debug.Assert(Here = 0)
If CanGet(1) Then
Dim ch As Char = Peek(1)
Select Case ch
Case "!"c
If CanGet(2) Then
Select Case (Peek(2))
Case "-"c
If NextIs(3, "-"c) Then
Return XmlMakeBeginCommentToken(precedingTrivia, s_scanNoTriviaFunc)
End If
Case "["c
If NextAre(3, "CDATA[") Then
Return XmlMakeBeginCDataToken(precedingTrivia, s_scanNoTriviaFunc)
End If
Case "D"c
If NextAre(3, "OCTYPE") Then
Return XmlMakeBeginDTDToken(precedingTrivia)
End If
End Select
End If
Case "?"c
Return XmlMakeBeginProcessingInstructionToken(precedingTrivia, s_scanNoTriviaFunc)
Case "/"c
Return XmlMakeBeginEndElementToken(precedingTrivia, s_scanNoTriviaFunc)
End Select
End If
Return XmlMakeLessToken(precedingTrivia)
Case "]"c
If NextAre(Here + 1, "]>") Then
' // If valid characters found then return them.
If Here <> 0 Then
Return XmlMakeTextLiteralToken(precedingTrivia, Here, scratch)
End If
' // Create an invalid character data token for the illegal ']]>' sequence
Return XmlMakeTextLiteralToken(precedingTrivia, 3, ERRID.ERR_XmlEndCDataNotAllowedInContent)
End If
GoTo ScanChars
Case Else
ScanChars:
' // Check characters are valid
Dim xmlCh = ScanXmlChar(Here)
If xmlCh.Length = 0 Then
' bad char
If Here > 0 Then
Return XmlMakeTextLiteralToken(precedingTrivia, Here, scratch)
Else
Return XmlMakeBadToken(precedingTrivia, 1, ERRID.ERR_IllegalChar)
End If
End If
xmlCh.AppendTo(scratch)
Here += xmlCh.Length
End Select
End While
' no more chars
If Here > 0 Then
Return XmlMakeTextLiteralToken(precedingTrivia, Here, scratch)
Else
Return MakeEofToken(precedingTrivia)
End If
End Function
Friend Function ScanXmlPIDataInXmlDoc(state As ScannerState) As SyntaxToken
Debug.Assert(IsScanningXmlDoc)
' // Scan the PI data after the white space
' // [16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'
' // [17] PITarget ::= Name - (('X' | 'x') ('M' | 'm') ('L' | 'l'))
Debug.Assert(state = ScannerState.StartProcessingInstruction OrElse
state = ScannerState.ProcessingInstruction)
Dim precedingTrivia = _triviaListPool.Allocate(Of VisualBasicSyntaxNode)()
Dim result As SyntaxToken
If IsAtNewLine() Then
Dim xDocTrivia = ScanXmlDocTrivia()
If xDocTrivia Is Nothing Then
Return MakeEofToken() ' XmlDoc lines must start with XmlDocTrivia
End If
precedingTrivia.Add(xDocTrivia)
End If
If state = ScannerState.StartProcessingInstruction AndAlso CanGet() Then
' // Whitespace
' // S ::= (#x20 | #x9 | #xD | #xA)+
Dim c = Peek()
Select Case c
Case CARRIAGE_RETURN, LINE_FEED, " "c, CHARACTER_TABULATION
Dim offsets = CreateOffsetRestorePoint()
Dim continueLine = ScanXmlTriviaInXmlDoc(c, precedingTrivia)
If Not continueLine Then
offsets.Restore()
result = SyntaxFactory.Token(precedingTrivia.ToList.Node, SyntaxKind.EndOfXmlToken, Nothing, String.Empty)
GoTo CleanUp
End If
End Select
End If
Dim Here = 0
While CanGet(Here)
Dim c As Char = Peek(Here)
Select Case (c)
Case CARRIAGE_RETURN, LINE_FEED
result = XmlMakeProcessingInstructionToken(precedingTrivia.ToList, Here + LengthOfLineBreak(c, Here))
GoTo CleanUp
Case "?"c
If NextIs(Here + 1, ">"c) Then
'// If valid characters found then return them.
If Here <> 0 Then
result = XmlMakeProcessingInstructionToken(precedingTrivia.ToList, Here)
GoTo CleanUp
End If
' // Create token for the '?>' termination sequence
result = XmlMakeEndProcessingInstructionToken(precedingTrivia.ToList)
GoTo CleanUp
End If
GoTo ScanChars
Case Else
ScanChars:
Dim xmlCh = ScanXmlChar(Here)
If xmlCh.Length > 0 Then
Here += xmlCh.Length
Continue While
End If
' bad char
If Here <> 0 Then
result = XmlMakeProcessingInstructionToken(precedingTrivia.ToList, Here)
GoTo CleanUp
Else
result = XmlMakeBadToken(precedingTrivia.ToList, 1, ERRID.ERR_IllegalChar)
GoTo CleanUp
End If
End Select
End While
' no more chars
If Here > 0 Then
result = XmlMakeProcessingInstructionToken(precedingTrivia.ToList, Here)
Else
result = MakeEofToken(precedingTrivia.ToList)
End If
CleanUp:
_triviaListPool.Free(precedingTrivia)
Return result
End Function
Private Function ScanXmlElementInXmlDoc(state As ScannerState) As SyntaxToken
Debug.Assert(IsScanningXmlDoc)
' // Only legal tokens
' // QName
' // /
' // >
' // =
' // Whitespace
Dim precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) = Nothing
If IsAtNewLine() AndAlso Not Me._doNotRequireXmlDocCommentPrefix Then
Dim xDocTrivia = ScanXmlDocTrivia()
If xDocTrivia Is Nothing Then
Return MakeEofToken() ' XmlDoc lines must start with XmlDocTrivia
End If
precedingTrivia = New CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)(xDocTrivia)
End If
While CanGet()
If Not precedingTrivia.Any AndAlso IsAtNewLine() AndAlso Not Me._doNotRequireXmlDocCommentPrefix Then
' this would indicate that we looked at Trivia, but did not find
' XmlDoc prefix (or we would not be at the line start)
' must terminate XmlDoc scanning
Return MakeEofToken(precedingTrivia)
End If
Dim c As Char = Peek()
Select Case (c)
' // Whitespace
' // S ::= (#x20 | #x9 | #xD | #xA)+
Case CARRIAGE_RETURN, LINE_FEED, " "c, CHARACTER_TABULATION
' we should not visit this place twice
Debug.Assert(Not precedingTrivia.Any)
Dim offsets = CreateOffsetRestorePoint()
Dim triviaList = _triviaListPool.Allocate(Of VisualBasicSyntaxNode)()
Dim continueLine = ScanXmlTriviaInXmlDoc(c, triviaList)
precedingTrivia = triviaList.ToList()
_triviaListPool.Free(triviaList)
If Not continueLine Then
offsets.Restore()
Return SyntaxFactory.Token(precedingTrivia.Node, SyntaxKind.EndOfXmlToken, Nothing, String.Empty)
End If
Case "/"c
If NextIs(1, ">"c) Then
Return XmlMakeEndEmptyElementToken(precedingTrivia)
End If
Return XmlMakeDivToken(precedingTrivia)
Case ">"c
Return XmlMakeGreaterToken(precedingTrivia)
Case "="c
Return XmlMakeEqualsToken(precedingTrivia)
Case "'"c, LEFT_SINGLE_QUOTATION_MARK, RIGHT_SINGLE_QUOTATION_MARK
Return XmlMakeSingleQuoteToken(precedingTrivia, c, isOpening:=True)
Case """"c, LEFT_DOUBLE_QUOTATION_MARK, RIGHT_DOUBLE_QUOTATION_MARK
Return XmlMakeDoubleQuoteToken(precedingTrivia, c, isOpening:=True)
Case "<"c
If CanGet(1) Then
Dim ch As Char = Peek(1)
Select Case ch
Case "!"c
If CanGet(2) Then
Select Case (Peek(2))
Case "-"c
If NextIs(3, "-"c) Then
Return XmlMakeBeginCommentToken(precedingTrivia, s_scanNoTriviaFunc)
End If
Case "["c
If NextAre(3, "CDATA[") Then
Return XmlMakeBeginCDataToken(precedingTrivia, s_scanNoTriviaFunc)
End If
Case "D"c
If NextAre(3, "OCTYPE") Then
Return XmlMakeBeginDTDToken(precedingTrivia)
End If
End Select
End If
Return XmlLessThanExclamationToken(state, precedingTrivia)
Case "?"c
Return XmlMakeBeginProcessingInstructionToken(precedingTrivia, s_scanNoTriviaFunc)
Case "/"c
Return XmlMakeBeginEndElementToken(precedingTrivia, s_scanNoTriviaFunc)
End Select
End If
Return XmlMakeLessToken(precedingTrivia)
Case "?"c
If NextIs(1, ">"c) Then
' // Create token for the '?>' termination sequence
Return XmlMakeEndProcessingInstructionToken(precedingTrivia)
End If
Return MakeQuestionToken(precedingTrivia, False)
Case "("c
Return XmlMakeLeftParenToken(precedingTrivia)
Case ")"c
Return XmlMakeRightParenToken(precedingTrivia)
Case "!"c,
";"c,
"#"c,
","c,
"}"c
Return XmlMakeBadToken(precedingTrivia, 1, ERRID.ERR_IllegalXmlNameChar)
Case ":"c
Return XmlMakeColonToken(precedingTrivia)
Case "["c
Return XmlMakeOpenBracketToken(state, precedingTrivia)
Case "]"c
Return XmlMakeCloseBracketToken(state, precedingTrivia)
Case Else
' // Because of weak scanning of QName, this state must always handle
' // '=' | '\'' | '"'| '/' | '>' | '<' | '?'
Return ScanXmlNcName(precedingTrivia)
End Select
End While
Return MakeEofToken(precedingTrivia)
End Function
'TODO: It makes sense to split Xml scanning functions that have XmlDoc functionality
' and place here (see ScanXmlContentInXmlDoc).
' may actually make it a derived XmlDocScanner class (consider caches).
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
'-----------------------------------------------------------------------------
' Contains scanner functionality related to XmlDoc comments
'-----------------------------------------------------------------------------
Option Compare Binary
Option Strict On
Imports Microsoft.CodeAnalysis.Syntax.InternalSyntax
Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts
Imports CoreInternalSyntax = Microsoft.CodeAnalysis.Syntax.InternalSyntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax
Partial Friend Class Scanner
Private _IsScanningXmlDoc As Boolean = False
Friend Property IsScanningXmlDoc As Boolean
Get
Return _IsScanningXmlDoc
End Get
Private Set(value As Boolean)
_IsScanningXmlDoc = value
End Set
End Property
''' <remarks>See description in TryScanXmlDocComment(...)</remarks>
Private _endOfXmlInsteadOfLastDocCommentLineBreak As Boolean
' bug 903247. First line should be treated in a special way.
Private _isStartingFirstXmlDocLine As Boolean = False
Private _doNotRequireXmlDocCommentPrefix As Boolean = False
Private ReadOnly Property ShouldReportXmlError As Boolean
Get
Return Not Me._IsScanningXmlDoc OrElse
Me._options.DocumentationMode = DocumentationMode.Diagnose
End Get
End Property
''' <summary>
''' This method is only to be used for parsing Cref and Name attributes as stand-alone entities
''' </summary>
Friend Sub ForceScanningXmlDocMode()
Me.IsScanningXmlDoc = True
Me._isStartingFirstXmlDocLine = False
Me._doNotRequireXmlDocCommentPrefix = True
End Sub
Private Function TryScanXmlDocComment(tList As SyntaxListBuilder) As Boolean
Debug.Assert(IsAtNewLine)
' leading whitespace until we see ''' should be regular whitespace
If CanGet() AndAlso IsWhitespace(Peek()) Then
Dim ws = ScanWhitespace()
tList.Add(ws)
End If
' SAVE the lookahead state and clear current token
#If DEBUG Then
Dim origPosition = _lineBufferOffset
#End If
Dim restorePoint = CreateRestorePoint()
' since we do not have lookahead tokens, this just
' resets current token to _lineBufferOffset
Me.GetNextTokenInState(ScannerState.Content)
Dim currentNonterminal = Me.GetCurrentSyntaxNode()
Dim docCommentSyntax = TryCast(currentNonterminal, DocumentationCommentTriviaSyntax)
' if we are lucky to get whole doc comment, we can just reuse it.
If docCommentSyntax IsNot Nothing Then
Me.MoveToNextSyntaxNodeInTrivia()
Else
Dim parser As New Parser(Me)
Me.IsScanningXmlDoc = True
Me._isStartingFirstXmlDocLine = True
' NOTE: Documentation comment syntax trivia must have at least one child xml node, because
' all the ['''] trivia are created as leading trivia for appropriate tokens.
' This means that we have to create at least one XmlText having trailing
' EOL to represent an empty documentation comment: ['''<eol>]
'
' The problem with this approach is that in presence of some errors (like
' not closed XML tags) we create missing tokens needed to represent the nodes
' *after* that last <eol> of the doc comment trivia, that means all the locations
' of created diagnostics will land on the first character of the next line
' after documentation comment
'
' To workaround this we parse XML nodes in two phases:
' - in the first phase we detect the last DocCommentLineBreak and create
' end-of-xml token instead; this should force all diagnostics to be
' reported on the next token location;
' - in the second phase we continue parsing XML nodes but don't create
' end-of-xml token which should just result in parsing one single node
' of XmlText type containing EOL;
' Then we merge the results and create resulting DocumentationCommentTrivia
' The first phase
Me._endOfXmlInsteadOfLastDocCommentLineBreak = True
Dim nodes = parser.ParseXmlContent(ScannerState.Content)
' The second phase
Me._endOfXmlInsteadOfLastDocCommentLineBreak = False
If nodes.Count = 0 AndAlso parser.CurrentToken.Kind = SyntaxKind.EndOfXmlToken Then
' This must be an empty documentation comment, we need to reset scanner so
' that the doc comment exterior trivia ([''']) lands on the final XmlNode
ResetLineBufferOffset()
restorePoint.RestoreTokens(includeLookAhead:=False)
Me._isStartingFirstXmlDocLine = True
End If
nodes = parser.ParseRestOfDocCommentContent(nodes)
Me.IsScanningXmlDoc = False
Debug.Assert(nodes.Any)
Debug.Assert(nodes(0).FullWidth > 0, "should at least get {'''EoL} ")
' restore _currentToken and lookahead,
' but keep offset and PP state
ResetLineBufferOffset()
docCommentSyntax = SyntaxFactory.DocumentationCommentTrivia(nodes)
If Me.Options.DocumentationMode < DocumentationMode.Diagnose Then
' All diagnostics coming from documentation comment are ignored
docCommentSyntax.ClearFlags(GreenNode.NodeFlags.ContainsDiagnostics)
End If
End If
' RESTORE lookahead state and current token if there were any
restorePoint.RestoreTokens(includeLookAhead:=True)
#If DEBUG Then
Debug.Assert(Me._lineBufferOffset = origPosition + docCommentSyntax.FullWidth OrElse
Me._endOfTerminatorTrivia = origPosition + docCommentSyntax.FullWidth)
#End If
tList.Add(docCommentSyntax)
Return True
End Function
' lexes (ws)'''
Private Function TrySkipXmlDocMarker(ByRef len As Integer) As Boolean
Dim Here = len
While CanGet(Here)
Dim c = Peek(Here)
If IsWhitespace(c) Then
Here += 1
Else
Exit While
End If
End While
If StartsXmlDoc(Here) Then
len = Here + 3
Return True
Else
Return False
End If
End Function
' scans (ws)'''
Private Function ScanXmlDocTrivia() As VisualBasicSyntaxNode
Debug.Assert(IsAtNewLine() OrElse _isStartingFirstXmlDocLine)
Dim len = 0
If TrySkipXmlDocMarker(len) Then
Return MakeDocumentationCommentExteriorTrivia(GetText(len))
Else
Return Nothing
End If
End Function
''' <summary>
''' Returns False if trivia ends line.
''' </summary>
Private Function ScanXmlTriviaInXmlDoc(c As Char, triviaList As SyntaxListBuilder(Of VisualBasicSyntaxNode)) As Boolean
Debug.Assert(IsScanningXmlDoc)
Debug.Assert(c = CARRIAGE_RETURN OrElse c = LINE_FEED OrElse c = " "c OrElse c = CHARACTER_TABULATION)
Dim len = 0
Do
If c = " "c OrElse c = CHARACTER_TABULATION Then
len += 1
ElseIf IsNewLine(c) Then
If len > 0 Then
triviaList.Add(MakeWhiteSpaceTrivia(GetText(len)))
len = 0
End If
' Only consume the end of line if the XML doc
' comment continues on the following line.
Dim offsets = CreateOffsetRestorePoint()
Dim endOfLineTrivia = ScanNewlineAsTrivia(c)
Dim ws = GetXmlWhitespaceLength(0)
If TrySkipXmlDocMarker(ws) Then
triviaList.Add(endOfLineTrivia)
triviaList.Add(MakeDocumentationCommentExteriorTrivia(GetText(ws)))
Else
offsets.Restore()
Return False
End If
Else
Exit Do
End If
c = Peek(len)
Loop
If len > 0 Then
triviaList.Add(MakeWhiteSpaceTrivia(GetText(len)))
End If
Return True
End Function
Private Function ScanXmlContentInXmlDoc() As SyntaxToken
Debug.Assert(IsScanningXmlDoc)
' // [14] CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*)
Dim precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) = Nothing
If IsAtNewLine() OrElse _isStartingFirstXmlDocLine Then
Dim xDocTrivia = ScanXmlDocTrivia()
_isStartingFirstXmlDocLine = False ' no longer starting
If xDocTrivia Is Nothing Then
Return MakeEofToken() ' XmlDoc lines must start with XmlDocTrivia
End If
precedingTrivia = New CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)(xDocTrivia)
End If
Dim Here As Integer = 0
Dim scratch = GetScratch()
While CanGet(Here)
Dim c As Char = Peek(Here)
Select Case (c)
Case CARRIAGE_RETURN, LINE_FEED
If Here <> 0 Then
Return XmlMakeTextLiteralToken(precedingTrivia, Here, scratch)
End If
Here = SkipLineBreak(c, Here)
If _endOfXmlInsteadOfLastDocCommentLineBreak Then
Dim tempHere As Integer = Here
If Not TrySkipXmlDocMarker(tempHere) Then
' NOTE: we need to reset the buffer so that precedingTrivia
' lands on the next token
ResetLineBufferOffset()
Return SyntaxFactory.Token(Nothing, SyntaxKind.EndOfXmlToken, Nothing, String.Empty)
End If
End If
' line breaks in Doc comments are separate tokens.
Return MakeDocCommentLineBreakToken(precedingTrivia, Here)
Case " "c, CHARACTER_TABULATION
scratch.Append(c)
Here += 1
Case "&"c
If Here <> 0 Then
Return XmlMakeTextLiteralToken(precedingTrivia, Here, scratch)
End If
Return ScanXmlReference(precedingTrivia)
Case "<"c
If Here <> 0 Then
Return XmlMakeTextLiteralToken(precedingTrivia, Here, scratch)
End If
Debug.Assert(Here = 0)
If CanGet(1) Then
Dim ch As Char = Peek(1)
Select Case ch
Case "!"c
If CanGet(2) Then
Select Case (Peek(2))
Case "-"c
If NextIs(3, "-"c) Then
Return XmlMakeBeginCommentToken(precedingTrivia, s_scanNoTriviaFunc)
End If
Case "["c
If NextAre(3, "CDATA[") Then
Return XmlMakeBeginCDataToken(precedingTrivia, s_scanNoTriviaFunc)
End If
Case "D"c
If NextAre(3, "OCTYPE") Then
Return XmlMakeBeginDTDToken(precedingTrivia)
End If
End Select
End If
Case "?"c
Return XmlMakeBeginProcessingInstructionToken(precedingTrivia, s_scanNoTriviaFunc)
Case "/"c
Return XmlMakeBeginEndElementToken(precedingTrivia, s_scanNoTriviaFunc)
End Select
End If
Return XmlMakeLessToken(precedingTrivia)
Case "]"c
If NextAre(Here + 1, "]>") Then
' // If valid characters found then return them.
If Here <> 0 Then
Return XmlMakeTextLiteralToken(precedingTrivia, Here, scratch)
End If
' // Create an invalid character data token for the illegal ']]>' sequence
Return XmlMakeTextLiteralToken(precedingTrivia, 3, ERRID.ERR_XmlEndCDataNotAllowedInContent)
End If
GoTo ScanChars
Case Else
ScanChars:
' // Check characters are valid
Dim xmlCh = ScanXmlChar(Here)
If xmlCh.Length = 0 Then
' bad char
If Here > 0 Then
Return XmlMakeTextLiteralToken(precedingTrivia, Here, scratch)
Else
Return XmlMakeBadToken(precedingTrivia, 1, ERRID.ERR_IllegalChar)
End If
End If
xmlCh.AppendTo(scratch)
Here += xmlCh.Length
End Select
End While
' no more chars
If Here > 0 Then
Return XmlMakeTextLiteralToken(precedingTrivia, Here, scratch)
Else
Return MakeEofToken(precedingTrivia)
End If
End Function
Friend Function ScanXmlPIDataInXmlDoc(state As ScannerState) As SyntaxToken
Debug.Assert(IsScanningXmlDoc)
' // Scan the PI data after the white space
' // [16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'
' // [17] PITarget ::= Name - (('X' | 'x') ('M' | 'm') ('L' | 'l'))
Debug.Assert(state = ScannerState.StartProcessingInstruction OrElse
state = ScannerState.ProcessingInstruction)
Dim precedingTrivia = _triviaListPool.Allocate(Of VisualBasicSyntaxNode)()
Dim result As SyntaxToken
If IsAtNewLine() Then
Dim xDocTrivia = ScanXmlDocTrivia()
If xDocTrivia Is Nothing Then
Return MakeEofToken() ' XmlDoc lines must start with XmlDocTrivia
End If
precedingTrivia.Add(xDocTrivia)
End If
If state = ScannerState.StartProcessingInstruction AndAlso CanGet() Then
' // Whitespace
' // S ::= (#x20 | #x9 | #xD | #xA)+
Dim c = Peek()
Select Case c
Case CARRIAGE_RETURN, LINE_FEED, " "c, CHARACTER_TABULATION
Dim offsets = CreateOffsetRestorePoint()
Dim continueLine = ScanXmlTriviaInXmlDoc(c, precedingTrivia)
If Not continueLine Then
offsets.Restore()
result = SyntaxFactory.Token(precedingTrivia.ToList.Node, SyntaxKind.EndOfXmlToken, Nothing, String.Empty)
GoTo CleanUp
End If
End Select
End If
Dim Here = 0
While CanGet(Here)
Dim c As Char = Peek(Here)
Select Case (c)
Case CARRIAGE_RETURN, LINE_FEED
result = XmlMakeProcessingInstructionToken(precedingTrivia.ToList, Here + LengthOfLineBreak(c, Here))
GoTo CleanUp
Case "?"c
If NextIs(Here + 1, ">"c) Then
'// If valid characters found then return them.
If Here <> 0 Then
result = XmlMakeProcessingInstructionToken(precedingTrivia.ToList, Here)
GoTo CleanUp
End If
' // Create token for the '?>' termination sequence
result = XmlMakeEndProcessingInstructionToken(precedingTrivia.ToList)
GoTo CleanUp
End If
GoTo ScanChars
Case Else
ScanChars:
Dim xmlCh = ScanXmlChar(Here)
If xmlCh.Length > 0 Then
Here += xmlCh.Length
Continue While
End If
' bad char
If Here <> 0 Then
result = XmlMakeProcessingInstructionToken(precedingTrivia.ToList, Here)
GoTo CleanUp
Else
result = XmlMakeBadToken(precedingTrivia.ToList, 1, ERRID.ERR_IllegalChar)
GoTo CleanUp
End If
End Select
End While
' no more chars
If Here > 0 Then
result = XmlMakeProcessingInstructionToken(precedingTrivia.ToList, Here)
Else
result = MakeEofToken(precedingTrivia.ToList)
End If
CleanUp:
_triviaListPool.Free(precedingTrivia)
Return result
End Function
Private Function ScanXmlElementInXmlDoc(state As ScannerState) As SyntaxToken
Debug.Assert(IsScanningXmlDoc)
' // Only legal tokens
' // QName
' // /
' // >
' // =
' // Whitespace
Dim precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) = Nothing
If IsAtNewLine() AndAlso Not Me._doNotRequireXmlDocCommentPrefix Then
Dim xDocTrivia = ScanXmlDocTrivia()
If xDocTrivia Is Nothing Then
Return MakeEofToken() ' XmlDoc lines must start with XmlDocTrivia
End If
precedingTrivia = New CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)(xDocTrivia)
End If
While CanGet()
If Not precedingTrivia.Any AndAlso IsAtNewLine() AndAlso Not Me._doNotRequireXmlDocCommentPrefix Then
' this would indicate that we looked at Trivia, but did not find
' XmlDoc prefix (or we would not be at the line start)
' must terminate XmlDoc scanning
Return MakeEofToken(precedingTrivia)
End If
Dim c As Char = Peek()
Select Case (c)
' // Whitespace
' // S ::= (#x20 | #x9 | #xD | #xA)+
Case CARRIAGE_RETURN, LINE_FEED, " "c, CHARACTER_TABULATION
' we should not visit this place twice
Debug.Assert(Not precedingTrivia.Any)
Dim offsets = CreateOffsetRestorePoint()
Dim triviaList = _triviaListPool.Allocate(Of VisualBasicSyntaxNode)()
Dim continueLine = ScanXmlTriviaInXmlDoc(c, triviaList)
precedingTrivia = triviaList.ToList()
_triviaListPool.Free(triviaList)
If Not continueLine Then
offsets.Restore()
Return SyntaxFactory.Token(precedingTrivia.Node, SyntaxKind.EndOfXmlToken, Nothing, String.Empty)
End If
Case "/"c
If NextIs(1, ">"c) Then
Return XmlMakeEndEmptyElementToken(precedingTrivia)
End If
Return XmlMakeDivToken(precedingTrivia)
Case ">"c
Return XmlMakeGreaterToken(precedingTrivia)
Case "="c
Return XmlMakeEqualsToken(precedingTrivia)
Case "'"c, LEFT_SINGLE_QUOTATION_MARK, RIGHT_SINGLE_QUOTATION_MARK
Return XmlMakeSingleQuoteToken(precedingTrivia, c, isOpening:=True)
Case """"c, LEFT_DOUBLE_QUOTATION_MARK, RIGHT_DOUBLE_QUOTATION_MARK
Return XmlMakeDoubleQuoteToken(precedingTrivia, c, isOpening:=True)
Case "<"c
If CanGet(1) Then
Dim ch As Char = Peek(1)
Select Case ch
Case "!"c
If CanGet(2) Then
Select Case (Peek(2))
Case "-"c
If NextIs(3, "-"c) Then
Return XmlMakeBeginCommentToken(precedingTrivia, s_scanNoTriviaFunc)
End If
Case "["c
If NextAre(3, "CDATA[") Then
Return XmlMakeBeginCDataToken(precedingTrivia, s_scanNoTriviaFunc)
End If
Case "D"c
If NextAre(3, "OCTYPE") Then
Return XmlMakeBeginDTDToken(precedingTrivia)
End If
End Select
End If
Return XmlLessThanExclamationToken(state, precedingTrivia)
Case "?"c
Return XmlMakeBeginProcessingInstructionToken(precedingTrivia, s_scanNoTriviaFunc)
Case "/"c
Return XmlMakeBeginEndElementToken(precedingTrivia, s_scanNoTriviaFunc)
End Select
End If
Return XmlMakeLessToken(precedingTrivia)
Case "?"c
If NextIs(1, ">"c) Then
' // Create token for the '?>' termination sequence
Return XmlMakeEndProcessingInstructionToken(precedingTrivia)
End If
Return MakeQuestionToken(precedingTrivia, False)
Case "("c
Return XmlMakeLeftParenToken(precedingTrivia)
Case ")"c
Return XmlMakeRightParenToken(precedingTrivia)
Case "!"c,
";"c,
"#"c,
","c,
"}"c
Return XmlMakeBadToken(precedingTrivia, 1, ERRID.ERR_IllegalXmlNameChar)
Case ":"c
Return XmlMakeColonToken(precedingTrivia)
Case "["c
Return XmlMakeOpenBracketToken(state, precedingTrivia)
Case "]"c
Return XmlMakeCloseBracketToken(state, precedingTrivia)
Case Else
' // Because of weak scanning of QName, this state must always handle
' // '=' | '\'' | '"'| '/' | '>' | '<' | '?'
Return ScanXmlNcName(precedingTrivia)
End Select
End While
Return MakeEofToken(precedingTrivia)
End Function
'TODO: It makes sense to split Xml scanning functions that have XmlDoc functionality
' and place here (see ScanXmlContentInXmlDoc).
' may actually make it a derived XmlDocScanner class (consider caches).
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Compilers/CSharp/Test/Symbol/Symbols/Source/TypeMapTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class TypeMapTests : CSharpTestBase
{
// take a type of the form Something<X> and return the type X.
private TypeSymbol TypeArg(TypeSymbol t)
{
var nts = t as NamedTypeSymbol;
Assert.NotNull(nts);
Assert.Equal(1, nts.Arity);
return nts.TypeArguments()[0];
}
[Fact]
public void TestMap1()
{
var text =
@"
public class Box<T> {}
public class A<T> {
public class TBox : Box<T> {}
public class B<U> {
public class TBox : Box<T> {}
public class UBox : Box<U> {}
public class C {
public class TBox : Box<T> {}
public class UBox : Box<U> {}
}
}
}
public class E {}
public class F {}
public class Top : A<E> { // base is A<E>
public class BF : B<F> {} // base is A<E>.B<F>
}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var at = global.GetTypeMembers("A", 1).Single(); // A<T>
var t = at.TypeParameters[0];
Assert.Equal(t, TypeArg(at.GetTypeMembers("TBox", 0).Single().BaseType()));
var atbu = at.GetTypeMembers("B", 1).Single(); // A<T>.B<U>
var u = atbu.TypeParameters[0];
var c = atbu.GetTypeMembers("C", 0).Single(); // A<T>.B<U>.C
Assert.Equal(atbu, c.ContainingType);
Assert.Equal(u, TypeArg(c.ContainingType));
Assert.Equal(at, c.ContainingType.ContainingType);
Assert.Equal(t, TypeArg(c.ContainingType.ContainingType));
var e = global.GetTypeMembers("E", 0).Single(); // E
var f = global.GetTypeMembers("F", 0).Single(); // F
var top = global.GetTypeMembers("Top", 0).Single(); // Top
var ae = top.BaseType(); // A<E>
Assert.Equal(at, ae.OriginalDefinition);
Assert.Equal(at, at.ConstructedFrom);
Assert.Equal(e, TypeArg(ae));
var bf = top.GetTypeMembers("BF", 0).Single(); // Top.BF
Assert.Equal(top, bf.ContainingType);
var aebf = bf.BaseType();
Assert.Equal(f, TypeArg(aebf));
Assert.Equal(ae, aebf.ContainingType);
var aebfc = aebf.GetTypeMembers("C", 0).Single(); // A<E>.B<F>.C
Assert.Equal(c, aebfc.OriginalDefinition);
Assert.NotEqual(c, aebfc.ConstructedFrom);
Assert.Equal(f, TypeArg(aebfc.ContainingType));
Assert.Equal(e, TypeArg(aebfc.ContainingType.ContainingType));
Assert.Equal(e, TypeArg(aebfc.GetTypeMembers("TBox", 0).Single().BaseType()));
Assert.Equal(f, TypeArg(aebfc.GetTypeMembers("UBox", 0).Single().BaseType())); // exercises alpha-renaming.
Assert.Equal(aebfc, DeepConstruct(c, ImmutableArray.Create<TypeSymbol>(e, f))); // exercise DeepConstruct
}
/// <summary>
/// Returns a constructed type given the type it is constructed from and type arguments for its enclosing types and itself.
/// </summary>
/// <param name="typeArguments">the type arguments that will replace the type parameters, starting with those for enclosing types</param>
/// <returns></returns>
private static NamedTypeSymbol DeepConstruct(NamedTypeSymbol type, ImmutableArray<TypeSymbol> typeArguments)
{
Assert.True(type.IsDefinition);
var allTypeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance();
type.GetAllTypeParameters(allTypeParameters);
return new TypeMap(allTypeParameters.ToImmutableAndFree(), typeArguments.SelectAsArray(t => TypeWithAnnotations.Create(t))).SubstituteNamedType(type);
}
[Fact]
public void ConstructedError()
{
var text =
@"
class C
{
NonExistentType<int> field;
}
";
var tree = Parse(text);
var comp = CreateCompilation(tree);
var global = comp.GlobalNamespace;
var c = global.GetTypeMembers("C", 0).Single() as NamedTypeSymbol;
var field = c.GetMembers("field").Single() as FieldSymbol;
var neti = field.Type as NamedTypeSymbol;
Assert.Equal(SpecialType.System_Int32, neti.TypeArguments()[0].SpecialType);
}
[Fact]
public void Generics4()
{
string source = @"
class C1<C1T1, C1T2>
{
public class C2<C2T1, C2T2>
{
public class C3<C3T1, C3T2>
{
public C1<int, C3T2>.C2<byte, C3T2>.C3<char, C3T2> V1;
}
}
}
";
var compilation = CreateCompilation(source);
var _int = compilation.GetSpecialType(SpecialType.System_Int32);
var _byte = compilation.GetSpecialType(SpecialType.System_Byte);
var _char = compilation.GetSpecialType(SpecialType.System_Char);
var C1 = compilation.GetTypeByMetadataName("C1`2");
var c1OfByteChar = C1.Construct(_byte, _char);
Assert.Equal("C1<System.Byte, System.Char>", c1OfByteChar.ToTestDisplayString());
var c1OfByteChar_c2 = (NamedTypeSymbol)(c1OfByteChar.GetMembers()[0]);
var c1OfByteChar_c2OfIntInt = c1OfByteChar_c2.Construct(_int, _int);
Assert.Equal("C1<System.Byte, System.Char>.C2<System.Int32, System.Int32>", c1OfByteChar_c2OfIntInt.ToTestDisplayString());
var c1OfByteChar_c2OfIntInt_c3 = (NamedTypeSymbol)(c1OfByteChar_c2OfIntInt.GetMembers()[0]);
var c1OfByteChar_c2OfIntInt_c3OfIntByte = c1OfByteChar_c2OfIntInt_c3.Construct(_int, _byte);
Assert.Equal("C1<System.Byte, System.Char>.C2<System.Int32, System.Int32>.C3<System.Int32, System.Byte>", c1OfByteChar_c2OfIntInt_c3OfIntByte.ToTestDisplayString());
var v1 = c1OfByteChar_c2OfIntInt_c3OfIntByte.GetMembers().OfType<FieldSymbol>().First();
var type = v1.TypeWithAnnotations;
Assert.Equal("C1<System.Int32, System.Byte>.C2<System.Byte, System.Byte>.C3<System.Char, System.Byte>", type.Type.ToTestDisplayString());
}
[Fact]
public void Generics5()
{
string source = @"
class C1<C1T1, C1T2>
{
public class C2<C2T1, C2T2>
{
public class C3<C3T1, C3T2>
{
public C1<int, C3T2>.C2<byte, C3T2>.C3<char, C3T2> V1;
}
}
}
";
var compilation = CreateCompilation(source);
var _int = compilation.GetSpecialType(SpecialType.System_Int32);
var _byte = compilation.GetSpecialType(SpecialType.System_Byte);
var _char = compilation.GetSpecialType(SpecialType.System_Char);
var C1 = compilation.GetTypeByMetadataName("C1`2");
var c1OfByteChar = C1.Construct(_byte, _char);
Assert.Equal("C1<System.Byte, System.Char>", c1OfByteChar.ToTestDisplayString());
var c1OfByteChar_c2 = (NamedTypeSymbol)(c1OfByteChar.GetMembers()[0]);
Assert.Throws<ArgumentException>(() =>
{
var c1OfByteChar_c2OfIntInt = c1OfByteChar_c2.Construct(_byte, _char, _int, _int);
});
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class TypeMapTests : CSharpTestBase
{
// take a type of the form Something<X> and return the type X.
private TypeSymbol TypeArg(TypeSymbol t)
{
var nts = t as NamedTypeSymbol;
Assert.NotNull(nts);
Assert.Equal(1, nts.Arity);
return nts.TypeArguments()[0];
}
[Fact]
public void TestMap1()
{
var text =
@"
public class Box<T> {}
public class A<T> {
public class TBox : Box<T> {}
public class B<U> {
public class TBox : Box<T> {}
public class UBox : Box<U> {}
public class C {
public class TBox : Box<T> {}
public class UBox : Box<U> {}
}
}
}
public class E {}
public class F {}
public class Top : A<E> { // base is A<E>
public class BF : B<F> {} // base is A<E>.B<F>
}
";
var comp = CreateEmptyCompilation(text);
var global = comp.GlobalNamespace;
var at = global.GetTypeMembers("A", 1).Single(); // A<T>
var t = at.TypeParameters[0];
Assert.Equal(t, TypeArg(at.GetTypeMembers("TBox", 0).Single().BaseType()));
var atbu = at.GetTypeMembers("B", 1).Single(); // A<T>.B<U>
var u = atbu.TypeParameters[0];
var c = atbu.GetTypeMembers("C", 0).Single(); // A<T>.B<U>.C
Assert.Equal(atbu, c.ContainingType);
Assert.Equal(u, TypeArg(c.ContainingType));
Assert.Equal(at, c.ContainingType.ContainingType);
Assert.Equal(t, TypeArg(c.ContainingType.ContainingType));
var e = global.GetTypeMembers("E", 0).Single(); // E
var f = global.GetTypeMembers("F", 0).Single(); // F
var top = global.GetTypeMembers("Top", 0).Single(); // Top
var ae = top.BaseType(); // A<E>
Assert.Equal(at, ae.OriginalDefinition);
Assert.Equal(at, at.ConstructedFrom);
Assert.Equal(e, TypeArg(ae));
var bf = top.GetTypeMembers("BF", 0).Single(); // Top.BF
Assert.Equal(top, bf.ContainingType);
var aebf = bf.BaseType();
Assert.Equal(f, TypeArg(aebf));
Assert.Equal(ae, aebf.ContainingType);
var aebfc = aebf.GetTypeMembers("C", 0).Single(); // A<E>.B<F>.C
Assert.Equal(c, aebfc.OriginalDefinition);
Assert.NotEqual(c, aebfc.ConstructedFrom);
Assert.Equal(f, TypeArg(aebfc.ContainingType));
Assert.Equal(e, TypeArg(aebfc.ContainingType.ContainingType));
Assert.Equal(e, TypeArg(aebfc.GetTypeMembers("TBox", 0).Single().BaseType()));
Assert.Equal(f, TypeArg(aebfc.GetTypeMembers("UBox", 0).Single().BaseType())); // exercises alpha-renaming.
Assert.Equal(aebfc, DeepConstruct(c, ImmutableArray.Create<TypeSymbol>(e, f))); // exercise DeepConstruct
}
/// <summary>
/// Returns a constructed type given the type it is constructed from and type arguments for its enclosing types and itself.
/// </summary>
/// <param name="typeArguments">the type arguments that will replace the type parameters, starting with those for enclosing types</param>
/// <returns></returns>
private static NamedTypeSymbol DeepConstruct(NamedTypeSymbol type, ImmutableArray<TypeSymbol> typeArguments)
{
Assert.True(type.IsDefinition);
var allTypeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance();
type.GetAllTypeParameters(allTypeParameters);
return new TypeMap(allTypeParameters.ToImmutableAndFree(), typeArguments.SelectAsArray(t => TypeWithAnnotations.Create(t))).SubstituteNamedType(type);
}
[Fact]
public void ConstructedError()
{
var text =
@"
class C
{
NonExistentType<int> field;
}
";
var tree = Parse(text);
var comp = CreateCompilation(tree);
var global = comp.GlobalNamespace;
var c = global.GetTypeMembers("C", 0).Single() as NamedTypeSymbol;
var field = c.GetMembers("field").Single() as FieldSymbol;
var neti = field.Type as NamedTypeSymbol;
Assert.Equal(SpecialType.System_Int32, neti.TypeArguments()[0].SpecialType);
}
[Fact]
public void Generics4()
{
string source = @"
class C1<C1T1, C1T2>
{
public class C2<C2T1, C2T2>
{
public class C3<C3T1, C3T2>
{
public C1<int, C3T2>.C2<byte, C3T2>.C3<char, C3T2> V1;
}
}
}
";
var compilation = CreateCompilation(source);
var _int = compilation.GetSpecialType(SpecialType.System_Int32);
var _byte = compilation.GetSpecialType(SpecialType.System_Byte);
var _char = compilation.GetSpecialType(SpecialType.System_Char);
var C1 = compilation.GetTypeByMetadataName("C1`2");
var c1OfByteChar = C1.Construct(_byte, _char);
Assert.Equal("C1<System.Byte, System.Char>", c1OfByteChar.ToTestDisplayString());
var c1OfByteChar_c2 = (NamedTypeSymbol)(c1OfByteChar.GetMembers()[0]);
var c1OfByteChar_c2OfIntInt = c1OfByteChar_c2.Construct(_int, _int);
Assert.Equal("C1<System.Byte, System.Char>.C2<System.Int32, System.Int32>", c1OfByteChar_c2OfIntInt.ToTestDisplayString());
var c1OfByteChar_c2OfIntInt_c3 = (NamedTypeSymbol)(c1OfByteChar_c2OfIntInt.GetMembers()[0]);
var c1OfByteChar_c2OfIntInt_c3OfIntByte = c1OfByteChar_c2OfIntInt_c3.Construct(_int, _byte);
Assert.Equal("C1<System.Byte, System.Char>.C2<System.Int32, System.Int32>.C3<System.Int32, System.Byte>", c1OfByteChar_c2OfIntInt_c3OfIntByte.ToTestDisplayString());
var v1 = c1OfByteChar_c2OfIntInt_c3OfIntByte.GetMembers().OfType<FieldSymbol>().First();
var type = v1.TypeWithAnnotations;
Assert.Equal("C1<System.Int32, System.Byte>.C2<System.Byte, System.Byte>.C3<System.Char, System.Byte>", type.Type.ToTestDisplayString());
}
[Fact]
public void Generics5()
{
string source = @"
class C1<C1T1, C1T2>
{
public class C2<C2T1, C2T2>
{
public class C3<C3T1, C3T2>
{
public C1<int, C3T2>.C2<byte, C3T2>.C3<char, C3T2> V1;
}
}
}
";
var compilation = CreateCompilation(source);
var _int = compilation.GetSpecialType(SpecialType.System_Int32);
var _byte = compilation.GetSpecialType(SpecialType.System_Byte);
var _char = compilation.GetSpecialType(SpecialType.System_Char);
var C1 = compilation.GetTypeByMetadataName("C1`2");
var c1OfByteChar = C1.Construct(_byte, _char);
Assert.Equal("C1<System.Byte, System.Char>", c1OfByteChar.ToTestDisplayString());
var c1OfByteChar_c2 = (NamedTypeSymbol)(c1OfByteChar.GetMembers()[0]);
Assert.Throws<ArgumentException>(() =>
{
var c1OfByteChar_c2OfIntInt = c1OfByteChar_c2.Construct(_byte, _char, _int, _int);
});
}
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/VisualStudio/Core/Def/Storage/ProjectContainerKeyCache.cs | // Licensed to the .NET Foundation under one or more 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.Runtime.CompilerServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.PersistentStorage;
using Microsoft.VisualStudio.RpcContracts.Caching;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Storage
{
/// <summary>
/// Cache of our own internal roslyn storage keys to the equivalent platform cloud cache keys. Cloud cache keys can
/// store a lot of date in them (like their 'dimensions' dictionary. We don't want to continually recreate these as
/// we read/write date to the db.
/// </summary>
internal class ProjectContainerKeyCache
{
private static readonly ImmutableSortedDictionary<string, string?> EmptyDimensions = ImmutableSortedDictionary.Create<string, string?>(StringComparer.Ordinal);
/// <summary>
/// Container key explicitly for the project itself.
/// </summary>
public readonly CacheContainerKey? ProjectContainerKey;
/// <summary>
/// Cache from document green nodes to the container keys we've computed for it. We can avoid computing these
/// container keys when called repeatedly for the same documents.
/// </summary>
/// <remarks>
/// We can use a normal Dictionary here instead of a <see cref="ConditionalWeakTable{TKey, TValue}"/> as
/// instances of <see cref="ProjectContainerKeyCache"/> are always owned in a context where the <see
/// cref="ProjectState"/> is alive. As that instance is alive, all <see cref="TextDocumentState"/>s the project
/// points at will be held alive strongly too.
/// </remarks>
private readonly Dictionary<TextDocumentState, CacheContainerKey?> _documentToContainerKey = new();
private readonly Func<TextDocumentState, CacheContainerKey?> _documentToContainerKeyCallback;
public ProjectContainerKeyCache(string relativePathBase, ProjectKey projectKey)
{
ProjectContainerKey = CreateProjectContainerKey(relativePathBase, projectKey);
_documentToContainerKeyCallback = ds => CreateDocumentContainerKey(relativePathBase, DocumentKey.ToDocumentKey(projectKey, ds));
}
public CacheContainerKey? GetDocumentContainerKey(TextDocumentState state)
{
lock (_documentToContainerKey)
return _documentToContainerKey.GetOrAdd(state, _documentToContainerKeyCallback);
}
public static CacheContainerKey? CreateProjectContainerKey(
string relativePathBase, ProjectKey projectKey)
{
// Creates a container key for this project. The container key is a mix of the project's name, relative
// file path (to the solution), and optional parse options.
// If we don't have a valid solution path, we can't store anything.
if (string.IsNullOrEmpty(relativePathBase))
return null;
// We have to have a file path for this project
if (RoslynString.IsNullOrEmpty(projectKey.FilePath))
return null;
// The file path has to be relative to the base path the DB is associated with (either the solution-path or
// repo-path).
var relativePath = PathUtilities.GetRelativePath(relativePathBase, projectKey.FilePath!);
if (relativePath == projectKey.FilePath)
return null;
var dimensions = EmptyDimensions
.Add($"{nameof(ProjectKey)}.{nameof(ProjectKey.Name)}", projectKey.Name)
.Add($"{nameof(ProjectKey)}.{nameof(ProjectKey.FilePath)}", relativePath)
.Add($"{nameof(ProjectKey)}.{nameof(ProjectKey.ParseOptionsChecksum)}", projectKey.ParseOptionsChecksum.ToString());
return new CacheContainerKey("Roslyn.Project", dimensions);
}
public static CacheContainerKey? CreateDocumentContainerKey(
string relativePathBase,
DocumentKey documentKey)
{
// See if we can get a project key for this info. If not, we def can't get a doc key.
var projectContainerKey = CreateProjectContainerKey(relativePathBase, documentKey.Project);
if (projectContainerKey == null)
return null;
// We have to have a file path for this document
if (string.IsNullOrEmpty(documentKey.FilePath))
return null;
// The file path has to be relative to the base path the DB is associated with (either the solution-path or
// repo-path).
var relativePath = PathUtilities.GetRelativePath(relativePathBase, documentKey.FilePath!);
if (relativePath == documentKey.FilePath)
return null;
var dimensions = projectContainerKey.Value.Dimensions
.Add($"{nameof(DocumentKey)}.{nameof(DocumentKey.Name)}", documentKey.Name)
.Add($"{nameof(DocumentKey)}.{nameof(DocumentKey.FilePath)}", relativePath);
return new CacheContainerKey("Roslyn.Document", dimensions);
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Runtime.CompilerServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.PersistentStorage;
using Microsoft.VisualStudio.RpcContracts.Caching;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Storage
{
/// <summary>
/// Cache of our own internal roslyn storage keys to the equivalent platform cloud cache keys. Cloud cache keys can
/// store a lot of date in them (like their 'dimensions' dictionary. We don't want to continually recreate these as
/// we read/write date to the db.
/// </summary>
internal class ProjectContainerKeyCache
{
private static readonly ImmutableSortedDictionary<string, string?> EmptyDimensions = ImmutableSortedDictionary.Create<string, string?>(StringComparer.Ordinal);
/// <summary>
/// Container key explicitly for the project itself.
/// </summary>
public readonly CacheContainerKey? ProjectContainerKey;
/// <summary>
/// Cache from document green nodes to the container keys we've computed for it. We can avoid computing these
/// container keys when called repeatedly for the same documents.
/// </summary>
/// <remarks>
/// We can use a normal Dictionary here instead of a <see cref="ConditionalWeakTable{TKey, TValue}"/> as
/// instances of <see cref="ProjectContainerKeyCache"/> are always owned in a context where the <see
/// cref="ProjectState"/> is alive. As that instance is alive, all <see cref="TextDocumentState"/>s the project
/// points at will be held alive strongly too.
/// </remarks>
private readonly Dictionary<TextDocumentState, CacheContainerKey?> _documentToContainerKey = new();
private readonly Func<TextDocumentState, CacheContainerKey?> _documentToContainerKeyCallback;
public ProjectContainerKeyCache(string relativePathBase, ProjectKey projectKey)
{
ProjectContainerKey = CreateProjectContainerKey(relativePathBase, projectKey);
_documentToContainerKeyCallback = ds => CreateDocumentContainerKey(relativePathBase, DocumentKey.ToDocumentKey(projectKey, ds));
}
public CacheContainerKey? GetDocumentContainerKey(TextDocumentState state)
{
lock (_documentToContainerKey)
return _documentToContainerKey.GetOrAdd(state, _documentToContainerKeyCallback);
}
public static CacheContainerKey? CreateProjectContainerKey(
string relativePathBase, ProjectKey projectKey)
{
// Creates a container key for this project. The container key is a mix of the project's name, relative
// file path (to the solution), and optional parse options.
// If we don't have a valid solution path, we can't store anything.
if (string.IsNullOrEmpty(relativePathBase))
return null;
// We have to have a file path for this project
if (RoslynString.IsNullOrEmpty(projectKey.FilePath))
return null;
// The file path has to be relative to the base path the DB is associated with (either the solution-path or
// repo-path).
var relativePath = PathUtilities.GetRelativePath(relativePathBase, projectKey.FilePath!);
if (relativePath == projectKey.FilePath)
return null;
var dimensions = EmptyDimensions
.Add($"{nameof(ProjectKey)}.{nameof(ProjectKey.Name)}", projectKey.Name)
.Add($"{nameof(ProjectKey)}.{nameof(ProjectKey.FilePath)}", relativePath)
.Add($"{nameof(ProjectKey)}.{nameof(ProjectKey.ParseOptionsChecksum)}", projectKey.ParseOptionsChecksum.ToString());
return new CacheContainerKey("Roslyn.Project", dimensions);
}
public static CacheContainerKey? CreateDocumentContainerKey(
string relativePathBase,
DocumentKey documentKey)
{
// See if we can get a project key for this info. If not, we def can't get a doc key.
var projectContainerKey = CreateProjectContainerKey(relativePathBase, documentKey.Project);
if (projectContainerKey == null)
return null;
// We have to have a file path for this document
if (string.IsNullOrEmpty(documentKey.FilePath))
return null;
// The file path has to be relative to the base path the DB is associated with (either the solution-path or
// repo-path).
var relativePath = PathUtilities.GetRelativePath(relativePathBase, documentKey.FilePath!);
if (relativePath == documentKey.FilePath)
return null;
var dimensions = projectContainerKey.Value.Dimensions
.Add($"{nameof(DocumentKey)}.{nameof(DocumentKey.Name)}", documentKey.Name)
.Add($"{nameof(DocumentKey)}.{nameof(DocumentKey.FilePath)}", relativePath);
return new CacheContainerKey("Roslyn.Document", dimensions);
}
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Analyzers/CSharp/Tests/SimplifyLinqExpression/CSharpSimplifyLinqExpressionFixAllTests.cs | // Licensed to the .NET Foundation under one or more 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.Tasks;
using Microsoft.CodeAnalysis.CSharp.SimplifyLinqExpression;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.Analyzers.UnitTests.SimplifyLinqExpression
{
using VerifyCS = CSharpCodeFixVerifier<
CSharpSimplifyLinqExpressionDiagnosticAnalyzer,
CSharpSimplifyLinqExpressionCodeFixProvider>;
public partial class CSharpSimplifyLinqExpressionTests
{
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task FixAllInDocument()
{
await new VerifyCS.Test
{
TestCode = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
static void M()
{
IEnumerable<string> test = new List<string> { ""hello"", ""world"", ""!"" };
var test1 = [|test.Where(x => x.Equals('!')).Any()|];
var test2 = [|test.Where(x => x.Equals('!')).SingleOrDefault()|];
var test3 = [|test.Where(x => x.Equals('!')).Last()|];
var test4 = [|test.Where(x => x.Equals('!')).Count()|];
var test5 = [|test.Where(x => x.Equals('!')).FirstOrDefault()|];
}
}",
FixedCode = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
static void M()
{
IEnumerable<string> test = new List<string> { ""hello"", ""world"", ""!"" };
var test1 = test.Any(x => x.Equals('!'));
var test2 = test.SingleOrDefault(x => x.Equals('!'));
var test3 = test.Last(x => x.Equals('!'));
var test4 = test.Count(x => x.Equals('!'));
var test5 = test.FirstOrDefault(x => x.Equals('!'));
}
}",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task FixAllInDocumentExplicitCall()
{
var testCode = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
static void M()
{
IEnumerable<string> test = new List<string> { ""hello"", ""world"", ""!"" };
var test1 = [|Enumerable.Where(test, x => x.Equals(""!"")).Any()|];
var test2 = [|Enumerable.Where(test, x => x.Equals(""!"")).SingleOrDefault()|];
var test3 = [|Enumerable.Where(test, x => x.Equals(""!"")).Last()|];
var test4 = [|Enumerable.Where(test, x => x.Equals(""!"")).Count()|];
var test5 = [|Enumerable.Where(test, x => x.Equals(""!"")).FirstOrDefault()|];
}
}";
var fixedCode = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
static void M()
{
IEnumerable<string> test = new List<string> { ""hello"", ""world"", ""!"" };
var test1 = Enumerable.Any(test, x => x.Equals(""!""));
var test2 = Enumerable.SingleOrDefault(test, x => x.Equals(""!""));
var test3 = Enumerable.Last(test, x => x.Equals(""!""));
var test4 = Enumerable.Count(test, x => x.Equals(""!""));
var test5 = Enumerable.FirstOrDefault(test, x => x.Equals(""!""));
}
}";
await VerifyCS.VerifyCodeFixAsync(testCode, fixedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task NestedInDocument()
{
await new VerifyCS.Test
{
TestCode = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
static void M()
{
var test = new List<string> { ""hello"", ""world"", ""!"" };
var test1 = [|test.Where(x => x.Equals('!')).Any()|];
var test2 = [|test.Where(x => x.Equals('!')).SingleOrDefault()|];
var test3 = [|test.Where(x => x.Equals('!')).Last()|];
var test4 = test.Where(x => x.Equals('!')).Count();
var test5 = from x in test where x.Equals('!') select x;
var test6 = [|test.Where(a => [|a.Where(s => s.Equals(""hello"")).FirstOrDefault()|].Equals(""hello"")).FirstOrDefault()|];
}
}",
FixedCode = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
static void M()
{
var test = new List<string> { ""hello"", ""world"", ""!"" };
var test1 = test.Any(x => x.Equals('!'));
var test2 = test.SingleOrDefault(x => x.Equals('!'));
var test3 = test.Last(x => x.Equals('!'));
var test4 = test.Where(x => x.Equals('!')).Count();
var test5 = from x in test where x.Equals('!') select x;
var test6 = test.FirstOrDefault(a => a.FirstOrDefault(s => s.Equals(""hello"")).Equals(""hello""));
}
}",
}.RunAsync();
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Tasks;
using Microsoft.CodeAnalysis.CSharp.SimplifyLinqExpression;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.Analyzers.UnitTests.SimplifyLinqExpression
{
using VerifyCS = CSharpCodeFixVerifier<
CSharpSimplifyLinqExpressionDiagnosticAnalyzer,
CSharpSimplifyLinqExpressionCodeFixProvider>;
public partial class CSharpSimplifyLinqExpressionTests
{
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task FixAllInDocument()
{
await new VerifyCS.Test
{
TestCode = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
static void M()
{
IEnumerable<string> test = new List<string> { ""hello"", ""world"", ""!"" };
var test1 = [|test.Where(x => x.Equals('!')).Any()|];
var test2 = [|test.Where(x => x.Equals('!')).SingleOrDefault()|];
var test3 = [|test.Where(x => x.Equals('!')).Last()|];
var test4 = [|test.Where(x => x.Equals('!')).Count()|];
var test5 = [|test.Where(x => x.Equals('!')).FirstOrDefault()|];
}
}",
FixedCode = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
static void M()
{
IEnumerable<string> test = new List<string> { ""hello"", ""world"", ""!"" };
var test1 = test.Any(x => x.Equals('!'));
var test2 = test.SingleOrDefault(x => x.Equals('!'));
var test3 = test.Last(x => x.Equals('!'));
var test4 = test.Count(x => x.Equals('!'));
var test5 = test.FirstOrDefault(x => x.Equals('!'));
}
}",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task FixAllInDocumentExplicitCall()
{
var testCode = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
static void M()
{
IEnumerable<string> test = new List<string> { ""hello"", ""world"", ""!"" };
var test1 = [|Enumerable.Where(test, x => x.Equals(""!"")).Any()|];
var test2 = [|Enumerable.Where(test, x => x.Equals(""!"")).SingleOrDefault()|];
var test3 = [|Enumerable.Where(test, x => x.Equals(""!"")).Last()|];
var test4 = [|Enumerable.Where(test, x => x.Equals(""!"")).Count()|];
var test5 = [|Enumerable.Where(test, x => x.Equals(""!"")).FirstOrDefault()|];
}
}";
var fixedCode = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
static void M()
{
IEnumerable<string> test = new List<string> { ""hello"", ""world"", ""!"" };
var test1 = Enumerable.Any(test, x => x.Equals(""!""));
var test2 = Enumerable.SingleOrDefault(test, x => x.Equals(""!""));
var test3 = Enumerable.Last(test, x => x.Equals(""!""));
var test4 = Enumerable.Count(test, x => x.Equals(""!""));
var test5 = Enumerable.FirstOrDefault(test, x => x.Equals(""!""));
}
}";
await VerifyCS.VerifyCodeFixAsync(testCode, fixedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task NestedInDocument()
{
await new VerifyCS.Test
{
TestCode = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
static void M()
{
var test = new List<string> { ""hello"", ""world"", ""!"" };
var test1 = [|test.Where(x => x.Equals('!')).Any()|];
var test2 = [|test.Where(x => x.Equals('!')).SingleOrDefault()|];
var test3 = [|test.Where(x => x.Equals('!')).Last()|];
var test4 = test.Where(x => x.Equals('!')).Count();
var test5 = from x in test where x.Equals('!') select x;
var test6 = [|test.Where(a => [|a.Where(s => s.Equals(""hello"")).FirstOrDefault()|].Equals(""hello"")).FirstOrDefault()|];
}
}",
FixedCode = @"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
static void M()
{
var test = new List<string> { ""hello"", ""world"", ""!"" };
var test1 = test.Any(x => x.Equals('!'));
var test2 = test.SingleOrDefault(x => x.Equals('!'));
var test3 = test.Last(x => x.Equals('!'));
var test4 = test.Where(x => x.Equals('!')).Count();
var test5 = from x in test where x.Equals('!') select x;
var test6 = test.FirstOrDefault(a => a.FirstOrDefault(s => s.Equals(""hello"")).Equals(""hello""));
}
}",
}.RunAsync();
}
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedEvent.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using Cci = Microsoft.Cci;
namespace Microsoft.CodeAnalysis.Emit.NoPia
{
internal abstract partial class EmbeddedTypesManager<
TPEModuleBuilder,
TModuleCompilationState,
TEmbeddedTypesManager,
TSyntaxNode,
TAttributeData,
TSymbol,
TAssemblySymbol,
TNamedTypeSymbol,
TFieldSymbol,
TMethodSymbol,
TEventSymbol,
TPropertySymbol,
TParameterSymbol,
TTypeParameterSymbol,
TEmbeddedType,
TEmbeddedField,
TEmbeddedMethod,
TEmbeddedEvent,
TEmbeddedProperty,
TEmbeddedParameter,
TEmbeddedTypeParameter>
{
internal abstract class CommonEmbeddedEvent : CommonEmbeddedMember<TEventSymbol>, Cci.IEventDefinition
{
private readonly TEmbeddedMethod _adder;
private readonly TEmbeddedMethod _remover;
private readonly TEmbeddedMethod _caller;
private int _isUsedForComAwareEventBinding;
protected CommonEmbeddedEvent(TEventSymbol underlyingEvent, TEmbeddedMethod adder, TEmbeddedMethod remover, TEmbeddedMethod caller) :
base(underlyingEvent)
{
Debug.Assert(adder != null || remover != null);
_adder = adder;
_remover = remover;
_caller = caller;
}
internal override TEmbeddedTypesManager TypeManager
{
get
{
return AnAccessor.TypeManager;
}
}
protected abstract bool IsRuntimeSpecial { get; }
protected abstract bool IsSpecialName { get; }
protected abstract Cci.ITypeReference GetType(TPEModuleBuilder moduleBuilder, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics);
protected abstract TEmbeddedType ContainingType { get; }
protected abstract Cci.TypeMemberVisibility Visibility { get; }
protected abstract string Name { get; }
public TEventSymbol UnderlyingEvent
{
get
{
return this.UnderlyingSymbol;
}
}
protected abstract void EmbedCorrespondingComEventInterfaceMethodInternal(TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool isUsedForComAwareEventBinding);
internal void EmbedCorrespondingComEventInterfaceMethod(TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool isUsedForComAwareEventBinding)
{
if (_isUsedForComAwareEventBinding == 0 &&
(!isUsedForComAwareEventBinding ||
Interlocked.CompareExchange(ref _isUsedForComAwareEventBinding, 1, 0) == 0))
{
Debug.Assert(!isUsedForComAwareEventBinding || _isUsedForComAwareEventBinding != 0);
EmbedCorrespondingComEventInterfaceMethodInternal(syntaxNodeOpt, diagnostics, isUsedForComAwareEventBinding);
}
Debug.Assert(!isUsedForComAwareEventBinding || _isUsedForComAwareEventBinding != 0);
}
Cci.IMethodReference Cci.IEventDefinition.Adder
{
get { return _adder; }
}
Cci.IMethodReference Cci.IEventDefinition.Remover
{
get { return _remover; }
}
Cci.IMethodReference Cci.IEventDefinition.Caller
{
get { return _caller; }
}
IEnumerable<Cci.IMethodReference> Cci.IEventDefinition.GetAccessors(EmitContext context)
{
if (_adder != null)
{
yield return _adder;
}
if (_remover != null)
{
yield return _remover;
}
if (_caller != null)
{
yield return _caller;
}
}
bool Cci.IEventDefinition.IsRuntimeSpecial
{
get
{
return IsRuntimeSpecial;
}
}
bool Cci.IEventDefinition.IsSpecialName
{
get
{
return IsSpecialName;
}
}
Cci.ITypeReference Cci.IEventDefinition.GetType(EmitContext context)
{
return GetType((TPEModuleBuilder)context.Module, (TSyntaxNode)context.SyntaxNode, context.Diagnostics);
}
protected TEmbeddedMethod AnAccessor
{
get
{
return _adder ?? _remover;
}
}
Cci.ITypeDefinition Cci.ITypeDefinitionMember.ContainingTypeDefinition
{
get { return ContainingType; }
}
Cci.TypeMemberVisibility Cci.ITypeDefinitionMember.Visibility
{
get
{
return Visibility;
}
}
Cci.ITypeReference Cci.ITypeMemberReference.GetContainingType(EmitContext context)
{
return ContainingType;
}
void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor)
{
visitor.Visit((Cci.IEventDefinition)this);
}
Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context)
{
return this;
}
string Cci.INamedEntity.Name
{
get
{
return Name;
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using Cci = Microsoft.Cci;
namespace Microsoft.CodeAnalysis.Emit.NoPia
{
internal abstract partial class EmbeddedTypesManager<
TPEModuleBuilder,
TModuleCompilationState,
TEmbeddedTypesManager,
TSyntaxNode,
TAttributeData,
TSymbol,
TAssemblySymbol,
TNamedTypeSymbol,
TFieldSymbol,
TMethodSymbol,
TEventSymbol,
TPropertySymbol,
TParameterSymbol,
TTypeParameterSymbol,
TEmbeddedType,
TEmbeddedField,
TEmbeddedMethod,
TEmbeddedEvent,
TEmbeddedProperty,
TEmbeddedParameter,
TEmbeddedTypeParameter>
{
internal abstract class CommonEmbeddedEvent : CommonEmbeddedMember<TEventSymbol>, Cci.IEventDefinition
{
private readonly TEmbeddedMethod _adder;
private readonly TEmbeddedMethod _remover;
private readonly TEmbeddedMethod _caller;
private int _isUsedForComAwareEventBinding;
protected CommonEmbeddedEvent(TEventSymbol underlyingEvent, TEmbeddedMethod adder, TEmbeddedMethod remover, TEmbeddedMethod caller) :
base(underlyingEvent)
{
Debug.Assert(adder != null || remover != null);
_adder = adder;
_remover = remover;
_caller = caller;
}
internal override TEmbeddedTypesManager TypeManager
{
get
{
return AnAccessor.TypeManager;
}
}
protected abstract bool IsRuntimeSpecial { get; }
protected abstract bool IsSpecialName { get; }
protected abstract Cci.ITypeReference GetType(TPEModuleBuilder moduleBuilder, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics);
protected abstract TEmbeddedType ContainingType { get; }
protected abstract Cci.TypeMemberVisibility Visibility { get; }
protected abstract string Name { get; }
public TEventSymbol UnderlyingEvent
{
get
{
return this.UnderlyingSymbol;
}
}
protected abstract void EmbedCorrespondingComEventInterfaceMethodInternal(TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool isUsedForComAwareEventBinding);
internal void EmbedCorrespondingComEventInterfaceMethod(TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool isUsedForComAwareEventBinding)
{
if (_isUsedForComAwareEventBinding == 0 &&
(!isUsedForComAwareEventBinding ||
Interlocked.CompareExchange(ref _isUsedForComAwareEventBinding, 1, 0) == 0))
{
Debug.Assert(!isUsedForComAwareEventBinding || _isUsedForComAwareEventBinding != 0);
EmbedCorrespondingComEventInterfaceMethodInternal(syntaxNodeOpt, diagnostics, isUsedForComAwareEventBinding);
}
Debug.Assert(!isUsedForComAwareEventBinding || _isUsedForComAwareEventBinding != 0);
}
Cci.IMethodReference Cci.IEventDefinition.Adder
{
get { return _adder; }
}
Cci.IMethodReference Cci.IEventDefinition.Remover
{
get { return _remover; }
}
Cci.IMethodReference Cci.IEventDefinition.Caller
{
get { return _caller; }
}
IEnumerable<Cci.IMethodReference> Cci.IEventDefinition.GetAccessors(EmitContext context)
{
if (_adder != null)
{
yield return _adder;
}
if (_remover != null)
{
yield return _remover;
}
if (_caller != null)
{
yield return _caller;
}
}
bool Cci.IEventDefinition.IsRuntimeSpecial
{
get
{
return IsRuntimeSpecial;
}
}
bool Cci.IEventDefinition.IsSpecialName
{
get
{
return IsSpecialName;
}
}
Cci.ITypeReference Cci.IEventDefinition.GetType(EmitContext context)
{
return GetType((TPEModuleBuilder)context.Module, (TSyntaxNode)context.SyntaxNode, context.Diagnostics);
}
protected TEmbeddedMethod AnAccessor
{
get
{
return _adder ?? _remover;
}
}
Cci.ITypeDefinition Cci.ITypeDefinitionMember.ContainingTypeDefinition
{
get { return ContainingType; }
}
Cci.TypeMemberVisibility Cci.ITypeDefinitionMember.Visibility
{
get
{
return Visibility;
}
}
Cci.ITypeReference Cci.ITypeMemberReference.GetContainingType(EmitContext context)
{
return ContainingType;
}
void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor)
{
visitor.Visit((Cci.IEventDefinition)this);
}
Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context)
{
return this;
}
string Cci.INamedEntity.Name
{
get
{
return Name;
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrRuntimeInstance.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
#region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
// References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Microsoft.VisualStudio.Debugger.Symbols;
using Type = Microsoft.VisualStudio.Debugger.Metadata.Type;
namespace Microsoft.VisualStudio.Debugger.Clr
{
internal delegate DkmClrValue GetMemberValueDelegate(DkmClrValue value, string memberName);
internal delegate DkmClrModuleInstance GetModuleDelegate(DkmClrRuntimeInstance runtime, Assembly assembly);
public class DkmClrRuntimeInstance : DkmRuntimeInstance
{
internal static readonly DkmClrRuntimeInstance DefaultRuntime = new DkmClrRuntimeInstance(new Assembly[0]);
internal readonly Assembly[] Assemblies;
internal readonly DkmClrModuleInstance[] Modules;
private readonly DkmClrModuleInstance _defaultModule;
private readonly DkmClrAppDomain _appDomain; // exactly one for now
private readonly Dictionary<string, DkmClrObjectFavoritesInfo> _favoritesByTypeName;
internal readonly GetMemberValueDelegate GetMemberValue;
internal DkmClrRuntimeInstance(
Assembly[] assemblies,
GetModuleDelegate getModule = null,
GetMemberValueDelegate getMemberValue = null,
bool enableNativeDebugging = false)
: base(enableNativeDebugging)
{
if (getModule == null)
{
getModule = (r, a) => new DkmClrModuleInstance(r, a, (a != null) ? new DkmModule(a.GetName().Name + ".dll") : null);
}
this.Assemblies = assemblies;
this.Modules = assemblies.Select(a => getModule(this, a)).Where(m => m != null).ToArray();
_defaultModule = getModule(this, null);
_appDomain = new DkmClrAppDomain(this);
this.GetMemberValue = getMemberValue;
}
internal DkmClrRuntimeInstance(Assembly[] assemblies, Dictionary<string, DkmClrObjectFavoritesInfo> favoritesByTypeName)
: this(assemblies)
{
_favoritesByTypeName = favoritesByTypeName;
}
internal DkmClrModuleInstance DefaultModule
{
get { return _defaultModule; }
}
internal DkmClrAppDomain DefaultAppDomain
{
get { return _appDomain; }
}
internal DkmClrType GetType(Type type)
{
var assembly = ((AssemblyImpl)type.Assembly).Assembly;
var module = this.Modules.FirstOrDefault(m => m.Assembly == assembly) ?? _defaultModule;
return new DkmClrType(module, _appDomain, type, GetObjectFavoritesInfo(type));
}
internal DkmClrType GetType(System.Type type)
{
var assembly = type.Assembly;
var module = this.Modules.First(m => m.Assembly == assembly);
return new DkmClrType(module, _appDomain, (TypeImpl)type, GetObjectFavoritesInfo((TypeImpl)type));
}
internal DkmClrType GetType(string typeName, params System.Type[] typeArguments)
{
foreach (var module in WithMscorlibLast(this.Modules))
{
var assembly = module.Assembly;
var type = assembly.GetType(typeName);
if (type != null)
{
var result = new DkmClrType(module, _appDomain, (TypeImpl)type, GetObjectFavoritesInfo((TypeImpl)type));
if (typeArguments.Length > 0)
{
result = result.MakeGenericType(typeArguments.Select(this.GetType).ToArray());
}
return result;
}
}
return null;
}
private static IEnumerable<DkmClrModuleInstance> WithMscorlibLast(DkmClrModuleInstance[] list)
{
DkmClrModuleInstance mscorlib = null;
foreach (var module in list)
{
if (IsMscorlib(module.Assembly))
{
Debug.Assert(mscorlib == null);
mscorlib = module;
}
else
{
yield return module;
}
}
if (mscorlib != null)
{
yield return mscorlib;
}
}
private static bool IsMscorlib(Assembly assembly)
{
return assembly.GetReferencedAssemblies().Length == 0 && (object)assembly.GetType("System.Object") != null;
}
internal DkmClrModuleInstance FindClrModuleInstance(Guid mvid)
{
return this.Modules.FirstOrDefault(m => m.Mvid == mvid) ?? _defaultModule;
}
private DkmClrObjectFavoritesInfo GetObjectFavoritesInfo(Type type)
{
DkmClrObjectFavoritesInfo favorites = null;
if (_favoritesByTypeName != null)
{
if (type.IsGenericType)
{
type = type.GetGenericTypeDefinition();
}
_favoritesByTypeName.TryGetValue(type.FullName, out favorites);
}
return favorites;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
#region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
// References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Microsoft.VisualStudio.Debugger.Symbols;
using Type = Microsoft.VisualStudio.Debugger.Metadata.Type;
namespace Microsoft.VisualStudio.Debugger.Clr
{
internal delegate DkmClrValue GetMemberValueDelegate(DkmClrValue value, string memberName);
internal delegate DkmClrModuleInstance GetModuleDelegate(DkmClrRuntimeInstance runtime, Assembly assembly);
public class DkmClrRuntimeInstance : DkmRuntimeInstance
{
internal static readonly DkmClrRuntimeInstance DefaultRuntime = new DkmClrRuntimeInstance(new Assembly[0]);
internal readonly Assembly[] Assemblies;
internal readonly DkmClrModuleInstance[] Modules;
private readonly DkmClrModuleInstance _defaultModule;
private readonly DkmClrAppDomain _appDomain; // exactly one for now
private readonly Dictionary<string, DkmClrObjectFavoritesInfo> _favoritesByTypeName;
internal readonly GetMemberValueDelegate GetMemberValue;
internal DkmClrRuntimeInstance(
Assembly[] assemblies,
GetModuleDelegate getModule = null,
GetMemberValueDelegate getMemberValue = null,
bool enableNativeDebugging = false)
: base(enableNativeDebugging)
{
if (getModule == null)
{
getModule = (r, a) => new DkmClrModuleInstance(r, a, (a != null) ? new DkmModule(a.GetName().Name + ".dll") : null);
}
this.Assemblies = assemblies;
this.Modules = assemblies.Select(a => getModule(this, a)).Where(m => m != null).ToArray();
_defaultModule = getModule(this, null);
_appDomain = new DkmClrAppDomain(this);
this.GetMemberValue = getMemberValue;
}
internal DkmClrRuntimeInstance(Assembly[] assemblies, Dictionary<string, DkmClrObjectFavoritesInfo> favoritesByTypeName)
: this(assemblies)
{
_favoritesByTypeName = favoritesByTypeName;
}
internal DkmClrModuleInstance DefaultModule
{
get { return _defaultModule; }
}
internal DkmClrAppDomain DefaultAppDomain
{
get { return _appDomain; }
}
internal DkmClrType GetType(Type type)
{
var assembly = ((AssemblyImpl)type.Assembly).Assembly;
var module = this.Modules.FirstOrDefault(m => m.Assembly == assembly) ?? _defaultModule;
return new DkmClrType(module, _appDomain, type, GetObjectFavoritesInfo(type));
}
internal DkmClrType GetType(System.Type type)
{
var assembly = type.Assembly;
var module = this.Modules.First(m => m.Assembly == assembly);
return new DkmClrType(module, _appDomain, (TypeImpl)type, GetObjectFavoritesInfo((TypeImpl)type));
}
internal DkmClrType GetType(string typeName, params System.Type[] typeArguments)
{
foreach (var module in WithMscorlibLast(this.Modules))
{
var assembly = module.Assembly;
var type = assembly.GetType(typeName);
if (type != null)
{
var result = new DkmClrType(module, _appDomain, (TypeImpl)type, GetObjectFavoritesInfo((TypeImpl)type));
if (typeArguments.Length > 0)
{
result = result.MakeGenericType(typeArguments.Select(this.GetType).ToArray());
}
return result;
}
}
return null;
}
private static IEnumerable<DkmClrModuleInstance> WithMscorlibLast(DkmClrModuleInstance[] list)
{
DkmClrModuleInstance mscorlib = null;
foreach (var module in list)
{
if (IsMscorlib(module.Assembly))
{
Debug.Assert(mscorlib == null);
mscorlib = module;
}
else
{
yield return module;
}
}
if (mscorlib != null)
{
yield return mscorlib;
}
}
private static bool IsMscorlib(Assembly assembly)
{
return assembly.GetReferencedAssemblies().Length == 0 && (object)assembly.GetType("System.Object") != null;
}
internal DkmClrModuleInstance FindClrModuleInstance(Guid mvid)
{
return this.Modules.FirstOrDefault(m => m.Mvid == mvid) ?? _defaultModule;
}
private DkmClrObjectFavoritesInfo GetObjectFavoritesInfo(Type type)
{
DkmClrObjectFavoritesInfo favorites = null;
if (_favoritesByTypeName != null)
{
if (type.IsGenericType)
{
type = type.GetGenericTypeDefinition();
}
_favoritesByTypeName.TryGetValue(type.FullName, out favorites);
}
return favorites;
}
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/EditorFeatures/CSharpTest/SplitOrMergeIfStatements/SplitIntoNestedIfStatementsTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.SplitOrMergeIfStatements;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SplitOrMergeIfStatements
{
[Trait(Traits.Feature, Traits.Features.CodeActionsSplitIntoNestedIfStatements)]
public sealed class SplitIntoNestedIfStatementsTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new CSharpSplitIntoNestedIfStatementsCodeRefactoringProvider();
[Theory]
[InlineData("a [||]&& b")]
[InlineData("a &[||]& b")]
[InlineData("a &&[||] b")]
[InlineData("a [|&&|] b")]
public async Task SplitOnAndOperatorSpans(string condition)
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (" + condition + @")
{
}
}
}",
@"class C
{
void M(bool a, bool b)
{
if (a)
{
if (b)
{
}
}
}
}");
}
[Theory]
[InlineData("a [|&|]& b")]
[InlineData("a[| &&|] b")]
[InlineData("a[||] && b")]
public async Task NotSplitOnAndOperatorSpans(string condition)
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (" + condition + @")
{
}
}
}");
}
[Fact]
public async Task NotSplitOnIfKeyword()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
[||]if (a && b)
{
}
}
}");
}
[Fact]
public async Task NotSplitOnOrOperator()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (a [||]|| b)
{
}
}
}");
}
[Fact]
public async Task NotSplitOnBitwiseAndOperator()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (a [||]& b)
{
}
}
}");
}
[Fact]
public async Task NotSplitOnAndOperatorOutsideIfStatement()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
var v = a [||]&& b;
}
}");
}
[Fact]
public async Task NotSplitOnAndOperatorInIfStatementBody()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (a && b)
a [||]&& b;
}
}");
}
[Fact]
public async Task SplitWithChainedAndExpression1()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b, bool c, bool d)
{
if (a [||]&& b && c && d)
{
}
}
}",
@"class C
{
void M(bool a, bool b, bool c, bool d)
{
if (a)
{
if (b && c && d)
{
}
}
}
}");
}
[Fact]
public async Task SplitWithChainedAndExpression2()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b, bool c, bool d)
{
if (a && b [||]&& c && d)
{
}
}
}",
@"class C
{
void M(bool a, bool b, bool c, bool d)
{
if (a && b)
{
if (c && d)
{
}
}
}
}");
}
[Fact]
public async Task SplitWithChainedAndExpression3()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b, bool c, bool d)
{
if (a && b && c [||]&& d)
{
}
}
}",
@"class C
{
void M(bool a, bool b, bool c, bool d)
{
if (a && b && c)
{
if (d)
{
}
}
}
}");
}
[Fact]
public async Task NotSplitInsideParentheses1()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b, bool c, bool d)
{
if ((a [||]&& b) && c && d)
{
}
}
}");
}
[Fact]
public async Task NotSplitInsideParentheses2()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b, bool c, bool d)
{
if (a && b && (c [||]&& d))
{
}
}
}");
}
[Fact]
public async Task NotSplitInsideParentheses3()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b, bool c, bool d)
{
if ((a && b [||]&& c && d))
{
}
}
}");
}
[Fact]
public async Task SplitWithOtherExpressionInsideParentheses1()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b, bool c, bool d)
{
if (a [||]&& (b && c) && d)
{
}
}
}",
@"class C
{
void M(bool a, bool b, bool c, bool d)
{
if (a)
{
if ((b && c) && d)
{
}
}
}
}");
}
[Fact]
public async Task SplitWithOtherExpressionInsideParentheses2()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b, bool c, bool d)
{
if (a && (b && c) [||]&& d)
{
}
}
}",
@"class C
{
void M(bool a, bool b, bool c, bool d)
{
if (a && (b && c))
{
if (d)
{
}
}
}
}");
}
[Fact]
public async Task NotSplitWithMixedOrExpression1()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b, bool c)
{
if (a [||]&& b || c)
{
}
}
}");
}
[Fact]
public async Task NotSplitWithMixedOrExpression2()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b, bool c)
{
if (a || b [||]&& c)
{
}
}
}");
}
[Fact]
public async Task SplitWithMixedOrExpressionInsideParentheses1()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b, bool c)
{
if (a [||]&& (b || c))
{
}
}
}",
@"class C
{
void M(bool a, bool b, bool c)
{
if (a)
{
if ((b || c))
{
}
}
}
}");
}
[Fact]
public async Task SplitWithMixedOrExpressionInsideParentheses2()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b, bool c)
{
if ((a || b) [||]&& c)
{
}
}
}",
@"class C
{
void M(bool a, bool b, bool c)
{
if ((a || b))
{
if (c)
{
}
}
}
}");
}
[Fact]
public async Task SplitWithMixedBitwiseOrExpression1()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b, bool c)
{
if (a [||]&& b | c)
{
}
}
}",
@"class C
{
void M(bool a, bool b, bool c)
{
if (a)
{
if (b | c)
{
}
}
}
}");
}
[Fact]
public async Task SplitWithMixedBitwiseOrExpression2()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b, bool c)
{
if (a | b [||]&& c)
{
}
}
}",
@"class C
{
void M(bool a, bool b, bool c)
{
if (a | b)
{
if (c)
{
}
}
}
}");
}
[Fact]
public async Task SplitWithStatementInsideBlock()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (a [||]&& b)
{
System.Console.WriteLine(a && b);
}
}
}",
@"class C
{
void M(bool a, bool b)
{
if (a)
{
if (b)
{
System.Console.WriteLine(a && b);
}
}
}
}");
}
[Fact]
public async Task SplitWithStatementWithoutBlock()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (a [||]&& b)
System.Console.WriteLine(a && b);
}
}",
@"class C
{
void M(bool a, bool b)
{
if (a)
{
if (b)
System.Console.WriteLine(a && b);
}
}
}");
}
[Fact]
public async Task SplitWithNestedIfStatement()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (a [||]&& b)
if (true) { }
}
}",
@"class C
{
void M(bool a, bool b)
{
if (a)
{
if (b)
if (true) { }
}
}
}");
}
[Fact]
public async Task SplitWithMissingStatement()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (a [||]&& b)
}
}",
@"class C
{
void M(bool a, bool b)
{
if (a)
{
if (b)
}
}
}");
}
[Fact]
public async Task SplitWithElseStatementInsideBlock()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (a [||]&& b)
System.Console.WriteLine();
else
{
System.Console.WriteLine(a && b);
}
}
}",
@"class C
{
void M(bool a, bool b)
{
if (a)
{
if (b)
System.Console.WriteLine();
else
{
System.Console.WriteLine(a && b);
}
}
else
{
System.Console.WriteLine(a && b);
}
}
}");
}
[Fact]
public async Task SplitWithElseStatementWithoutBlock()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (a [||]&& b)
System.Console.WriteLine();
else
System.Console.WriteLine(a && b);
}
}",
@"class C
{
void M(bool a, bool b)
{
if (a)
{
if (b)
System.Console.WriteLine();
else
System.Console.WriteLine(a && b);
}
else
System.Console.WriteLine(a && b);
}
}");
}
[Fact]
public async Task SplitWithElseNestedIfStatement()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (a [||]&& b)
System.Console.WriteLine();
else if (true) { }
}
}",
@"class C
{
void M(bool a, bool b)
{
if (a)
{
if (b)
System.Console.WriteLine();
else if (true) { }
}
else if (true) { }
}
}");
}
[Fact]
public async Task SplitWithElseIfElse()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (a [||]&& b)
System.Console.WriteLine();
else if (a)
System.Console.WriteLine(a);
else
System.Console.WriteLine(b);
}
}",
@"class C
{
void M(bool a, bool b)
{
if (a)
{
if (b)
System.Console.WriteLine();
else if (a)
System.Console.WriteLine(a);
else
System.Console.WriteLine(b);
}
else if (a)
System.Console.WriteLine(a);
else
System.Console.WriteLine(b);
}
}");
}
[Fact]
public async Task SplitAsPartOfElseIfElse()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (true)
System.Console.WriteLine();
else if (a [||]&& b)
System.Console.WriteLine(a);
else
System.Console.WriteLine(b);
}
}",
@"class C
{
void M(bool a, bool b)
{
if (true)
System.Console.WriteLine();
else if (a)
{
if (b)
System.Console.WriteLine(a);
else
System.Console.WriteLine(b);
}
else
System.Console.WriteLine(b);
}
}");
}
[Fact]
public async Task SplitWithMissingElseStatement()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (a [||]&& b)
System.Console.WriteLine();
else
}
}",
@"class C
{
void M(bool a, bool b)
{
if (a)
{
if (b)
System.Console.WriteLine();
else
}
else
}
}");
}
[Fact]
public async Task SplitWithPreservedSingleLineFormatting()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (a [||]&& b) System.Console.WriteLine();
}
}",
@"class C
{
void M(bool a, bool b)
{
if (a)
{
if (b) System.Console.WriteLine();
}
}
}");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.SplitOrMergeIfStatements;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SplitOrMergeIfStatements
{
[Trait(Traits.Feature, Traits.Features.CodeActionsSplitIntoNestedIfStatements)]
public sealed class SplitIntoNestedIfStatementsTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new CSharpSplitIntoNestedIfStatementsCodeRefactoringProvider();
[Theory]
[InlineData("a [||]&& b")]
[InlineData("a &[||]& b")]
[InlineData("a &&[||] b")]
[InlineData("a [|&&|] b")]
public async Task SplitOnAndOperatorSpans(string condition)
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (" + condition + @")
{
}
}
}",
@"class C
{
void M(bool a, bool b)
{
if (a)
{
if (b)
{
}
}
}
}");
}
[Theory]
[InlineData("a [|&|]& b")]
[InlineData("a[| &&|] b")]
[InlineData("a[||] && b")]
public async Task NotSplitOnAndOperatorSpans(string condition)
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (" + condition + @")
{
}
}
}");
}
[Fact]
public async Task NotSplitOnIfKeyword()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
[||]if (a && b)
{
}
}
}");
}
[Fact]
public async Task NotSplitOnOrOperator()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (a [||]|| b)
{
}
}
}");
}
[Fact]
public async Task NotSplitOnBitwiseAndOperator()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (a [||]& b)
{
}
}
}");
}
[Fact]
public async Task NotSplitOnAndOperatorOutsideIfStatement()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
var v = a [||]&& b;
}
}");
}
[Fact]
public async Task NotSplitOnAndOperatorInIfStatementBody()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (a && b)
a [||]&& b;
}
}");
}
[Fact]
public async Task SplitWithChainedAndExpression1()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b, bool c, bool d)
{
if (a [||]&& b && c && d)
{
}
}
}",
@"class C
{
void M(bool a, bool b, bool c, bool d)
{
if (a)
{
if (b && c && d)
{
}
}
}
}");
}
[Fact]
public async Task SplitWithChainedAndExpression2()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b, bool c, bool d)
{
if (a && b [||]&& c && d)
{
}
}
}",
@"class C
{
void M(bool a, bool b, bool c, bool d)
{
if (a && b)
{
if (c && d)
{
}
}
}
}");
}
[Fact]
public async Task SplitWithChainedAndExpression3()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b, bool c, bool d)
{
if (a && b && c [||]&& d)
{
}
}
}",
@"class C
{
void M(bool a, bool b, bool c, bool d)
{
if (a && b && c)
{
if (d)
{
}
}
}
}");
}
[Fact]
public async Task NotSplitInsideParentheses1()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b, bool c, bool d)
{
if ((a [||]&& b) && c && d)
{
}
}
}");
}
[Fact]
public async Task NotSplitInsideParentheses2()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b, bool c, bool d)
{
if (a && b && (c [||]&& d))
{
}
}
}");
}
[Fact]
public async Task NotSplitInsideParentheses3()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b, bool c, bool d)
{
if ((a && b [||]&& c && d))
{
}
}
}");
}
[Fact]
public async Task SplitWithOtherExpressionInsideParentheses1()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b, bool c, bool d)
{
if (a [||]&& (b && c) && d)
{
}
}
}",
@"class C
{
void M(bool a, bool b, bool c, bool d)
{
if (a)
{
if ((b && c) && d)
{
}
}
}
}");
}
[Fact]
public async Task SplitWithOtherExpressionInsideParentheses2()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b, bool c, bool d)
{
if (a && (b && c) [||]&& d)
{
}
}
}",
@"class C
{
void M(bool a, bool b, bool c, bool d)
{
if (a && (b && c))
{
if (d)
{
}
}
}
}");
}
[Fact]
public async Task NotSplitWithMixedOrExpression1()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b, bool c)
{
if (a [||]&& b || c)
{
}
}
}");
}
[Fact]
public async Task NotSplitWithMixedOrExpression2()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b, bool c)
{
if (a || b [||]&& c)
{
}
}
}");
}
[Fact]
public async Task SplitWithMixedOrExpressionInsideParentheses1()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b, bool c)
{
if (a [||]&& (b || c))
{
}
}
}",
@"class C
{
void M(bool a, bool b, bool c)
{
if (a)
{
if ((b || c))
{
}
}
}
}");
}
[Fact]
public async Task SplitWithMixedOrExpressionInsideParentheses2()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b, bool c)
{
if ((a || b) [||]&& c)
{
}
}
}",
@"class C
{
void M(bool a, bool b, bool c)
{
if ((a || b))
{
if (c)
{
}
}
}
}");
}
[Fact]
public async Task SplitWithMixedBitwiseOrExpression1()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b, bool c)
{
if (a [||]&& b | c)
{
}
}
}",
@"class C
{
void M(bool a, bool b, bool c)
{
if (a)
{
if (b | c)
{
}
}
}
}");
}
[Fact]
public async Task SplitWithMixedBitwiseOrExpression2()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b, bool c)
{
if (a | b [||]&& c)
{
}
}
}",
@"class C
{
void M(bool a, bool b, bool c)
{
if (a | b)
{
if (c)
{
}
}
}
}");
}
[Fact]
public async Task SplitWithStatementInsideBlock()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (a [||]&& b)
{
System.Console.WriteLine(a && b);
}
}
}",
@"class C
{
void M(bool a, bool b)
{
if (a)
{
if (b)
{
System.Console.WriteLine(a && b);
}
}
}
}");
}
[Fact]
public async Task SplitWithStatementWithoutBlock()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (a [||]&& b)
System.Console.WriteLine(a && b);
}
}",
@"class C
{
void M(bool a, bool b)
{
if (a)
{
if (b)
System.Console.WriteLine(a && b);
}
}
}");
}
[Fact]
public async Task SplitWithNestedIfStatement()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (a [||]&& b)
if (true) { }
}
}",
@"class C
{
void M(bool a, bool b)
{
if (a)
{
if (b)
if (true) { }
}
}
}");
}
[Fact]
public async Task SplitWithMissingStatement()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (a [||]&& b)
}
}",
@"class C
{
void M(bool a, bool b)
{
if (a)
{
if (b)
}
}
}");
}
[Fact]
public async Task SplitWithElseStatementInsideBlock()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (a [||]&& b)
System.Console.WriteLine();
else
{
System.Console.WriteLine(a && b);
}
}
}",
@"class C
{
void M(bool a, bool b)
{
if (a)
{
if (b)
System.Console.WriteLine();
else
{
System.Console.WriteLine(a && b);
}
}
else
{
System.Console.WriteLine(a && b);
}
}
}");
}
[Fact]
public async Task SplitWithElseStatementWithoutBlock()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (a [||]&& b)
System.Console.WriteLine();
else
System.Console.WriteLine(a && b);
}
}",
@"class C
{
void M(bool a, bool b)
{
if (a)
{
if (b)
System.Console.WriteLine();
else
System.Console.WriteLine(a && b);
}
else
System.Console.WriteLine(a && b);
}
}");
}
[Fact]
public async Task SplitWithElseNestedIfStatement()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (a [||]&& b)
System.Console.WriteLine();
else if (true) { }
}
}",
@"class C
{
void M(bool a, bool b)
{
if (a)
{
if (b)
System.Console.WriteLine();
else if (true) { }
}
else if (true) { }
}
}");
}
[Fact]
public async Task SplitWithElseIfElse()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (a [||]&& b)
System.Console.WriteLine();
else if (a)
System.Console.WriteLine(a);
else
System.Console.WriteLine(b);
}
}",
@"class C
{
void M(bool a, bool b)
{
if (a)
{
if (b)
System.Console.WriteLine();
else if (a)
System.Console.WriteLine(a);
else
System.Console.WriteLine(b);
}
else if (a)
System.Console.WriteLine(a);
else
System.Console.WriteLine(b);
}
}");
}
[Fact]
public async Task SplitAsPartOfElseIfElse()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (true)
System.Console.WriteLine();
else if (a [||]&& b)
System.Console.WriteLine(a);
else
System.Console.WriteLine(b);
}
}",
@"class C
{
void M(bool a, bool b)
{
if (true)
System.Console.WriteLine();
else if (a)
{
if (b)
System.Console.WriteLine(a);
else
System.Console.WriteLine(b);
}
else
System.Console.WriteLine(b);
}
}");
}
[Fact]
public async Task SplitWithMissingElseStatement()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (a [||]&& b)
System.Console.WriteLine();
else
}
}",
@"class C
{
void M(bool a, bool b)
{
if (a)
{
if (b)
System.Console.WriteLine();
else
}
else
}
}");
}
[Fact]
public async Task SplitWithPreservedSingleLineFormatting()
{
await TestInRegularAndScriptAsync(
@"class C
{
void M(bool a, bool b)
{
if (a [||]&& b) System.Console.WriteLine();
}
}",
@"class C
{
void M(bool a, bool b)
{
if (a)
{
if (b) System.Console.WriteLine();
}
}
}");
}
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/ExpressionEvaluator/Core/Source/ExpressionCompiler/PDB/MethodDebugInfo.Portable.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal partial class MethodDebugInfo<TTypeSymbol, TLocalSymbol>
{
/// <exception cref="BadImageFormatException">Invalid data format.</exception>
public static MethodDebugInfo<TTypeSymbol, TLocalSymbol> ReadFromPortable(
MetadataReader reader,
int methodToken,
int ilOffset,
EESymbolProvider<TTypeSymbol, TLocalSymbol>? symbolProvider,
bool isVisualBasicMethod)
{
ImmutableDictionary<int, ImmutableArray<bool>>? dynamicLocalMap;
ImmutableDictionary<int, ImmutableArray<string?>>? tupleLocalMap;
ImmutableArray<ImmutableArray<ImportRecord>> importGroups;
ImmutableArray<ExternAliasRecord> externAliases;
ImmutableArray<string> localVariableNames;
ImmutableArray<TLocalSymbol> localConstants;
ILSpan reuseSpan;
var methodHandle = GetDeltaRelativeMethodDefinitionHandle(reader, methodToken);
// TODO: only null in DTEE case where we looking for default namesapace
if (symbolProvider != null)
{
ReadLocalScopeInformation(
reader,
methodHandle,
ilOffset,
symbolProvider,
isVisualBasicMethod,
out importGroups,
out externAliases,
out localVariableNames,
out dynamicLocalMap,
out tupleLocalMap,
out localConstants,
out reuseSpan);
}
else
{
dynamicLocalMap = null;
tupleLocalMap = null;
importGroups = ImmutableArray<ImmutableArray<ImportRecord>>.Empty;
externAliases = ImmutableArray<ExternAliasRecord>.Empty;
localVariableNames = ImmutableArray<string>.Empty;
localConstants = ImmutableArray<TLocalSymbol>.Empty;
reuseSpan = ILSpan.MaxValue;
}
ReadMethodCustomDebugInformation(reader, methodHandle, out var hoistedLocalScopes, out var defaultNamespace);
return new MethodDebugInfo<TTypeSymbol, TLocalSymbol>(
hoistedLocalScopes,
importGroups,
externAliases,
dynamicLocalMap,
tupleLocalMap,
defaultNamespace,
localVariableNames,
localConstants,
reuseSpan);
}
/// <summary>
/// Maps global method token to a handle local to the current delta PDB.
/// Debug tables referring to methods currently use local handles, not global handles.
/// See https://github.com/dotnet/roslyn/issues/16286
/// </summary>
private static MethodDefinitionHandle GetDeltaRelativeMethodDefinitionHandle(MetadataReader reader, int methodToken)
{
var globalHandle = (MethodDefinitionHandle)MetadataTokens.EntityHandle(methodToken);
if (reader.GetTableRowCount(TableIndex.EncMap) == 0)
{
return globalHandle;
}
var globalDebugHandle = globalHandle.ToDebugInformationHandle();
int rowId = 1;
foreach (var handle in reader.GetEditAndContinueMapEntries())
{
if (handle.Kind == HandleKind.MethodDebugInformation)
{
if (handle == globalDebugHandle)
{
return MetadataTokens.MethodDefinitionHandle(rowId);
}
rowId++;
}
}
// compiler generated invalid EncMap table:
throw new BadImageFormatException();
}
private static void ReadLocalScopeInformation(
MetadataReader reader,
MethodDefinitionHandle methodHandle,
int ilOffset,
EESymbolProvider<TTypeSymbol, TLocalSymbol> symbolProvider,
bool isVisualBasicMethod,
out ImmutableArray<ImmutableArray<ImportRecord>> importGroups,
out ImmutableArray<ExternAliasRecord> externAliases,
out ImmutableArray<string> localVariableNames,
out ImmutableDictionary<int, ImmutableArray<bool>>? dynamicLocalMap,
out ImmutableDictionary<int, ImmutableArray<string?>>? tupleLocalMap,
out ImmutableArray<TLocalSymbol> localConstants,
out ILSpan reuseSpan)
{
var localVariableNamesBuilder = ArrayBuilder<string>.GetInstance();
var localConstantsBuilder = ArrayBuilder<TLocalSymbol>.GetInstance();
ImmutableDictionary<int, ImmutableArray<bool>>.Builder? lazyDynamicLocalsBuilder = null;
ImmutableDictionary<int, ImmutableArray<string?>>.Builder? lazyTupleLocalsBuilder = null;
var innerMostImportScope = default(ImportScopeHandle);
uint reuseSpanStart = 0;
uint reuseSpanEnd = uint.MaxValue;
try
{
foreach (var scopeHandle in reader.GetLocalScopes(methodHandle))
{
try
{
var scope = reader.GetLocalScope(scopeHandle);
if (ilOffset < scope.StartOffset)
{
// scopes are sorted by StartOffset, hence all scopes that follow can't contain ilOffset
reuseSpanEnd = Math.Min(reuseSpanEnd, (uint)scope.StartOffset);
break;
}
if (ilOffset >= scope.EndOffset)
{
// ilOffset is not in this scope, go to next one
reuseSpanStart = Math.Max(reuseSpanStart, (uint)scope.EndOffset);
continue;
}
// reuse span is a subspan of the inner-most scope containing the IL offset:
reuseSpanStart = Math.Max(reuseSpanStart, (uint)scope.StartOffset);
reuseSpanEnd = Math.Min(reuseSpanEnd, (uint)scope.EndOffset);
// imports (use the inner-most):
innerMostImportScope = scope.ImportScope;
// locals (from all contained scopes):
foreach (var variableHandle in scope.GetLocalVariables())
{
var variable = reader.GetLocalVariable(variableHandle);
if ((variable.Attributes & LocalVariableAttributes.DebuggerHidden) != 0)
{
continue;
}
localVariableNamesBuilder.SetItem(variable.Index, reader.GetString(variable.Name));
var dynamicFlags = ReadDynamicCustomDebugInformation(reader, variableHandle);
if (!dynamicFlags.IsDefault)
{
lazyDynamicLocalsBuilder ??= ImmutableDictionary.CreateBuilder<int, ImmutableArray<bool>>();
lazyDynamicLocalsBuilder[variable.Index] = dynamicFlags;
}
var tupleElementNames = ReadTupleCustomDebugInformation(reader, variableHandle);
if (!tupleElementNames.IsDefault)
{
lazyTupleLocalsBuilder ??= ImmutableDictionary.CreateBuilder<int, ImmutableArray<string?>>();
lazyTupleLocalsBuilder[variable.Index] = tupleElementNames;
}
}
// constants (from all contained scopes):
foreach (var constantHandle in scope.GetLocalConstants())
{
var constant = reader.GetLocalConstant(constantHandle);
var sigReader = reader.GetBlobReader(constant.Signature);
symbolProvider.DecodeLocalConstant(ref sigReader, out var typeSymbol, out var value);
var name = reader.GetString(constant.Name);
var dynamicFlags = ReadDynamicCustomDebugInformation(reader, constantHandle);
var tupleElementNames = ReadTupleCustomDebugInformation(reader, constantHandle);
localConstantsBuilder.Add(symbolProvider.GetLocalConstant(name, typeSymbol, value, dynamicFlags, tupleElementNames));
}
}
catch (Exception e) when (e is UnsupportedSignatureContent || e is BadImageFormatException)
{
// ignore scopes with invalid data
}
}
}
finally
{
localVariableNames = localVariableNamesBuilder.ToImmutableAndFree();
localConstants = localConstantsBuilder.ToImmutableAndFree();
dynamicLocalMap = lazyDynamicLocalsBuilder?.ToImmutable();
tupleLocalMap = lazyTupleLocalsBuilder?.ToImmutable();
reuseSpan = new ILSpan(reuseSpanStart, reuseSpanEnd);
}
var importGroupsBuilder = ArrayBuilder<ImmutableArray<ImportRecord>>.GetInstance();
var externAliasesBuilder = ArrayBuilder<ExternAliasRecord>.GetInstance();
if (!innerMostImportScope.IsNil)
{
PopulateImports(reader, innerMostImportScope, symbolProvider, isVisualBasicMethod, importGroupsBuilder, externAliasesBuilder);
}
importGroups = importGroupsBuilder.ToImmutableAndFree();
externAliases = externAliasesBuilder.ToImmutableAndFree();
}
private static string ReadUtf8String(MetadataReader reader, BlobHandle handle)
{
var bytes = reader.GetBlobBytes(handle);
return Encoding.UTF8.GetString(bytes, 0, bytes.Length);
}
/// <summary>
/// Read UTF8 string with null terminator.
/// </summary>
private static string ReadUtf8String(ref BlobReader reader)
{
var builder = ArrayBuilder<byte>.GetInstance();
while (true)
{
var b = reader.ReadByte();
if (b == 0)
{
break;
}
builder.Add(b);
}
var bytes = builder.ToArrayAndFree();
return Encoding.UTF8.GetString(bytes, 0, bytes.Length);
}
private static void PopulateImports(
MetadataReader reader,
ImportScopeHandle handle,
EESymbolProvider<TTypeSymbol, TLocalSymbol> symbolProvider,
bool isVisualBasicMethod,
ArrayBuilder<ImmutableArray<ImportRecord>> importGroupsBuilder,
ArrayBuilder<ExternAliasRecord> externAliasesBuilder)
{
var importGroupBuilder = ArrayBuilder<ImportRecord>.GetInstance();
while (!handle.IsNil)
{
var importScope = reader.GetImportScope(handle);
try
{
PopulateImports(reader, importScope, symbolProvider, importGroupBuilder, externAliasesBuilder);
}
catch (BadImageFormatException)
{
// ignore invalid imports
}
// Portable PDBs represent project-level scope as the root of the chain of scopes.
// This scope might contain aliases for assembly references, but is not considered
// to be part of imports groups.
if (isVisualBasicMethod || !importScope.Parent.IsNil)
{
importGroupsBuilder.Add(importGroupBuilder.ToImmutable());
importGroupBuilder.Clear();
}
else
{
// C# currently doesn't support global imports in PDBs
// https://github.com/dotnet/roslyn/issues/21862
Debug.Assert(importGroupBuilder.Count == 0);
}
handle = importScope.Parent;
}
importGroupBuilder.Free();
}
/// <exception cref="BadImageFormatException">Invalid data format.</exception>
private static void PopulateImports(
MetadataReader reader,
ImportScope importScope,
EESymbolProvider<TTypeSymbol, TLocalSymbol> symbolProvider,
ArrayBuilder<ImportRecord> importGroupBuilder,
ArrayBuilder<ExternAliasRecord> externAliasesBuilder)
{
foreach (ImportDefinition import in importScope.GetImports())
{
switch (import.Kind)
{
case ImportDefinitionKind.ImportNamespace:
importGroupBuilder.Add(new ImportRecord(
ImportTargetKind.Namespace,
targetString: ReadUtf8String(reader, import.TargetNamespace)));
break;
case ImportDefinitionKind.ImportAssemblyNamespace:
importGroupBuilder.Add(new ImportRecord(
ImportTargetKind.Namespace,
targetString: ReadUtf8String(reader, import.TargetNamespace),
targetAssembly: symbolProvider.GetReferencedAssembly(import.TargetAssembly)));
break;
case ImportDefinitionKind.ImportType:
importGroupBuilder.Add(new ImportRecord(
ImportTargetKind.Type,
targetType: symbolProvider.GetType(import.TargetType)));
break;
case ImportDefinitionKind.ImportXmlNamespace:
importGroupBuilder.Add(new ImportRecord(
ImportTargetKind.XmlNamespace,
alias: ReadUtf8String(reader, import.Alias),
targetString: ReadUtf8String(reader, import.TargetNamespace)));
break;
case ImportDefinitionKind.ImportAssemblyReferenceAlias:
importGroupBuilder.Add(new ImportRecord(
ImportTargetKind.Assembly,
alias: ReadUtf8String(reader, import.Alias)));
break;
case ImportDefinitionKind.AliasAssemblyReference:
externAliasesBuilder.Add(new ExternAliasRecord(
alias: ReadUtf8String(reader, import.Alias),
targetAssembly: symbolProvider.GetReferencedAssembly(import.TargetAssembly)));
break;
case ImportDefinitionKind.AliasNamespace:
importGroupBuilder.Add(new ImportRecord(
ImportTargetKind.Namespace,
alias: ReadUtf8String(reader, import.Alias),
targetString: ReadUtf8String(reader, import.TargetNamespace)));
break;
case ImportDefinitionKind.AliasAssemblyNamespace:
importGroupBuilder.Add(new ImportRecord(
ImportTargetKind.Namespace,
alias: ReadUtf8String(reader, import.Alias),
targetString: ReadUtf8String(reader, import.TargetNamespace),
targetAssembly: symbolProvider.GetReferencedAssembly(import.TargetAssembly)));
break;
case ImportDefinitionKind.AliasType:
importGroupBuilder.Add(new ImportRecord(
ImportTargetKind.Type,
alias: ReadUtf8String(reader, import.Alias),
targetType: symbolProvider.GetType(import.TargetType)));
break;
}
}
}
/// <exception cref="BadImageFormatException">Invalid data format.</exception>
private static void ReadMethodCustomDebugInformation(
MetadataReader reader,
MethodDefinitionHandle methodHandle,
out ImmutableArray<HoistedLocalScopeRecord> hoistedLocalScopes,
out string defaultNamespace)
{
hoistedLocalScopes = TryGetCustomDebugInformation(reader, methodHandle, PortableCustomDebugInfoKinds.StateMachineHoistedLocalScopes, out var info) ?
DecodeHoistedLocalScopes(reader.GetBlobReader(info.Value)) :
ImmutableArray<HoistedLocalScopeRecord>.Empty;
// TODO: consider looking this up once per module (not for every method)
defaultNamespace = TryGetCustomDebugInformation(reader, EntityHandle.ModuleDefinition, PortableCustomDebugInfoKinds.DefaultNamespace, out info) ?
DecodeDefaultNamespace(reader.GetBlobReader(info.Value)) :
"";
}
/// <exception cref="BadImageFormatException">Invalid data format.</exception>
private static ImmutableArray<bool> ReadDynamicCustomDebugInformation(MetadataReader reader, EntityHandle variableOrConstantHandle)
{
if (TryGetCustomDebugInformation(reader, variableOrConstantHandle, PortableCustomDebugInfoKinds.DynamicLocalVariables, out var info))
{
return DecodeDynamicFlags(reader.GetBlobReader(info.Value));
}
return default;
}
/// <exception cref="BadImageFormatException">Invalid data format.</exception>
private static ImmutableArray<string?> ReadTupleCustomDebugInformation(MetadataReader reader, EntityHandle variableOrConstantHandle)
{
if (TryGetCustomDebugInformation(reader, variableOrConstantHandle, PortableCustomDebugInfoKinds.TupleElementNames, out var info))
{
return DecodeTupleElementNames(reader.GetBlobReader(info.Value));
}
return default;
}
/// <exception cref="BadImageFormatException">Invalid data format.</exception>
private static bool TryGetCustomDebugInformation(MetadataReader reader, EntityHandle handle, Guid kind, out CustomDebugInformation customDebugInfo)
{
bool foundAny = false;
customDebugInfo = default;
foreach (var infoHandle in reader.GetCustomDebugInformation(handle))
{
var info = reader.GetCustomDebugInformation(infoHandle);
var id = reader.GetGuid(info.Kind);
if (id == kind)
{
if (foundAny)
{
throw new BadImageFormatException();
}
customDebugInfo = info;
foundAny = true;
}
}
return foundAny;
}
/// <exception cref="BadImageFormatException">Invalid data format.</exception>
private static ImmutableArray<bool> DecodeDynamicFlags(BlobReader reader)
{
var builder = ImmutableArray.CreateBuilder<bool>(reader.Length * 8);
while (reader.RemainingBytes > 0)
{
int b = reader.ReadByte();
for (int i = 1; i < 0x100; i <<= 1)
{
builder.Add((b & i) != 0);
}
}
return builder.MoveToImmutable();
}
/// <exception cref="BadImageFormatException">Invalid data format.</exception>
private static ImmutableArray<string?> DecodeTupleElementNames(BlobReader reader)
{
var builder = ArrayBuilder<string?>.GetInstance();
while (reader.RemainingBytes > 0)
{
var value = ReadUtf8String(ref reader);
builder.Add(value.Length == 0 ? null : value);
}
return builder.ToImmutableAndFree();
}
/// <exception cref="BadImageFormatException">Invalid data format.</exception>
private static ImmutableArray<HoistedLocalScopeRecord> DecodeHoistedLocalScopes(BlobReader reader)
{
var result = ArrayBuilder<HoistedLocalScopeRecord>.GetInstance();
do
{
int startOffset = reader.ReadInt32();
int length = reader.ReadInt32();
result.Add(new HoistedLocalScopeRecord(startOffset, length));
}
while (reader.RemainingBytes > 0);
return result.ToImmutableAndFree();
}
private static string DecodeDefaultNamespace(BlobReader reader)
{
return reader.ReadUTF8(reader.Length);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal partial class MethodDebugInfo<TTypeSymbol, TLocalSymbol>
{
/// <exception cref="BadImageFormatException">Invalid data format.</exception>
public static MethodDebugInfo<TTypeSymbol, TLocalSymbol> ReadFromPortable(
MetadataReader reader,
int methodToken,
int ilOffset,
EESymbolProvider<TTypeSymbol, TLocalSymbol>? symbolProvider,
bool isVisualBasicMethod)
{
ImmutableDictionary<int, ImmutableArray<bool>>? dynamicLocalMap;
ImmutableDictionary<int, ImmutableArray<string?>>? tupleLocalMap;
ImmutableArray<ImmutableArray<ImportRecord>> importGroups;
ImmutableArray<ExternAliasRecord> externAliases;
ImmutableArray<string> localVariableNames;
ImmutableArray<TLocalSymbol> localConstants;
ILSpan reuseSpan;
var methodHandle = GetDeltaRelativeMethodDefinitionHandle(reader, methodToken);
// TODO: only null in DTEE case where we looking for default namesapace
if (symbolProvider != null)
{
ReadLocalScopeInformation(
reader,
methodHandle,
ilOffset,
symbolProvider,
isVisualBasicMethod,
out importGroups,
out externAliases,
out localVariableNames,
out dynamicLocalMap,
out tupleLocalMap,
out localConstants,
out reuseSpan);
}
else
{
dynamicLocalMap = null;
tupleLocalMap = null;
importGroups = ImmutableArray<ImmutableArray<ImportRecord>>.Empty;
externAliases = ImmutableArray<ExternAliasRecord>.Empty;
localVariableNames = ImmutableArray<string>.Empty;
localConstants = ImmutableArray<TLocalSymbol>.Empty;
reuseSpan = ILSpan.MaxValue;
}
ReadMethodCustomDebugInformation(reader, methodHandle, out var hoistedLocalScopes, out var defaultNamespace);
return new MethodDebugInfo<TTypeSymbol, TLocalSymbol>(
hoistedLocalScopes,
importGroups,
externAliases,
dynamicLocalMap,
tupleLocalMap,
defaultNamespace,
localVariableNames,
localConstants,
reuseSpan);
}
/// <summary>
/// Maps global method token to a handle local to the current delta PDB.
/// Debug tables referring to methods currently use local handles, not global handles.
/// See https://github.com/dotnet/roslyn/issues/16286
/// </summary>
private static MethodDefinitionHandle GetDeltaRelativeMethodDefinitionHandle(MetadataReader reader, int methodToken)
{
var globalHandle = (MethodDefinitionHandle)MetadataTokens.EntityHandle(methodToken);
if (reader.GetTableRowCount(TableIndex.EncMap) == 0)
{
return globalHandle;
}
var globalDebugHandle = globalHandle.ToDebugInformationHandle();
int rowId = 1;
foreach (var handle in reader.GetEditAndContinueMapEntries())
{
if (handle.Kind == HandleKind.MethodDebugInformation)
{
if (handle == globalDebugHandle)
{
return MetadataTokens.MethodDefinitionHandle(rowId);
}
rowId++;
}
}
// compiler generated invalid EncMap table:
throw new BadImageFormatException();
}
private static void ReadLocalScopeInformation(
MetadataReader reader,
MethodDefinitionHandle methodHandle,
int ilOffset,
EESymbolProvider<TTypeSymbol, TLocalSymbol> symbolProvider,
bool isVisualBasicMethod,
out ImmutableArray<ImmutableArray<ImportRecord>> importGroups,
out ImmutableArray<ExternAliasRecord> externAliases,
out ImmutableArray<string> localVariableNames,
out ImmutableDictionary<int, ImmutableArray<bool>>? dynamicLocalMap,
out ImmutableDictionary<int, ImmutableArray<string?>>? tupleLocalMap,
out ImmutableArray<TLocalSymbol> localConstants,
out ILSpan reuseSpan)
{
var localVariableNamesBuilder = ArrayBuilder<string>.GetInstance();
var localConstantsBuilder = ArrayBuilder<TLocalSymbol>.GetInstance();
ImmutableDictionary<int, ImmutableArray<bool>>.Builder? lazyDynamicLocalsBuilder = null;
ImmutableDictionary<int, ImmutableArray<string?>>.Builder? lazyTupleLocalsBuilder = null;
var innerMostImportScope = default(ImportScopeHandle);
uint reuseSpanStart = 0;
uint reuseSpanEnd = uint.MaxValue;
try
{
foreach (var scopeHandle in reader.GetLocalScopes(methodHandle))
{
try
{
var scope = reader.GetLocalScope(scopeHandle);
if (ilOffset < scope.StartOffset)
{
// scopes are sorted by StartOffset, hence all scopes that follow can't contain ilOffset
reuseSpanEnd = Math.Min(reuseSpanEnd, (uint)scope.StartOffset);
break;
}
if (ilOffset >= scope.EndOffset)
{
// ilOffset is not in this scope, go to next one
reuseSpanStart = Math.Max(reuseSpanStart, (uint)scope.EndOffset);
continue;
}
// reuse span is a subspan of the inner-most scope containing the IL offset:
reuseSpanStart = Math.Max(reuseSpanStart, (uint)scope.StartOffset);
reuseSpanEnd = Math.Min(reuseSpanEnd, (uint)scope.EndOffset);
// imports (use the inner-most):
innerMostImportScope = scope.ImportScope;
// locals (from all contained scopes):
foreach (var variableHandle in scope.GetLocalVariables())
{
var variable = reader.GetLocalVariable(variableHandle);
if ((variable.Attributes & LocalVariableAttributes.DebuggerHidden) != 0)
{
continue;
}
localVariableNamesBuilder.SetItem(variable.Index, reader.GetString(variable.Name));
var dynamicFlags = ReadDynamicCustomDebugInformation(reader, variableHandle);
if (!dynamicFlags.IsDefault)
{
lazyDynamicLocalsBuilder ??= ImmutableDictionary.CreateBuilder<int, ImmutableArray<bool>>();
lazyDynamicLocalsBuilder[variable.Index] = dynamicFlags;
}
var tupleElementNames = ReadTupleCustomDebugInformation(reader, variableHandle);
if (!tupleElementNames.IsDefault)
{
lazyTupleLocalsBuilder ??= ImmutableDictionary.CreateBuilder<int, ImmutableArray<string?>>();
lazyTupleLocalsBuilder[variable.Index] = tupleElementNames;
}
}
// constants (from all contained scopes):
foreach (var constantHandle in scope.GetLocalConstants())
{
var constant = reader.GetLocalConstant(constantHandle);
var sigReader = reader.GetBlobReader(constant.Signature);
symbolProvider.DecodeLocalConstant(ref sigReader, out var typeSymbol, out var value);
var name = reader.GetString(constant.Name);
var dynamicFlags = ReadDynamicCustomDebugInformation(reader, constantHandle);
var tupleElementNames = ReadTupleCustomDebugInformation(reader, constantHandle);
localConstantsBuilder.Add(symbolProvider.GetLocalConstant(name, typeSymbol, value, dynamicFlags, tupleElementNames));
}
}
catch (Exception e) when (e is UnsupportedSignatureContent || e is BadImageFormatException)
{
// ignore scopes with invalid data
}
}
}
finally
{
localVariableNames = localVariableNamesBuilder.ToImmutableAndFree();
localConstants = localConstantsBuilder.ToImmutableAndFree();
dynamicLocalMap = lazyDynamicLocalsBuilder?.ToImmutable();
tupleLocalMap = lazyTupleLocalsBuilder?.ToImmutable();
reuseSpan = new ILSpan(reuseSpanStart, reuseSpanEnd);
}
var importGroupsBuilder = ArrayBuilder<ImmutableArray<ImportRecord>>.GetInstance();
var externAliasesBuilder = ArrayBuilder<ExternAliasRecord>.GetInstance();
if (!innerMostImportScope.IsNil)
{
PopulateImports(reader, innerMostImportScope, symbolProvider, isVisualBasicMethod, importGroupsBuilder, externAliasesBuilder);
}
importGroups = importGroupsBuilder.ToImmutableAndFree();
externAliases = externAliasesBuilder.ToImmutableAndFree();
}
private static string ReadUtf8String(MetadataReader reader, BlobHandle handle)
{
var bytes = reader.GetBlobBytes(handle);
return Encoding.UTF8.GetString(bytes, 0, bytes.Length);
}
/// <summary>
/// Read UTF8 string with null terminator.
/// </summary>
private static string ReadUtf8String(ref BlobReader reader)
{
var builder = ArrayBuilder<byte>.GetInstance();
while (true)
{
var b = reader.ReadByte();
if (b == 0)
{
break;
}
builder.Add(b);
}
var bytes = builder.ToArrayAndFree();
return Encoding.UTF8.GetString(bytes, 0, bytes.Length);
}
private static void PopulateImports(
MetadataReader reader,
ImportScopeHandle handle,
EESymbolProvider<TTypeSymbol, TLocalSymbol> symbolProvider,
bool isVisualBasicMethod,
ArrayBuilder<ImmutableArray<ImportRecord>> importGroupsBuilder,
ArrayBuilder<ExternAliasRecord> externAliasesBuilder)
{
var importGroupBuilder = ArrayBuilder<ImportRecord>.GetInstance();
while (!handle.IsNil)
{
var importScope = reader.GetImportScope(handle);
try
{
PopulateImports(reader, importScope, symbolProvider, importGroupBuilder, externAliasesBuilder);
}
catch (BadImageFormatException)
{
// ignore invalid imports
}
// Portable PDBs represent project-level scope as the root of the chain of scopes.
// This scope might contain aliases for assembly references, but is not considered
// to be part of imports groups.
if (isVisualBasicMethod || !importScope.Parent.IsNil)
{
importGroupsBuilder.Add(importGroupBuilder.ToImmutable());
importGroupBuilder.Clear();
}
else
{
// C# currently doesn't support global imports in PDBs
// https://github.com/dotnet/roslyn/issues/21862
Debug.Assert(importGroupBuilder.Count == 0);
}
handle = importScope.Parent;
}
importGroupBuilder.Free();
}
/// <exception cref="BadImageFormatException">Invalid data format.</exception>
private static void PopulateImports(
MetadataReader reader,
ImportScope importScope,
EESymbolProvider<TTypeSymbol, TLocalSymbol> symbolProvider,
ArrayBuilder<ImportRecord> importGroupBuilder,
ArrayBuilder<ExternAliasRecord> externAliasesBuilder)
{
foreach (ImportDefinition import in importScope.GetImports())
{
switch (import.Kind)
{
case ImportDefinitionKind.ImportNamespace:
importGroupBuilder.Add(new ImportRecord(
ImportTargetKind.Namespace,
targetString: ReadUtf8String(reader, import.TargetNamespace)));
break;
case ImportDefinitionKind.ImportAssemblyNamespace:
importGroupBuilder.Add(new ImportRecord(
ImportTargetKind.Namespace,
targetString: ReadUtf8String(reader, import.TargetNamespace),
targetAssembly: symbolProvider.GetReferencedAssembly(import.TargetAssembly)));
break;
case ImportDefinitionKind.ImportType:
importGroupBuilder.Add(new ImportRecord(
ImportTargetKind.Type,
targetType: symbolProvider.GetType(import.TargetType)));
break;
case ImportDefinitionKind.ImportXmlNamespace:
importGroupBuilder.Add(new ImportRecord(
ImportTargetKind.XmlNamespace,
alias: ReadUtf8String(reader, import.Alias),
targetString: ReadUtf8String(reader, import.TargetNamespace)));
break;
case ImportDefinitionKind.ImportAssemblyReferenceAlias:
importGroupBuilder.Add(new ImportRecord(
ImportTargetKind.Assembly,
alias: ReadUtf8String(reader, import.Alias)));
break;
case ImportDefinitionKind.AliasAssemblyReference:
externAliasesBuilder.Add(new ExternAliasRecord(
alias: ReadUtf8String(reader, import.Alias),
targetAssembly: symbolProvider.GetReferencedAssembly(import.TargetAssembly)));
break;
case ImportDefinitionKind.AliasNamespace:
importGroupBuilder.Add(new ImportRecord(
ImportTargetKind.Namespace,
alias: ReadUtf8String(reader, import.Alias),
targetString: ReadUtf8String(reader, import.TargetNamespace)));
break;
case ImportDefinitionKind.AliasAssemblyNamespace:
importGroupBuilder.Add(new ImportRecord(
ImportTargetKind.Namespace,
alias: ReadUtf8String(reader, import.Alias),
targetString: ReadUtf8String(reader, import.TargetNamespace),
targetAssembly: symbolProvider.GetReferencedAssembly(import.TargetAssembly)));
break;
case ImportDefinitionKind.AliasType:
importGroupBuilder.Add(new ImportRecord(
ImportTargetKind.Type,
alias: ReadUtf8String(reader, import.Alias),
targetType: symbolProvider.GetType(import.TargetType)));
break;
}
}
}
/// <exception cref="BadImageFormatException">Invalid data format.</exception>
private static void ReadMethodCustomDebugInformation(
MetadataReader reader,
MethodDefinitionHandle methodHandle,
out ImmutableArray<HoistedLocalScopeRecord> hoistedLocalScopes,
out string defaultNamespace)
{
hoistedLocalScopes = TryGetCustomDebugInformation(reader, methodHandle, PortableCustomDebugInfoKinds.StateMachineHoistedLocalScopes, out var info) ?
DecodeHoistedLocalScopes(reader.GetBlobReader(info.Value)) :
ImmutableArray<HoistedLocalScopeRecord>.Empty;
// TODO: consider looking this up once per module (not for every method)
defaultNamespace = TryGetCustomDebugInformation(reader, EntityHandle.ModuleDefinition, PortableCustomDebugInfoKinds.DefaultNamespace, out info) ?
DecodeDefaultNamespace(reader.GetBlobReader(info.Value)) :
"";
}
/// <exception cref="BadImageFormatException">Invalid data format.</exception>
private static ImmutableArray<bool> ReadDynamicCustomDebugInformation(MetadataReader reader, EntityHandle variableOrConstantHandle)
{
if (TryGetCustomDebugInformation(reader, variableOrConstantHandle, PortableCustomDebugInfoKinds.DynamicLocalVariables, out var info))
{
return DecodeDynamicFlags(reader.GetBlobReader(info.Value));
}
return default;
}
/// <exception cref="BadImageFormatException">Invalid data format.</exception>
private static ImmutableArray<string?> ReadTupleCustomDebugInformation(MetadataReader reader, EntityHandle variableOrConstantHandle)
{
if (TryGetCustomDebugInformation(reader, variableOrConstantHandle, PortableCustomDebugInfoKinds.TupleElementNames, out var info))
{
return DecodeTupleElementNames(reader.GetBlobReader(info.Value));
}
return default;
}
/// <exception cref="BadImageFormatException">Invalid data format.</exception>
private static bool TryGetCustomDebugInformation(MetadataReader reader, EntityHandle handle, Guid kind, out CustomDebugInformation customDebugInfo)
{
bool foundAny = false;
customDebugInfo = default;
foreach (var infoHandle in reader.GetCustomDebugInformation(handle))
{
var info = reader.GetCustomDebugInformation(infoHandle);
var id = reader.GetGuid(info.Kind);
if (id == kind)
{
if (foundAny)
{
throw new BadImageFormatException();
}
customDebugInfo = info;
foundAny = true;
}
}
return foundAny;
}
/// <exception cref="BadImageFormatException">Invalid data format.</exception>
private static ImmutableArray<bool> DecodeDynamicFlags(BlobReader reader)
{
var builder = ImmutableArray.CreateBuilder<bool>(reader.Length * 8);
while (reader.RemainingBytes > 0)
{
int b = reader.ReadByte();
for (int i = 1; i < 0x100; i <<= 1)
{
builder.Add((b & i) != 0);
}
}
return builder.MoveToImmutable();
}
/// <exception cref="BadImageFormatException">Invalid data format.</exception>
private static ImmutableArray<string?> DecodeTupleElementNames(BlobReader reader)
{
var builder = ArrayBuilder<string?>.GetInstance();
while (reader.RemainingBytes > 0)
{
var value = ReadUtf8String(ref reader);
builder.Add(value.Length == 0 ? null : value);
}
return builder.ToImmutableAndFree();
}
/// <exception cref="BadImageFormatException">Invalid data format.</exception>
private static ImmutableArray<HoistedLocalScopeRecord> DecodeHoistedLocalScopes(BlobReader reader)
{
var result = ArrayBuilder<HoistedLocalScopeRecord>.GetInstance();
do
{
int startOffset = reader.ReadInt32();
int length = reader.ReadInt32();
result.Add(new HoistedLocalScopeRecord(startOffset, length));
}
while (reader.RemainingBytes > 0);
return result.ToImmutableAndFree();
}
private static string DecodeDefaultNamespace(BlobReader reader)
{
return reader.ReadUTF8(reader.Length);
}
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Workspaces/Core/Portable/Workspace/Host/DocumentService/ISpanMappingService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Host
{
/// <summary>
/// Map spans in a document to other spans even in other document
///
/// this will be used by various features if provided to convert span in one document to other spans.
///
/// for example, it is used to show spans users expect in a razor file rather than spans in
/// auto generated file that is implementation detail or navigate to the right place rather
/// than the generated file and etc.
/// </summary>
internal interface ISpanMappingService : IDocumentService
{
/// <summary>
/// Whether this span mapping service can handle mapping import directives added to a document.
/// </summary>
bool SupportsMappingImportDirectives { get; }
Task<ImmutableArray<(string mappedFilePath, TextChange mappedTextChange)>> GetMappedTextChangesAsync(
Document oldDocument,
Document newDocument,
CancellationToken cancellationToken);
/// <summary>
/// Map spans in the document to more appropriate locations
///
/// in current design, this can NOT map a span to a span that is not backed by a file.
/// for example, roslyn supports someone to have a document that is not backed by a file. and current design doesn't allow
/// such document to be returned from this API
/// for example, span on razor secondary buffer document in roslyn solution mapped to a span on razor cshtml file is possible but
/// a span on razor cshtml file to a span on secondary buffer document is not possible since secondary buffer document is not backed by a file
/// </summary>
/// <param name="document">Document given spans belong to</param>
/// <param name="spans">Spans in the document</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Return mapped span. order of result should be same as the given span</returns>
Task<ImmutableArray<MappedSpanResult>> MapSpansAsync(Document document, IEnumerable<TextSpan> spans, CancellationToken cancellationToken);
}
/// <summary>
/// Result of span mapping
/// </summary>
internal struct MappedSpanResult
{
/// <summary>
/// Path to mapped file
/// </summary>
public readonly string FilePath;
/// <summary>
/// LinePosition representation of the Span
/// </summary>
public readonly LinePositionSpan LinePositionSpan;
/// <summary>
/// Mapped span
/// </summary>
public readonly TextSpan Span;
public MappedSpanResult(string filePath, LinePositionSpan linePositionSpan, TextSpan span)
{
if (string.IsNullOrEmpty(filePath))
{
throw new System.ArgumentException(nameof(filePath));
}
FilePath = filePath;
LinePositionSpan = linePositionSpan;
Span = span;
}
public bool IsDefault => FilePath == 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.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Host
{
/// <summary>
/// Map spans in a document to other spans even in other document
///
/// this will be used by various features if provided to convert span in one document to other spans.
///
/// for example, it is used to show spans users expect in a razor file rather than spans in
/// auto generated file that is implementation detail or navigate to the right place rather
/// than the generated file and etc.
/// </summary>
internal interface ISpanMappingService : IDocumentService
{
/// <summary>
/// Whether this span mapping service can handle mapping import directives added to a document.
/// </summary>
bool SupportsMappingImportDirectives { get; }
Task<ImmutableArray<(string mappedFilePath, TextChange mappedTextChange)>> GetMappedTextChangesAsync(
Document oldDocument,
Document newDocument,
CancellationToken cancellationToken);
/// <summary>
/// Map spans in the document to more appropriate locations
///
/// in current design, this can NOT map a span to a span that is not backed by a file.
/// for example, roslyn supports someone to have a document that is not backed by a file. and current design doesn't allow
/// such document to be returned from this API
/// for example, span on razor secondary buffer document in roslyn solution mapped to a span on razor cshtml file is possible but
/// a span on razor cshtml file to a span on secondary buffer document is not possible since secondary buffer document is not backed by a file
/// </summary>
/// <param name="document">Document given spans belong to</param>
/// <param name="spans">Spans in the document</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Return mapped span. order of result should be same as the given span</returns>
Task<ImmutableArray<MappedSpanResult>> MapSpansAsync(Document document, IEnumerable<TextSpan> spans, CancellationToken cancellationToken);
}
/// <summary>
/// Result of span mapping
/// </summary>
internal struct MappedSpanResult
{
/// <summary>
/// Path to mapped file
/// </summary>
public readonly string FilePath;
/// <summary>
/// LinePosition representation of the Span
/// </summary>
public readonly LinePositionSpan LinePositionSpan;
/// <summary>
/// Mapped span
/// </summary>
public readonly TextSpan Span;
public MappedSpanResult(string filePath, LinePositionSpan linePositionSpan, TextSpan span)
{
if (string.IsNullOrEmpty(filePath))
{
throw new System.ArgumentException(nameof(filePath));
}
FilePath = filePath;
LinePositionSpan = linePositionSpan;
Span = span;
}
public bool IsDefault => FilePath == null;
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/MefWorkspaceServices.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Host;
using Microsoft.CodeAnalysis.Host.Mef;
[assembly: DebuggerTypeProxy(typeof(MefWorkspaceServices.LazyServiceMetadataDebuggerProxy), Target = typeof(ImmutableArray<Lazy<IWorkspaceService, WorkspaceServiceMetadata>>))]
namespace Microsoft.CodeAnalysis.Host.Mef
{
internal sealed class MefWorkspaceServices : HostWorkspaceServices
{
private readonly IMefHostExportProvider _exportProvider;
private readonly Workspace _workspace;
private readonly ImmutableArray<Lazy<IWorkspaceService, WorkspaceServiceMetadata>> _services;
// map of type name to workspace service
private ImmutableDictionary<Type, Lazy<IWorkspaceService, WorkspaceServiceMetadata>> _serviceMap
= ImmutableDictionary<Type, Lazy<IWorkspaceService, WorkspaceServiceMetadata>>.Empty;
// accumulated cache for language services
private ImmutableDictionary<string, MefLanguageServices> _languageServicesMap
= ImmutableDictionary<string, MefLanguageServices>.Empty;
public MefWorkspaceServices(IMefHostExportProvider host, Workspace workspace)
{
_exportProvider = host;
_workspace = workspace;
var services = host.GetExports<IWorkspaceService, WorkspaceServiceMetadata>();
var factories = host.GetExports<IWorkspaceServiceFactory, WorkspaceServiceMetadata>()
.Select(lz => new Lazy<IWorkspaceService, WorkspaceServiceMetadata>(() => lz.Value.CreateService(this), lz.Metadata));
_services = services.Concat(factories).ToImmutableArray();
}
public override HostServices HostServices
{
get { return (HostServices)_exportProvider; }
}
internal IMefHostExportProvider HostExportProvider => _exportProvider;
public override Workspace Workspace => _workspace;
public override TWorkspaceService GetService<TWorkspaceService>()
{
if (TryGetService(typeof(TWorkspaceService), out var service))
{
return (TWorkspaceService)service.Value;
}
else
{
return default;
}
}
private bool TryGetService(Type serviceType, out Lazy<IWorkspaceService, WorkspaceServiceMetadata> service)
{
if (!_serviceMap.TryGetValue(serviceType, out service))
{
service = ImmutableInterlocked.GetOrAdd(ref _serviceMap, serviceType, svctype =>
{
// Pick from list of exported factories and instances
// PERF: Hoist AssemblyQualifiedName out of inner lambda to avoid repeated string allocations.
var assemblyQualifiedName = svctype.AssemblyQualifiedName;
return PickWorkspaceService(_services.Where(lz => lz.Metadata.ServiceType == assemblyQualifiedName));
});
}
return service != null;
}
private Lazy<IWorkspaceService, WorkspaceServiceMetadata> PickWorkspaceService(IEnumerable<Lazy<IWorkspaceService, WorkspaceServiceMetadata>> services)
{
Lazy<IWorkspaceService, WorkspaceServiceMetadata> service;
#if !CODE_STYLE
// test layer overrides all other layers and workspace kind:
if (TryGetServiceByLayer(ServiceLayer.Test, services, out service))
{
return service;
}
#endif
// workspace specific kind is best
if (TryGetServiceByLayer(_workspace.Kind, services, out service))
{
return service;
}
// host layer overrides editor, desktop or default
if (TryGetServiceByLayer(ServiceLayer.Host, services, out service))
{
return service;
}
// editor layer overrides desktop or default
if (TryGetServiceByLayer(ServiceLayer.Editor, services, out service))
{
return service;
}
// desktop layer overrides default
if (TryGetServiceByLayer(ServiceLayer.Desktop, services, out service))
{
return service;
}
// that just leaves default
if (TryGetServiceByLayer(ServiceLayer.Default, services, out service))
{
return service;
}
// no service.
return null;
}
private static bool TryGetServiceByLayer(string layer, IEnumerable<Lazy<IWorkspaceService, WorkspaceServiceMetadata>> services, out Lazy<IWorkspaceService, WorkspaceServiceMetadata> service)
{
service = services.SingleOrDefault(lz => lz.Metadata.Layer == layer);
return service != null;
}
private IEnumerable<string> _languages;
private IEnumerable<string> GetSupportedLanguages()
{
if (_languages == null)
{
var list = _exportProvider.GetExports<ILanguageService, LanguageServiceMetadata>().Select(lz => lz.Metadata.Language).Concat(
_exportProvider.GetExports<ILanguageServiceFactory, LanguageServiceMetadata>().Select(lz => lz.Metadata.Language))
.Distinct();
Interlocked.CompareExchange(ref _languages, list, null);
}
return _languages;
}
public override IEnumerable<string> SupportedLanguages
{
get { return this.GetSupportedLanguages(); }
}
public override bool IsSupported(string languageName)
=> this.GetSupportedLanguages().Contains(languageName);
public override HostLanguageServices GetLanguageServices(string languageName)
{
var currentServicesMap = _languageServicesMap;
if (!currentServicesMap.TryGetValue(languageName, out var languageServices))
{
languageServices = ImmutableInterlocked.GetOrAdd(ref _languageServicesMap, languageName, static (languageName, self) => new MefLanguageServices(self, languageName), this);
}
if (languageServices.HasServices)
{
return languageServices;
}
else
{
// throws exception
#pragma warning disable RS0030 // Do not used banned API 'GetLanguageServices', use 'GetExtendedLanguageServices' instead - allowed in this context.
return base.GetLanguageServices(languageName);
#pragma warning restore RS0030 // Do not used banned APIs
}
}
public override IEnumerable<TLanguageService> FindLanguageServices<TLanguageService>(MetadataFilter filter)
{
foreach (var language in this.SupportedLanguages)
{
#pragma warning disable RS0030 // Do not used banned API 'GetLanguageServices', use 'GetExtendedLanguageServices' instead - allowed in this context.
var services = (MefLanguageServices)this.GetLanguageServices(language);
#pragma warning restore RS0030 // Do not used banned APIs
if (services.TryGetService(typeof(TLanguageService), out var service))
{
if (filter(service.Metadata.Data))
{
yield return (TLanguageService)service.Value;
}
}
}
}
internal bool TryGetLanguageServices(string languageName, out MefLanguageServices languageServices)
=> _languageServicesMap.TryGetValue(languageName, out languageServices);
internal sealed class LazyServiceMetadataDebuggerProxy
{
private readonly ImmutableArray<Lazy<IWorkspaceService, WorkspaceServiceMetadata>> _services;
public LazyServiceMetadataDebuggerProxy(ImmutableArray<Lazy<IWorkspaceService, WorkspaceServiceMetadata>> services) =>
_services = services;
public (string type, string layer)[] Metadata
=> _services.Select(s => (s.Metadata.ServiceType, s.Metadata.Layer)).ToArray();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
[assembly: DebuggerTypeProxy(typeof(MefWorkspaceServices.LazyServiceMetadataDebuggerProxy), Target = typeof(ImmutableArray<Lazy<IWorkspaceService, WorkspaceServiceMetadata>>))]
namespace Microsoft.CodeAnalysis.Host.Mef
{
internal sealed class MefWorkspaceServices : HostWorkspaceServices
{
private readonly IMefHostExportProvider _exportProvider;
private readonly Workspace _workspace;
private readonly ImmutableArray<Lazy<IWorkspaceService, WorkspaceServiceMetadata>> _services;
// map of type name to workspace service
private ImmutableDictionary<Type, Lazy<IWorkspaceService, WorkspaceServiceMetadata>> _serviceMap
= ImmutableDictionary<Type, Lazy<IWorkspaceService, WorkspaceServiceMetadata>>.Empty;
// accumulated cache for language services
private ImmutableDictionary<string, MefLanguageServices> _languageServicesMap
= ImmutableDictionary<string, MefLanguageServices>.Empty;
public MefWorkspaceServices(IMefHostExportProvider host, Workspace workspace)
{
_exportProvider = host;
_workspace = workspace;
var services = host.GetExports<IWorkspaceService, WorkspaceServiceMetadata>();
var factories = host.GetExports<IWorkspaceServiceFactory, WorkspaceServiceMetadata>()
.Select(lz => new Lazy<IWorkspaceService, WorkspaceServiceMetadata>(() => lz.Value.CreateService(this), lz.Metadata));
_services = services.Concat(factories).ToImmutableArray();
}
public override HostServices HostServices
{
get { return (HostServices)_exportProvider; }
}
internal IMefHostExportProvider HostExportProvider => _exportProvider;
public override Workspace Workspace => _workspace;
public override TWorkspaceService GetService<TWorkspaceService>()
{
if (TryGetService(typeof(TWorkspaceService), out var service))
{
return (TWorkspaceService)service.Value;
}
else
{
return default;
}
}
private bool TryGetService(Type serviceType, out Lazy<IWorkspaceService, WorkspaceServiceMetadata> service)
{
if (!_serviceMap.TryGetValue(serviceType, out service))
{
service = ImmutableInterlocked.GetOrAdd(ref _serviceMap, serviceType, svctype =>
{
// Pick from list of exported factories and instances
// PERF: Hoist AssemblyQualifiedName out of inner lambda to avoid repeated string allocations.
var assemblyQualifiedName = svctype.AssemblyQualifiedName;
return PickWorkspaceService(_services.Where(lz => lz.Metadata.ServiceType == assemblyQualifiedName));
});
}
return service != null;
}
private Lazy<IWorkspaceService, WorkspaceServiceMetadata> PickWorkspaceService(IEnumerable<Lazy<IWorkspaceService, WorkspaceServiceMetadata>> services)
{
Lazy<IWorkspaceService, WorkspaceServiceMetadata> service;
#if !CODE_STYLE
// test layer overrides all other layers and workspace kind:
if (TryGetServiceByLayer(ServiceLayer.Test, services, out service))
{
return service;
}
#endif
// workspace specific kind is best
if (TryGetServiceByLayer(_workspace.Kind, services, out service))
{
return service;
}
// host layer overrides editor, desktop or default
if (TryGetServiceByLayer(ServiceLayer.Host, services, out service))
{
return service;
}
// editor layer overrides desktop or default
if (TryGetServiceByLayer(ServiceLayer.Editor, services, out service))
{
return service;
}
// desktop layer overrides default
if (TryGetServiceByLayer(ServiceLayer.Desktop, services, out service))
{
return service;
}
// that just leaves default
if (TryGetServiceByLayer(ServiceLayer.Default, services, out service))
{
return service;
}
// no service.
return null;
}
private static bool TryGetServiceByLayer(string layer, IEnumerable<Lazy<IWorkspaceService, WorkspaceServiceMetadata>> services, out Lazy<IWorkspaceService, WorkspaceServiceMetadata> service)
{
service = services.SingleOrDefault(lz => lz.Metadata.Layer == layer);
return service != null;
}
private IEnumerable<string> _languages;
private IEnumerable<string> GetSupportedLanguages()
{
if (_languages == null)
{
var list = _exportProvider.GetExports<ILanguageService, LanguageServiceMetadata>().Select(lz => lz.Metadata.Language).Concat(
_exportProvider.GetExports<ILanguageServiceFactory, LanguageServiceMetadata>().Select(lz => lz.Metadata.Language))
.Distinct();
Interlocked.CompareExchange(ref _languages, list, null);
}
return _languages;
}
public override IEnumerable<string> SupportedLanguages
{
get { return this.GetSupportedLanguages(); }
}
public override bool IsSupported(string languageName)
=> this.GetSupportedLanguages().Contains(languageName);
public override HostLanguageServices GetLanguageServices(string languageName)
{
var currentServicesMap = _languageServicesMap;
if (!currentServicesMap.TryGetValue(languageName, out var languageServices))
{
languageServices = ImmutableInterlocked.GetOrAdd(ref _languageServicesMap, languageName, static (languageName, self) => new MefLanguageServices(self, languageName), this);
}
if (languageServices.HasServices)
{
return languageServices;
}
else
{
// throws exception
#pragma warning disable RS0030 // Do not used banned API 'GetLanguageServices', use 'GetExtendedLanguageServices' instead - allowed in this context.
return base.GetLanguageServices(languageName);
#pragma warning restore RS0030 // Do not used banned APIs
}
}
public override IEnumerable<TLanguageService> FindLanguageServices<TLanguageService>(MetadataFilter filter)
{
foreach (var language in this.SupportedLanguages)
{
#pragma warning disable RS0030 // Do not used banned API 'GetLanguageServices', use 'GetExtendedLanguageServices' instead - allowed in this context.
var services = (MefLanguageServices)this.GetLanguageServices(language);
#pragma warning restore RS0030 // Do not used banned APIs
if (services.TryGetService(typeof(TLanguageService), out var service))
{
if (filter(service.Metadata.Data))
{
yield return (TLanguageService)service.Value;
}
}
}
}
internal bool TryGetLanguageServices(string languageName, out MefLanguageServices languageServices)
=> _languageServicesMap.TryGetValue(languageName, out languageServices);
internal sealed class LazyServiceMetadataDebuggerProxy
{
private readonly ImmutableArray<Lazy<IWorkspaceService, WorkspaceServiceMetadata>> _services;
public LazyServiceMetadataDebuggerProxy(ImmutableArray<Lazy<IWorkspaceService, WorkspaceServiceMetadata>> services) =>
_services = services;
public (string type, string layer)[] Metadata
=> _services.Select(s => (s.Metadata.ServiceType, s.Metadata.Layer)).ToArray();
}
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Compilers/CSharp/Portable/Emitter/Model/EventSymbolAdapter.cs | // Licensed to the .NET Foundation under one or more 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;
using Microsoft.Cci;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.Emit;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal partial class
#if DEBUG
EventSymbolAdapter : SymbolAdapter,
#else
EventSymbol :
#endif
Cci.IEventDefinition
{
#region IEventDefinition Members
IEnumerable<Cci.IMethodReference> Cci.IEventDefinition.GetAccessors(EmitContext context)
{
CheckDefinitionInvariant();
var addMethod = AdaptedEventSymbol.AddMethod?.GetCciAdapter();
RoslynDebug.Assert((object?)addMethod != null);
if (addMethod.ShouldInclude(context))
{
yield return addMethod;
}
var removeMethod = AdaptedEventSymbol.RemoveMethod?.GetCciAdapter();
RoslynDebug.Assert((object?)removeMethod != null);
if (removeMethod.ShouldInclude(context))
{
yield return removeMethod;
}
}
Cci.IMethodReference Cci.IEventDefinition.Adder
{
get
{
CheckDefinitionInvariant();
var addMethod = AdaptedEventSymbol.AddMethod?.GetCciAdapter();
RoslynDebug.Assert((object?)addMethod != null);
return addMethod;
}
}
Cci.IMethodReference Cci.IEventDefinition.Remover
{
get
{
CheckDefinitionInvariant();
var removeMethod = AdaptedEventSymbol.RemoveMethod?.GetCciAdapter();
RoslynDebug.Assert((object?)removeMethod != null);
return removeMethod;
}
}
bool Cci.IEventDefinition.IsRuntimeSpecial
{
get
{
CheckDefinitionInvariant();
return AdaptedEventSymbol.HasRuntimeSpecialName;
}
}
bool Cci.IEventDefinition.IsSpecialName
{
get
{
CheckDefinitionInvariant();
return AdaptedEventSymbol.HasSpecialName;
}
}
Cci.IMethodReference? Cci.IEventDefinition.Caller
{
get
{
CheckDefinitionInvariant();
return null; // C# doesn't use the raise/fire accessor
}
}
Cci.ITypeReference Cci.IEventDefinition.GetType(EmitContext context)
{
return ((PEModuleBuilder)context.Module).Translate(AdaptedEventSymbol.Type, syntaxNodeOpt: (CSharpSyntaxNode?)context.SyntaxNode, diagnostics: context.Diagnostics);
}
#endregion
#region ITypeDefinitionMember Members
Cci.ITypeDefinition Cci.ITypeDefinitionMember.ContainingTypeDefinition
{
get
{
CheckDefinitionInvariant();
return AdaptedEventSymbol.ContainingType.GetCciAdapter();
}
}
Cci.TypeMemberVisibility Cci.ITypeDefinitionMember.Visibility
{
get
{
CheckDefinitionInvariant();
return PEModuleBuilder.MemberVisibility(AdaptedEventSymbol);
}
}
#endregion
#region ITypeMemberReference Members
Cci.ITypeReference Cci.ITypeMemberReference.GetContainingType(EmitContext context)
{
CheckDefinitionInvariant();
return AdaptedEventSymbol.ContainingType.GetCciAdapter();
}
#endregion
#region IReference Members
void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor)
{
CheckDefinitionInvariant();
visitor.Visit((Cci.IEventDefinition)this);
}
Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context)
{
CheckDefinitionInvariant();
return this;
}
#endregion
#region INamedEntity Members
string Cci.INamedEntity.Name
{
get
{
CheckDefinitionInvariant();
return AdaptedEventSymbol.MetadataName;
}
}
#endregion
}
internal partial class EventSymbol
{
#if DEBUG
private EventSymbolAdapter? _lazyAdapter;
protected sealed override SymbolAdapter GetCciAdapterImpl() => GetCciAdapter();
internal new EventSymbolAdapter GetCciAdapter()
{
if (_lazyAdapter is null)
{
return InterlockedOperations.Initialize(ref _lazyAdapter, new EventSymbolAdapter(this));
}
return _lazyAdapter;
}
#else
internal EventSymbol AdaptedEventSymbol => this;
internal new EventSymbol GetCciAdapter()
{
return this;
}
#endif
internal virtual bool HasRuntimeSpecialName
{
get
{
CheckDefinitionInvariant();
return false;
}
}
}
#if DEBUG
internal partial class EventSymbolAdapter
{
internal EventSymbolAdapter(EventSymbol underlyingEventSymbol)
{
AdaptedEventSymbol = underlyingEventSymbol;
}
internal sealed override Symbol AdaptedSymbol => AdaptedEventSymbol;
internal EventSymbol AdaptedEventSymbol { get; }
}
#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 System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Cci;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.Emit;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal partial class
#if DEBUG
EventSymbolAdapter : SymbolAdapter,
#else
EventSymbol :
#endif
Cci.IEventDefinition
{
#region IEventDefinition Members
IEnumerable<Cci.IMethodReference> Cci.IEventDefinition.GetAccessors(EmitContext context)
{
CheckDefinitionInvariant();
var addMethod = AdaptedEventSymbol.AddMethod?.GetCciAdapter();
RoslynDebug.Assert((object?)addMethod != null);
if (addMethod.ShouldInclude(context))
{
yield return addMethod;
}
var removeMethod = AdaptedEventSymbol.RemoveMethod?.GetCciAdapter();
RoslynDebug.Assert((object?)removeMethod != null);
if (removeMethod.ShouldInclude(context))
{
yield return removeMethod;
}
}
Cci.IMethodReference Cci.IEventDefinition.Adder
{
get
{
CheckDefinitionInvariant();
var addMethod = AdaptedEventSymbol.AddMethod?.GetCciAdapter();
RoslynDebug.Assert((object?)addMethod != null);
return addMethod;
}
}
Cci.IMethodReference Cci.IEventDefinition.Remover
{
get
{
CheckDefinitionInvariant();
var removeMethod = AdaptedEventSymbol.RemoveMethod?.GetCciAdapter();
RoslynDebug.Assert((object?)removeMethod != null);
return removeMethod;
}
}
bool Cci.IEventDefinition.IsRuntimeSpecial
{
get
{
CheckDefinitionInvariant();
return AdaptedEventSymbol.HasRuntimeSpecialName;
}
}
bool Cci.IEventDefinition.IsSpecialName
{
get
{
CheckDefinitionInvariant();
return AdaptedEventSymbol.HasSpecialName;
}
}
Cci.IMethodReference? Cci.IEventDefinition.Caller
{
get
{
CheckDefinitionInvariant();
return null; // C# doesn't use the raise/fire accessor
}
}
Cci.ITypeReference Cci.IEventDefinition.GetType(EmitContext context)
{
return ((PEModuleBuilder)context.Module).Translate(AdaptedEventSymbol.Type, syntaxNodeOpt: (CSharpSyntaxNode?)context.SyntaxNode, diagnostics: context.Diagnostics);
}
#endregion
#region ITypeDefinitionMember Members
Cci.ITypeDefinition Cci.ITypeDefinitionMember.ContainingTypeDefinition
{
get
{
CheckDefinitionInvariant();
return AdaptedEventSymbol.ContainingType.GetCciAdapter();
}
}
Cci.TypeMemberVisibility Cci.ITypeDefinitionMember.Visibility
{
get
{
CheckDefinitionInvariant();
return PEModuleBuilder.MemberVisibility(AdaptedEventSymbol);
}
}
#endregion
#region ITypeMemberReference Members
Cci.ITypeReference Cci.ITypeMemberReference.GetContainingType(EmitContext context)
{
CheckDefinitionInvariant();
return AdaptedEventSymbol.ContainingType.GetCciAdapter();
}
#endregion
#region IReference Members
void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor)
{
CheckDefinitionInvariant();
visitor.Visit((Cci.IEventDefinition)this);
}
Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context)
{
CheckDefinitionInvariant();
return this;
}
#endregion
#region INamedEntity Members
string Cci.INamedEntity.Name
{
get
{
CheckDefinitionInvariant();
return AdaptedEventSymbol.MetadataName;
}
}
#endregion
}
internal partial class EventSymbol
{
#if DEBUG
private EventSymbolAdapter? _lazyAdapter;
protected sealed override SymbolAdapter GetCciAdapterImpl() => GetCciAdapter();
internal new EventSymbolAdapter GetCciAdapter()
{
if (_lazyAdapter is null)
{
return InterlockedOperations.Initialize(ref _lazyAdapter, new EventSymbolAdapter(this));
}
return _lazyAdapter;
}
#else
internal EventSymbol AdaptedEventSymbol => this;
internal new EventSymbol GetCciAdapter()
{
return this;
}
#endif
internal virtual bool HasRuntimeSpecialName
{
get
{
CheckDefinitionInvariant();
return false;
}
}
}
#if DEBUG
internal partial class EventSymbolAdapter
{
internal EventSymbolAdapter(EventSymbol underlyingEventSymbol)
{
AdaptedEventSymbol = underlyingEventSymbol;
}
internal sealed override Symbol AdaptedSymbol => AdaptedEventSymbol;
internal EventSymbol AdaptedEventSymbol { get; }
}
#endif
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Analyzers/CSharp/Analyzers/AddRequiredParentheses/CSharpAddRequiredPatternParenthesesDiagnosticAnalyzer.cs | // Licensed to the .NET Foundation under one or more 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.AddRequiredParentheses;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Precedence;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.AddRequiredParentheses
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class CSharpAddRequiredPatternParenthesesDiagnosticAnalyzer :
AbstractAddRequiredParenthesesDiagnosticAnalyzer<
PatternSyntax, BinaryPatternSyntax, SyntaxKind>
{
public CSharpAddRequiredPatternParenthesesDiagnosticAnalyzer()
: base(CSharpPatternPrecedenceService.Instance)
{
}
private static readonly ImmutableArray<SyntaxKind> s_kinds = ImmutableArray.Create(
SyntaxKind.AndPattern,
SyntaxKind.OrPattern);
protected override ImmutableArray<SyntaxKind> GetSyntaxNodeKinds()
=> s_kinds;
protected override int GetPrecedence(BinaryPatternSyntax pattern)
=> (int)pattern.GetOperatorPrecedence();
protected override bool IsBinaryLike(PatternSyntax node)
=> node is BinaryPatternSyntax;
protected override (PatternSyntax, SyntaxToken, PatternSyntax) GetPartsOfBinaryLike(BinaryPatternSyntax binaryPattern)
{
Debug.Assert(IsBinaryLike(binaryPattern));
return (binaryPattern.Left, binaryPattern.OperatorToken, binaryPattern.Right);
}
protected override PatternSyntax? TryGetAppropriateParent(BinaryPatternSyntax binaryLike)
=> binaryLike.Parent as PatternSyntax;
}
}
| // Licensed to the .NET Foundation under one or more 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.AddRequiredParentheses;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Precedence;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.AddRequiredParentheses
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class CSharpAddRequiredPatternParenthesesDiagnosticAnalyzer :
AbstractAddRequiredParenthesesDiagnosticAnalyzer<
PatternSyntax, BinaryPatternSyntax, SyntaxKind>
{
public CSharpAddRequiredPatternParenthesesDiagnosticAnalyzer()
: base(CSharpPatternPrecedenceService.Instance)
{
}
private static readonly ImmutableArray<SyntaxKind> s_kinds = ImmutableArray.Create(
SyntaxKind.AndPattern,
SyntaxKind.OrPattern);
protected override ImmutableArray<SyntaxKind> GetSyntaxNodeKinds()
=> s_kinds;
protected override int GetPrecedence(BinaryPatternSyntax pattern)
=> (int)pattern.GetOperatorPrecedence();
protected override bool IsBinaryLike(PatternSyntax node)
=> node is BinaryPatternSyntax;
protected override (PatternSyntax, SyntaxToken, PatternSyntax) GetPartsOfBinaryLike(BinaryPatternSyntax binaryPattern)
{
Debug.Assert(IsBinaryLike(binaryPattern));
return (binaryPattern.Left, binaryPattern.OperatorToken, binaryPattern.Right);
}
protected override PatternSyntax? TryGetAppropriateParent(BinaryPatternSyntax binaryLike)
=> binaryLike.Parent as PatternSyntax;
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Features/Core/Portable/RQName/Nodes/RQNullType.cs | // Licensed to the .NET Foundation under one or more 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.Features.RQName.SimpleTree;
namespace Microsoft.CodeAnalysis.Features.RQName.Nodes
{
internal class RQNullType : RQType
{
public static readonly RQNullType Singleton = new();
private RQNullType() { }
public override SimpleTreeNode ToSimpleTree()
=> new SimpleLeafNode(RQNameStrings.Null);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Features.RQName.SimpleTree;
namespace Microsoft.CodeAnalysis.Features.RQName.Nodes
{
internal class RQNullType : RQType
{
public static readonly RQNullType Singleton = new();
private RQNullType() { }
public override SimpleTreeNode ToSimpleTree()
=> new SimpleLeafNode(RQNameStrings.Null);
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Compilers/VisualBasic/Test/Semantic/Semantics/MissingRuntimeHelpers.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.IO
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.SpecialType
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Public Class MissingRuntimeHelpers
Inherits BasicTestBase
<Fact>
Public Sub SpecialMembers()
Dim compilationDef =
<compilation name="SpecialMembers">
<file name="a.vb">
Class Program
Sub Main()
Dim Ob As Object = Nothing
Dim St As String = Nothing
Dim [Do] as Double = 0
Dim Da as Date = Nothing
Dim De as Decimal = Nothing
Dim ChArray As Char() = Nothing
Test([Do] ^ [Do])
Test(Da > Da)
Test(De > De)
Test(De + De)
Test(St + St)
Test(-De)
Test(CType(ChArray, String))
Test(CDec([Do]))
Test(CInt(De))
Test(CInt([Do]))
End Sub
Sub Test(x As Object)
End Sub
End Class
Namespace System
Public Class [Object]
End Class
Public Class [String]
End Class
Public Class Array
End Class
Public Structure Void
End Structure
Public Structure [Double]
End Structure
Public Structure Int32
End Structure
Public Structure [Boolean]
End Structure
Public Structure DateTime
End Structure
Public Structure [Decimal]
End Structure
Public Structure [Char]
End Structure
Public Class ValueType
End Class
End Namespace
</file>
</compilation>
Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(compilationDef, New MetadataReference() {})
AssertTheseEmitDiagnostics(compilation,
<expected>
BC35000: Requested operation is not available because the runtime library function 'System.DateTime.New' is not defined.
Dim Da as Date = Nothing
~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.Decimal.New' is not defined.
Dim De as Decimal = Nothing
~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.Math.Pow' is not defined.
Test([Do] ^ [Do])
~~~~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.DateTime.Compare' is not defined.
Test(Da > Da)
~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.Decimal.Compare' is not defined.
Test(De > De)
~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.Decimal.Add' is not defined.
Test(De + De)
~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.String.Concat' is not defined.
Test(St + St)
~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.Decimal.Negate' is not defined.
Test(-De)
~~~
BC35000: Requested operation is not available because the runtime library function 'System.String.New' is not defined.
Test(CType(ChArray, String))
~~~~~~~~~~~~~~~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.Decimal.New' is not defined.
Test(CDec([Do]))
~~~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.Convert.ToInt32' is not defined.
Test(CInt(De))
~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.Math.Round' is not defined.
Test(CInt([Do]))
~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub WellKnownMembers()
Dim compilationDef =
<compilation name="WellKnownMembers">
<file name="a.vb">
Class Program
Sub Main()
Dim Ob As Object = Nothing
Dim St as String = Nothing
Dim [Do] as Double = 0
Dim Bo As Boolean = false
Test(St > St)
Test(Ob AndAlso Ob)
Test(Ob + Ob)
Test(St Like St)
Test(Ob > Ob)
Test(Not Ob)
Test(CType(Ob, Char()))
Test(CLng(Ob))
Test(CStr([Do]))
Test(CInt(St))
Test(CDec(Bo))
End Sub
Sub Test(x As Object)
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(compilationDef)
AssertTheseEmitDiagnostics(compilation,
<expected>
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.Operators.CompareString' is not defined.
Test(St > St)
~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean' is not defined.
Test(Ob AndAlso Ob)
~~~~~~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.Operators.AddObject' is not defined.
Test(Ob + Ob)
~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.LikeOperator.LikeString' is not defined.
Test(St Like St)
~~~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.Operators.CompareObjectGreater' is not defined.
Test(Ob > Ob)
~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.Operators.NotObject' is not defined.
Test(Not Ob)
~~~~~~
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.Conversions.ToCharArrayRankOne' is not defined.
Test(CType(Ob, Char()))
~~~~~~~~~~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.Conversions.ToLong' is not defined.
Test(CLng(Ob))
~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.Conversions.ToString' is not defined.
Test(CStr([Do]))
~~~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger' is not defined.
Test(CInt(St))
~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.Conversions.ToDecimal' is not defined.
Test(CDec(Bo))
~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub MissingCompareExchange()
Dim compilationDef =
<compilation name="SpecialMembers">
<file name="a.vb">
Delegate Sub E1()
Class Program
public event e as E1
public shared Sub Main()
dim v as new Program
AddHandler v.e, AddressOf Main
End Sub
End Class
Namespace System
Public Class [Object]
End Class
Public Class [String]
End Class
Public Class Array
End Class
Public Structure Void
End Structure
Public Structure [Double]
End Structure
Public Structure Int32
End Structure
Public Structure [Boolean]
End Structure
Public Structure DateTime
End Structure
Public Structure [Decimal]
End Structure
Public Structure [Char]
End Structure
Public Structure IntPtr
End Structure
Public Class ValueType
End Class
Public Class [Delegate]
End Class
Public Class MulticastDelegate
End Class
End Namespace
</file>
</compilation>
Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(compilationDef, New MetadataReference() {})
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<expected>
BC30002: Type 'System.AsyncCallback' is not defined.
Delegate Sub E1()
~~~~~~~~~~~~~~~~~
BC30002: Type 'System.IAsyncResult' is not defined.
Delegate Sub E1()
~~~~~~~~~~~~~~~~~
</expected>)
CompilationUtils.AssertTheseCompileDiagnostics(compilation,
<expected>
BC30002: Type 'System.AsyncCallback' is not defined.
Delegate Sub E1()
~~~~~~~~~~~~~~~~~
BC30002: Type 'System.IAsyncResult' is not defined.
Delegate Sub E1()
~~~~~~~~~~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.Delegate.Combine' is not defined.
public event e as E1
~~~~~~~~~~~~~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.Delegate.Remove' is not defined.
public event e as E1
~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub MalformedSystemArray()
Dim compilationDef =
<compilation name="SpecialMembers">
<file name="a.vb">
Class Program
public shared Sub Main()
dim x() as integer = nothing
for each e in x
next
End Sub
End Class
Namespace System
Public Class [Object]
End Class
Public Class [String]
End Class
Public Class Array
Public Readonly Property Length as integer
Get
return 0
end get
end property
End Class
Public Structure Void
End Structure
Public Structure [Double]
End Structure
Public Structure Int32
End Structure
Public Structure [Boolean]
End Structure
Public Structure DateTime
End Structure
Public Structure [Decimal]
End Structure
Public Structure [Char]
End Structure
Public Structure IntPtr
End Structure
Public Class ValueType
End Class
End Namespace
</file>
</compilation>
Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(compilationDef, New MetadataReference() {})
CompilationUtils.AssertTheseCompileDiagnostics(compilation,
<expected>
BC32023: Expression is of type 'Integer()', which is not a collection type.
for each e in x
~
</expected>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC32023: Expression is of type 'Integer()', which is not a collection type.
for each e in x
~
</expected>)
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.IO
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.SpecialType
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Public Class MissingRuntimeHelpers
Inherits BasicTestBase
<Fact>
Public Sub SpecialMembers()
Dim compilationDef =
<compilation name="SpecialMembers">
<file name="a.vb">
Class Program
Sub Main()
Dim Ob As Object = Nothing
Dim St As String = Nothing
Dim [Do] as Double = 0
Dim Da as Date = Nothing
Dim De as Decimal = Nothing
Dim ChArray As Char() = Nothing
Test([Do] ^ [Do])
Test(Da > Da)
Test(De > De)
Test(De + De)
Test(St + St)
Test(-De)
Test(CType(ChArray, String))
Test(CDec([Do]))
Test(CInt(De))
Test(CInt([Do]))
End Sub
Sub Test(x As Object)
End Sub
End Class
Namespace System
Public Class [Object]
End Class
Public Class [String]
End Class
Public Class Array
End Class
Public Structure Void
End Structure
Public Structure [Double]
End Structure
Public Structure Int32
End Structure
Public Structure [Boolean]
End Structure
Public Structure DateTime
End Structure
Public Structure [Decimal]
End Structure
Public Structure [Char]
End Structure
Public Class ValueType
End Class
End Namespace
</file>
</compilation>
Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(compilationDef, New MetadataReference() {})
AssertTheseEmitDiagnostics(compilation,
<expected>
BC35000: Requested operation is not available because the runtime library function 'System.DateTime.New' is not defined.
Dim Da as Date = Nothing
~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.Decimal.New' is not defined.
Dim De as Decimal = Nothing
~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.Math.Pow' is not defined.
Test([Do] ^ [Do])
~~~~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.DateTime.Compare' is not defined.
Test(Da > Da)
~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.Decimal.Compare' is not defined.
Test(De > De)
~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.Decimal.Add' is not defined.
Test(De + De)
~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.String.Concat' is not defined.
Test(St + St)
~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.Decimal.Negate' is not defined.
Test(-De)
~~~
BC35000: Requested operation is not available because the runtime library function 'System.String.New' is not defined.
Test(CType(ChArray, String))
~~~~~~~~~~~~~~~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.Decimal.New' is not defined.
Test(CDec([Do]))
~~~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.Convert.ToInt32' is not defined.
Test(CInt(De))
~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.Math.Round' is not defined.
Test(CInt([Do]))
~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub WellKnownMembers()
Dim compilationDef =
<compilation name="WellKnownMembers">
<file name="a.vb">
Class Program
Sub Main()
Dim Ob As Object = Nothing
Dim St as String = Nothing
Dim [Do] as Double = 0
Dim Bo As Boolean = false
Test(St > St)
Test(Ob AndAlso Ob)
Test(Ob + Ob)
Test(St Like St)
Test(Ob > Ob)
Test(Not Ob)
Test(CType(Ob, Char()))
Test(CLng(Ob))
Test(CStr([Do]))
Test(CInt(St))
Test(CDec(Bo))
End Sub
Sub Test(x As Object)
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(compilationDef)
AssertTheseEmitDiagnostics(compilation,
<expected>
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.Operators.CompareString' is not defined.
Test(St > St)
~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean' is not defined.
Test(Ob AndAlso Ob)
~~~~~~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.Operators.AddObject' is not defined.
Test(Ob + Ob)
~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.LikeOperator.LikeString' is not defined.
Test(St Like St)
~~~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.Operators.CompareObjectGreater' is not defined.
Test(Ob > Ob)
~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.Operators.NotObject' is not defined.
Test(Not Ob)
~~~~~~
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.Conversions.ToCharArrayRankOne' is not defined.
Test(CType(Ob, Char()))
~~~~~~~~~~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.Conversions.ToLong' is not defined.
Test(CLng(Ob))
~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.Conversions.ToString' is not defined.
Test(CStr([Do]))
~~~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger' is not defined.
Test(CInt(St))
~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.Conversions.ToDecimal' is not defined.
Test(CDec(Bo))
~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub MissingCompareExchange()
Dim compilationDef =
<compilation name="SpecialMembers">
<file name="a.vb">
Delegate Sub E1()
Class Program
public event e as E1
public shared Sub Main()
dim v as new Program
AddHandler v.e, AddressOf Main
End Sub
End Class
Namespace System
Public Class [Object]
End Class
Public Class [String]
End Class
Public Class Array
End Class
Public Structure Void
End Structure
Public Structure [Double]
End Structure
Public Structure Int32
End Structure
Public Structure [Boolean]
End Structure
Public Structure DateTime
End Structure
Public Structure [Decimal]
End Structure
Public Structure [Char]
End Structure
Public Structure IntPtr
End Structure
Public Class ValueType
End Class
Public Class [Delegate]
End Class
Public Class MulticastDelegate
End Class
End Namespace
</file>
</compilation>
Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(compilationDef, New MetadataReference() {})
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation,
<expected>
BC30002: Type 'System.AsyncCallback' is not defined.
Delegate Sub E1()
~~~~~~~~~~~~~~~~~
BC30002: Type 'System.IAsyncResult' is not defined.
Delegate Sub E1()
~~~~~~~~~~~~~~~~~
</expected>)
CompilationUtils.AssertTheseCompileDiagnostics(compilation,
<expected>
BC30002: Type 'System.AsyncCallback' is not defined.
Delegate Sub E1()
~~~~~~~~~~~~~~~~~
BC30002: Type 'System.IAsyncResult' is not defined.
Delegate Sub E1()
~~~~~~~~~~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.Delegate.Combine' is not defined.
public event e as E1
~~~~~~~~~~~~~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.Delegate.Remove' is not defined.
public event e as E1
~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub MalformedSystemArray()
Dim compilationDef =
<compilation name="SpecialMembers">
<file name="a.vb">
Class Program
public shared Sub Main()
dim x() as integer = nothing
for each e in x
next
End Sub
End Class
Namespace System
Public Class [Object]
End Class
Public Class [String]
End Class
Public Class Array
Public Readonly Property Length as integer
Get
return 0
end get
end property
End Class
Public Structure Void
End Structure
Public Structure [Double]
End Structure
Public Structure Int32
End Structure
Public Structure [Boolean]
End Structure
Public Structure DateTime
End Structure
Public Structure [Decimal]
End Structure
Public Structure [Char]
End Structure
Public Structure IntPtr
End Structure
Public Class ValueType
End Class
End Namespace
</file>
</compilation>
Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(compilationDef, New MetadataReference() {})
CompilationUtils.AssertTheseCompileDiagnostics(compilation,
<expected>
BC32023: Expression is of type 'Integer()', which is not a collection type.
for each e in x
~
</expected>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC32023: Expression is of type 'Integer()', which is not a collection type.
for each e in x
~
</expected>)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Workspaces/Core/Portable/TemporaryStorage/TemporaryStorageServiceFactory.cs | // Licensed to the .NET Foundation under one or more 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.IO;
using System.IO.MemoryMappedFiles;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Host
{
[ExportWorkspaceServiceFactory(typeof(ITemporaryStorageService), ServiceLayer.Default), Shared]
internal partial class TemporaryStorageServiceFactory : IWorkspaceServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TemporaryStorageServiceFactory()
{
}
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
{
var textFactory = workspaceServices.GetRequiredService<ITextFactoryService>();
// MemoryMapped files which are used by the TemporaryStorageService are present in .NET Framework (including Mono)
// and .NET Core Windows. For non-Windows .NET Core scenarios, we can return the TrivialTemporaryStorageService
// until https://github.com/dotnet/runtime/issues/30878 is fixed.
return PlatformInformation.IsWindows || PlatformInformation.IsRunningOnMono
? (ITemporaryStorageService)new TemporaryStorageService(textFactory)
: TrivialTemporaryStorageService.Instance;
}
/// <summary>
/// Temporarily stores text and streams in memory mapped files.
/// </summary>
internal class TemporaryStorageService : ITemporaryStorageService2
{
/// <summary>
/// The maximum size in bytes of a single storage unit in a memory mapped file which is shared with other
/// storage units.
/// </summary>
/// <remarks>
/// <para>This value was arbitrarily chosen and appears to work well. Can be changed if data suggests
/// something better.</para>
/// </remarks>
/// <seealso cref="_weakFileReference"/>
private const long SingleFileThreshold = 128 * 1024;
/// <summary>
/// The size in bytes of a memory mapped file created to store multiple temporary objects.
/// </summary>
/// <remarks>
/// <para>This value was arbitrarily chosen and appears to work well. Can be changed if data suggests
/// something better.</para>
/// </remarks>
/// <seealso cref="_weakFileReference"/>
private const long MultiFileBlockSize = SingleFileThreshold * 32;
private readonly ITextFactoryService _textFactory;
/// <summary>
/// The synchronization object for accessing the memory mapped file related fields (indicated in the remarks
/// of each field).
/// </summary>
/// <remarks>
/// <para>PERF DEV NOTE: A concurrent (but complex) implementation of this type with identical semantics is
/// available in source control history. The use of exclusive locks was not causing any measurable
/// performance overhead even on 28-thread machines at the time this was written.</para>
/// </remarks>
private readonly object _gate = new();
/// <summary>
/// The most recent memory mapped file for creating multiple storage units. It will be used via bump-pointer
/// allocation until space is no longer available in it.
/// </summary>
/// <remarks>
/// <para>Access should be synchronized on <see cref="_gate"/>.</para>
/// </remarks>
private ReferenceCountedDisposable<MemoryMappedFile>.WeakReference _weakFileReference;
/// <summary>The name of the current memory mapped file for multiple storage units.</summary>
/// <remarks>
/// <para>Access should be synchronized on <see cref="_gate"/>.</para>
/// </remarks>
/// <seealso cref="_weakFileReference"/>
private string? _name;
/// <summary>The total size of the current memory mapped file for multiple storage units.</summary>
/// <remarks>
/// <para>Access should be synchronized on <see cref="_gate"/>.</para>
/// </remarks>
/// <seealso cref="_weakFileReference"/>
private long _fileSize;
/// <summary>
/// The offset into the current memory mapped file where the next storage unit can be held.
/// </summary>
/// <remarks>
/// <para>Access should be synchronized on <see cref="_gate"/>.</para>
/// </remarks>
/// <seealso cref="_weakFileReference"/>
private long _offset;
public TemporaryStorageService(ITextFactoryService textFactory)
=> _textFactory = textFactory;
public ITemporaryTextStorage CreateTemporaryTextStorage(CancellationToken cancellationToken)
=> new TemporaryTextStorage(this);
public ITemporaryTextStorage AttachTemporaryTextStorage(string storageName, long offset, long size, SourceHashAlgorithm checksumAlgorithm, Encoding? encoding, CancellationToken cancellationToken)
=> new TemporaryTextStorage(this, storageName, offset, size, checksumAlgorithm, encoding);
public ITemporaryStreamStorage CreateTemporaryStreamStorage(CancellationToken cancellationToken)
=> new TemporaryStreamStorage(this);
public ITemporaryStreamStorage AttachTemporaryStreamStorage(string storageName, long offset, long size, CancellationToken cancellationToken)
=> new TemporaryStreamStorage(this, storageName, offset, size);
/// <summary>
/// Allocate shared storage of a specified size.
/// </summary>
/// <remarks>
/// <para>"Small" requests are fulfilled from oversized memory mapped files which support several individual
/// storage units. Larger requests are allocated in their own memory mapped files.</para>
/// </remarks>
/// <param name="size">The size of the shared storage block to allocate.</param>
/// <returns>A <see cref="MemoryMappedInfo"/> describing the allocated block.</returns>
private MemoryMappedInfo CreateTemporaryStorage(long size)
{
if (size >= SingleFileThreshold)
{
// Larger blocks are allocated separately
var mapName = CreateUniqueName(size);
var storage = MemoryMappedFile.CreateNew(mapName, size);
return new MemoryMappedInfo(new ReferenceCountedDisposable<MemoryMappedFile>(storage), mapName, offset: 0, size: size);
}
lock (_gate)
{
// Obtain a reference to the memory mapped file, creating one if necessary. If a reference counted
// handle to a memory mapped file is obtained in this section, it must either be disposed before
// returning or returned to the caller who will own it through the MemoryMappedInfo.
var reference = _weakFileReference.TryAddReference();
if (reference == null || _offset + size > _fileSize)
{
var mapName = CreateUniqueName(MultiFileBlockSize);
var file = MemoryMappedFile.CreateNew(mapName, MultiFileBlockSize);
reference = new ReferenceCountedDisposable<MemoryMappedFile>(file);
_weakFileReference = new ReferenceCountedDisposable<MemoryMappedFile>.WeakReference(reference);
_name = mapName;
_fileSize = MultiFileBlockSize;
_offset = size;
return new MemoryMappedInfo(reference, _name, offset: 0, size: size);
}
else
{
// Reserve additional space in the existing storage location
Contract.ThrowIfNull(_name);
_offset += size;
return new MemoryMappedInfo(reference, _name, _offset - size, size);
}
}
}
public static string CreateUniqueName(long size)
=> "Roslyn Temp Storage " + size.ToString() + " " + Guid.NewGuid().ToString("N");
private sealed class TemporaryTextStorage : ITemporaryTextStorage, ITemporaryTextStorageWithName
{
private readonly TemporaryStorageService _service;
private SourceHashAlgorithm _checksumAlgorithm;
private Encoding? _encoding;
private ImmutableArray<byte> _checksum;
private MemoryMappedInfo? _memoryMappedInfo;
public TemporaryTextStorage(TemporaryStorageService service)
=> _service = service;
public TemporaryTextStorage(TemporaryStorageService service, string storageName, long offset, long size, SourceHashAlgorithm checksumAlgorithm, Encoding? encoding)
{
_service = service;
_checksumAlgorithm = checksumAlgorithm;
_encoding = encoding;
_memoryMappedInfo = new MemoryMappedInfo(storageName, offset, size);
}
// TODO: cleanup https://github.com/dotnet/roslyn/issues/43037
// Offet, Size not accessed if Name is null
public string? Name => _memoryMappedInfo?.Name;
public long Offset => _memoryMappedInfo!.Offset;
public long Size => _memoryMappedInfo!.Size;
public SourceHashAlgorithm ChecksumAlgorithm => _checksumAlgorithm;
public Encoding? Encoding => _encoding;
public ImmutableArray<byte> GetChecksum()
{
if (_checksum.IsDefault)
{
ImmutableInterlocked.InterlockedInitialize(ref _checksum, ReadText(CancellationToken.None).GetChecksum());
}
return _checksum;
}
public void Dispose()
{
// Destructors of SafeHandle and FileStream in MemoryMappedFile
// will eventually release resources if this Dispose is not called
// explicitly
_memoryMappedInfo?.Dispose();
_memoryMappedInfo = null;
_encoding = null;
}
public SourceText ReadText(CancellationToken cancellationToken)
{
if (_memoryMappedInfo == null)
{
throw new InvalidOperationException();
}
using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_ReadText, cancellationToken))
{
using var stream = _memoryMappedInfo.CreateReadableStream();
using var reader = CreateTextReaderFromTemporaryStorage((ISupportDirectMemoryAccess)stream, (int)stream.Length);
// we pass in encoding we got from original source text even if it is null.
return _service._textFactory.CreateText(reader, _encoding, cancellationToken);
}
}
public Task<SourceText> ReadTextAsync(CancellationToken cancellationToken)
{
// There is a reason for implementing it like this: proper async implementation
// that reads the underlying memory mapped file stream in an asynchronous fashion
// doesn't actually work. Windows doesn't offer
// any non-blocking way to read from a memory mapped file; the underlying memcpy
// may block as the memory pages back in and that's something you have to live
// with. Therefore, any implementation that attempts to use async will still
// always be blocking at least one threadpool thread in the memcpy in the case
// of a page fault. Therefore, if we're going to be blocking a thread, we should
// just block one thread and do the whole thing at once vs. a fake "async"
// implementation which will continue to requeue work back to the thread pool.
return Task.Factory.StartNew(() => ReadText(cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default);
}
public void WriteText(SourceText text, CancellationToken cancellationToken)
{
if (_memoryMappedInfo != null)
{
throw new InvalidOperationException();
}
using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_WriteText, cancellationToken))
{
_checksumAlgorithm = text.ChecksumAlgorithm;
_encoding = text.Encoding;
// the method we use to get text out of SourceText uses Unicode (2bytes per char).
var size = Encoding.Unicode.GetMaxByteCount(text.Length);
_memoryMappedInfo = _service.CreateTemporaryStorage(size);
// Write the source text out as Unicode. We expect that to be cheap.
using var stream = _memoryMappedInfo.CreateWritableStream();
using var writer = new StreamWriter(stream, Encoding.Unicode);
text.Write(writer, cancellationToken);
}
}
public Task WriteTextAsync(SourceText text, CancellationToken cancellationToken = default)
{
// See commentary in ReadTextAsync for why this is implemented this way.
return Task.Factory.StartNew(() => WriteText(text, cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default);
}
private static unsafe TextReader CreateTextReaderFromTemporaryStorage(ISupportDirectMemoryAccess accessor, int streamLength)
{
var src = (char*)accessor.GetPointer();
// BOM: Unicode, little endian
// Skip the BOM when creating the reader
Debug.Assert(*src == 0xFEFF);
return new DirectMemoryAccessStreamReader(src + 1, streamLength / sizeof(char) - 1);
}
}
private class TemporaryStreamStorage : ITemporaryStreamStorage, ITemporaryStorageWithName
{
private readonly TemporaryStorageService _service;
private MemoryMappedInfo? _memoryMappedInfo;
public TemporaryStreamStorage(TemporaryStorageService service)
=> _service = service;
public TemporaryStreamStorage(TemporaryStorageService service, string storageName, long offset, long size)
{
_service = service;
_memoryMappedInfo = new MemoryMappedInfo(storageName, offset, size);
}
// TODO: clean up https://github.com/dotnet/roslyn/issues/43037
// Offset, Size is only used when Name is not null.
public string? Name => _memoryMappedInfo?.Name;
public long Offset => _memoryMappedInfo!.Offset;
public long Size => _memoryMappedInfo!.Size;
public void Dispose()
{
// Destructors of SafeHandle and FileStream in MemoryMappedFile
// will eventually release resources if this Dispose is not called
// explicitly
_memoryMappedInfo?.Dispose();
_memoryMappedInfo = null;
}
public Stream ReadStream(CancellationToken cancellationToken)
{
if (_memoryMappedInfo == null)
{
throw new InvalidOperationException();
}
using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_ReadStream, cancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
return _memoryMappedInfo.CreateReadableStream();
}
}
public Task<Stream> ReadStreamAsync(CancellationToken cancellationToken = default)
{
// See commentary in ReadTextAsync for why this is implemented this way.
return Task.Factory.StartNew(() => ReadStream(cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default);
}
public void WriteStream(Stream stream, CancellationToken cancellationToken = default)
{
// The Wait() here will not actually block, since with useAsync: false, the
// entire operation will already be done when WaitStreamMaybeAsync completes.
WriteStreamMaybeAsync(stream, useAsync: false, cancellationToken: cancellationToken).GetAwaiter().GetResult();
}
public Task WriteStreamAsync(Stream stream, CancellationToken cancellationToken = default)
=> WriteStreamMaybeAsync(stream, useAsync: true, cancellationToken: cancellationToken);
private async Task WriteStreamMaybeAsync(Stream stream, bool useAsync, CancellationToken cancellationToken)
{
if (_memoryMappedInfo != null)
{
throw new InvalidOperationException(WorkspacesResources.Temporary_storage_cannot_be_written_more_than_once);
}
using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_WriteStream, cancellationToken))
{
var size = stream.Length;
_memoryMappedInfo = _service.CreateTemporaryStorage(size);
using var viewStream = _memoryMappedInfo.CreateWritableStream();
var buffer = SharedPools.ByteArray.Allocate();
try
{
while (true)
{
int count;
if (useAsync)
{
count = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);
}
else
{
count = stream.Read(buffer, 0, buffer.Length);
}
if (count == 0)
{
break;
}
viewStream.Write(buffer, 0, count);
}
}
finally
{
SharedPools.ByteArray.Free(buffer);
}
}
}
}
}
internal unsafe class DirectMemoryAccessStreamReader : TextReaderWithLength
{
private char* _position;
private readonly char* _end;
public DirectMemoryAccessStreamReader(char* src, int length)
: base(length)
{
RoslynDebug.Assert(src != null);
RoslynDebug.Assert(length >= 0);
_position = src;
_end = _position + length;
}
public override int Peek()
{
if (_position >= _end)
{
return -1;
}
return *_position;
}
public override int Read()
{
if (_position >= _end)
{
return -1;
}
return *_position++;
}
public override int Read(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (index < 0 || index >= buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
if (count < 0 || (index + count) > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
count = Math.Min(count, (int)(_end - _position));
if (count > 0)
{
Marshal.Copy((IntPtr)_position, buffer, index, count);
_position += count;
}
return count;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Host
{
[ExportWorkspaceServiceFactory(typeof(ITemporaryStorageService), ServiceLayer.Default), Shared]
internal partial class TemporaryStorageServiceFactory : IWorkspaceServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TemporaryStorageServiceFactory()
{
}
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
{
var textFactory = workspaceServices.GetRequiredService<ITextFactoryService>();
// MemoryMapped files which are used by the TemporaryStorageService are present in .NET Framework (including Mono)
// and .NET Core Windows. For non-Windows .NET Core scenarios, we can return the TrivialTemporaryStorageService
// until https://github.com/dotnet/runtime/issues/30878 is fixed.
return PlatformInformation.IsWindows || PlatformInformation.IsRunningOnMono
? (ITemporaryStorageService)new TemporaryStorageService(textFactory)
: TrivialTemporaryStorageService.Instance;
}
/// <summary>
/// Temporarily stores text and streams in memory mapped files.
/// </summary>
internal class TemporaryStorageService : ITemporaryStorageService2
{
/// <summary>
/// The maximum size in bytes of a single storage unit in a memory mapped file which is shared with other
/// storage units.
/// </summary>
/// <remarks>
/// <para>This value was arbitrarily chosen and appears to work well. Can be changed if data suggests
/// something better.</para>
/// </remarks>
/// <seealso cref="_weakFileReference"/>
private const long SingleFileThreshold = 128 * 1024;
/// <summary>
/// The size in bytes of a memory mapped file created to store multiple temporary objects.
/// </summary>
/// <remarks>
/// <para>This value was arbitrarily chosen and appears to work well. Can be changed if data suggests
/// something better.</para>
/// </remarks>
/// <seealso cref="_weakFileReference"/>
private const long MultiFileBlockSize = SingleFileThreshold * 32;
private readonly ITextFactoryService _textFactory;
/// <summary>
/// The synchronization object for accessing the memory mapped file related fields (indicated in the remarks
/// of each field).
/// </summary>
/// <remarks>
/// <para>PERF DEV NOTE: A concurrent (but complex) implementation of this type with identical semantics is
/// available in source control history. The use of exclusive locks was not causing any measurable
/// performance overhead even on 28-thread machines at the time this was written.</para>
/// </remarks>
private readonly object _gate = new();
/// <summary>
/// The most recent memory mapped file for creating multiple storage units. It will be used via bump-pointer
/// allocation until space is no longer available in it.
/// </summary>
/// <remarks>
/// <para>Access should be synchronized on <see cref="_gate"/>.</para>
/// </remarks>
private ReferenceCountedDisposable<MemoryMappedFile>.WeakReference _weakFileReference;
/// <summary>The name of the current memory mapped file for multiple storage units.</summary>
/// <remarks>
/// <para>Access should be synchronized on <see cref="_gate"/>.</para>
/// </remarks>
/// <seealso cref="_weakFileReference"/>
private string? _name;
/// <summary>The total size of the current memory mapped file for multiple storage units.</summary>
/// <remarks>
/// <para>Access should be synchronized on <see cref="_gate"/>.</para>
/// </remarks>
/// <seealso cref="_weakFileReference"/>
private long _fileSize;
/// <summary>
/// The offset into the current memory mapped file where the next storage unit can be held.
/// </summary>
/// <remarks>
/// <para>Access should be synchronized on <see cref="_gate"/>.</para>
/// </remarks>
/// <seealso cref="_weakFileReference"/>
private long _offset;
public TemporaryStorageService(ITextFactoryService textFactory)
=> _textFactory = textFactory;
public ITemporaryTextStorage CreateTemporaryTextStorage(CancellationToken cancellationToken)
=> new TemporaryTextStorage(this);
public ITemporaryTextStorage AttachTemporaryTextStorage(string storageName, long offset, long size, SourceHashAlgorithm checksumAlgorithm, Encoding? encoding, CancellationToken cancellationToken)
=> new TemporaryTextStorage(this, storageName, offset, size, checksumAlgorithm, encoding);
public ITemporaryStreamStorage CreateTemporaryStreamStorage(CancellationToken cancellationToken)
=> new TemporaryStreamStorage(this);
public ITemporaryStreamStorage AttachTemporaryStreamStorage(string storageName, long offset, long size, CancellationToken cancellationToken)
=> new TemporaryStreamStorage(this, storageName, offset, size);
/// <summary>
/// Allocate shared storage of a specified size.
/// </summary>
/// <remarks>
/// <para>"Small" requests are fulfilled from oversized memory mapped files which support several individual
/// storage units. Larger requests are allocated in their own memory mapped files.</para>
/// </remarks>
/// <param name="size">The size of the shared storage block to allocate.</param>
/// <returns>A <see cref="MemoryMappedInfo"/> describing the allocated block.</returns>
private MemoryMappedInfo CreateTemporaryStorage(long size)
{
if (size >= SingleFileThreshold)
{
// Larger blocks are allocated separately
var mapName = CreateUniqueName(size);
var storage = MemoryMappedFile.CreateNew(mapName, size);
return new MemoryMappedInfo(new ReferenceCountedDisposable<MemoryMappedFile>(storage), mapName, offset: 0, size: size);
}
lock (_gate)
{
// Obtain a reference to the memory mapped file, creating one if necessary. If a reference counted
// handle to a memory mapped file is obtained in this section, it must either be disposed before
// returning or returned to the caller who will own it through the MemoryMappedInfo.
var reference = _weakFileReference.TryAddReference();
if (reference == null || _offset + size > _fileSize)
{
var mapName = CreateUniqueName(MultiFileBlockSize);
var file = MemoryMappedFile.CreateNew(mapName, MultiFileBlockSize);
reference = new ReferenceCountedDisposable<MemoryMappedFile>(file);
_weakFileReference = new ReferenceCountedDisposable<MemoryMappedFile>.WeakReference(reference);
_name = mapName;
_fileSize = MultiFileBlockSize;
_offset = size;
return new MemoryMappedInfo(reference, _name, offset: 0, size: size);
}
else
{
// Reserve additional space in the existing storage location
Contract.ThrowIfNull(_name);
_offset += size;
return new MemoryMappedInfo(reference, _name, _offset - size, size);
}
}
}
public static string CreateUniqueName(long size)
=> "Roslyn Temp Storage " + size.ToString() + " " + Guid.NewGuid().ToString("N");
private sealed class TemporaryTextStorage : ITemporaryTextStorage, ITemporaryTextStorageWithName
{
private readonly TemporaryStorageService _service;
private SourceHashAlgorithm _checksumAlgorithm;
private Encoding? _encoding;
private ImmutableArray<byte> _checksum;
private MemoryMappedInfo? _memoryMappedInfo;
public TemporaryTextStorage(TemporaryStorageService service)
=> _service = service;
public TemporaryTextStorage(TemporaryStorageService service, string storageName, long offset, long size, SourceHashAlgorithm checksumAlgorithm, Encoding? encoding)
{
_service = service;
_checksumAlgorithm = checksumAlgorithm;
_encoding = encoding;
_memoryMappedInfo = new MemoryMappedInfo(storageName, offset, size);
}
// TODO: cleanup https://github.com/dotnet/roslyn/issues/43037
// Offet, Size not accessed if Name is null
public string? Name => _memoryMappedInfo?.Name;
public long Offset => _memoryMappedInfo!.Offset;
public long Size => _memoryMappedInfo!.Size;
public SourceHashAlgorithm ChecksumAlgorithm => _checksumAlgorithm;
public Encoding? Encoding => _encoding;
public ImmutableArray<byte> GetChecksum()
{
if (_checksum.IsDefault)
{
ImmutableInterlocked.InterlockedInitialize(ref _checksum, ReadText(CancellationToken.None).GetChecksum());
}
return _checksum;
}
public void Dispose()
{
// Destructors of SafeHandle and FileStream in MemoryMappedFile
// will eventually release resources if this Dispose is not called
// explicitly
_memoryMappedInfo?.Dispose();
_memoryMappedInfo = null;
_encoding = null;
}
public SourceText ReadText(CancellationToken cancellationToken)
{
if (_memoryMappedInfo == null)
{
throw new InvalidOperationException();
}
using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_ReadText, cancellationToken))
{
using var stream = _memoryMappedInfo.CreateReadableStream();
using var reader = CreateTextReaderFromTemporaryStorage((ISupportDirectMemoryAccess)stream, (int)stream.Length);
// we pass in encoding we got from original source text even if it is null.
return _service._textFactory.CreateText(reader, _encoding, cancellationToken);
}
}
public Task<SourceText> ReadTextAsync(CancellationToken cancellationToken)
{
// There is a reason for implementing it like this: proper async implementation
// that reads the underlying memory mapped file stream in an asynchronous fashion
// doesn't actually work. Windows doesn't offer
// any non-blocking way to read from a memory mapped file; the underlying memcpy
// may block as the memory pages back in and that's something you have to live
// with. Therefore, any implementation that attempts to use async will still
// always be blocking at least one threadpool thread in the memcpy in the case
// of a page fault. Therefore, if we're going to be blocking a thread, we should
// just block one thread and do the whole thing at once vs. a fake "async"
// implementation which will continue to requeue work back to the thread pool.
return Task.Factory.StartNew(() => ReadText(cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default);
}
public void WriteText(SourceText text, CancellationToken cancellationToken)
{
if (_memoryMappedInfo != null)
{
throw new InvalidOperationException();
}
using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_WriteText, cancellationToken))
{
_checksumAlgorithm = text.ChecksumAlgorithm;
_encoding = text.Encoding;
// the method we use to get text out of SourceText uses Unicode (2bytes per char).
var size = Encoding.Unicode.GetMaxByteCount(text.Length);
_memoryMappedInfo = _service.CreateTemporaryStorage(size);
// Write the source text out as Unicode. We expect that to be cheap.
using var stream = _memoryMappedInfo.CreateWritableStream();
using var writer = new StreamWriter(stream, Encoding.Unicode);
text.Write(writer, cancellationToken);
}
}
public Task WriteTextAsync(SourceText text, CancellationToken cancellationToken = default)
{
// See commentary in ReadTextAsync for why this is implemented this way.
return Task.Factory.StartNew(() => WriteText(text, cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default);
}
private static unsafe TextReader CreateTextReaderFromTemporaryStorage(ISupportDirectMemoryAccess accessor, int streamLength)
{
var src = (char*)accessor.GetPointer();
// BOM: Unicode, little endian
// Skip the BOM when creating the reader
Debug.Assert(*src == 0xFEFF);
return new DirectMemoryAccessStreamReader(src + 1, streamLength / sizeof(char) - 1);
}
}
private class TemporaryStreamStorage : ITemporaryStreamStorage, ITemporaryStorageWithName
{
private readonly TemporaryStorageService _service;
private MemoryMappedInfo? _memoryMappedInfo;
public TemporaryStreamStorage(TemporaryStorageService service)
=> _service = service;
public TemporaryStreamStorage(TemporaryStorageService service, string storageName, long offset, long size)
{
_service = service;
_memoryMappedInfo = new MemoryMappedInfo(storageName, offset, size);
}
// TODO: clean up https://github.com/dotnet/roslyn/issues/43037
// Offset, Size is only used when Name is not null.
public string? Name => _memoryMappedInfo?.Name;
public long Offset => _memoryMappedInfo!.Offset;
public long Size => _memoryMappedInfo!.Size;
public void Dispose()
{
// Destructors of SafeHandle and FileStream in MemoryMappedFile
// will eventually release resources if this Dispose is not called
// explicitly
_memoryMappedInfo?.Dispose();
_memoryMappedInfo = null;
}
public Stream ReadStream(CancellationToken cancellationToken)
{
if (_memoryMappedInfo == null)
{
throw new InvalidOperationException();
}
using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_ReadStream, cancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
return _memoryMappedInfo.CreateReadableStream();
}
}
public Task<Stream> ReadStreamAsync(CancellationToken cancellationToken = default)
{
// See commentary in ReadTextAsync for why this is implemented this way.
return Task.Factory.StartNew(() => ReadStream(cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default);
}
public void WriteStream(Stream stream, CancellationToken cancellationToken = default)
{
// The Wait() here will not actually block, since with useAsync: false, the
// entire operation will already be done when WaitStreamMaybeAsync completes.
WriteStreamMaybeAsync(stream, useAsync: false, cancellationToken: cancellationToken).GetAwaiter().GetResult();
}
public Task WriteStreamAsync(Stream stream, CancellationToken cancellationToken = default)
=> WriteStreamMaybeAsync(stream, useAsync: true, cancellationToken: cancellationToken);
private async Task WriteStreamMaybeAsync(Stream stream, bool useAsync, CancellationToken cancellationToken)
{
if (_memoryMappedInfo != null)
{
throw new InvalidOperationException(WorkspacesResources.Temporary_storage_cannot_be_written_more_than_once);
}
using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_WriteStream, cancellationToken))
{
var size = stream.Length;
_memoryMappedInfo = _service.CreateTemporaryStorage(size);
using var viewStream = _memoryMappedInfo.CreateWritableStream();
var buffer = SharedPools.ByteArray.Allocate();
try
{
while (true)
{
int count;
if (useAsync)
{
count = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);
}
else
{
count = stream.Read(buffer, 0, buffer.Length);
}
if (count == 0)
{
break;
}
viewStream.Write(buffer, 0, count);
}
}
finally
{
SharedPools.ByteArray.Free(buffer);
}
}
}
}
}
internal unsafe class DirectMemoryAccessStreamReader : TextReaderWithLength
{
private char* _position;
private readonly char* _end;
public DirectMemoryAccessStreamReader(char* src, int length)
: base(length)
{
RoslynDebug.Assert(src != null);
RoslynDebug.Assert(length >= 0);
_position = src;
_end = _position + length;
}
public override int Peek()
{
if (_position >= _end)
{
return -1;
}
return *_position;
}
public override int Read()
{
if (_position >= _end)
{
return -1;
}
return *_position++;
}
public override int Read(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (index < 0 || index >= buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
if (count < 0 || (index + count) > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
count = Math.Min(count, (int)(_end - _position));
if (count > 0)
{
Marshal.Copy((IntPtr)_position, buffer, index, count);
_position += count;
}
return count;
}
}
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Workspaces/CSharp/Portable/Simplification/Reducers/CSharpCastReducer.Rewriter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Simplification;
namespace Microsoft.CodeAnalysis.CSharp.Simplification
{
internal partial class CSharpCastReducer
{
private class Rewriter : AbstractReductionRewriter
{
public Rewriter(ObjectPool<IReductionRewriter> pool)
: base(pool)
{
}
public override SyntaxNode VisitCastExpression(CastExpressionSyntax node)
{
return SimplifyExpression(
node,
newNode: base.VisitCastExpression(node),
simplifier: s_simplifyCast);
}
public override SyntaxNode VisitBinaryExpression(BinaryExpressionSyntax node)
{
var result = base.VisitBinaryExpression(node);
var reducedNode = result as BinaryExpressionSyntax;
if (reducedNode != node && reducedNode != null)
{
if ((node.Left.IsKind(SyntaxKind.CastExpression) && !reducedNode.Left.IsKind(SyntaxKind.CastExpression)) ||
(node.Right.IsKind(SyntaxKind.CastExpression) && !reducedNode.Right.IsKind(SyntaxKind.CastExpression)))
{
// Cast simplification inside a binary expression, check if we need to parenthesize the binary expression to avoid breaking parent syntax.
// For example, cast removal in below case leads to syntax errors in error free code, unless parenting binary expression is parenthesized:
// Original: Goo(x < (int)i, x > y)
// Incorrect cast removal: Goo(x < i, x > y)
// Correct cast removal: Goo((x < i), x > y)
// We'll do the following to detect such cases:
// 1) Get the topmostExpressionAncestor of node.
// 2) Get the reducedAncestor after replacing node with reducedNode within it.
// 3) Reparse the reducedAncestor to get reparsedAncestor.
// 4) Check for syntax equivalence of reducedAncestor and reparsedAncestor. If not syntactically equivalent,
// then cast removal breaks the syntax and needs explicit parentheses around the binary expression.
var topmostExpressionAncestor = node
.AncestorsAndSelf()
.OfType<ExpressionSyntax>()
.LastOrDefault();
if (topmostExpressionAncestor != null && topmostExpressionAncestor != node)
{
var reducedAncestor = topmostExpressionAncestor.ReplaceNode(node, reducedNode);
var reparsedAncestor = SyntaxFactory.ParseExpression(reducedAncestor.ToFullString());
if (reparsedAncestor != null && !reparsedAncestor.IsEquivalentTo(reducedAncestor))
{
return SyntaxFactory.ParenthesizedExpression(reducedNode)
.WithAdditionalAnnotations(Simplifier.Annotation);
}
}
}
}
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.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Simplification;
namespace Microsoft.CodeAnalysis.CSharp.Simplification
{
internal partial class CSharpCastReducer
{
private class Rewriter : AbstractReductionRewriter
{
public Rewriter(ObjectPool<IReductionRewriter> pool)
: base(pool)
{
}
public override SyntaxNode VisitCastExpression(CastExpressionSyntax node)
{
return SimplifyExpression(
node,
newNode: base.VisitCastExpression(node),
simplifier: s_simplifyCast);
}
public override SyntaxNode VisitBinaryExpression(BinaryExpressionSyntax node)
{
var result = base.VisitBinaryExpression(node);
var reducedNode = result as BinaryExpressionSyntax;
if (reducedNode != node && reducedNode != null)
{
if ((node.Left.IsKind(SyntaxKind.CastExpression) && !reducedNode.Left.IsKind(SyntaxKind.CastExpression)) ||
(node.Right.IsKind(SyntaxKind.CastExpression) && !reducedNode.Right.IsKind(SyntaxKind.CastExpression)))
{
// Cast simplification inside a binary expression, check if we need to parenthesize the binary expression to avoid breaking parent syntax.
// For example, cast removal in below case leads to syntax errors in error free code, unless parenting binary expression is parenthesized:
// Original: Goo(x < (int)i, x > y)
// Incorrect cast removal: Goo(x < i, x > y)
// Correct cast removal: Goo((x < i), x > y)
// We'll do the following to detect such cases:
// 1) Get the topmostExpressionAncestor of node.
// 2) Get the reducedAncestor after replacing node with reducedNode within it.
// 3) Reparse the reducedAncestor to get reparsedAncestor.
// 4) Check for syntax equivalence of reducedAncestor and reparsedAncestor. If not syntactically equivalent,
// then cast removal breaks the syntax and needs explicit parentheses around the binary expression.
var topmostExpressionAncestor = node
.AncestorsAndSelf()
.OfType<ExpressionSyntax>()
.LastOrDefault();
if (topmostExpressionAncestor != null && topmostExpressionAncestor != node)
{
var reducedAncestor = topmostExpressionAncestor.ReplaceNode(node, reducedNode);
var reparsedAncestor = SyntaxFactory.ParseExpression(reducedAncestor.ToFullString());
if (reparsedAncestor != null && !reparsedAncestor.IsEquivalentTo(reducedAncestor))
{
return SyntaxFactory.ParenthesizedExpression(reducedNode)
.WithAdditionalAnnotations(Simplifier.Annotation);
}
}
}
}
return result;
}
}
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Compilers/CSharp/Portable/Symbols/Retargeting/RetargetingNamedTypeSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Globalization;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting
{
/// <summary>
/// Represents a type of a RetargetingModuleSymbol. Essentially this is a wrapper around
/// another NamedTypeSymbol that is responsible for retargeting referenced symbols from one assembly to another.
/// It can retarget symbols for multiple assemblies at the same time.
/// </summary>
internal sealed class RetargetingNamedTypeSymbol : WrappedNamedTypeSymbol
{
/// <summary>
/// Owning RetargetingModuleSymbol.
/// </summary>
private readonly RetargetingModuleSymbol _retargetingModule;
private ImmutableArray<TypeParameterSymbol> _lazyTypeParameters;
private NamedTypeSymbol _lazyBaseType = ErrorTypeSymbol.UnknownResultType;
private ImmutableArray<NamedTypeSymbol> _lazyInterfaces = default(ImmutableArray<NamedTypeSymbol>);
private NamedTypeSymbol _lazyDeclaredBaseType = ErrorTypeSymbol.UnknownResultType;
private ImmutableArray<NamedTypeSymbol> _lazyDeclaredInterfaces;
private ImmutableArray<CSharpAttributeData> _lazyCustomAttributes;
private CachedUseSiteInfo<AssemblySymbol> _lazyCachedUseSiteInfo = CachedUseSiteInfo<AssemblySymbol>.Uninitialized;
public RetargetingNamedTypeSymbol(RetargetingModuleSymbol retargetingModule, NamedTypeSymbol underlyingType, TupleExtraData tupleData = null)
: base(underlyingType, tupleData)
{
Debug.Assert((object)retargetingModule != null);
Debug.Assert(!(underlyingType is RetargetingNamedTypeSymbol));
_retargetingModule = retargetingModule;
}
protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData)
{
return new RetargetingNamedTypeSymbol(_retargetingModule, _underlyingType, newData);
}
private RetargetingModuleSymbol.RetargetingSymbolTranslator RetargetingTranslator
{
get
{
return _retargetingModule.RetargetingTranslator;
}
}
public override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get
{
if (_lazyTypeParameters.IsDefault)
{
if (this.Arity == 0)
{
_lazyTypeParameters = ImmutableArray<TypeParameterSymbol>.Empty;
}
else
{
ImmutableInterlocked.InterlockedCompareExchange(ref _lazyTypeParameters,
this.RetargetingTranslator.Retarget(_underlyingType.TypeParameters), default(ImmutableArray<TypeParameterSymbol>));
}
}
return _lazyTypeParameters;
}
}
internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics
{
get
{
// This is always the instance type, so the type arguments are the same as the type parameters.
return GetTypeParametersAsTypeArguments();
}
}
public override NamedTypeSymbol ConstructedFrom
{
get
{
return this;
}
}
public override NamedTypeSymbol EnumUnderlyingType
{
get
{
var underlying = _underlyingType.EnumUnderlyingType;
return (object)underlying == null ? null : this.RetargetingTranslator.Retarget(underlying, RetargetOptions.RetargetPrimitiveTypesByTypeCode); // comes from field's signature.
}
}
public override IEnumerable<string> MemberNames
{
get
{
return _underlyingType.MemberNames;
}
}
public override ImmutableArray<Symbol> GetMembers()
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetMembers());
}
internal override ImmutableArray<Symbol> GetMembersUnordered()
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetMembersUnordered());
}
public override ImmutableArray<Symbol> GetMembers(string name)
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetMembers(name));
}
public override void InitializeTupleFieldDefinitionsToIndexMap()
{
Debug.Assert(this.IsTupleType);
Debug.Assert(this.IsDefinition); // we only store a map for definitions
var retargetedMap = new SmallDictionary<FieldSymbol, int>(ReferenceEqualityComparer.Instance);
foreach ((FieldSymbol field, int index) in _underlyingType.TupleFieldDefinitionsToIndexMap)
{
retargetedMap.Add(this.RetargetingTranslator.Retarget(field), index);
}
this.TupleData!.SetFieldDefinitionsToIndexMap(retargetedMap);
}
internal override IEnumerable<FieldSymbol> GetFieldsToEmit()
{
foreach (FieldSymbol f in _underlyingType.GetFieldsToEmit())
{
yield return this.RetargetingTranslator.Retarget(f);
}
}
internal override IEnumerable<MethodSymbol> GetMethodsToEmit()
{
bool isInterface = _underlyingType.IsInterfaceType();
foreach (MethodSymbol method in _underlyingType.GetMethodsToEmit())
{
Debug.Assert((object)method != null);
int gapSize = isInterface ? Microsoft.CodeAnalysis.ModuleExtensions.GetVTableGapSize(method.MetadataName) : 0;
if (gapSize > 0)
{
do
{
yield return null;
gapSize--;
}
while (gapSize > 0);
}
else
{
yield return this.RetargetingTranslator.Retarget(method);
}
}
}
internal override IEnumerable<PropertySymbol> GetPropertiesToEmit()
{
foreach (PropertySymbol p in _underlyingType.GetPropertiesToEmit())
{
yield return this.RetargetingTranslator.Retarget(p);
}
}
internal override IEnumerable<EventSymbol> GetEventsToEmit()
{
foreach (EventSymbol e in _underlyingType.GetEventsToEmit())
{
yield return this.RetargetingTranslator.Retarget(e);
}
}
internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers()
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetEarlyAttributeDecodingMembers());
}
internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name)
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetEarlyAttributeDecodingMembers(name));
}
internal override ImmutableArray<NamedTypeSymbol> GetTypeMembersUnordered()
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetTypeMembersUnordered());
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers()
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetTypeMembers());
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name)
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetTypeMembers(name));
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity)
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetTypeMembers(name, arity));
}
public override Symbol ContainingSymbol
{
get
{
return this.RetargetingTranslator.Retarget(_underlyingType.ContainingSymbol);
}
}
public override ImmutableArray<CSharpAttributeData> GetAttributes()
{
return this.RetargetingTranslator.GetRetargetedAttributes(_underlyingType.GetAttributes(), ref _lazyCustomAttributes);
}
internal override IEnumerable<CSharpAttributeData> GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder)
{
return this.RetargetingTranslator.RetargetAttributes(_underlyingType.GetCustomAttributesToEmit(moduleBuilder));
}
public override AssemblySymbol ContainingAssembly
{
get
{
return _retargetingModule.ContainingAssembly;
}
}
internal override ModuleSymbol ContainingModule
{
get
{
return _retargetingModule;
}
}
internal override NamedTypeSymbol LookupMetadataType(ref MetadataTypeName typeName)
{
return this.RetargetingTranslator.Retarget(_underlyingType.LookupMetadataType(ref typeName), RetargetOptions.RetargetPrimitiveTypesByName);
}
private static ExtendedErrorTypeSymbol CyclicInheritanceError(RetargetingNamedTypeSymbol type, TypeSymbol declaredBase)
{
var info = new CSDiagnosticInfo(ErrorCode.ERR_ImportedCircularBase, declaredBase, type);
return new ExtendedErrorTypeSymbol(declaredBase, LookupResultKind.NotReferencable, info, true);
}
internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics
{
get
{
if (ReferenceEquals(_lazyBaseType, ErrorTypeSymbol.UnknownResultType))
{
NamedTypeSymbol acyclicBase = GetDeclaredBaseType(null);
if ((object)acyclicBase == null)
{
// if base was not declared, get it from BaseType that should set it to some default
var underlyingBase = _underlyingType.BaseTypeNoUseSiteDiagnostics;
if ((object)underlyingBase != null)
{
acyclicBase = this.RetargetingTranslator.Retarget(underlyingBase, RetargetOptions.RetargetPrimitiveTypesByName);
}
}
if ((object)acyclicBase != null && BaseTypeAnalysis.TypeDependsOn(acyclicBase, this))
{
return CyclicInheritanceError(this, acyclicBase);
}
Interlocked.CompareExchange(ref _lazyBaseType, acyclicBase, ErrorTypeSymbol.UnknownResultType);
}
return _lazyBaseType;
}
}
internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved)
{
if (_lazyInterfaces.IsDefault)
{
var declaredInterfaces = GetDeclaredInterfaces(basesBeingResolved);
if (!IsInterface)
{
// only interfaces needs to check for inheritance cycles via interfaces.
return declaredInterfaces;
}
ImmutableArray<NamedTypeSymbol> result = declaredInterfaces
.SelectAsArray(t => BaseTypeAnalysis.TypeDependsOn(t, this) ? CyclicInheritanceError(this, t) : t);
ImmutableInterlocked.InterlockedCompareExchange(ref _lazyInterfaces, result, default(ImmutableArray<NamedTypeSymbol>));
}
return _lazyInterfaces;
}
internal override ImmutableArray<NamedTypeSymbol> GetInterfacesToEmit()
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetInterfacesToEmit());
}
internal override NamedTypeSymbol GetDeclaredBaseType(ConsList<TypeSymbol> basesBeingResolved)
{
if (ReferenceEquals(_lazyDeclaredBaseType, ErrorTypeSymbol.UnknownResultType))
{
var underlyingBase = _underlyingType.GetDeclaredBaseType(basesBeingResolved);
var declaredBase = (object)underlyingBase != null ? this.RetargetingTranslator.Retarget(underlyingBase, RetargetOptions.RetargetPrimitiveTypesByName) : null;
Interlocked.CompareExchange(ref _lazyDeclaredBaseType, declaredBase, ErrorTypeSymbol.UnknownResultType);
}
return _lazyDeclaredBaseType;
}
internal override ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<TypeSymbol> basesBeingResolved)
{
if (_lazyDeclaredInterfaces.IsDefault)
{
var underlyingBaseInterfaces = _underlyingType.GetDeclaredInterfaces(basesBeingResolved);
var result = this.RetargetingTranslator.Retarget(underlyingBaseInterfaces);
ImmutableInterlocked.InterlockedCompareExchange(ref _lazyDeclaredInterfaces, result, default(ImmutableArray<NamedTypeSymbol>));
}
return _lazyDeclaredInterfaces;
}
internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo()
{
if (!_lazyCachedUseSiteInfo.IsInitialized)
{
AssemblySymbol primaryDependency = PrimaryDependency;
_lazyCachedUseSiteInfo.Initialize(primaryDependency, new UseSiteInfo<AssemblySymbol>(primaryDependency).AdjustDiagnosticInfo(CalculateUseSiteDiagnostic()));
}
return _lazyCachedUseSiteInfo.ToUseSiteInfo(PrimaryDependency);
}
internal override NamedTypeSymbol ComImportCoClass
{
get
{
NamedTypeSymbol coClass = _underlyingType.ComImportCoClass;
return (object)coClass == null ? null : this.RetargetingTranslator.Retarget(coClass, RetargetOptions.RetargetPrimitiveTypesByName);
}
}
internal override bool IsComImport
{
get { return _underlyingType.IsComImport; }
}
internal sealed override CSharpCompilation DeclaringCompilation // perf, not correctness
{
get { return null; }
}
public sealed override bool AreLocalsZeroed
{
get { throw ExceptionUtilities.Unreachable; }
}
internal sealed override NamedTypeSymbol AsNativeInteger() => throw ExceptionUtilities.Unreachable;
internal sealed override NamedTypeSymbol NativeIntegerUnderlyingType => null;
internal sealed override bool IsRecord => _underlyingType.IsRecord;
internal sealed override bool IsRecordStruct => _underlyingType.IsRecordStruct;
internal sealed override bool HasPossibleWellKnownCloneMethod() => _underlyingType.HasPossibleWellKnownCloneMethod();
internal override bool HasFieldInitializers() => _underlyingType.HasFieldInitializers();
internal override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls()
{
foreach ((MethodSymbol body, MethodSymbol implemented) in _underlyingType.SynthesizedInterfaceMethodImpls())
{
var newBody = this.RetargetingTranslator.Retarget(body, MemberSignatureComparer.RetargetedExplicitImplementationComparer);
var newImplemented = this.RetargetingTranslator.Retarget(implemented, MemberSignatureComparer.RetargetedExplicitImplementationComparer);
if (newBody is object && newImplemented is object)
{
yield return (newBody, newImplemented);
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Globalization;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting
{
/// <summary>
/// Represents a type of a RetargetingModuleSymbol. Essentially this is a wrapper around
/// another NamedTypeSymbol that is responsible for retargeting referenced symbols from one assembly to another.
/// It can retarget symbols for multiple assemblies at the same time.
/// </summary>
internal sealed class RetargetingNamedTypeSymbol : WrappedNamedTypeSymbol
{
/// <summary>
/// Owning RetargetingModuleSymbol.
/// </summary>
private readonly RetargetingModuleSymbol _retargetingModule;
private ImmutableArray<TypeParameterSymbol> _lazyTypeParameters;
private NamedTypeSymbol _lazyBaseType = ErrorTypeSymbol.UnknownResultType;
private ImmutableArray<NamedTypeSymbol> _lazyInterfaces = default(ImmutableArray<NamedTypeSymbol>);
private NamedTypeSymbol _lazyDeclaredBaseType = ErrorTypeSymbol.UnknownResultType;
private ImmutableArray<NamedTypeSymbol> _lazyDeclaredInterfaces;
private ImmutableArray<CSharpAttributeData> _lazyCustomAttributes;
private CachedUseSiteInfo<AssemblySymbol> _lazyCachedUseSiteInfo = CachedUseSiteInfo<AssemblySymbol>.Uninitialized;
public RetargetingNamedTypeSymbol(RetargetingModuleSymbol retargetingModule, NamedTypeSymbol underlyingType, TupleExtraData tupleData = null)
: base(underlyingType, tupleData)
{
Debug.Assert((object)retargetingModule != null);
Debug.Assert(!(underlyingType is RetargetingNamedTypeSymbol));
_retargetingModule = retargetingModule;
}
protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData)
{
return new RetargetingNamedTypeSymbol(_retargetingModule, _underlyingType, newData);
}
private RetargetingModuleSymbol.RetargetingSymbolTranslator RetargetingTranslator
{
get
{
return _retargetingModule.RetargetingTranslator;
}
}
public override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get
{
if (_lazyTypeParameters.IsDefault)
{
if (this.Arity == 0)
{
_lazyTypeParameters = ImmutableArray<TypeParameterSymbol>.Empty;
}
else
{
ImmutableInterlocked.InterlockedCompareExchange(ref _lazyTypeParameters,
this.RetargetingTranslator.Retarget(_underlyingType.TypeParameters), default(ImmutableArray<TypeParameterSymbol>));
}
}
return _lazyTypeParameters;
}
}
internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics
{
get
{
// This is always the instance type, so the type arguments are the same as the type parameters.
return GetTypeParametersAsTypeArguments();
}
}
public override NamedTypeSymbol ConstructedFrom
{
get
{
return this;
}
}
public override NamedTypeSymbol EnumUnderlyingType
{
get
{
var underlying = _underlyingType.EnumUnderlyingType;
return (object)underlying == null ? null : this.RetargetingTranslator.Retarget(underlying, RetargetOptions.RetargetPrimitiveTypesByTypeCode); // comes from field's signature.
}
}
public override IEnumerable<string> MemberNames
{
get
{
return _underlyingType.MemberNames;
}
}
public override ImmutableArray<Symbol> GetMembers()
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetMembers());
}
internal override ImmutableArray<Symbol> GetMembersUnordered()
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetMembersUnordered());
}
public override ImmutableArray<Symbol> GetMembers(string name)
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetMembers(name));
}
public override void InitializeTupleFieldDefinitionsToIndexMap()
{
Debug.Assert(this.IsTupleType);
Debug.Assert(this.IsDefinition); // we only store a map for definitions
var retargetedMap = new SmallDictionary<FieldSymbol, int>(ReferenceEqualityComparer.Instance);
foreach ((FieldSymbol field, int index) in _underlyingType.TupleFieldDefinitionsToIndexMap)
{
retargetedMap.Add(this.RetargetingTranslator.Retarget(field), index);
}
this.TupleData!.SetFieldDefinitionsToIndexMap(retargetedMap);
}
internal override IEnumerable<FieldSymbol> GetFieldsToEmit()
{
foreach (FieldSymbol f in _underlyingType.GetFieldsToEmit())
{
yield return this.RetargetingTranslator.Retarget(f);
}
}
internal override IEnumerable<MethodSymbol> GetMethodsToEmit()
{
bool isInterface = _underlyingType.IsInterfaceType();
foreach (MethodSymbol method in _underlyingType.GetMethodsToEmit())
{
Debug.Assert((object)method != null);
int gapSize = isInterface ? Microsoft.CodeAnalysis.ModuleExtensions.GetVTableGapSize(method.MetadataName) : 0;
if (gapSize > 0)
{
do
{
yield return null;
gapSize--;
}
while (gapSize > 0);
}
else
{
yield return this.RetargetingTranslator.Retarget(method);
}
}
}
internal override IEnumerable<PropertySymbol> GetPropertiesToEmit()
{
foreach (PropertySymbol p in _underlyingType.GetPropertiesToEmit())
{
yield return this.RetargetingTranslator.Retarget(p);
}
}
internal override IEnumerable<EventSymbol> GetEventsToEmit()
{
foreach (EventSymbol e in _underlyingType.GetEventsToEmit())
{
yield return this.RetargetingTranslator.Retarget(e);
}
}
internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers()
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetEarlyAttributeDecodingMembers());
}
internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name)
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetEarlyAttributeDecodingMembers(name));
}
internal override ImmutableArray<NamedTypeSymbol> GetTypeMembersUnordered()
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetTypeMembersUnordered());
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers()
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetTypeMembers());
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name)
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetTypeMembers(name));
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity)
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetTypeMembers(name, arity));
}
public override Symbol ContainingSymbol
{
get
{
return this.RetargetingTranslator.Retarget(_underlyingType.ContainingSymbol);
}
}
public override ImmutableArray<CSharpAttributeData> GetAttributes()
{
return this.RetargetingTranslator.GetRetargetedAttributes(_underlyingType.GetAttributes(), ref _lazyCustomAttributes);
}
internal override IEnumerable<CSharpAttributeData> GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder)
{
return this.RetargetingTranslator.RetargetAttributes(_underlyingType.GetCustomAttributesToEmit(moduleBuilder));
}
public override AssemblySymbol ContainingAssembly
{
get
{
return _retargetingModule.ContainingAssembly;
}
}
internal override ModuleSymbol ContainingModule
{
get
{
return _retargetingModule;
}
}
internal override NamedTypeSymbol LookupMetadataType(ref MetadataTypeName typeName)
{
return this.RetargetingTranslator.Retarget(_underlyingType.LookupMetadataType(ref typeName), RetargetOptions.RetargetPrimitiveTypesByName);
}
private static ExtendedErrorTypeSymbol CyclicInheritanceError(RetargetingNamedTypeSymbol type, TypeSymbol declaredBase)
{
var info = new CSDiagnosticInfo(ErrorCode.ERR_ImportedCircularBase, declaredBase, type);
return new ExtendedErrorTypeSymbol(declaredBase, LookupResultKind.NotReferencable, info, true);
}
internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics
{
get
{
if (ReferenceEquals(_lazyBaseType, ErrorTypeSymbol.UnknownResultType))
{
NamedTypeSymbol acyclicBase = GetDeclaredBaseType(null);
if ((object)acyclicBase == null)
{
// if base was not declared, get it from BaseType that should set it to some default
var underlyingBase = _underlyingType.BaseTypeNoUseSiteDiagnostics;
if ((object)underlyingBase != null)
{
acyclicBase = this.RetargetingTranslator.Retarget(underlyingBase, RetargetOptions.RetargetPrimitiveTypesByName);
}
}
if ((object)acyclicBase != null && BaseTypeAnalysis.TypeDependsOn(acyclicBase, this))
{
return CyclicInheritanceError(this, acyclicBase);
}
Interlocked.CompareExchange(ref _lazyBaseType, acyclicBase, ErrorTypeSymbol.UnknownResultType);
}
return _lazyBaseType;
}
}
internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved)
{
if (_lazyInterfaces.IsDefault)
{
var declaredInterfaces = GetDeclaredInterfaces(basesBeingResolved);
if (!IsInterface)
{
// only interfaces needs to check for inheritance cycles via interfaces.
return declaredInterfaces;
}
ImmutableArray<NamedTypeSymbol> result = declaredInterfaces
.SelectAsArray(t => BaseTypeAnalysis.TypeDependsOn(t, this) ? CyclicInheritanceError(this, t) : t);
ImmutableInterlocked.InterlockedCompareExchange(ref _lazyInterfaces, result, default(ImmutableArray<NamedTypeSymbol>));
}
return _lazyInterfaces;
}
internal override ImmutableArray<NamedTypeSymbol> GetInterfacesToEmit()
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetInterfacesToEmit());
}
internal override NamedTypeSymbol GetDeclaredBaseType(ConsList<TypeSymbol> basesBeingResolved)
{
if (ReferenceEquals(_lazyDeclaredBaseType, ErrorTypeSymbol.UnknownResultType))
{
var underlyingBase = _underlyingType.GetDeclaredBaseType(basesBeingResolved);
var declaredBase = (object)underlyingBase != null ? this.RetargetingTranslator.Retarget(underlyingBase, RetargetOptions.RetargetPrimitiveTypesByName) : null;
Interlocked.CompareExchange(ref _lazyDeclaredBaseType, declaredBase, ErrorTypeSymbol.UnknownResultType);
}
return _lazyDeclaredBaseType;
}
internal override ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<TypeSymbol> basesBeingResolved)
{
if (_lazyDeclaredInterfaces.IsDefault)
{
var underlyingBaseInterfaces = _underlyingType.GetDeclaredInterfaces(basesBeingResolved);
var result = this.RetargetingTranslator.Retarget(underlyingBaseInterfaces);
ImmutableInterlocked.InterlockedCompareExchange(ref _lazyDeclaredInterfaces, result, default(ImmutableArray<NamedTypeSymbol>));
}
return _lazyDeclaredInterfaces;
}
internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo()
{
if (!_lazyCachedUseSiteInfo.IsInitialized)
{
AssemblySymbol primaryDependency = PrimaryDependency;
_lazyCachedUseSiteInfo.Initialize(primaryDependency, new UseSiteInfo<AssemblySymbol>(primaryDependency).AdjustDiagnosticInfo(CalculateUseSiteDiagnostic()));
}
return _lazyCachedUseSiteInfo.ToUseSiteInfo(PrimaryDependency);
}
internal override NamedTypeSymbol ComImportCoClass
{
get
{
NamedTypeSymbol coClass = _underlyingType.ComImportCoClass;
return (object)coClass == null ? null : this.RetargetingTranslator.Retarget(coClass, RetargetOptions.RetargetPrimitiveTypesByName);
}
}
internal override bool IsComImport
{
get { return _underlyingType.IsComImport; }
}
internal sealed override CSharpCompilation DeclaringCompilation // perf, not correctness
{
get { return null; }
}
public sealed override bool AreLocalsZeroed
{
get { throw ExceptionUtilities.Unreachable; }
}
internal sealed override NamedTypeSymbol AsNativeInteger() => throw ExceptionUtilities.Unreachable;
internal sealed override NamedTypeSymbol NativeIntegerUnderlyingType => null;
internal sealed override bool IsRecord => _underlyingType.IsRecord;
internal sealed override bool IsRecordStruct => _underlyingType.IsRecordStruct;
internal sealed override bool HasPossibleWellKnownCloneMethod() => _underlyingType.HasPossibleWellKnownCloneMethod();
internal override bool HasFieldInitializers() => _underlyingType.HasFieldInitializers();
internal override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls()
{
foreach ((MethodSymbol body, MethodSymbol implemented) in _underlyingType.SynthesizedInterfaceMethodImpls())
{
var newBody = this.RetargetingTranslator.Retarget(body, MemberSignatureComparer.RetargetedExplicitImplementationComparer);
var newImplemented = this.RetargetingTranslator.Retarget(implemented, MemberSignatureComparer.RetargetedExplicitImplementationComparer);
if (newBody is object && newImplemented is object)
{
yield return (newBody, newImplemented);
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Test/Perf/Utilities/TestUtilities.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Roslyn.Test.Performance.Utilities
{
/// <summary>
/// Global statics shared between the runner and tests.
/// </summary>
public static class RuntimeSettings
{
/// <summary>
/// Used as a pseudo-return value for tests to send test objects
/// back to the runner.
/// </summary>
public static PerfTest[] ResultTests = null;
/// <summary>
/// The logger that is being used by the process.
/// </summary>
public static ILogger Logger = new ConsoleAndFileLogger();
/// <summary>
/// True if the logger should be verbose.
/// </summary>
public static bool IsVerbose = true;
/// <summary>
/// True if a runner is orchestrating the test runs.
/// </summary>
public static bool IsRunnerAttached = false;
}
public static class TestUtilities
{
/// <returns>
/// Returns the path to CPC
/// </returns>
public static string GetCPCDirectoryPath()
{
return Environment.ExpandEnvironmentVariables(@"%SYSTEMDRIVE%\CPC");
}
/// <returns>
/// The path to the ViBenchToJson executable.
/// </returns>
public static string GetViBenchToJsonExeFilePath()
{
return Path.Combine(GetCPCDirectoryPath(), "ViBenchToJson.exe");
}
//
// Process spawning and error handling.
//
/// <summary>
/// The result of a ShellOut completing.
/// </summary>
public class ProcessResult
{
/// <summary>
/// The path to the executable that was run.
/// </summary>
public string ExecutablePath { get; set; }
/// <summary>
/// The arguments that were passed to the process.
/// </summary>
public string Args { get; set; }
/// <summary>
/// The exit code of the process.
/// </summary>
public int Code { get; set; }
/// <summary>
/// The entire standard-out of the process.
/// </summary>
public string StdOut { get; set; }
/// <summary>
/// The entire standard-error of the process.
/// </summary>
public string StdErr { get; set; }
/// <summary>
/// True if the command returned an exit code other
/// than zero.
/// </summary>
public bool Failed => Code != 0;
/// <summary>
/// True if the command returned an exit code of 0.
/// </summary>
public bool Succeeded => !Failed;
}
/// <summary>
/// Shells out, and if the process fails, log the error and quit the script.
/// </summary>
public static void ShellOutVital(
string file,
string args,
string workingDirectory = null,
CancellationToken cancellationToken = default(CancellationToken))
{
var result = ShellOut(file, args, workingDirectory, cancellationToken);
if (result.Failed)
{
LogProcessResult(result);
throw new System.Exception("ShellOutVital Failed");
}
}
/// <summary>
/// Shells out, blocks, and returns the ProcessResult.
/// </summary>
public static ProcessResult ShellOut(
string file,
string args,
string workingDirectory = null,
CancellationToken cancellationToken = default(CancellationToken))
{
if (workingDirectory == null)
{
workingDirectory = AppDomain.CurrentDomain.BaseDirectory;
}
var tcs = new TaskCompletionSource<ProcessResult>();
var startInfo = new ProcessStartInfo(file, args);
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.WorkingDirectory = workingDirectory;
var process = new Process
{
StartInfo = startInfo,
EnableRaisingEvents = true,
};
if (cancellationToken != default(CancellationToken))
{
cancellationToken.Register(() => process.Kill());
}
if (RuntimeSettings.IsVerbose)
{
Log($"running \"{file}\" with arguments \"{args}\" from directory {workingDirectory}");
}
process.Start();
var output = new StringWriter();
var error = new StringWriter();
process.OutputDataReceived += (s, e) =>
{
if (!String.IsNullOrEmpty(e.Data))
{
output.WriteLine(e.Data);
}
};
process.ErrorDataReceived += (s, e) =>
{
if (!String.IsNullOrEmpty(e.Data))
{
error.WriteLine(e.Data);
}
};
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
return new ProcessResult
{
ExecutablePath = file,
Args = args,
Code = process.ExitCode,
StdOut = output.ToString(),
StdErr = error.ToString(),
};
}
/// <summary>
/// Shells out and returns the string gathered from the stdout of the
/// executing process.
///
/// Throws an exception if the process fails.
/// </summary>
public static string StdoutFrom(string program, string args = "", string workingDirectory = null)
{
var result = ShellOut(program, args, workingDirectory);
if (result.Failed)
{
LogProcessResult(result);
throw new Exception("Shelling out failed");
}
return result.StdOut.Trim();
}
/// <summary>
/// Logs a message.
///
/// The actual implementation of this method may change depending on
/// if the script is being run standalone or through the test runner.
/// </summary>
public static void Log(string info)
{
RuntimeSettings.Logger.Log(info);
RuntimeSettings.Logger.Flush();
}
/// <summary>
/// Logs the result of a finished process
/// </summary>
public static void LogProcessResult(ProcessResult result)
{
RuntimeSettings.Logger.Log(String.Format("The process \"{0}\" {1} with code {2}",
$"{result.ExecutablePath} {result.Args}",
result.Failed ? "failed" : "succeeded",
result.Code));
RuntimeSettings.Logger.Log($"Standard Out:\n{result.StdOut}");
RuntimeSettings.Logger.Log($"\nStandard Error:\n{result.StdErr}");
}
/// <summary>
/// Either runs the provided tests, or schedules them to be run by the
/// runner.
/// </summary>
public static void TestThisPlease(params PerfTest[] tests)
{
if (RuntimeSettings.IsRunnerAttached)
{
RuntimeSettings.ResultTests = tests;
}
else
{
foreach (var test in tests)
{
test.Setup();
for (int i = 0; i < test.Iterations; i++)
{
test.Test();
}
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Roslyn.Test.Performance.Utilities
{
/// <summary>
/// Global statics shared between the runner and tests.
/// </summary>
public static class RuntimeSettings
{
/// <summary>
/// Used as a pseudo-return value for tests to send test objects
/// back to the runner.
/// </summary>
public static PerfTest[] ResultTests = null;
/// <summary>
/// The logger that is being used by the process.
/// </summary>
public static ILogger Logger = new ConsoleAndFileLogger();
/// <summary>
/// True if the logger should be verbose.
/// </summary>
public static bool IsVerbose = true;
/// <summary>
/// True if a runner is orchestrating the test runs.
/// </summary>
public static bool IsRunnerAttached = false;
}
public static class TestUtilities
{
/// <returns>
/// Returns the path to CPC
/// </returns>
public static string GetCPCDirectoryPath()
{
return Environment.ExpandEnvironmentVariables(@"%SYSTEMDRIVE%\CPC");
}
/// <returns>
/// The path to the ViBenchToJson executable.
/// </returns>
public static string GetViBenchToJsonExeFilePath()
{
return Path.Combine(GetCPCDirectoryPath(), "ViBenchToJson.exe");
}
//
// Process spawning and error handling.
//
/// <summary>
/// The result of a ShellOut completing.
/// </summary>
public class ProcessResult
{
/// <summary>
/// The path to the executable that was run.
/// </summary>
public string ExecutablePath { get; set; }
/// <summary>
/// The arguments that were passed to the process.
/// </summary>
public string Args { get; set; }
/// <summary>
/// The exit code of the process.
/// </summary>
public int Code { get; set; }
/// <summary>
/// The entire standard-out of the process.
/// </summary>
public string StdOut { get; set; }
/// <summary>
/// The entire standard-error of the process.
/// </summary>
public string StdErr { get; set; }
/// <summary>
/// True if the command returned an exit code other
/// than zero.
/// </summary>
public bool Failed => Code != 0;
/// <summary>
/// True if the command returned an exit code of 0.
/// </summary>
public bool Succeeded => !Failed;
}
/// <summary>
/// Shells out, and if the process fails, log the error and quit the script.
/// </summary>
public static void ShellOutVital(
string file,
string args,
string workingDirectory = null,
CancellationToken cancellationToken = default(CancellationToken))
{
var result = ShellOut(file, args, workingDirectory, cancellationToken);
if (result.Failed)
{
LogProcessResult(result);
throw new System.Exception("ShellOutVital Failed");
}
}
/// <summary>
/// Shells out, blocks, and returns the ProcessResult.
/// </summary>
public static ProcessResult ShellOut(
string file,
string args,
string workingDirectory = null,
CancellationToken cancellationToken = default(CancellationToken))
{
if (workingDirectory == null)
{
workingDirectory = AppDomain.CurrentDomain.BaseDirectory;
}
var tcs = new TaskCompletionSource<ProcessResult>();
var startInfo = new ProcessStartInfo(file, args);
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.WorkingDirectory = workingDirectory;
var process = new Process
{
StartInfo = startInfo,
EnableRaisingEvents = true,
};
if (cancellationToken != default(CancellationToken))
{
cancellationToken.Register(() => process.Kill());
}
if (RuntimeSettings.IsVerbose)
{
Log($"running \"{file}\" with arguments \"{args}\" from directory {workingDirectory}");
}
process.Start();
var output = new StringWriter();
var error = new StringWriter();
process.OutputDataReceived += (s, e) =>
{
if (!String.IsNullOrEmpty(e.Data))
{
output.WriteLine(e.Data);
}
};
process.ErrorDataReceived += (s, e) =>
{
if (!String.IsNullOrEmpty(e.Data))
{
error.WriteLine(e.Data);
}
};
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
return new ProcessResult
{
ExecutablePath = file,
Args = args,
Code = process.ExitCode,
StdOut = output.ToString(),
StdErr = error.ToString(),
};
}
/// <summary>
/// Shells out and returns the string gathered from the stdout of the
/// executing process.
///
/// Throws an exception if the process fails.
/// </summary>
public static string StdoutFrom(string program, string args = "", string workingDirectory = null)
{
var result = ShellOut(program, args, workingDirectory);
if (result.Failed)
{
LogProcessResult(result);
throw new Exception("Shelling out failed");
}
return result.StdOut.Trim();
}
/// <summary>
/// Logs a message.
///
/// The actual implementation of this method may change depending on
/// if the script is being run standalone or through the test runner.
/// </summary>
public static void Log(string info)
{
RuntimeSettings.Logger.Log(info);
RuntimeSettings.Logger.Flush();
}
/// <summary>
/// Logs the result of a finished process
/// </summary>
public static void LogProcessResult(ProcessResult result)
{
RuntimeSettings.Logger.Log(String.Format("The process \"{0}\" {1} with code {2}",
$"{result.ExecutablePath} {result.Args}",
result.Failed ? "failed" : "succeeded",
result.Code));
RuntimeSettings.Logger.Log($"Standard Out:\n{result.StdOut}");
RuntimeSettings.Logger.Log($"\nStandard Error:\n{result.StdErr}");
}
/// <summary>
/// Either runs the provided tests, or schedules them to be run by the
/// runner.
/// </summary>
public static void TestThisPlease(params PerfTest[] tests)
{
if (RuntimeSettings.IsRunnerAttached)
{
RuntimeSettings.ResultTests = tests;
}
else
{
foreach (var test in tests)
{
test.Setup();
for (int i = 0; i < test.Iterations; i++)
{
test.Test();
}
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Features/Core/Portable/Structure/BlockStructure.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.Structure
{
internal class BlockStructure
{
public ImmutableArray<BlockSpan> Spans { get; }
public BlockStructure(ImmutableArray<BlockSpan> spans)
=> Spans = spans;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.Structure
{
internal class BlockStructure
{
public ImmutableArray<BlockSpan> Spans { get; }
public BlockStructure(ImmutableArray<BlockSpan> spans)
=> Spans = spans;
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Compilers/CSharp/Test/Symbol/Symbols/Retargeting/RetargetCustomModifiers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Xunit;
using Roslyn.Test.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Retargeting
{
public class RetargetCustomModifiers : CSharpTestBase
{
[Fact]
public void Test1()
{
var oldMsCorLib = TestMetadata.Net40.mscorlib;
var newMsCorLib = TestMetadata.Net451.mscorlib;
var c1 = CSharpCompilation.Create("C1", references: new[]
{
oldMsCorLib,
TestReferences.SymbolsTests.CustomModifiers.Modifiers.netmodule
});
var c1Assembly = c1.Assembly;
CSharpCompilation c2 = CSharpCompilation.Create("C2", references: new MetadataReference[] { newMsCorLib, new CSharpCompilationReference(c1) });
var mscorlibAssembly = c2.GetReferencedAssemblySymbol(newMsCorLib);
Assert.NotSame(mscorlibAssembly, c1.GetReferencedAssemblySymbol(oldMsCorLib));
var modifiers = c2.GlobalNamespace.GetTypeMembers("Modifiers").Single();
Assert.IsAssignableFrom<PENamedTypeSymbol>(modifiers);
FieldSymbol f0 = modifiers.GetMembers("F0").OfType<FieldSymbol>().Single();
Assert.Equal(1, f0.TypeWithAnnotations.CustomModifiers.Length);
var f0Mod = f0.TypeWithAnnotations.CustomModifiers[0];
Assert.True(f0Mod.IsOptional);
Assert.Equal("System.Runtime.CompilerServices.IsConst", f0Mod.Modifier.ToTestDisplayString());
Assert.Same(mscorlibAssembly, f0Mod.Modifier.ContainingAssembly.GetSymbol());
MethodSymbol m1 = modifiers.GetMembers("F1").OfType<MethodSymbol>().Single();
ParameterSymbol p1 = m1.Parameters[0];
ParameterSymbol p2 = modifiers.GetMembers("F2").OfType<MethodSymbol>().Single().Parameters[0];
MethodSymbol m5 = modifiers.GetMembers("F5").OfType<MethodSymbol>().Single();
ParameterSymbol p5 = m5.Parameters[0];
ParameterSymbol p6 = modifiers.GetMembers("F6").OfType<MethodSymbol>().Single().Parameters[0];
MethodSymbol m7 = modifiers.GetMembers("F7").OfType<MethodSymbol>().Single();
Assert.Equal(0, m1.ReturnTypeWithAnnotations.CustomModifiers.Length);
Assert.Equal(1, p1.TypeWithAnnotations.CustomModifiers.Length);
var p1Mod = p1.TypeWithAnnotations.CustomModifiers[0];
Assert.True(p1Mod.IsOptional);
Assert.Equal("System.Runtime.CompilerServices.IsConst", p1Mod.Modifier.ToTestDisplayString());
Assert.Same(mscorlibAssembly, p1Mod.Modifier.ContainingAssembly.GetSymbol());
Assert.Equal(2, p2.TypeWithAnnotations.CustomModifiers.Length);
foreach (var p2Mod in p2.TypeWithAnnotations.CustomModifiers)
{
Assert.True(p2Mod.IsOptional);
Assert.Equal("System.Runtime.CompilerServices.IsConst", p2Mod.Modifier.ToTestDisplayString());
Assert.Same(mscorlibAssembly, p2Mod.Modifier.ContainingAssembly.GetSymbol());
}
Assert.True(m5.ReturnsVoid);
Assert.Equal(1, m5.ReturnTypeWithAnnotations.CustomModifiers.Length);
var m5Mod = m5.ReturnTypeWithAnnotations.CustomModifiers[0];
Assert.True(m5Mod.IsOptional);
Assert.Equal("System.Runtime.CompilerServices.IsConst", m5Mod.Modifier.ToTestDisplayString());
Assert.Same(mscorlibAssembly, m5Mod.Modifier.ContainingAssembly.GetSymbol());
Assert.Equal(0, p5.TypeWithAnnotations.CustomModifiers.Length);
ArrayTypeSymbol p5Type = (ArrayTypeSymbol)p5.Type;
Assert.Equal("System.Int32", p5Type.ElementType.ToTestDisplayString());
Assert.Equal(1, p5Type.ElementTypeWithAnnotations.CustomModifiers.Length);
var p5TypeMod = p5Type.ElementTypeWithAnnotations.CustomModifiers[0];
Assert.True(p5TypeMod.IsOptional);
Assert.Equal("System.Runtime.CompilerServices.IsConst", p5TypeMod.Modifier.ToTestDisplayString());
Assert.Same(mscorlibAssembly, p5TypeMod.Modifier.ContainingAssembly.GetSymbol());
Assert.Equal(0, p6.TypeWithAnnotations.CustomModifiers.Length);
PointerTypeSymbol p6Type = (PointerTypeSymbol)p6.Type;
Assert.Equal("System.Int32", p6Type.PointedAtType.ToTestDisplayString());
Assert.Equal(1, p6Type.PointedAtTypeWithAnnotations.CustomModifiers.Length);
var p6TypeMod = p6Type.PointedAtTypeWithAnnotations.CustomModifiers[0];
Assert.True(p6TypeMod.IsOptional);
Assert.Equal("System.Runtime.CompilerServices.IsConst", p6TypeMod.Modifier.ToTestDisplayString());
Assert.Same(mscorlibAssembly, p6TypeMod.Modifier.ContainingAssembly.GetSymbol());
Assert.False(m7.ReturnsVoid);
Assert.Equal(1, m7.ReturnTypeWithAnnotations.CustomModifiers.Length);
var m7Mod = m7.ReturnTypeWithAnnotations.CustomModifiers[0];
Assert.True(m7Mod.IsOptional);
Assert.Equal("System.Runtime.CompilerServices.IsConst", m7Mod.Modifier.ToTestDisplayString());
Assert.Same(mscorlibAssembly, m7Mod.Modifier.ContainingAssembly.GetSymbol());
}
[Fact]
public void Test2()
{
var oldMsCorLib = TestMetadata.Net40.mscorlib;
var newMsCorLib = TestMetadata.Net451.mscorlib;
var source = @"
public class Modifiers
{
public volatile int volatileFld;
void F1(System.DateTime* p)
{
}
}
";
CSharpCompilation c1 = CSharpCompilation.Create("C1", new[] { Parse(source) }, new[] { oldMsCorLib });
var c1Assembly = c1.Assembly;
var r1 = new CSharpCompilationReference(c1);
CSharpCompilation c2 = CSharpCompilation.Create("C2", references: new[] { (MetadataReference)newMsCorLib, r1 });
var c1AsmRef = c2.GetReferencedAssemblySymbol(r1);
Assert.NotSame(c1Assembly, c1AsmRef);
var mscorlibAssembly = c2.GetReferencedAssemblySymbol(newMsCorLib);
Assert.NotSame(mscorlibAssembly, c1.GetReferencedAssemblySymbol(oldMsCorLib));
var modifiers = c2.GlobalNamespace.GetTypeMembers("Modifiers").Single();
Assert.IsType<RetargetingNamedTypeSymbol>(modifiers);
FieldSymbol volatileFld = modifiers.GetMembers("volatileFld").OfType<FieldSymbol>().Single();
Assert.Equal(1, volatileFld.TypeWithAnnotations.CustomModifiers.Length);
var volatileFldMod = volatileFld.TypeWithAnnotations.CustomModifiers[0];
Assert.False(volatileFldMod.IsOptional);
Assert.Equal("System.Runtime.CompilerServices.IsVolatile", volatileFldMod.Modifier.ToTestDisplayString());
Assert.Equal(SpecialType.System_Int32, volatileFld.Type.SpecialType);
Assert.Same(mscorlibAssembly, ((CSharpCustomModifier)volatileFldMod).ModifierSymbol.ContainingAssembly);
Assert.Equal("volatileFld", volatileFld.Name);
Assert.True(volatileFld.IsVolatile);
Assert.Same(volatileFld, volatileFld.OriginalDefinition);
Assert.Null(volatileFld.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false));
Assert.Null(volatileFld.ConstantValue);
Assert.Null(volatileFld.AssociatedSymbol);
Assert.Same(c1AsmRef, volatileFld.ContainingAssembly);
Assert.Same(c1AsmRef.Modules[0], volatileFld.ContainingModule);
Assert.Same(modifiers, volatileFld.ContainingSymbol);
Assert.Equal(Accessibility.Public, volatileFld.DeclaredAccessibility);
Assert.False(volatileFld.IsConst);
Assert.False(volatileFld.IsReadOnly);
Assert.False(volatileFld.IsStatic);
Assert.Same(volatileFld.ContainingModule, ((RetargetingFieldSymbol)volatileFld).RetargetingModule);
Assert.Same(c1Assembly, ((RetargetingFieldSymbol)volatileFld).UnderlyingField.ContainingAssembly);
MethodSymbol m1 = modifiers.GetMembers("F1").OfType<MethodSymbol>().Single();
Assert.Equal(0, m1.ReturnTypeWithAnnotations.CustomModifiers.Length);
Assert.True(!m1.ExplicitInterfaceImplementations.IsDefault);
Assert.Equal(0, m1.ExplicitInterfaceImplementations.Length);
Assert.False(m1.HidesBaseMethodsByName);
Assert.False(m1.IsExtensionMethod);
Assert.Equal(((RetargetingMethodSymbol)m1).UnderlyingMethod.CallingConvention, m1.CallingConvention);
Assert.Null(m1.AssociatedSymbol);
Assert.Same(c1AsmRef.Modules[0], m1.ContainingModule);
ParameterSymbol p1 = m1.Parameters[0];
Assert.Equal(0, p1.TypeWithAnnotations.CustomModifiers.Length);
Assert.Same(c1AsmRef.Modules[0], p1.ContainingModule);
Assert.False(p1.HasExplicitDefaultValue, "Parameter has default value");
Assert.Equal(0, p1.Ordinal);
PointerTypeSymbol p1Type = (PointerTypeSymbol)p1.Type;
Assert.Null(p1Type.ContainingAssembly);
Assert.Same(mscorlibAssembly, p1Type.PointedAtType.ContainingAssembly);
Assert.Equal(SpecialType.System_DateTime, p1Type.PointedAtType.SpecialType);
Assert.Equal(0, p1.TypeWithAnnotations.CustomModifiers.Length);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Xunit;
using Roslyn.Test.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Retargeting
{
public class RetargetCustomModifiers : CSharpTestBase
{
[Fact]
public void Test1()
{
var oldMsCorLib = TestMetadata.Net40.mscorlib;
var newMsCorLib = TestMetadata.Net451.mscorlib;
var c1 = CSharpCompilation.Create("C1", references: new[]
{
oldMsCorLib,
TestReferences.SymbolsTests.CustomModifiers.Modifiers.netmodule
});
var c1Assembly = c1.Assembly;
CSharpCompilation c2 = CSharpCompilation.Create("C2", references: new MetadataReference[] { newMsCorLib, new CSharpCompilationReference(c1) });
var mscorlibAssembly = c2.GetReferencedAssemblySymbol(newMsCorLib);
Assert.NotSame(mscorlibAssembly, c1.GetReferencedAssemblySymbol(oldMsCorLib));
var modifiers = c2.GlobalNamespace.GetTypeMembers("Modifiers").Single();
Assert.IsAssignableFrom<PENamedTypeSymbol>(modifiers);
FieldSymbol f0 = modifiers.GetMembers("F0").OfType<FieldSymbol>().Single();
Assert.Equal(1, f0.TypeWithAnnotations.CustomModifiers.Length);
var f0Mod = f0.TypeWithAnnotations.CustomModifiers[0];
Assert.True(f0Mod.IsOptional);
Assert.Equal("System.Runtime.CompilerServices.IsConst", f0Mod.Modifier.ToTestDisplayString());
Assert.Same(mscorlibAssembly, f0Mod.Modifier.ContainingAssembly.GetSymbol());
MethodSymbol m1 = modifiers.GetMembers("F1").OfType<MethodSymbol>().Single();
ParameterSymbol p1 = m1.Parameters[0];
ParameterSymbol p2 = modifiers.GetMembers("F2").OfType<MethodSymbol>().Single().Parameters[0];
MethodSymbol m5 = modifiers.GetMembers("F5").OfType<MethodSymbol>().Single();
ParameterSymbol p5 = m5.Parameters[0];
ParameterSymbol p6 = modifiers.GetMembers("F6").OfType<MethodSymbol>().Single().Parameters[0];
MethodSymbol m7 = modifiers.GetMembers("F7").OfType<MethodSymbol>().Single();
Assert.Equal(0, m1.ReturnTypeWithAnnotations.CustomModifiers.Length);
Assert.Equal(1, p1.TypeWithAnnotations.CustomModifiers.Length);
var p1Mod = p1.TypeWithAnnotations.CustomModifiers[0];
Assert.True(p1Mod.IsOptional);
Assert.Equal("System.Runtime.CompilerServices.IsConst", p1Mod.Modifier.ToTestDisplayString());
Assert.Same(mscorlibAssembly, p1Mod.Modifier.ContainingAssembly.GetSymbol());
Assert.Equal(2, p2.TypeWithAnnotations.CustomModifiers.Length);
foreach (var p2Mod in p2.TypeWithAnnotations.CustomModifiers)
{
Assert.True(p2Mod.IsOptional);
Assert.Equal("System.Runtime.CompilerServices.IsConst", p2Mod.Modifier.ToTestDisplayString());
Assert.Same(mscorlibAssembly, p2Mod.Modifier.ContainingAssembly.GetSymbol());
}
Assert.True(m5.ReturnsVoid);
Assert.Equal(1, m5.ReturnTypeWithAnnotations.CustomModifiers.Length);
var m5Mod = m5.ReturnTypeWithAnnotations.CustomModifiers[0];
Assert.True(m5Mod.IsOptional);
Assert.Equal("System.Runtime.CompilerServices.IsConst", m5Mod.Modifier.ToTestDisplayString());
Assert.Same(mscorlibAssembly, m5Mod.Modifier.ContainingAssembly.GetSymbol());
Assert.Equal(0, p5.TypeWithAnnotations.CustomModifiers.Length);
ArrayTypeSymbol p5Type = (ArrayTypeSymbol)p5.Type;
Assert.Equal("System.Int32", p5Type.ElementType.ToTestDisplayString());
Assert.Equal(1, p5Type.ElementTypeWithAnnotations.CustomModifiers.Length);
var p5TypeMod = p5Type.ElementTypeWithAnnotations.CustomModifiers[0];
Assert.True(p5TypeMod.IsOptional);
Assert.Equal("System.Runtime.CompilerServices.IsConst", p5TypeMod.Modifier.ToTestDisplayString());
Assert.Same(mscorlibAssembly, p5TypeMod.Modifier.ContainingAssembly.GetSymbol());
Assert.Equal(0, p6.TypeWithAnnotations.CustomModifiers.Length);
PointerTypeSymbol p6Type = (PointerTypeSymbol)p6.Type;
Assert.Equal("System.Int32", p6Type.PointedAtType.ToTestDisplayString());
Assert.Equal(1, p6Type.PointedAtTypeWithAnnotations.CustomModifiers.Length);
var p6TypeMod = p6Type.PointedAtTypeWithAnnotations.CustomModifiers[0];
Assert.True(p6TypeMod.IsOptional);
Assert.Equal("System.Runtime.CompilerServices.IsConst", p6TypeMod.Modifier.ToTestDisplayString());
Assert.Same(mscorlibAssembly, p6TypeMod.Modifier.ContainingAssembly.GetSymbol());
Assert.False(m7.ReturnsVoid);
Assert.Equal(1, m7.ReturnTypeWithAnnotations.CustomModifiers.Length);
var m7Mod = m7.ReturnTypeWithAnnotations.CustomModifiers[0];
Assert.True(m7Mod.IsOptional);
Assert.Equal("System.Runtime.CompilerServices.IsConst", m7Mod.Modifier.ToTestDisplayString());
Assert.Same(mscorlibAssembly, m7Mod.Modifier.ContainingAssembly.GetSymbol());
}
[Fact]
public void Test2()
{
var oldMsCorLib = TestMetadata.Net40.mscorlib;
var newMsCorLib = TestMetadata.Net451.mscorlib;
var source = @"
public class Modifiers
{
public volatile int volatileFld;
void F1(System.DateTime* p)
{
}
}
";
CSharpCompilation c1 = CSharpCompilation.Create("C1", new[] { Parse(source) }, new[] { oldMsCorLib });
var c1Assembly = c1.Assembly;
var r1 = new CSharpCompilationReference(c1);
CSharpCompilation c2 = CSharpCompilation.Create("C2", references: new[] { (MetadataReference)newMsCorLib, r1 });
var c1AsmRef = c2.GetReferencedAssemblySymbol(r1);
Assert.NotSame(c1Assembly, c1AsmRef);
var mscorlibAssembly = c2.GetReferencedAssemblySymbol(newMsCorLib);
Assert.NotSame(mscorlibAssembly, c1.GetReferencedAssemblySymbol(oldMsCorLib));
var modifiers = c2.GlobalNamespace.GetTypeMembers("Modifiers").Single();
Assert.IsType<RetargetingNamedTypeSymbol>(modifiers);
FieldSymbol volatileFld = modifiers.GetMembers("volatileFld").OfType<FieldSymbol>().Single();
Assert.Equal(1, volatileFld.TypeWithAnnotations.CustomModifiers.Length);
var volatileFldMod = volatileFld.TypeWithAnnotations.CustomModifiers[0];
Assert.False(volatileFldMod.IsOptional);
Assert.Equal("System.Runtime.CompilerServices.IsVolatile", volatileFldMod.Modifier.ToTestDisplayString());
Assert.Equal(SpecialType.System_Int32, volatileFld.Type.SpecialType);
Assert.Same(mscorlibAssembly, ((CSharpCustomModifier)volatileFldMod).ModifierSymbol.ContainingAssembly);
Assert.Equal("volatileFld", volatileFld.Name);
Assert.True(volatileFld.IsVolatile);
Assert.Same(volatileFld, volatileFld.OriginalDefinition);
Assert.Null(volatileFld.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false));
Assert.Null(volatileFld.ConstantValue);
Assert.Null(volatileFld.AssociatedSymbol);
Assert.Same(c1AsmRef, volatileFld.ContainingAssembly);
Assert.Same(c1AsmRef.Modules[0], volatileFld.ContainingModule);
Assert.Same(modifiers, volatileFld.ContainingSymbol);
Assert.Equal(Accessibility.Public, volatileFld.DeclaredAccessibility);
Assert.False(volatileFld.IsConst);
Assert.False(volatileFld.IsReadOnly);
Assert.False(volatileFld.IsStatic);
Assert.Same(volatileFld.ContainingModule, ((RetargetingFieldSymbol)volatileFld).RetargetingModule);
Assert.Same(c1Assembly, ((RetargetingFieldSymbol)volatileFld).UnderlyingField.ContainingAssembly);
MethodSymbol m1 = modifiers.GetMembers("F1").OfType<MethodSymbol>().Single();
Assert.Equal(0, m1.ReturnTypeWithAnnotations.CustomModifiers.Length);
Assert.True(!m1.ExplicitInterfaceImplementations.IsDefault);
Assert.Equal(0, m1.ExplicitInterfaceImplementations.Length);
Assert.False(m1.HidesBaseMethodsByName);
Assert.False(m1.IsExtensionMethod);
Assert.Equal(((RetargetingMethodSymbol)m1).UnderlyingMethod.CallingConvention, m1.CallingConvention);
Assert.Null(m1.AssociatedSymbol);
Assert.Same(c1AsmRef.Modules[0], m1.ContainingModule);
ParameterSymbol p1 = m1.Parameters[0];
Assert.Equal(0, p1.TypeWithAnnotations.CustomModifiers.Length);
Assert.Same(c1AsmRef.Modules[0], p1.ContainingModule);
Assert.False(p1.HasExplicitDefaultValue, "Parameter has default value");
Assert.Equal(0, p1.Ordinal);
PointerTypeSymbol p1Type = (PointerTypeSymbol)p1.Type;
Assert.Null(p1Type.ContainingAssembly);
Assert.Same(mscorlibAssembly, p1Type.PointedAtType.ContainingAssembly);
Assert.Equal(SpecialType.System_DateTime, p1Type.PointedAtType.SpecialType);
Assert.Equal(0, p1.TypeWithAnnotations.CustomModifiers.Length);
}
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Compilers/CSharp/Portable/Symbols/Source/SourceOrdinaryMethodSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed class SourceOrdinaryMethodSymbol : SourceOrdinaryMethodSymbolBase
{
private readonly TypeSymbol _explicitInterfaceType;
private readonly bool _isExpressionBodied;
private readonly bool _hasAnyBody;
private readonly RefKind _refKind;
private bool _lazyIsVararg;
/// <summary>
/// A collection of type parameter constraint types, populated when
/// constraint types for the first type parameter is requested.
/// Initialized in two steps. Hold a copy if accessing during initialization.
/// </summary>
private ImmutableArray<ImmutableArray<TypeWithAnnotations>> _lazyTypeParameterConstraintTypes;
/// <summary>
/// A collection of type parameter constraint kinds, populated when
/// constraint kinds for the first type parameter is requested.
/// Initialized in two steps. Hold a copy if accessing during initialization.
/// </summary>
private ImmutableArray<TypeParameterConstraintKind> _lazyTypeParameterConstraintKinds;
/// <summary>
/// If this symbol represents a partial method definition or implementation part, its other part (if any).
/// This should be set, if at all, before this symbol appears among the members of its owner.
/// The implementation part is not listed among the "members" of the enclosing type.
/// </summary>
private SourceOrdinaryMethodSymbol _otherPartOfPartial;
public static SourceOrdinaryMethodSymbol CreateMethodSymbol(
NamedTypeSymbol containingType,
Binder bodyBinder,
MethodDeclarationSyntax syntax,
bool isNullableAnalysisEnabled,
BindingDiagnosticBag diagnostics)
{
var interfaceSpecifier = syntax.ExplicitInterfaceSpecifier;
var nameToken = syntax.Identifier;
TypeSymbol explicitInterfaceType;
var name = ExplicitInterfaceHelpers.GetMemberNameAndInterfaceSymbol(bodyBinder, interfaceSpecifier, nameToken.ValueText, diagnostics, out explicitInterfaceType, aliasQualifierOpt: out _);
var location = new SourceLocation(nameToken);
var methodKind = interfaceSpecifier == null
? MethodKind.Ordinary
: MethodKind.ExplicitInterfaceImplementation;
return new SourceOrdinaryMethodSymbol(containingType, explicitInterfaceType, name, location, syntax, methodKind, isNullableAnalysisEnabled, diagnostics);
}
private SourceOrdinaryMethodSymbol(
NamedTypeSymbol containingType,
TypeSymbol explicitInterfaceType,
string name,
Location location,
MethodDeclarationSyntax syntax,
MethodKind methodKind,
bool isNullableAnalysisEnabled,
BindingDiagnosticBag diagnostics) :
base(containingType,
name,
location,
syntax,
methodKind,
isIterator: SyntaxFacts.HasYieldOperations(syntax.Body),
isExtensionMethod: syntax.ParameterList.Parameters.FirstOrDefault() is ParameterSyntax firstParam &&
!firstParam.IsArgList &&
firstParam.Modifiers.Any(SyntaxKind.ThisKeyword),
isPartial: syntax.Modifiers.IndexOf(SyntaxKind.PartialKeyword) < 0,
isReadOnly: false,
hasBody: syntax.Body != null || syntax.ExpressionBody != null,
isNullableAnalysisEnabled: isNullableAnalysisEnabled,
diagnostics)
{
Debug.Assert(diagnostics.DiagnosticBag is object);
_explicitInterfaceType = explicitInterfaceType;
bool hasBlockBody = syntax.Body != null;
_isExpressionBodied = !hasBlockBody && syntax.ExpressionBody != null;
bool hasBody = hasBlockBody || _isExpressionBodied;
_hasAnyBody = hasBody;
_refKind = syntax.ReturnType.GetRefKind();
CheckForBlockAndExpressionBody(
syntax.Body, syntax.ExpressionBody, syntax, diagnostics);
}
protected override ImmutableArray<TypeParameterSymbol> MakeTypeParameters(CSharpSyntaxNode node, BindingDiagnosticBag diagnostics)
{
var syntax = (MethodDeclarationSyntax)node;
if (syntax.Arity == 0)
{
ReportErrorIfHasConstraints(syntax.ConstraintClauses, diagnostics.DiagnosticBag);
return ImmutableArray<TypeParameterSymbol>.Empty;
}
else
{
return MakeTypeParameters(syntax, diagnostics);
}
}
protected override (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters, bool IsVararg, ImmutableArray<TypeParameterConstraintClause> DeclaredConstraintsForOverrideOrImplementation) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics)
{
var syntax = GetSyntax();
var withTypeParamsBinder = this.DeclaringCompilation.GetBinderFactory(syntax.SyntaxTree).GetBinder(syntax.ReturnType, syntax, this);
SyntaxToken arglistToken;
// Constraint checking for parameter and return types must be delayed until
// the method has been added to the containing type member list since
// evaluating the constraints may depend on accessing this method from
// the container (comparing this method to others to find overrides for
// instance). Constraints are checked in AfterAddingTypeMembersChecks.
var signatureBinder = withTypeParamsBinder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this);
ImmutableArray<ParameterSymbol> parameters = ParameterHelpers.MakeParameters(
signatureBinder, this, syntax.ParameterList, out arglistToken,
allowRefOrOut: true,
allowThis: true,
addRefReadOnlyModifier: IsVirtual || IsAbstract,
diagnostics: diagnostics);
_lazyIsVararg = (arglistToken.Kind() == SyntaxKind.ArgListKeyword);
RefKind refKind;
var returnTypeSyntax = syntax.ReturnType.SkipRef(out refKind);
TypeWithAnnotations returnType = signatureBinder.BindType(returnTypeSyntax, diagnostics);
// span-like types are returnable in general
if (returnType.IsRestrictedType(ignoreSpanLikeTypes: true))
{
if (returnType.SpecialType == SpecialType.System_TypedReference &&
(this.ContainingType.SpecialType == SpecialType.System_TypedReference || this.ContainingType.SpecialType == SpecialType.System_ArgIterator))
{
// Two special cases: methods in the special types TypedReference and ArgIterator are allowed to return TypedReference
}
else
{
// The return type of a method, delegate, or function pointer cannot be '{0}'
diagnostics.Add(ErrorCode.ERR_MethodReturnCantBeRefAny, syntax.ReturnType.Location, returnType.Type);
}
}
Debug.Assert(this.RefKind == RefKind.None || !returnType.IsVoidType() || returnTypeSyntax.HasErrors);
ImmutableArray<TypeParameterConstraintClause> declaredConstraints = default;
if (this.Arity != 0 && (syntax.ExplicitInterfaceSpecifier != null || IsOverride))
{
// When a generic method overrides a generic method declared in a base class, or is an
// explicit interface member implementation of a method in a base interface, the method
// shall not specify any type-parameter-constraints-clauses, except for a struct, class, or default constraint.
// In these cases, the type parameters of the method inherit constraints from the method being overridden or
// implemented.
if (syntax.ConstraintClauses.Count > 0)
{
Binder.CheckFeatureAvailability(syntax.SyntaxTree, MessageID.IDS_OverrideWithConstraints, diagnostics,
syntax.ConstraintClauses[0].WhereKeyword.GetLocation());
declaredConstraints = signatureBinder.WithAdditionalFlags(BinderFlags.GenericConstraintsClause | BinderFlags.SuppressConstraintChecks).
BindTypeParameterConstraintClauses(this, TypeParameters, syntax.TypeParameterList, syntax.ConstraintClauses,
diagnostics, performOnlyCycleSafeValidation: false, isForOverride: true);
Debug.Assert(declaredConstraints.All(clause => clause.ConstraintTypes.IsEmpty));
}
// Force resolution of nullable type parameter used in the signature of an override or explicit interface implementation
// based on constraints specified by the declaration.
foreach (var param in parameters)
{
forceMethodTypeParameters(param.TypeWithAnnotations, this, declaredConstraints);
}
forceMethodTypeParameters(returnType, this, declaredConstraints);
}
return (returnType, parameters, _lazyIsVararg, declaredConstraints);
static void forceMethodTypeParameters(TypeWithAnnotations type, SourceOrdinaryMethodSymbol method, ImmutableArray<TypeParameterConstraintClause> declaredConstraints)
{
type.VisitType(null, (type, args, unused2) =>
{
if (type.DefaultType is TypeParameterSymbol typeParameterSymbol && typeParameterSymbol.DeclaringMethod == (object)args.method)
{
var asValueType = args.declaredConstraints.IsDefault ||
(args.declaredConstraints[typeParameterSymbol.Ordinal].Constraints & (TypeParameterConstraintKind.ReferenceType | TypeParameterConstraintKind.Default)) == 0;
type.TryForceResolve(asValueType);
}
return false;
}, typePredicate: null, arg: (method, declaredConstraints), canDigThroughNullable: false, useDefaultType: true);
}
}
protected override void ExtensionMethodChecks(BindingDiagnosticBag diagnostics)
{
// errors relevant for extension methods
if (IsExtensionMethod)
{
var syntax = GetSyntax();
var location = locations[0];
var parameter0Type = this.Parameters[0].TypeWithAnnotations;
var parameter0RefKind = this.Parameters[0].RefKind;
if (!parameter0Type.Type.IsValidExtensionParameterType())
{
// Duplicate Dev10 behavior by selecting the parameter type.
var parameterSyntax = syntax.ParameterList.Parameters[0];
Debug.Assert(parameterSyntax.Type != null);
var loc = parameterSyntax.Type.Location;
diagnostics.Add(ErrorCode.ERR_BadTypeforThis, loc, parameter0Type.Type);
}
else if (parameter0RefKind == RefKind.Ref && !parameter0Type.Type.IsValueType)
{
diagnostics.Add(ErrorCode.ERR_RefExtensionMustBeValueTypeOrConstrainedToOne, location, Name);
}
else if (parameter0RefKind == RefKind.In && parameter0Type.TypeKind != TypeKind.Struct)
{
diagnostics.Add(ErrorCode.ERR_InExtensionMustBeValueType, location, Name);
}
else if ((object)ContainingType.ContainingType != null)
{
diagnostics.Add(ErrorCode.ERR_ExtensionMethodsDecl, location, ContainingType.Name);
}
else if (!ContainingType.IsScriptClass && !(ContainingType.IsStatic && ContainingType.Arity == 0))
{
// Duplicate Dev10 behavior by selecting the containing type identifier. However if there
// is no containing type (in the interactive case for instance), select the method identifier.
var typeDecl = syntax.Parent as TypeDeclarationSyntax;
var identifier = (typeDecl != null) ? typeDecl.Identifier : syntax.Identifier;
var loc = identifier.GetLocation();
diagnostics.Add(ErrorCode.ERR_BadExtensionAgg, loc);
}
else if (!IsStatic)
{
diagnostics.Add(ErrorCode.ERR_BadExtensionMeth, location);
}
else
{
// Verify ExtensionAttribute is available.
var attributeConstructor = Binder.GetWellKnownTypeMember(DeclaringCompilation, WellKnownMember.System_Runtime_CompilerServices_ExtensionAttribute__ctor, out var useSiteInfo);
Location thisLocation = syntax.ParameterList.Parameters[0].Modifiers.FirstOrDefault(SyntaxKind.ThisKeyword).GetLocation();
if ((object)attributeConstructor == null)
{
var memberDescriptor = WellKnownMembers.GetDescriptor(WellKnownMember.System_Runtime_CompilerServices_ExtensionAttribute__ctor);
// do not use Binder.ReportUseSiteErrorForAttributeCtor in this case, because we'll need to report a special error id, not a generic use site error.
diagnostics.Add(
ErrorCode.ERR_ExtensionAttrNotFound,
thisLocation,
memberDescriptor.DeclaringTypeMetadataName);
}
else
{
diagnostics.Add(useSiteInfo, thisLocation);
}
}
}
}
protected override MethodSymbol FindExplicitlyImplementedMethod(BindingDiagnosticBag diagnostics)
{
var syntax = GetSyntax();
return this.FindExplicitlyImplementedMethod(isOperator: false, _explicitInterfaceType, syntax.Identifier.ValueText, syntax.ExplicitInterfaceSpecifier, diagnostics);
}
protected override Location ReturnTypeLocation => GetSyntax().ReturnType.Location;
protected override TypeSymbol ExplicitInterfaceType => _explicitInterfaceType;
protected override bool HasAnyBody => _hasAnyBody;
internal MethodDeclarationSyntax GetSyntax()
{
Debug.Assert(syntaxReferenceOpt != null);
return (MethodDeclarationSyntax)syntaxReferenceOpt.GetSyntax();
}
protected override void CompleteAsyncMethodChecksBetweenStartAndFinish()
{
if (IsPartialDefinition)
{
DeclaringCompilation.SymbolDeclaredEvent(this);
}
}
public override ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes()
{
if (_lazyTypeParameterConstraintTypes.IsDefault)
{
GetTypeParameterConstraintKinds();
var diagnostics = BindingDiagnosticBag.GetInstance();
var syntax = GetSyntax();
var withTypeParametersBinder =
this.DeclaringCompilation
.GetBinderFactory(syntax.SyntaxTree)
.GetBinder(syntax.ReturnType, syntax, this);
var constraints = this.MakeTypeParameterConstraintTypes(
withTypeParametersBinder,
TypeParameters,
syntax.TypeParameterList,
syntax.ConstraintClauses,
diagnostics);
if (ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeParameterConstraintTypes, constraints))
{
this.AddDeclarationDiagnostics(diagnostics);
}
diagnostics.Free();
}
return _lazyTypeParameterConstraintTypes;
}
public override ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds()
{
if (_lazyTypeParameterConstraintKinds.IsDefault)
{
var syntax = GetSyntax();
var withTypeParametersBinder =
this.DeclaringCompilation
.GetBinderFactory(syntax.SyntaxTree)
.GetBinder(syntax.ReturnType, syntax, this);
var constraints = this.MakeTypeParameterConstraintKinds(
withTypeParametersBinder,
TypeParameters,
syntax.TypeParameterList,
syntax.ConstraintClauses);
ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeParameterConstraintKinds, constraints);
}
return _lazyTypeParameterConstraintKinds;
}
public override bool IsVararg
{
get
{
LazyMethodChecks();
return _lazyIsVararg;
}
}
protected override int GetParameterCountFromSyntax() => GetSyntax().ParameterList.ParameterCount;
public override RefKind RefKind
{
get
{
return _refKind;
}
}
internal static void InitializePartialMethodParts(SourceOrdinaryMethodSymbol definition, SourceOrdinaryMethodSymbol implementation)
{
Debug.Assert(definition.IsPartialDefinition);
Debug.Assert(implementation.IsPartialImplementation);
Debug.Assert((object)definition._otherPartOfPartial == null || (object)definition._otherPartOfPartial == implementation);
Debug.Assert((object)implementation._otherPartOfPartial == null || (object)implementation._otherPartOfPartial == definition);
definition._otherPartOfPartial = implementation;
implementation._otherPartOfPartial = definition;
}
/// <summary>
/// If this is a partial implementation part returns the definition part and vice versa.
/// </summary>
internal SourceOrdinaryMethodSymbol OtherPartOfPartial
{
get { return _otherPartOfPartial; }
}
/// <summary>
/// Returns true if this symbol represents a partial method definition (the part that specifies a signature but no body).
/// </summary>
internal bool IsPartialDefinition
{
get
{
return this.IsPartial && !_hasAnyBody && !HasExternModifier;
}
}
/// <summary>
/// Returns true if this symbol represents a partial method implementation (the part that specifies both signature and body).
/// </summary>
internal bool IsPartialImplementation
{
get
{
return this.IsPartial && (_hasAnyBody || HasExternModifier);
}
}
/// <summary>
/// True if this is a partial method that doesn't have an implementation part.
/// </summary>
internal bool IsPartialWithoutImplementation
{
get
{
return this.IsPartialDefinition && (object)_otherPartOfPartial == null;
}
}
/// <summary>
/// Returns the implementation part of a partial method definition,
/// or null if this is not a partial method or it is the definition part.
/// </summary>
internal SourceOrdinaryMethodSymbol SourcePartialDefinition
{
get
{
return this.IsPartialImplementation ? _otherPartOfPartial : null;
}
}
/// <summary>
/// Returns the definition part of a partial method implementation,
/// or null if this is not a partial method or it is the implementation part.
/// </summary>
internal SourceOrdinaryMethodSymbol SourcePartialImplementation
{
get
{
return this.IsPartialDefinition ? _otherPartOfPartial : null;
}
}
public override MethodSymbol PartialDefinitionPart
{
get
{
return SourcePartialDefinition;
}
}
public override MethodSymbol PartialImplementationPart
{
get
{
return SourcePartialImplementation;
}
}
public sealed override bool IsExtern
{
get
{
return IsPartialDefinition
? _otherPartOfPartial?.IsExtern ?? false
: HasExternModifier;
}
}
public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken))
{
ref var lazyDocComment = ref expandIncludes ? ref this.lazyExpandedDocComment : ref this.lazyDocComment;
return SourceDocumentationCommentUtils.GetAndCacheDocumentationComment(SourcePartialImplementation ?? this, expandIncludes, ref lazyDocComment);
}
protected override SourceMemberMethodSymbol BoundAttributesSource
{
get
{
return this.SourcePartialDefinition;
}
}
internal override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations()
{
if ((object)this.SourcePartialImplementation != null)
{
return OneOrMany.Create(ImmutableArray.Create(AttributeDeclarationSyntaxList, this.SourcePartialImplementation.AttributeDeclarationSyntaxList));
}
else
{
return OneOrMany.Create(AttributeDeclarationSyntaxList);
}
}
private SyntaxList<AttributeListSyntax> AttributeDeclarationSyntaxList
{
get
{
var sourceContainer = this.ContainingType as SourceMemberContainerTypeSymbol;
if ((object)sourceContainer != null && sourceContainer.AnyMemberHasAttributes)
{
return this.GetSyntax().AttributeLists;
}
return default(SyntaxList<AttributeListSyntax>);
}
}
internal override bool IsExpressionBodied
{
get { return _isExpressionBodied; }
}
protected override DeclarationModifiers MakeDeclarationModifiers(DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics)
{
var syntax = GetSyntax();
return ModifierUtils.MakeAndCheckNontypeMemberModifiers(syntax.Modifiers, defaultAccess: DeclarationModifiers.None, allowedModifiers, Locations[0], diagnostics, out _);
}
private ImmutableArray<TypeParameterSymbol> MakeTypeParameters(MethodDeclarationSyntax syntax, BindingDiagnosticBag diagnostics)
{
Debug.Assert(syntax.TypeParameterList != null);
OverriddenMethodTypeParameterMapBase typeMap = null;
if (this.IsOverride)
{
typeMap = new OverriddenMethodTypeParameterMap(this);
}
else if (this.IsExplicitInterfaceImplementation)
{
typeMap = new ExplicitInterfaceMethodTypeParameterMap(this);
}
var typeParameters = syntax.TypeParameterList.Parameters;
var result = ArrayBuilder<TypeParameterSymbol>.GetInstance();
for (int ordinal = 0; ordinal < typeParameters.Count; ordinal++)
{
var parameter = typeParameters[ordinal];
if (parameter.VarianceKeyword.Kind() != SyntaxKind.None)
{
diagnostics.Add(ErrorCode.ERR_IllegalVarianceSyntax, parameter.VarianceKeyword.GetLocation());
}
var identifier = parameter.Identifier;
var location = identifier.GetLocation();
var name = identifier.ValueText;
// Note: It is not an error to have a type parameter named the same as its enclosing method: void M<M>() {}
for (int i = 0; i < result.Count; i++)
{
if (name == result[i].Name)
{
diagnostics.Add(ErrorCode.ERR_DuplicateTypeParameter, location, name);
break;
}
}
SourceMemberContainerTypeSymbol.ReportTypeNamedRecord(identifier.Text, this.DeclaringCompilation, diagnostics.DiagnosticBag, location);
var tpEnclosing = ContainingType.FindEnclosingTypeParameter(name);
if ((object)tpEnclosing != null)
{
// Type parameter '{0}' has the same name as the type parameter from outer type '{1}'
diagnostics.Add(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, location, name, tpEnclosing.ContainingType);
}
var syntaxRefs = ImmutableArray.Create(parameter.GetReference());
var locations = ImmutableArray.Create(location);
var typeParameter = (typeMap != null) ?
(TypeParameterSymbol)new SourceOverridingMethodTypeParameterSymbol(
typeMap,
name,
ordinal,
locations,
syntaxRefs) :
new SourceMethodTypeParameterSymbol(
this,
name,
ordinal,
locations,
syntaxRefs);
result.Add(typeParameter);
}
return result.ToImmutableAndFree();
}
internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken)
{
var implementingPart = this.SourcePartialImplementation;
if ((object)implementingPart != null)
{
implementingPart.ForceComplete(locationOpt, cancellationToken);
}
base.ForceComplete(locationOpt, cancellationToken);
}
internal override bool IsDefinedInSourceTree(
SyntaxTree tree,
TextSpan? definedWithinSpan,
CancellationToken cancellationToken = default(CancellationToken))
{
// Since only the declaring (and not the implementing) part of a partial method appears in the member
// list, we need to ensure we complete the implementation part when needed.
return
base.IsDefinedInSourceTree(tree, definedWithinSpan, cancellationToken) ||
this.SourcePartialImplementation?.IsDefinedInSourceTree(tree, definedWithinSpan, cancellationToken) == true;
}
protected override void CheckConstraintsForExplicitInterfaceType(ConversionsBase conversions, BindingDiagnosticBag diagnostics)
{
if ((object)_explicitInterfaceType != null)
{
var syntax = this.GetSyntax();
Debug.Assert(syntax.ExplicitInterfaceSpecifier != null);
_explicitInterfaceType.CheckAllConstraints(DeclaringCompilation, conversions, new SourceLocation(syntax.ExplicitInterfaceSpecifier.Name), diagnostics);
}
}
protected override void PartialMethodChecks(BindingDiagnosticBag diagnostics)
{
var implementingPart = this.SourcePartialImplementation;
if ((object)implementingPart != null)
{
PartialMethodChecks(this, implementingPart, diagnostics);
}
}
/// <summary>
/// Report differences between the defining and implementing
/// parts of a partial method. Diagnostics are reported on the
/// implementing part, matching Dev10 behavior.
/// </summary>
private static void PartialMethodChecks(SourceOrdinaryMethodSymbol definition, SourceOrdinaryMethodSymbol implementation, BindingDiagnosticBag diagnostics)
{
Debug.Assert(!ReferenceEquals(definition, implementation));
MethodSymbol constructedDefinition = definition.ConstructIfGeneric(TypeMap.TypeParametersAsTypeSymbolsWithIgnoredAnnotations(implementation.TypeParameters));
bool hasTypeDifferences = !constructedDefinition.ReturnTypeWithAnnotations.Equals(implementation.ReturnTypeWithAnnotations, TypeCompareKind.AllIgnoreOptions);
if (hasTypeDifferences)
{
diagnostics.Add(ErrorCode.ERR_PartialMethodReturnTypeDifference, implementation.Locations[0]);
}
else if (MemberSignatureComparer.ConsideringTupleNamesCreatesDifference(definition, implementation))
{
hasTypeDifferences = true;
diagnostics.Add(ErrorCode.ERR_PartialMethodInconsistentTupleNames, implementation.Locations[0], definition, implementation);
}
if (definition.RefKind != implementation.RefKind)
{
diagnostics.Add(ErrorCode.ERR_PartialMethodRefReturnDifference, implementation.Locations[0]);
}
if (definition.IsStatic != implementation.IsStatic)
{
diagnostics.Add(ErrorCode.ERR_PartialMethodStaticDifference, implementation.Locations[0]);
}
if (definition.IsDeclaredReadOnly != implementation.IsDeclaredReadOnly)
{
diagnostics.Add(ErrorCode.ERR_PartialMethodReadOnlyDifference, implementation.Locations[0]);
}
if (definition.IsExtensionMethod != implementation.IsExtensionMethod)
{
diagnostics.Add(ErrorCode.ERR_PartialMethodExtensionDifference, implementation.Locations[0]);
}
if (definition.IsUnsafe != implementation.IsUnsafe && definition.CompilationAllowsUnsafe()) // Don't cascade.
{
diagnostics.Add(ErrorCode.ERR_PartialMethodUnsafeDifference, implementation.Locations[0]);
}
if (definition.IsParams() != implementation.IsParams())
{
diagnostics.Add(ErrorCode.ERR_PartialMethodParamsDifference, implementation.Locations[0]);
}
if (definition.HasExplicitAccessModifier != implementation.HasExplicitAccessModifier
|| definition.DeclaredAccessibility != implementation.DeclaredAccessibility)
{
diagnostics.Add(ErrorCode.ERR_PartialMethodAccessibilityDifference, implementation.Locations[0]);
}
if (definition.IsVirtual != implementation.IsVirtual
|| definition.IsOverride != implementation.IsOverride
|| definition.IsSealed != implementation.IsSealed
|| definition.IsNew != implementation.IsNew)
{
diagnostics.Add(ErrorCode.ERR_PartialMethodExtendedModDifference, implementation.Locations[0]);
}
PartialMethodConstraintsChecks(definition, implementation, diagnostics);
if (SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride(
implementation.DeclaringCompilation,
constructedDefinition,
implementation,
diagnostics,
static (diagnostics, implementedMethod, implementingMethod, topLevel, arg) =>
{
// report only if this is an unsafe *nullability* difference
diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnPartial, implementingMethod.Locations[0]);
},
static (diagnostics, implementedMethod, implementingMethod, implementingParameter, blameAttributes, arg) =>
{
diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial, implementingMethod.Locations[0], new FormattedSymbol(implementingParameter, SymbolDisplayFormat.ShortFormat));
},
extraArgument: (object)null))
{
hasTypeDifferences = true;
}
if ((!hasTypeDifferences && !MemberSignatureComparer.PartialMethodsStrictComparer.Equals(definition, implementation)) ||
hasDifferencesInParameterOrTypeParameterName(definition, implementation))
{
diagnostics.Add(ErrorCode.WRN_PartialMethodTypeDifference, implementation.Locations[0],
new FormattedSymbol(definition, SymbolDisplayFormat.MinimallyQualifiedFormat),
new FormattedSymbol(implementation, SymbolDisplayFormat.MinimallyQualifiedFormat));
}
static bool hasDifferencesInParameterOrTypeParameterName(SourceOrdinaryMethodSymbol definition, SourceOrdinaryMethodSymbol implementation)
{
return !definition.Parameters.SequenceEqual(implementation.Parameters, (a, b) => a.Name == b.Name) ||
!definition.TypeParameters.SequenceEqual(implementation.TypeParameters, (a, b) => a.Name == b.Name);
}
}
private static void PartialMethodConstraintsChecks(SourceOrdinaryMethodSymbol definition, SourceOrdinaryMethodSymbol implementation, BindingDiagnosticBag diagnostics)
{
Debug.Assert(!ReferenceEquals(definition, implementation));
Debug.Assert(definition.Arity == implementation.Arity);
var typeParameters1 = definition.TypeParameters;
int arity = typeParameters1.Length;
if (arity == 0)
{
return;
}
var typeParameters2 = implementation.TypeParameters;
var indexedTypeParameters = IndexedTypeParameterSymbol.Take(arity);
var typeMap1 = new TypeMap(typeParameters1, indexedTypeParameters, allowAlpha: true);
var typeMap2 = new TypeMap(typeParameters2, indexedTypeParameters, allowAlpha: true);
// Report any mismatched method constraints.
for (int i = 0; i < arity; i++)
{
var typeParameter1 = typeParameters1[i];
var typeParameter2 = typeParameters2[i];
if (!MemberSignatureComparer.HaveSameConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2))
{
diagnostics.Add(ErrorCode.ERR_PartialMethodInconsistentConstraints, implementation.Locations[0], implementation, typeParameter2.Name);
}
else if (!MemberSignatureComparer.HaveSameNullabilityInConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2))
{
diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInConstraintsOnPartialImplementation, implementation.Locations[0], implementation, typeParameter2.Name);
}
}
}
internal override bool CallsAreOmitted(SyntaxTree syntaxTree)
{
if (this.IsPartialWithoutImplementation)
{
return true;
}
return base.CallsAreOmitted(syntaxTree);
}
internal override bool GenerateDebugInfo => !IsAsync && !IsIterator;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed class SourceOrdinaryMethodSymbol : SourceOrdinaryMethodSymbolBase
{
private readonly TypeSymbol _explicitInterfaceType;
private readonly bool _isExpressionBodied;
private readonly bool _hasAnyBody;
private readonly RefKind _refKind;
private bool _lazyIsVararg;
/// <summary>
/// A collection of type parameter constraint types, populated when
/// constraint types for the first type parameter is requested.
/// Initialized in two steps. Hold a copy if accessing during initialization.
/// </summary>
private ImmutableArray<ImmutableArray<TypeWithAnnotations>> _lazyTypeParameterConstraintTypes;
/// <summary>
/// A collection of type parameter constraint kinds, populated when
/// constraint kinds for the first type parameter is requested.
/// Initialized in two steps. Hold a copy if accessing during initialization.
/// </summary>
private ImmutableArray<TypeParameterConstraintKind> _lazyTypeParameterConstraintKinds;
/// <summary>
/// If this symbol represents a partial method definition or implementation part, its other part (if any).
/// This should be set, if at all, before this symbol appears among the members of its owner.
/// The implementation part is not listed among the "members" of the enclosing type.
/// </summary>
private SourceOrdinaryMethodSymbol _otherPartOfPartial;
public static SourceOrdinaryMethodSymbol CreateMethodSymbol(
NamedTypeSymbol containingType,
Binder bodyBinder,
MethodDeclarationSyntax syntax,
bool isNullableAnalysisEnabled,
BindingDiagnosticBag diagnostics)
{
var interfaceSpecifier = syntax.ExplicitInterfaceSpecifier;
var nameToken = syntax.Identifier;
TypeSymbol explicitInterfaceType;
var name = ExplicitInterfaceHelpers.GetMemberNameAndInterfaceSymbol(bodyBinder, interfaceSpecifier, nameToken.ValueText, diagnostics, out explicitInterfaceType, aliasQualifierOpt: out _);
var location = new SourceLocation(nameToken);
var methodKind = interfaceSpecifier == null
? MethodKind.Ordinary
: MethodKind.ExplicitInterfaceImplementation;
return new SourceOrdinaryMethodSymbol(containingType, explicitInterfaceType, name, location, syntax, methodKind, isNullableAnalysisEnabled, diagnostics);
}
private SourceOrdinaryMethodSymbol(
NamedTypeSymbol containingType,
TypeSymbol explicitInterfaceType,
string name,
Location location,
MethodDeclarationSyntax syntax,
MethodKind methodKind,
bool isNullableAnalysisEnabled,
BindingDiagnosticBag diagnostics) :
base(containingType,
name,
location,
syntax,
methodKind,
isIterator: SyntaxFacts.HasYieldOperations(syntax.Body),
isExtensionMethod: syntax.ParameterList.Parameters.FirstOrDefault() is ParameterSyntax firstParam &&
!firstParam.IsArgList &&
firstParam.Modifiers.Any(SyntaxKind.ThisKeyword),
isPartial: syntax.Modifiers.IndexOf(SyntaxKind.PartialKeyword) < 0,
isReadOnly: false,
hasBody: syntax.Body != null || syntax.ExpressionBody != null,
isNullableAnalysisEnabled: isNullableAnalysisEnabled,
diagnostics)
{
Debug.Assert(diagnostics.DiagnosticBag is object);
_explicitInterfaceType = explicitInterfaceType;
bool hasBlockBody = syntax.Body != null;
_isExpressionBodied = !hasBlockBody && syntax.ExpressionBody != null;
bool hasBody = hasBlockBody || _isExpressionBodied;
_hasAnyBody = hasBody;
_refKind = syntax.ReturnType.GetRefKind();
CheckForBlockAndExpressionBody(
syntax.Body, syntax.ExpressionBody, syntax, diagnostics);
}
protected override ImmutableArray<TypeParameterSymbol> MakeTypeParameters(CSharpSyntaxNode node, BindingDiagnosticBag diagnostics)
{
var syntax = (MethodDeclarationSyntax)node;
if (syntax.Arity == 0)
{
ReportErrorIfHasConstraints(syntax.ConstraintClauses, diagnostics.DiagnosticBag);
return ImmutableArray<TypeParameterSymbol>.Empty;
}
else
{
return MakeTypeParameters(syntax, diagnostics);
}
}
protected override (TypeWithAnnotations ReturnType, ImmutableArray<ParameterSymbol> Parameters, bool IsVararg, ImmutableArray<TypeParameterConstraintClause> DeclaredConstraintsForOverrideOrImplementation) MakeParametersAndBindReturnType(BindingDiagnosticBag diagnostics)
{
var syntax = GetSyntax();
var withTypeParamsBinder = this.DeclaringCompilation.GetBinderFactory(syntax.SyntaxTree).GetBinder(syntax.ReturnType, syntax, this);
SyntaxToken arglistToken;
// Constraint checking for parameter and return types must be delayed until
// the method has been added to the containing type member list since
// evaluating the constraints may depend on accessing this method from
// the container (comparing this method to others to find overrides for
// instance). Constraints are checked in AfterAddingTypeMembersChecks.
var signatureBinder = withTypeParamsBinder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this);
ImmutableArray<ParameterSymbol> parameters = ParameterHelpers.MakeParameters(
signatureBinder, this, syntax.ParameterList, out arglistToken,
allowRefOrOut: true,
allowThis: true,
addRefReadOnlyModifier: IsVirtual || IsAbstract,
diagnostics: diagnostics);
_lazyIsVararg = (arglistToken.Kind() == SyntaxKind.ArgListKeyword);
RefKind refKind;
var returnTypeSyntax = syntax.ReturnType.SkipRef(out refKind);
TypeWithAnnotations returnType = signatureBinder.BindType(returnTypeSyntax, diagnostics);
// span-like types are returnable in general
if (returnType.IsRestrictedType(ignoreSpanLikeTypes: true))
{
if (returnType.SpecialType == SpecialType.System_TypedReference &&
(this.ContainingType.SpecialType == SpecialType.System_TypedReference || this.ContainingType.SpecialType == SpecialType.System_ArgIterator))
{
// Two special cases: methods in the special types TypedReference and ArgIterator are allowed to return TypedReference
}
else
{
// The return type of a method, delegate, or function pointer cannot be '{0}'
diagnostics.Add(ErrorCode.ERR_MethodReturnCantBeRefAny, syntax.ReturnType.Location, returnType.Type);
}
}
Debug.Assert(this.RefKind == RefKind.None || !returnType.IsVoidType() || returnTypeSyntax.HasErrors);
ImmutableArray<TypeParameterConstraintClause> declaredConstraints = default;
if (this.Arity != 0 && (syntax.ExplicitInterfaceSpecifier != null || IsOverride))
{
// When a generic method overrides a generic method declared in a base class, or is an
// explicit interface member implementation of a method in a base interface, the method
// shall not specify any type-parameter-constraints-clauses, except for a struct, class, or default constraint.
// In these cases, the type parameters of the method inherit constraints from the method being overridden or
// implemented.
if (syntax.ConstraintClauses.Count > 0)
{
Binder.CheckFeatureAvailability(syntax.SyntaxTree, MessageID.IDS_OverrideWithConstraints, diagnostics,
syntax.ConstraintClauses[0].WhereKeyword.GetLocation());
declaredConstraints = signatureBinder.WithAdditionalFlags(BinderFlags.GenericConstraintsClause | BinderFlags.SuppressConstraintChecks).
BindTypeParameterConstraintClauses(this, TypeParameters, syntax.TypeParameterList, syntax.ConstraintClauses,
diagnostics, performOnlyCycleSafeValidation: false, isForOverride: true);
Debug.Assert(declaredConstraints.All(clause => clause.ConstraintTypes.IsEmpty));
}
// Force resolution of nullable type parameter used in the signature of an override or explicit interface implementation
// based on constraints specified by the declaration.
foreach (var param in parameters)
{
forceMethodTypeParameters(param.TypeWithAnnotations, this, declaredConstraints);
}
forceMethodTypeParameters(returnType, this, declaredConstraints);
}
return (returnType, parameters, _lazyIsVararg, declaredConstraints);
static void forceMethodTypeParameters(TypeWithAnnotations type, SourceOrdinaryMethodSymbol method, ImmutableArray<TypeParameterConstraintClause> declaredConstraints)
{
type.VisitType(null, (type, args, unused2) =>
{
if (type.DefaultType is TypeParameterSymbol typeParameterSymbol && typeParameterSymbol.DeclaringMethod == (object)args.method)
{
var asValueType = args.declaredConstraints.IsDefault ||
(args.declaredConstraints[typeParameterSymbol.Ordinal].Constraints & (TypeParameterConstraintKind.ReferenceType | TypeParameterConstraintKind.Default)) == 0;
type.TryForceResolve(asValueType);
}
return false;
}, typePredicate: null, arg: (method, declaredConstraints), canDigThroughNullable: false, useDefaultType: true);
}
}
protected override void ExtensionMethodChecks(BindingDiagnosticBag diagnostics)
{
// errors relevant for extension methods
if (IsExtensionMethod)
{
var syntax = GetSyntax();
var location = locations[0];
var parameter0Type = this.Parameters[0].TypeWithAnnotations;
var parameter0RefKind = this.Parameters[0].RefKind;
if (!parameter0Type.Type.IsValidExtensionParameterType())
{
// Duplicate Dev10 behavior by selecting the parameter type.
var parameterSyntax = syntax.ParameterList.Parameters[0];
Debug.Assert(parameterSyntax.Type != null);
var loc = parameterSyntax.Type.Location;
diagnostics.Add(ErrorCode.ERR_BadTypeforThis, loc, parameter0Type.Type);
}
else if (parameter0RefKind == RefKind.Ref && !parameter0Type.Type.IsValueType)
{
diagnostics.Add(ErrorCode.ERR_RefExtensionMustBeValueTypeOrConstrainedToOne, location, Name);
}
else if (parameter0RefKind == RefKind.In && parameter0Type.TypeKind != TypeKind.Struct)
{
diagnostics.Add(ErrorCode.ERR_InExtensionMustBeValueType, location, Name);
}
else if ((object)ContainingType.ContainingType != null)
{
diagnostics.Add(ErrorCode.ERR_ExtensionMethodsDecl, location, ContainingType.Name);
}
else if (!ContainingType.IsScriptClass && !(ContainingType.IsStatic && ContainingType.Arity == 0))
{
// Duplicate Dev10 behavior by selecting the containing type identifier. However if there
// is no containing type (in the interactive case for instance), select the method identifier.
var typeDecl = syntax.Parent as TypeDeclarationSyntax;
var identifier = (typeDecl != null) ? typeDecl.Identifier : syntax.Identifier;
var loc = identifier.GetLocation();
diagnostics.Add(ErrorCode.ERR_BadExtensionAgg, loc);
}
else if (!IsStatic)
{
diagnostics.Add(ErrorCode.ERR_BadExtensionMeth, location);
}
else
{
// Verify ExtensionAttribute is available.
var attributeConstructor = Binder.GetWellKnownTypeMember(DeclaringCompilation, WellKnownMember.System_Runtime_CompilerServices_ExtensionAttribute__ctor, out var useSiteInfo);
Location thisLocation = syntax.ParameterList.Parameters[0].Modifiers.FirstOrDefault(SyntaxKind.ThisKeyword).GetLocation();
if ((object)attributeConstructor == null)
{
var memberDescriptor = WellKnownMembers.GetDescriptor(WellKnownMember.System_Runtime_CompilerServices_ExtensionAttribute__ctor);
// do not use Binder.ReportUseSiteErrorForAttributeCtor in this case, because we'll need to report a special error id, not a generic use site error.
diagnostics.Add(
ErrorCode.ERR_ExtensionAttrNotFound,
thisLocation,
memberDescriptor.DeclaringTypeMetadataName);
}
else
{
diagnostics.Add(useSiteInfo, thisLocation);
}
}
}
}
protected override MethodSymbol FindExplicitlyImplementedMethod(BindingDiagnosticBag diagnostics)
{
var syntax = GetSyntax();
return this.FindExplicitlyImplementedMethod(isOperator: false, _explicitInterfaceType, syntax.Identifier.ValueText, syntax.ExplicitInterfaceSpecifier, diagnostics);
}
protected override Location ReturnTypeLocation => GetSyntax().ReturnType.Location;
protected override TypeSymbol ExplicitInterfaceType => _explicitInterfaceType;
protected override bool HasAnyBody => _hasAnyBody;
internal MethodDeclarationSyntax GetSyntax()
{
Debug.Assert(syntaxReferenceOpt != null);
return (MethodDeclarationSyntax)syntaxReferenceOpt.GetSyntax();
}
protected override void CompleteAsyncMethodChecksBetweenStartAndFinish()
{
if (IsPartialDefinition)
{
DeclaringCompilation.SymbolDeclaredEvent(this);
}
}
public override ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes()
{
if (_lazyTypeParameterConstraintTypes.IsDefault)
{
GetTypeParameterConstraintKinds();
var diagnostics = BindingDiagnosticBag.GetInstance();
var syntax = GetSyntax();
var withTypeParametersBinder =
this.DeclaringCompilation
.GetBinderFactory(syntax.SyntaxTree)
.GetBinder(syntax.ReturnType, syntax, this);
var constraints = this.MakeTypeParameterConstraintTypes(
withTypeParametersBinder,
TypeParameters,
syntax.TypeParameterList,
syntax.ConstraintClauses,
diagnostics);
if (ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeParameterConstraintTypes, constraints))
{
this.AddDeclarationDiagnostics(diagnostics);
}
diagnostics.Free();
}
return _lazyTypeParameterConstraintTypes;
}
public override ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds()
{
if (_lazyTypeParameterConstraintKinds.IsDefault)
{
var syntax = GetSyntax();
var withTypeParametersBinder =
this.DeclaringCompilation
.GetBinderFactory(syntax.SyntaxTree)
.GetBinder(syntax.ReturnType, syntax, this);
var constraints = this.MakeTypeParameterConstraintKinds(
withTypeParametersBinder,
TypeParameters,
syntax.TypeParameterList,
syntax.ConstraintClauses);
ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeParameterConstraintKinds, constraints);
}
return _lazyTypeParameterConstraintKinds;
}
public override bool IsVararg
{
get
{
LazyMethodChecks();
return _lazyIsVararg;
}
}
protected override int GetParameterCountFromSyntax() => GetSyntax().ParameterList.ParameterCount;
public override RefKind RefKind
{
get
{
return _refKind;
}
}
internal static void InitializePartialMethodParts(SourceOrdinaryMethodSymbol definition, SourceOrdinaryMethodSymbol implementation)
{
Debug.Assert(definition.IsPartialDefinition);
Debug.Assert(implementation.IsPartialImplementation);
Debug.Assert((object)definition._otherPartOfPartial == null || (object)definition._otherPartOfPartial == implementation);
Debug.Assert((object)implementation._otherPartOfPartial == null || (object)implementation._otherPartOfPartial == definition);
definition._otherPartOfPartial = implementation;
implementation._otherPartOfPartial = definition;
}
/// <summary>
/// If this is a partial implementation part returns the definition part and vice versa.
/// </summary>
internal SourceOrdinaryMethodSymbol OtherPartOfPartial
{
get { return _otherPartOfPartial; }
}
/// <summary>
/// Returns true if this symbol represents a partial method definition (the part that specifies a signature but no body).
/// </summary>
internal bool IsPartialDefinition
{
get
{
return this.IsPartial && !_hasAnyBody && !HasExternModifier;
}
}
/// <summary>
/// Returns true if this symbol represents a partial method implementation (the part that specifies both signature and body).
/// </summary>
internal bool IsPartialImplementation
{
get
{
return this.IsPartial && (_hasAnyBody || HasExternModifier);
}
}
/// <summary>
/// True if this is a partial method that doesn't have an implementation part.
/// </summary>
internal bool IsPartialWithoutImplementation
{
get
{
return this.IsPartialDefinition && (object)_otherPartOfPartial == null;
}
}
/// <summary>
/// Returns the implementation part of a partial method definition,
/// or null if this is not a partial method or it is the definition part.
/// </summary>
internal SourceOrdinaryMethodSymbol SourcePartialDefinition
{
get
{
return this.IsPartialImplementation ? _otherPartOfPartial : null;
}
}
/// <summary>
/// Returns the definition part of a partial method implementation,
/// or null if this is not a partial method or it is the implementation part.
/// </summary>
internal SourceOrdinaryMethodSymbol SourcePartialImplementation
{
get
{
return this.IsPartialDefinition ? _otherPartOfPartial : null;
}
}
public override MethodSymbol PartialDefinitionPart
{
get
{
return SourcePartialDefinition;
}
}
public override MethodSymbol PartialImplementationPart
{
get
{
return SourcePartialImplementation;
}
}
public sealed override bool IsExtern
{
get
{
return IsPartialDefinition
? _otherPartOfPartial?.IsExtern ?? false
: HasExternModifier;
}
}
public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken))
{
ref var lazyDocComment = ref expandIncludes ? ref this.lazyExpandedDocComment : ref this.lazyDocComment;
return SourceDocumentationCommentUtils.GetAndCacheDocumentationComment(SourcePartialImplementation ?? this, expandIncludes, ref lazyDocComment);
}
protected override SourceMemberMethodSymbol BoundAttributesSource
{
get
{
return this.SourcePartialDefinition;
}
}
internal override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations()
{
if ((object)this.SourcePartialImplementation != null)
{
return OneOrMany.Create(ImmutableArray.Create(AttributeDeclarationSyntaxList, this.SourcePartialImplementation.AttributeDeclarationSyntaxList));
}
else
{
return OneOrMany.Create(AttributeDeclarationSyntaxList);
}
}
private SyntaxList<AttributeListSyntax> AttributeDeclarationSyntaxList
{
get
{
var sourceContainer = this.ContainingType as SourceMemberContainerTypeSymbol;
if ((object)sourceContainer != null && sourceContainer.AnyMemberHasAttributes)
{
return this.GetSyntax().AttributeLists;
}
return default(SyntaxList<AttributeListSyntax>);
}
}
internal override bool IsExpressionBodied
{
get { return _isExpressionBodied; }
}
protected override DeclarationModifiers MakeDeclarationModifiers(DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics)
{
var syntax = GetSyntax();
return ModifierUtils.MakeAndCheckNontypeMemberModifiers(syntax.Modifiers, defaultAccess: DeclarationModifiers.None, allowedModifiers, Locations[0], diagnostics, out _);
}
private ImmutableArray<TypeParameterSymbol> MakeTypeParameters(MethodDeclarationSyntax syntax, BindingDiagnosticBag diagnostics)
{
Debug.Assert(syntax.TypeParameterList != null);
OverriddenMethodTypeParameterMapBase typeMap = null;
if (this.IsOverride)
{
typeMap = new OverriddenMethodTypeParameterMap(this);
}
else if (this.IsExplicitInterfaceImplementation)
{
typeMap = new ExplicitInterfaceMethodTypeParameterMap(this);
}
var typeParameters = syntax.TypeParameterList.Parameters;
var result = ArrayBuilder<TypeParameterSymbol>.GetInstance();
for (int ordinal = 0; ordinal < typeParameters.Count; ordinal++)
{
var parameter = typeParameters[ordinal];
if (parameter.VarianceKeyword.Kind() != SyntaxKind.None)
{
diagnostics.Add(ErrorCode.ERR_IllegalVarianceSyntax, parameter.VarianceKeyword.GetLocation());
}
var identifier = parameter.Identifier;
var location = identifier.GetLocation();
var name = identifier.ValueText;
// Note: It is not an error to have a type parameter named the same as its enclosing method: void M<M>() {}
for (int i = 0; i < result.Count; i++)
{
if (name == result[i].Name)
{
diagnostics.Add(ErrorCode.ERR_DuplicateTypeParameter, location, name);
break;
}
}
SourceMemberContainerTypeSymbol.ReportTypeNamedRecord(identifier.Text, this.DeclaringCompilation, diagnostics.DiagnosticBag, location);
var tpEnclosing = ContainingType.FindEnclosingTypeParameter(name);
if ((object)tpEnclosing != null)
{
// Type parameter '{0}' has the same name as the type parameter from outer type '{1}'
diagnostics.Add(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, location, name, tpEnclosing.ContainingType);
}
var syntaxRefs = ImmutableArray.Create(parameter.GetReference());
var locations = ImmutableArray.Create(location);
var typeParameter = (typeMap != null) ?
(TypeParameterSymbol)new SourceOverridingMethodTypeParameterSymbol(
typeMap,
name,
ordinal,
locations,
syntaxRefs) :
new SourceMethodTypeParameterSymbol(
this,
name,
ordinal,
locations,
syntaxRefs);
result.Add(typeParameter);
}
return result.ToImmutableAndFree();
}
internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken)
{
var implementingPart = this.SourcePartialImplementation;
if ((object)implementingPart != null)
{
implementingPart.ForceComplete(locationOpt, cancellationToken);
}
base.ForceComplete(locationOpt, cancellationToken);
}
internal override bool IsDefinedInSourceTree(
SyntaxTree tree,
TextSpan? definedWithinSpan,
CancellationToken cancellationToken = default(CancellationToken))
{
// Since only the declaring (and not the implementing) part of a partial method appears in the member
// list, we need to ensure we complete the implementation part when needed.
return
base.IsDefinedInSourceTree(tree, definedWithinSpan, cancellationToken) ||
this.SourcePartialImplementation?.IsDefinedInSourceTree(tree, definedWithinSpan, cancellationToken) == true;
}
protected override void CheckConstraintsForExplicitInterfaceType(ConversionsBase conversions, BindingDiagnosticBag diagnostics)
{
if ((object)_explicitInterfaceType != null)
{
var syntax = this.GetSyntax();
Debug.Assert(syntax.ExplicitInterfaceSpecifier != null);
_explicitInterfaceType.CheckAllConstraints(DeclaringCompilation, conversions, new SourceLocation(syntax.ExplicitInterfaceSpecifier.Name), diagnostics);
}
}
protected override void PartialMethodChecks(BindingDiagnosticBag diagnostics)
{
var implementingPart = this.SourcePartialImplementation;
if ((object)implementingPart != null)
{
PartialMethodChecks(this, implementingPart, diagnostics);
}
}
/// <summary>
/// Report differences between the defining and implementing
/// parts of a partial method. Diagnostics are reported on the
/// implementing part, matching Dev10 behavior.
/// </summary>
private static void PartialMethodChecks(SourceOrdinaryMethodSymbol definition, SourceOrdinaryMethodSymbol implementation, BindingDiagnosticBag diagnostics)
{
Debug.Assert(!ReferenceEquals(definition, implementation));
MethodSymbol constructedDefinition = definition.ConstructIfGeneric(TypeMap.TypeParametersAsTypeSymbolsWithIgnoredAnnotations(implementation.TypeParameters));
bool hasTypeDifferences = !constructedDefinition.ReturnTypeWithAnnotations.Equals(implementation.ReturnTypeWithAnnotations, TypeCompareKind.AllIgnoreOptions);
if (hasTypeDifferences)
{
diagnostics.Add(ErrorCode.ERR_PartialMethodReturnTypeDifference, implementation.Locations[0]);
}
else if (MemberSignatureComparer.ConsideringTupleNamesCreatesDifference(definition, implementation))
{
hasTypeDifferences = true;
diagnostics.Add(ErrorCode.ERR_PartialMethodInconsistentTupleNames, implementation.Locations[0], definition, implementation);
}
if (definition.RefKind != implementation.RefKind)
{
diagnostics.Add(ErrorCode.ERR_PartialMethodRefReturnDifference, implementation.Locations[0]);
}
if (definition.IsStatic != implementation.IsStatic)
{
diagnostics.Add(ErrorCode.ERR_PartialMethodStaticDifference, implementation.Locations[0]);
}
if (definition.IsDeclaredReadOnly != implementation.IsDeclaredReadOnly)
{
diagnostics.Add(ErrorCode.ERR_PartialMethodReadOnlyDifference, implementation.Locations[0]);
}
if (definition.IsExtensionMethod != implementation.IsExtensionMethod)
{
diagnostics.Add(ErrorCode.ERR_PartialMethodExtensionDifference, implementation.Locations[0]);
}
if (definition.IsUnsafe != implementation.IsUnsafe && definition.CompilationAllowsUnsafe()) // Don't cascade.
{
diagnostics.Add(ErrorCode.ERR_PartialMethodUnsafeDifference, implementation.Locations[0]);
}
if (definition.IsParams() != implementation.IsParams())
{
diagnostics.Add(ErrorCode.ERR_PartialMethodParamsDifference, implementation.Locations[0]);
}
if (definition.HasExplicitAccessModifier != implementation.HasExplicitAccessModifier
|| definition.DeclaredAccessibility != implementation.DeclaredAccessibility)
{
diagnostics.Add(ErrorCode.ERR_PartialMethodAccessibilityDifference, implementation.Locations[0]);
}
if (definition.IsVirtual != implementation.IsVirtual
|| definition.IsOverride != implementation.IsOverride
|| definition.IsSealed != implementation.IsSealed
|| definition.IsNew != implementation.IsNew)
{
diagnostics.Add(ErrorCode.ERR_PartialMethodExtendedModDifference, implementation.Locations[0]);
}
PartialMethodConstraintsChecks(definition, implementation, diagnostics);
if (SourceMemberContainerTypeSymbol.CheckValidNullableMethodOverride(
implementation.DeclaringCompilation,
constructedDefinition,
implementation,
diagnostics,
static (diagnostics, implementedMethod, implementingMethod, topLevel, arg) =>
{
// report only if this is an unsafe *nullability* difference
diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnPartial, implementingMethod.Locations[0]);
},
static (diagnostics, implementedMethod, implementingMethod, implementingParameter, blameAttributes, arg) =>
{
diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial, implementingMethod.Locations[0], new FormattedSymbol(implementingParameter, SymbolDisplayFormat.ShortFormat));
},
extraArgument: (object)null))
{
hasTypeDifferences = true;
}
if ((!hasTypeDifferences && !MemberSignatureComparer.PartialMethodsStrictComparer.Equals(definition, implementation)) ||
hasDifferencesInParameterOrTypeParameterName(definition, implementation))
{
diagnostics.Add(ErrorCode.WRN_PartialMethodTypeDifference, implementation.Locations[0],
new FormattedSymbol(definition, SymbolDisplayFormat.MinimallyQualifiedFormat),
new FormattedSymbol(implementation, SymbolDisplayFormat.MinimallyQualifiedFormat));
}
static bool hasDifferencesInParameterOrTypeParameterName(SourceOrdinaryMethodSymbol definition, SourceOrdinaryMethodSymbol implementation)
{
return !definition.Parameters.SequenceEqual(implementation.Parameters, (a, b) => a.Name == b.Name) ||
!definition.TypeParameters.SequenceEqual(implementation.TypeParameters, (a, b) => a.Name == b.Name);
}
}
private static void PartialMethodConstraintsChecks(SourceOrdinaryMethodSymbol definition, SourceOrdinaryMethodSymbol implementation, BindingDiagnosticBag diagnostics)
{
Debug.Assert(!ReferenceEquals(definition, implementation));
Debug.Assert(definition.Arity == implementation.Arity);
var typeParameters1 = definition.TypeParameters;
int arity = typeParameters1.Length;
if (arity == 0)
{
return;
}
var typeParameters2 = implementation.TypeParameters;
var indexedTypeParameters = IndexedTypeParameterSymbol.Take(arity);
var typeMap1 = new TypeMap(typeParameters1, indexedTypeParameters, allowAlpha: true);
var typeMap2 = new TypeMap(typeParameters2, indexedTypeParameters, allowAlpha: true);
// Report any mismatched method constraints.
for (int i = 0; i < arity; i++)
{
var typeParameter1 = typeParameters1[i];
var typeParameter2 = typeParameters2[i];
if (!MemberSignatureComparer.HaveSameConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2))
{
diagnostics.Add(ErrorCode.ERR_PartialMethodInconsistentConstraints, implementation.Locations[0], implementation, typeParameter2.Name);
}
else if (!MemberSignatureComparer.HaveSameNullabilityInConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2))
{
diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInConstraintsOnPartialImplementation, implementation.Locations[0], implementation, typeParameter2.Name);
}
}
}
internal override bool CallsAreOmitted(SyntaxTree syntaxTree)
{
if (this.IsPartialWithoutImplementation)
{
return true;
}
return base.CallsAreOmitted(syntaxTree);
}
internal override bool GenerateDebugInfo => !IsAsync && !IsIterator;
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Features/CSharp/Portable/CodeFixes/AddExplicitCast/AttributeArgumentFixer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.AddExplicitCast
{
internal sealed partial class CSharpAddExplicitCastCodeFixProvider
{
private class AttributeArgumentFixer : Fixer<AttributeArgumentSyntax, AttributeArgumentListSyntax, AttributeSyntax>
{
public AttributeArgumentFixer(CSharpAddExplicitCastCodeFixProvider provider) : base(provider)
{
}
protected override ExpressionSyntax GetExpressionOfArgument(AttributeArgumentSyntax argument)
=> argument.Expression;
protected override AttributeArgumentSyntax GenerateNewArgument(AttributeArgumentSyntax oldArgument, ITypeSymbol conversionType)
=> oldArgument.WithExpression(oldArgument.Expression.Cast(conversionType));
protected override AttributeArgumentListSyntax GenerateNewArgumentList(AttributeArgumentListSyntax oldArgumentList, ArrayBuilder<AttributeArgumentSyntax> newArguments)
=> oldArgumentList.WithArguments(SyntaxFactory.SeparatedList(newArguments));
protected override SeparatedSyntaxList<AttributeArgumentSyntax> GetArgumentsOfArgumentList(AttributeArgumentListSyntax argumentList)
=> argumentList.Arguments;
protected override SymbolInfo GetSpeculativeSymbolInfo(SemanticModel semanticModel, AttributeArgumentListSyntax newArgumentList)
{
var newAttribute = (AttributeSyntax)newArgumentList.Parent!;
return semanticModel.GetSpeculativeSymbolInfo(newAttribute.SpanStart, newAttribute);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.AddExplicitCast
{
internal sealed partial class CSharpAddExplicitCastCodeFixProvider
{
private class AttributeArgumentFixer : Fixer<AttributeArgumentSyntax, AttributeArgumentListSyntax, AttributeSyntax>
{
public AttributeArgumentFixer(CSharpAddExplicitCastCodeFixProvider provider) : base(provider)
{
}
protected override ExpressionSyntax GetExpressionOfArgument(AttributeArgumentSyntax argument)
=> argument.Expression;
protected override AttributeArgumentSyntax GenerateNewArgument(AttributeArgumentSyntax oldArgument, ITypeSymbol conversionType)
=> oldArgument.WithExpression(oldArgument.Expression.Cast(conversionType));
protected override AttributeArgumentListSyntax GenerateNewArgumentList(AttributeArgumentListSyntax oldArgumentList, ArrayBuilder<AttributeArgumentSyntax> newArguments)
=> oldArgumentList.WithArguments(SyntaxFactory.SeparatedList(newArguments));
protected override SeparatedSyntaxList<AttributeArgumentSyntax> GetArgumentsOfArgumentList(AttributeArgumentListSyntax argumentList)
=> argumentList.Arguments;
protected override SymbolInfo GetSpeculativeSymbolInfo(SemanticModel semanticModel, AttributeArgumentListSyntax newArgumentList)
{
var newAttribute = (AttributeSyntax)newArgumentList.Parent!;
return semanticModel.GetSpeculativeSymbolInfo(newAttribute.SpanStart, newAttribute);
}
}
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/EditorFeatures/Test/RenameTracking/RenameTrackingTaggerProviderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.RenameTracking
{
[UseExportProvider]
public class RenameTrackingTaggerProviderTests
{
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotOnCreation()
{
var code = @"
class C$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotInBlankFile()
{
var code = @"$$";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("d");
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingTypingAtEnd()
{
var code = @"
class C$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("at");
await state.AssertTag("C", "Cat");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingTypingAtBeginning()
{
var code = @"
class $$C
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("AB");
await state.AssertTag("C", "ABC");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingTypingInMiddle()
{
var code = @"
class AB$$CD
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("ZZ");
await state.AssertTag("ABCD", "ABZZCD");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingDeleteFromEnd()
{
var code = @"
class ABC$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.Backspace();
await state.AssertTag("ABC", "AB");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingDeleteFromBeginning()
{
var code = @"
class $$ABC
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.Delete();
await state.AssertTag("ABC", "BC");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingDeleteFromMiddle()
{
var code = @"
class AB$$C
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.Backspace();
await state.AssertTag("ABC", "AC");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotOnClassKeyword()
{
var code = @"
class$$ ABCD
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("d");
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotAtMethodArgument()
{
var code = @"
class ABCD
{
void Goo(int x)
{
int abc = 3;
Goo($$
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("a");
await state.AssertNoTag();
state.EditorOperations.InsertText("b");
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingSessionContinuesAfterViewingTag()
{
var code = @"
class C$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("at");
await state.AssertTag("C", "Cat");
state.EditorOperations.InsertText("s");
await state.AssertTag("C", "Cats");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotInString()
{
var code = @"
class C
{
void Goo()
{
string s = ""abc$$""
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("d");
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingHandlesAtSignAsCSharpEscape()
{
var code = @"
class $$C
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("@");
await state.AssertTag("C", "@C");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingHandlesSquareBracketsAsVisualBasicEscape()
{
var code = @"
Class $$C
End Class";
using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic);
state.EditorOperations.InsertText("[");
await state.AssertNoTag();
state.MoveCaret(1);
state.EditorOperations.InsertText("]");
await state.AssertTag("C", "[C]");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotOnSquareBracketsInCSharp()
{
var code = @"
class $$C
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("[");
await state.AssertNoTag();
state.MoveCaret(1);
state.EditorOperations.InsertText("]");
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingHandlesUnicode()
{
var code = @"
class C$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("\u0414\u046E\u046A\u00DB\u00CA\u00DB\u00C4\u00C1\u00CD\u00E4\u00E1\u0152\u0178\u00F5\u00E0\u0178\u00FC\u00C4\u00B5\u00C1i\u00DBE\u00EA\u00E0\u00EA\u00E8\u00E4\u00E5\u00ED\u00F2\u00E8\u00F4\u00E8\u00EA\u00E0\u00F2\u00EE\u00F0\u00F1\u00EB\u00EE\u00E2\u00EE");
await state.AssertTag("C", "C\u0414\u046E\u046A\u00DB\u00CA\u00DB\u00C4\u00C1\u00CD\u00E4\u00E1\u0152\u0178\u00F5\u00E0\u0178\u00FC\u00C4\u00B5\u00C1i\u00DBE\u00EA\u00E0\u00EA\u00E8\u00E4\u00E5\u00ED\u00F2\u00E8\u00F4\u00E8\u00EA\u00E0\u00F2\u00EE\u00F0\u00F1\u00EB\u00EE\u00E2\u00EE");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingThroughKeyword()
{
var code = @"
class i$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("n");
await state.AssertNoTag();
state.EditorOperations.InsertText("t");
await state.AssertNoTag();
state.EditorOperations.InsertText("s");
await state.AssertTag("i", "ints");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingThroughIllegalStartCharacter()
{
var code = @"
class $$abc
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("9");
await state.AssertNoTag();
state.MoveCaret(-1);
state.EditorOperations.InsertText("t");
await state.AssertTag("abc", "t9abc");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingOnBothSidesOfIdentifier()
{
var code = @"
class $$Def
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("Abc");
await state.AssertTag("Def", "AbcDef");
state.MoveCaret(3);
state.EditorOperations.InsertText("Ghi");
await state.AssertTag("Def", "AbcDefGhi");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingThroughSameIdentifier()
{
var code = @"
class C$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("s");
await state.AssertTag("C", "Cs");
state.EditorOperations.Backspace();
await state.AssertNoTag();
state.EditorOperations.InsertText("s");
await state.AssertTag("C", "Cs");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingThroughEmptyString()
{
var code = @"
class C$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.Backspace();
await state.AssertNoTag();
state.EditorOperations.InsertText("D");
await state.AssertTag("C", "D");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingThroughEmptyStringWithCaretMove()
{
var code = @"
class C$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.Backspace();
state.MoveCaret(-4);
state.MoveCaret(4);
await state.AssertNoTag();
state.EditorOperations.InsertText("D");
await state.AssertTag("C", "D");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotThroughEmptyStringResumeOnDifferentSpace()
{
var code = @"
class C$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.Backspace();
// Move to previous space
state.MoveCaret(-1);
state.EditorOperations.InsertText("D");
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingReplaceIdentifierSuffix()
{
var code = @"
class Identifi[|er|]$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
var textSpan = state.HostDocument.SelectedSpans.Single();
state.EditorOperations.ReplaceText(new Span(textSpan.Start, textSpan.Length), "cation");
await state.AssertTag("Identifier", "Identification");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingReplaceIdentifierPrefix()
{
var code = @"
class $$[|Ident|]ifier
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
var textSpan = state.HostDocument.SelectedSpans.Single();
state.EditorOperations.ReplaceText(new Span(textSpan.Start, textSpan.Length), "Complex");
await state.AssertTag("Identifier", "Complexifier");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingReplaceIdentifierCompletely()
{
var code = @"
class [|Cat|]$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
var textSpan = state.HostDocument.SelectedSpans.Single();
state.EditorOperations.ReplaceText(new Span(textSpan.Start, textSpan.Length), "Dog");
await state.AssertTag("Cat", "Dog");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
[WorkItem(34280, "https://github.com/dotnet/roslyn/issues/34280")]
public async Task RenameTrackingReplaceIdentifierWithDiscard()
{
var code = @"
class Class
{
int Method()
{
int i;
[|i|]$$ = Method();
rteurn 0;
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
var textSpan = state.HostDocument.SelectedSpans.Single();
state.EditorOperations.ReplaceText(new Span(textSpan.Start, textSpan.Length), "_");
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotAfterInvoke()
{
var code = @"
class Cat$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("s");
await state.AssertTag("Cat", "Cats", invokeAction: true);
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingInvokeAndChangeBackToOriginal()
{
var code = @"
class Cat$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("s");
await state.AssertTag("Cat", "Cats", invokeAction: true);
await state.AssertNoTag();
state.EditorOperations.Backspace();
await state.AssertTag("Cats", "Cat");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingUndoOnceAndStartNewSession()
{
var code = @"
class Cat$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("abc");
await state.AssertTag("Cat", "Catabc", invokeAction: true);
await state.AssertNoTag();
// Back to original
state.Undo();
await state.AssertNoTag();
state.EditorOperations.InsertText("xyz");
await state.AssertTag("Cat", "Catxyz");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingUndoTwiceAndContinueSession()
{
var code = @"
class Cat$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("abc");
await state.AssertTag("Cat", "Catabc", invokeAction: true);
await state.AssertNoTag();
// Resume rename tracking session
state.Undo(2);
await state.AssertTag("Cat", "Catabc");
state.EditorOperations.InsertText("xyz");
await state.AssertTag("Cat", "Catabcxyz");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingRedoAlwaysClearsState()
{
var code = @"
class Cat$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("s");
await state.AssertTag("Cat", "Cats", invokeAction: true);
await state.AssertNoTag();
// Resume rename tracking session
state.Undo(2);
await state.AssertTag("Cat", "Cats");
state.Redo();
await state.AssertNoTag();
state.Redo();
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingUndoTwiceRedoTwiceUndoStillWorks()
{
var code = @"
class Cat$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("s");
await state.AssertTag("Cat", "Cats", invokeAction: true);
await state.AssertNoTag();
// Resume rename tracking session
state.Undo(2);
await state.AssertTag("Cat", "Cats");
state.Redo(2);
await state.AssertNoTag();
// Back to original
state.Undo();
await state.AssertNoTag();
// Resume rename tracking session
state.Undo();
await state.AssertTag("Cat", "Cats");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingOnReference_ParameterAsArgument()
{
var code = @"
class C
{
void M(int x)
{
M(x$$);
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("yz");
await state.AssertTag("x", "xyz");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingOnReference_ParameterAsNamedArgument()
{
var code = @"
class C
{
void M(int x)
{
M(x$$: x);
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("yz");
await state.AssertTag("x", "xyz");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingOnReference_Namespace()
{
var code = @"
namespace NS
{
class C
{
static void M()
{
NS$$.C.M();
}
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("A");
await state.AssertTag("NS", "NSA");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
[WorkItem(21657, "https://github.com/dotnet/roslyn/issues/21657")]
public async Task RenameTrackingOnReference_Attribute_CSharp()
{
var code = @"
using System;
class [|$$ustom|]Attribute : Attribute
{
}
";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("C");
await state.AssertTag("ustomAttribute", "CustomAttribute", invokeAction: true);
var expectedCode = @"
using System;
class CustomAttribute : Attribute
{
}
";
Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText());
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
[WorkItem(21657, "https://github.com/dotnet/roslyn/issues/21657")]
public async Task RenameTrackingOnReference_Attribute_VB()
{
var code = @"
Import System;
Public Class [|$$ustom|]Attribute
Inherits Attribute
End Class
";
using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic);
state.EditorOperations.InsertText("C");
await state.AssertTag("ustomAttribute", "CustomAttribute", invokeAction: true);
var expectedCode = @"
Import System;
Public Class CustomAttribute
Inherits Attribute
End Class
";
Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText());
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
[WorkItem(21657, "https://github.com/dotnet/roslyn/issues/21657")]
public async Task RenameTrackingOnReference_Capitalized_Attribute_VB()
{
var code = @"
Import System;
Public Class [|$$ustom|]ATTRIBUTE
Inherits Attribute
End Class
";
using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic);
state.EditorOperations.InsertText("C");
await state.AssertTag("ustomATTRIBUTE", "CustomATTRIBUTE", invokeAction: true);
var expectedCode = @"
Import System;
Public Class CustomATTRIBUTE
Inherits Attribute
End Class
";
Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText());
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
[WorkItem(21657, "https://github.com/dotnet/roslyn/issues/21657")]
public async Task RenameTrackingOnReference_Not_Capitalized_Attribute_VB()
{
var code = @"
Import System;
Public Class [|$$ustom|]attribute
Inherits Attribute
End Class
";
using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic);
state.EditorOperations.InsertText("C");
await state.AssertTag("ustomattribute", "Customattribute", invokeAction: true);
var expectedCode = @"
Import System;
Public Class Customattribute
Inherits Attribute
End Class
";
Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText());
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotifiesThirdPartiesOfRenameOperation()
{
var code = @"
class Cat$$
{
public Cat()
{
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("s");
await state.AssertTag("Cat", "Cats", invokeAction: true);
Assert.Equal(1, state.RefactorNotifyService.OnBeforeSymbolRenamedCount);
Assert.Equal(1, state.RefactorNotifyService.OnAfterSymbolRenamedCount);
var expectedCode = @"
class Cats
{
public Cats()
{
}
}";
Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText());
state.AssertNoNotificationMessage();
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingHonorsThirdPartyRequestsForCancellationBeforeRename()
{
var code = @"
class Cat$$
{
public Cat()
{
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp, onBeforeGlobalSymbolRenamedReturnValue: false);
state.EditorOperations.InsertText("s");
await state.AssertTag("Cat", "Cats", invokeAction: true);
Assert.Equal(1, state.RefactorNotifyService.OnBeforeSymbolRenamedCount);
// Make sure the rename didn't proceed
Assert.Equal(0, state.RefactorNotifyService.OnAfterSymbolRenamedCount);
await state.AssertNoTag();
var expectedCode = @"
class Cat
{
public Cat()
{
}
}";
Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText());
state.AssertNotificationMessage();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingAlertsAboutThirdPartyRequestsForCancellationAfterRename()
{
var code = @"
class Cat$$
{
public Cat()
{
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp, onAfterGlobalSymbolRenamedReturnValue: false);
state.EditorOperations.InsertText("s");
await state.AssertTag("Cat", "Cats", invokeAction: true);
Assert.Equal(1, state.RefactorNotifyService.OnBeforeSymbolRenamedCount);
Assert.Equal(1, state.RefactorNotifyService.OnAfterSymbolRenamedCount);
state.AssertNotificationMessage();
// Make sure the rename completed
var expectedCode = @"
class Cats
{
public Cats()
{
}
}";
Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText());
await state.AssertNoTag();
}
[WpfFact, WorkItem(530469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530469")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotWhenStartedFromTextualWordInTrivia()
{
var code = @"
Module Program
Sub Main()
Dim [x$$ = 1
End Sub
End Module";
using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic);
state.EditorOperations.InsertText("]");
await state.AssertNoTag();
}
[WpfFact, WorkItem(530495, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530495")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotWhenCaseCorrectingReference()
{
var code = @"
Module Program
Sub Main()
$$main()
End Sub
End Module";
using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic);
state.EditorOperations.Delete();
await state.AssertTag("main", "ain");
state.EditorOperations.InsertText("M");
await state.AssertNoTag();
}
[WpfFact, WorkItem(599508, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/599508")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotWhenNewIdentifierReferenceBinds()
{
var code = @"
Module Program
Sub Main()
$$[|main|]()
End Sub
Sub Goo()
End Sub
End Module";
using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic);
var textSpan = state.HostDocument.SelectedSpans.Single();
state.EditorOperations.ReplaceText(new Span(textSpan.Start, textSpan.Length), "Go");
await state.AssertTag("main", "Go");
state.EditorOperations.InsertText("o");
await state.AssertNoTag();
}
[WpfFact, WorkItem(530400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530400")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotWhenDeclaringEnumMembers()
{
var code = @"
Enum E
$$
End Enum";
using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic);
state.EditorOperations.InsertText(" a");
state.EditorOperations.InsertText("b");
await state.AssertNoTag();
}
[WpfFact, WorkItem(1028072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1028072")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public void RenameTrackingDoesNotThrowAggregateException()
{
var waitForResult = false;
var notRenamable = Task.FromResult(RenameTrackingTaggerProvider.TriggerIdentifierKind.NotRenamable);
Assert.False(RenameTrackingTaggerProvider.IsRenamableIdentifier(notRenamable, waitForResult, CancellationToken.None));
var source = new TaskCompletionSource<RenameTrackingTaggerProvider.TriggerIdentifierKind>();
Assert.False(RenameTrackingTaggerProvider.IsRenamableIdentifier(source.Task, waitForResult, CancellationToken.None));
source.TrySetResult(RenameTrackingTaggerProvider.TriggerIdentifierKind.RenamableReference);
Assert.True(RenameTrackingTaggerProvider.IsRenamableIdentifier(source.Task, waitForResult, CancellationToken.None));
source = new TaskCompletionSource<RenameTrackingTaggerProvider.TriggerIdentifierKind>();
source.TrySetCanceled();
Assert.False(RenameTrackingTaggerProvider.IsRenamableIdentifier(source.Task, waitForResult, CancellationToken.None));
Assert.False(RenameTrackingTaggerProvider.WaitForIsRenamableIdentifier(source.Task, CancellationToken.None));
source = new TaskCompletionSource<RenameTrackingTaggerProvider.TriggerIdentifierKind>();
source.TrySetException(new OperationCanceledException());
Assert.False(RenameTrackingTaggerProvider.IsRenamableIdentifier(source.Task, waitForResult, CancellationToken.None));
Assert.False(RenameTrackingTaggerProvider.WaitForIsRenamableIdentifier(source.Task, CancellationToken.None));
Assert.False(RenameTrackingTaggerProvider.WaitForIsRenamableIdentifier(source.Task, new CancellationTokenSource().Token));
source = new TaskCompletionSource<RenameTrackingTaggerProvider.TriggerIdentifierKind>();
Assert.Throws<OperationCanceledException>(() => RenameTrackingTaggerProvider.WaitForIsRenamableIdentifier(source.Task, new CancellationToken(canceled: true)));
var thrownException = new Exception();
source.TrySetException(thrownException);
var caughtException = Assert.Throws<Exception>(() => RenameTrackingTaggerProvider.WaitForIsRenamableIdentifier(source.Task, CancellationToken.None));
Assert.Same(thrownException, caughtException);
}
[WpfFact, WorkItem(1063943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1063943")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotFromReferenceWithWrongNumberOfArguments()
{
var code = @"
class C
{
void M(int x)
{
M$$();
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("eow");
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task CancelRenameTracking()
{
var code = @"
class C$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("at");
await state.AssertTag("C", "Cat");
state.SendEscape();
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotWhenDeclaringEnumMembersEvenAfterCancellation()
{
var code = @"
Enum E
$$
End Enum";
using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic);
state.EditorOperations.InsertText(" a");
state.EditorOperations.InsertText("b");
await state.AssertNoTag();
state.SendEscape();
state.EditorOperations.InsertText("c");
await state.AssertNoTag();
}
[WpfFact]
[WorkItem(540, "https://github.com/dotnet/roslyn/issues/540")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingDoesNotProvideDiagnosticAfterCancellation()
{
var code = @"
class C$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("at");
await state.AssertTag("C", "Cat");
Assert.NotNull(await state.TryGetCodeActionAsync());
state.SendEscape();
await state.AssertNoTag();
Assert.Null(await state.TryGetCodeActionAsync());
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTracking_Nameof_FromMethodGroupReference()
{
var code = @"
class C
{
void M()
{
nameof(M$$).ToString();
}
void M(int x)
{
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("at");
await state.AssertTag("M", "Mat", invokeAction: true);
// Make sure the rename completed
var expectedCode = @"
class C
{
void Mat()
{
nameof(Mat).ToString();
}
void Mat(int x)
{
}
}";
Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText());
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTracking_Nameof_FromMethodDefinition_NoOverloads()
{
var code = @"
class C
{
void M$$()
{
nameof(M).ToString();
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("at");
await state.AssertTag("M", "Mat", invokeAction: true);
// Make sure the rename completed
var expectedCode = @"
class C
{
void Mat()
{
nameof(Mat).ToString();
}
}";
Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText());
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTracking_Nameof_FromMethodDefinition_WithOverloads()
{
var code = @"
class C
{
void M$$()
{
nameof(M).ToString();
}
void M(int x)
{
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("at");
await state.AssertTag("M", "Mat", invokeAction: true);
// Make sure the rename completed
var expectedCode = @"
class C
{
void Mat()
{
nameof(M).ToString();
}
void M(int x)
{
}
}";
Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText());
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTracking_Nameof_FromReferenceToMetadata_NoTag()
{
var code = @"
class C
{
void M()
{
var x = nameof(ToString$$);
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("z");
await state.AssertNoTag();
}
[WpfFact]
[WorkItem(762964, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/762964")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTracking_NoTagWhenFirstEditChangesReferenceToAnotherSymbol()
{
var code = @"
class C
{
void M()
{
int abc = 7;
int ab = 8;
int z = abc$$;
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.Backspace();
await state.AssertNoTag();
}
[WpfFact]
[WorkItem(2605, "https://github.com/dotnet/roslyn/issues/2605")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTracking_CannotRenameToVarInCSharp()
{
var code = @"
class C
{
void M()
{
C$$ c;
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.Backspace();
state.EditorOperations.InsertText("va");
await state.AssertTag("C", "va");
Assert.NotNull(await state.TryGetCodeActionAsync());
state.EditorOperations.InsertText("r");
await state.AssertNoTag();
Assert.Null(await state.TryGetCodeActionAsync());
state.EditorOperations.InsertText("p");
await state.AssertTag("C", "varp");
Assert.NotNull(await state.TryGetCodeActionAsync());
}
[WpfFact]
[WorkItem(2605, "https://github.com/dotnet/roslyn/issues/2605")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTracking_CannotRenameFromVarInCSharp()
{
var code = @"
class C
{
void M()
{
var$$ c = new C();
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.Backspace();
await state.AssertNoTag();
Assert.Null(await state.TryGetCodeActionAsync());
}
[WpfFact]
[WorkItem(2605, "https://github.com/dotnet/roslyn/issues/2605")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTracking_CanRenameToVarInVisualBasic()
{
var code = @"
Class C
Sub M()
Dim x as C$$
End Sub
End Class";
using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic);
state.EditorOperations.Backspace();
state.EditorOperations.InsertText("var");
await state.AssertTag("C", "var");
Assert.NotNull(await state.TryGetCodeActionAsync());
}
[WpfFact]
[WorkItem(2605, "https://github.com/dotnet/roslyn/issues/2605")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTracking_CannotRenameToDynamicInCSharp()
{
var code = @"
class C
{
void M()
{
C$$ c;
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.Backspace();
state.EditorOperations.InsertText("dynami");
await state.AssertTag("C", "dynami");
Assert.NotNull(await state.TryGetCodeActionAsync());
state.EditorOperations.InsertText("c");
await state.AssertNoTag();
Assert.Null(await state.TryGetCodeActionAsync());
state.EditorOperations.InsertText("s");
await state.AssertTag("C", "dynamics");
Assert.NotNull(await state.TryGetCodeActionAsync());
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameImplicitTupleField()
{
var code = @"
class C
{
void M()
{
(int, int) x = (1, 2);
var y = x.Item1$$;
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.Backspace();
state.EditorOperations.Backspace();
await state.AssertNoTag();
Assert.Null(await state.TryGetCodeActionAsync());
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameImplicitTupleFieldVB()
{
var code = @"
class C
Sub M()
Dim x as (Integer, Integer) = (1, 2)
Dim y = x.Item1$$
End Sub
End Class
";
using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic);
state.EditorOperations.Backspace();
state.EditorOperations.Backspace();
await state.AssertNoTag();
Assert.Null(await state.TryGetCodeActionAsync());
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameImplicitTupleFieldExtended()
{
var code = @"
class C
{
void M()
{
(int, int, int, int, int, int, int, int, int, int) x = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
var y = x.Item9$$;
}
}
";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.Backspace();
state.EditorOperations.Backspace();
await state.AssertNoTag();
Assert.Null(await state.TryGetCodeActionAsync());
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameImplicitTupleFieldExtendedVB()
{
var code = @"
Class C
Sub M()
Dim x as (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Dim y = x.Item9$$
End Sub
End Class
";
using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic);
state.EditorOperations.Backspace();
state.EditorOperations.Backspace();
await state.AssertNoTag();
Assert.Null(await state.TryGetCodeActionAsync());
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
[WorkItem(371205, "https://devdiv.visualstudio.com/DevDiv/_workitems?_a=edit&id=371205")]
public async Task RenameTrackingNotOnExplicitTupleReturnDeclaration_CSharp()
{
var code = @"
class C
{
void M()
{
(int abc$$, int) x = (1, 2);
var y = x.abc;
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.Backspace();
state.EditorOperations.Backspace();
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
[WorkItem(371205, "https://devdiv.visualstudio.com/DevDiv/_workitems?_a=edit&id=371205")]
public async Task RenameTrackingNotOnExplicitTupleReturnDeclaration_VB()
{
var code = @"
class C
Sub M()
Dim x as (abc$$ as integer, int Item2 as integer) = (1, 2)
Dim y = x.abc
End Sub
End Class";
using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic);
state.EditorOperations.Backspace();
state.EditorOperations.Backspace();
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
[WorkItem(371205, "https://devdiv.visualstudio.com/DevDiv/_workitems?_a=edit&id=371205")]
public async Task RenameTrackingNotOnExplicitTupleFieldReference_CSharp()
{
var code = @"
class C
{
void M()
{
(int abc, int) x = (1, 2);
var y = x.abc$$;
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.Backspace();
state.EditorOperations.Backspace();
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
[WorkItem(371205, "https://devdiv.visualstudio.com/DevDiv/_workitems?_a=edit&id=371205")]
public async Task RenameTrackingNotOnExplicitTupleFieldReference_VB()
{
var code = @"
class C
Sub M()
Dim x as (abc as integer, int Item2 as integer) = (1, 2)
Dim y = x.abc$$
End Sub
End Class";
using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic);
state.EditorOperations.Backspace();
state.EditorOperations.Backspace();
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
[WorkItem(371205, "https://devdiv.visualstudio.com/DevDiv/_workitems?_a=edit&id=371205")]
public async Task RenameTrackingNotOnExplicitTupleElementsInDeclarations_CSharp()
{
var code = @"
class C
{
void M()
{
var t = (x$$: 1, y: 2);
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("2");
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
[WorkItem(371205, "https://devdiv.visualstudio.com/DevDiv/_workitems?_a=edit&id=371205")]
public async Task RenameTrackingNotOnExplicitTupleElementsInDeclarations_VB()
{
var code = @"
Class C
Sub M()
Dim t = (x$$:=1, y:=2)
End Sub
End Class";
using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic);
state.EditorOperations.InsertText("2");
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
[WorkItem(14159, "https://github.com/dotnet/roslyn/issues/14159")]
public async Task RenameTrackingNotOnWellKnownValueTupleType()
{
var workspaceXml = @"
<Workspace>
<Project Language=""C#"" CommonReferences=""true"" LanguageVersion=""7"">
<Document>
using System;
class C
{
void M()
{
var x = new ValueTuple$$<int>();
}
}
namespace System
{
public struct ValueTuple<T1>
{
public T1 Item1;
}
}
</Document>
</Project>
</Workspace>";
using var state = RenameTrackingTestState.CreateFromWorkspaceXml(workspaceXml, LanguageNames.CSharp);
state.EditorOperations.InsertText("2");
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
[WorkItem(14159, "https://github.com/dotnet/roslyn/issues/14159")]
public async Task RenameTrackingOnThingsCalledValueTupleThatAreNotTheWellKnownType()
{
var workspaceXml = @"
<Workspace>
<Project Language=""C#"" CommonReferences=""true"" LanguageVersion=""7"">
<Document>
class C
{
void M()
{
var x = new ValueTuple$$<int>();
}
}
public struct ValueTuple<T1>
{
public T1 Item1;
}
</Document>
</Project>
</Workspace>";
using var state = RenameTrackingTestState.CreateFromWorkspaceXml(workspaceXml, LanguageNames.CSharp);
state.EditorOperations.InsertText("2");
await state.AssertTag("ValueTuple", "ValueTuple2");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingOnDeconstruct()
{
var code = @"
class C
{
void Deconstruct$$(out int x1, out int x2) { x1 = 1; x2 = 2; }
void M()
{
var (y1, y2) = this;
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("2");
await state.AssertTag("Deconstruct", "Deconstruct2");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTracking_UnmanagedConstraint_Keyword()
{
var code = @"
class C<T> where T : $$unmanaged
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTracking_UnmanagedConstraint_Type()
{
var code = @"
interface unmanaged
{
}
class C<T> where T : $$unmanaged
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("my");
await state.AssertTag("unmanaged", "myunmanaged", invokeAction: true);
// Make sure the rename completed
var expectedCode = @"
interface myunmanaged
{
}
class C<T> where T : myunmanaged
{
}";
Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText());
await state.AssertNoTag();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.RenameTracking
{
[UseExportProvider]
public class RenameTrackingTaggerProviderTests
{
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotOnCreation()
{
var code = @"
class C$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotInBlankFile()
{
var code = @"$$";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("d");
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingTypingAtEnd()
{
var code = @"
class C$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("at");
await state.AssertTag("C", "Cat");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingTypingAtBeginning()
{
var code = @"
class $$C
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("AB");
await state.AssertTag("C", "ABC");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingTypingInMiddle()
{
var code = @"
class AB$$CD
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("ZZ");
await state.AssertTag("ABCD", "ABZZCD");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingDeleteFromEnd()
{
var code = @"
class ABC$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.Backspace();
await state.AssertTag("ABC", "AB");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingDeleteFromBeginning()
{
var code = @"
class $$ABC
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.Delete();
await state.AssertTag("ABC", "BC");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingDeleteFromMiddle()
{
var code = @"
class AB$$C
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.Backspace();
await state.AssertTag("ABC", "AC");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotOnClassKeyword()
{
var code = @"
class$$ ABCD
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("d");
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotAtMethodArgument()
{
var code = @"
class ABCD
{
void Goo(int x)
{
int abc = 3;
Goo($$
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("a");
await state.AssertNoTag();
state.EditorOperations.InsertText("b");
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingSessionContinuesAfterViewingTag()
{
var code = @"
class C$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("at");
await state.AssertTag("C", "Cat");
state.EditorOperations.InsertText("s");
await state.AssertTag("C", "Cats");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotInString()
{
var code = @"
class C
{
void Goo()
{
string s = ""abc$$""
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("d");
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingHandlesAtSignAsCSharpEscape()
{
var code = @"
class $$C
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("@");
await state.AssertTag("C", "@C");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingHandlesSquareBracketsAsVisualBasicEscape()
{
var code = @"
Class $$C
End Class";
using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic);
state.EditorOperations.InsertText("[");
await state.AssertNoTag();
state.MoveCaret(1);
state.EditorOperations.InsertText("]");
await state.AssertTag("C", "[C]");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotOnSquareBracketsInCSharp()
{
var code = @"
class $$C
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("[");
await state.AssertNoTag();
state.MoveCaret(1);
state.EditorOperations.InsertText("]");
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingHandlesUnicode()
{
var code = @"
class C$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("\u0414\u046E\u046A\u00DB\u00CA\u00DB\u00C4\u00C1\u00CD\u00E4\u00E1\u0152\u0178\u00F5\u00E0\u0178\u00FC\u00C4\u00B5\u00C1i\u00DBE\u00EA\u00E0\u00EA\u00E8\u00E4\u00E5\u00ED\u00F2\u00E8\u00F4\u00E8\u00EA\u00E0\u00F2\u00EE\u00F0\u00F1\u00EB\u00EE\u00E2\u00EE");
await state.AssertTag("C", "C\u0414\u046E\u046A\u00DB\u00CA\u00DB\u00C4\u00C1\u00CD\u00E4\u00E1\u0152\u0178\u00F5\u00E0\u0178\u00FC\u00C4\u00B5\u00C1i\u00DBE\u00EA\u00E0\u00EA\u00E8\u00E4\u00E5\u00ED\u00F2\u00E8\u00F4\u00E8\u00EA\u00E0\u00F2\u00EE\u00F0\u00F1\u00EB\u00EE\u00E2\u00EE");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingThroughKeyword()
{
var code = @"
class i$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("n");
await state.AssertNoTag();
state.EditorOperations.InsertText("t");
await state.AssertNoTag();
state.EditorOperations.InsertText("s");
await state.AssertTag("i", "ints");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingThroughIllegalStartCharacter()
{
var code = @"
class $$abc
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("9");
await state.AssertNoTag();
state.MoveCaret(-1);
state.EditorOperations.InsertText("t");
await state.AssertTag("abc", "t9abc");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingOnBothSidesOfIdentifier()
{
var code = @"
class $$Def
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("Abc");
await state.AssertTag("Def", "AbcDef");
state.MoveCaret(3);
state.EditorOperations.InsertText("Ghi");
await state.AssertTag("Def", "AbcDefGhi");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingThroughSameIdentifier()
{
var code = @"
class C$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("s");
await state.AssertTag("C", "Cs");
state.EditorOperations.Backspace();
await state.AssertNoTag();
state.EditorOperations.InsertText("s");
await state.AssertTag("C", "Cs");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingThroughEmptyString()
{
var code = @"
class C$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.Backspace();
await state.AssertNoTag();
state.EditorOperations.InsertText("D");
await state.AssertTag("C", "D");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingThroughEmptyStringWithCaretMove()
{
var code = @"
class C$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.Backspace();
state.MoveCaret(-4);
state.MoveCaret(4);
await state.AssertNoTag();
state.EditorOperations.InsertText("D");
await state.AssertTag("C", "D");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotThroughEmptyStringResumeOnDifferentSpace()
{
var code = @"
class C$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.Backspace();
// Move to previous space
state.MoveCaret(-1);
state.EditorOperations.InsertText("D");
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingReplaceIdentifierSuffix()
{
var code = @"
class Identifi[|er|]$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
var textSpan = state.HostDocument.SelectedSpans.Single();
state.EditorOperations.ReplaceText(new Span(textSpan.Start, textSpan.Length), "cation");
await state.AssertTag("Identifier", "Identification");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingReplaceIdentifierPrefix()
{
var code = @"
class $$[|Ident|]ifier
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
var textSpan = state.HostDocument.SelectedSpans.Single();
state.EditorOperations.ReplaceText(new Span(textSpan.Start, textSpan.Length), "Complex");
await state.AssertTag("Identifier", "Complexifier");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingReplaceIdentifierCompletely()
{
var code = @"
class [|Cat|]$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
var textSpan = state.HostDocument.SelectedSpans.Single();
state.EditorOperations.ReplaceText(new Span(textSpan.Start, textSpan.Length), "Dog");
await state.AssertTag("Cat", "Dog");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
[WorkItem(34280, "https://github.com/dotnet/roslyn/issues/34280")]
public async Task RenameTrackingReplaceIdentifierWithDiscard()
{
var code = @"
class Class
{
int Method()
{
int i;
[|i|]$$ = Method();
rteurn 0;
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
var textSpan = state.HostDocument.SelectedSpans.Single();
state.EditorOperations.ReplaceText(new Span(textSpan.Start, textSpan.Length), "_");
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotAfterInvoke()
{
var code = @"
class Cat$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("s");
await state.AssertTag("Cat", "Cats", invokeAction: true);
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingInvokeAndChangeBackToOriginal()
{
var code = @"
class Cat$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("s");
await state.AssertTag("Cat", "Cats", invokeAction: true);
await state.AssertNoTag();
state.EditorOperations.Backspace();
await state.AssertTag("Cats", "Cat");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingUndoOnceAndStartNewSession()
{
var code = @"
class Cat$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("abc");
await state.AssertTag("Cat", "Catabc", invokeAction: true);
await state.AssertNoTag();
// Back to original
state.Undo();
await state.AssertNoTag();
state.EditorOperations.InsertText("xyz");
await state.AssertTag("Cat", "Catxyz");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingUndoTwiceAndContinueSession()
{
var code = @"
class Cat$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("abc");
await state.AssertTag("Cat", "Catabc", invokeAction: true);
await state.AssertNoTag();
// Resume rename tracking session
state.Undo(2);
await state.AssertTag("Cat", "Catabc");
state.EditorOperations.InsertText("xyz");
await state.AssertTag("Cat", "Catabcxyz");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingRedoAlwaysClearsState()
{
var code = @"
class Cat$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("s");
await state.AssertTag("Cat", "Cats", invokeAction: true);
await state.AssertNoTag();
// Resume rename tracking session
state.Undo(2);
await state.AssertTag("Cat", "Cats");
state.Redo();
await state.AssertNoTag();
state.Redo();
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingUndoTwiceRedoTwiceUndoStillWorks()
{
var code = @"
class Cat$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("s");
await state.AssertTag("Cat", "Cats", invokeAction: true);
await state.AssertNoTag();
// Resume rename tracking session
state.Undo(2);
await state.AssertTag("Cat", "Cats");
state.Redo(2);
await state.AssertNoTag();
// Back to original
state.Undo();
await state.AssertNoTag();
// Resume rename tracking session
state.Undo();
await state.AssertTag("Cat", "Cats");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingOnReference_ParameterAsArgument()
{
var code = @"
class C
{
void M(int x)
{
M(x$$);
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("yz");
await state.AssertTag("x", "xyz");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingOnReference_ParameterAsNamedArgument()
{
var code = @"
class C
{
void M(int x)
{
M(x$$: x);
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("yz");
await state.AssertTag("x", "xyz");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingOnReference_Namespace()
{
var code = @"
namespace NS
{
class C
{
static void M()
{
NS$$.C.M();
}
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("A");
await state.AssertTag("NS", "NSA");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
[WorkItem(21657, "https://github.com/dotnet/roslyn/issues/21657")]
public async Task RenameTrackingOnReference_Attribute_CSharp()
{
var code = @"
using System;
class [|$$ustom|]Attribute : Attribute
{
}
";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("C");
await state.AssertTag("ustomAttribute", "CustomAttribute", invokeAction: true);
var expectedCode = @"
using System;
class CustomAttribute : Attribute
{
}
";
Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText());
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
[WorkItem(21657, "https://github.com/dotnet/roslyn/issues/21657")]
public async Task RenameTrackingOnReference_Attribute_VB()
{
var code = @"
Import System;
Public Class [|$$ustom|]Attribute
Inherits Attribute
End Class
";
using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic);
state.EditorOperations.InsertText("C");
await state.AssertTag("ustomAttribute", "CustomAttribute", invokeAction: true);
var expectedCode = @"
Import System;
Public Class CustomAttribute
Inherits Attribute
End Class
";
Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText());
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
[WorkItem(21657, "https://github.com/dotnet/roslyn/issues/21657")]
public async Task RenameTrackingOnReference_Capitalized_Attribute_VB()
{
var code = @"
Import System;
Public Class [|$$ustom|]ATTRIBUTE
Inherits Attribute
End Class
";
using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic);
state.EditorOperations.InsertText("C");
await state.AssertTag("ustomATTRIBUTE", "CustomATTRIBUTE", invokeAction: true);
var expectedCode = @"
Import System;
Public Class CustomATTRIBUTE
Inherits Attribute
End Class
";
Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText());
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
[WorkItem(21657, "https://github.com/dotnet/roslyn/issues/21657")]
public async Task RenameTrackingOnReference_Not_Capitalized_Attribute_VB()
{
var code = @"
Import System;
Public Class [|$$ustom|]attribute
Inherits Attribute
End Class
";
using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic);
state.EditorOperations.InsertText("C");
await state.AssertTag("ustomattribute", "Customattribute", invokeAction: true);
var expectedCode = @"
Import System;
Public Class Customattribute
Inherits Attribute
End Class
";
Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText());
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotifiesThirdPartiesOfRenameOperation()
{
var code = @"
class Cat$$
{
public Cat()
{
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("s");
await state.AssertTag("Cat", "Cats", invokeAction: true);
Assert.Equal(1, state.RefactorNotifyService.OnBeforeSymbolRenamedCount);
Assert.Equal(1, state.RefactorNotifyService.OnAfterSymbolRenamedCount);
var expectedCode = @"
class Cats
{
public Cats()
{
}
}";
Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText());
state.AssertNoNotificationMessage();
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingHonorsThirdPartyRequestsForCancellationBeforeRename()
{
var code = @"
class Cat$$
{
public Cat()
{
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp, onBeforeGlobalSymbolRenamedReturnValue: false);
state.EditorOperations.InsertText("s");
await state.AssertTag("Cat", "Cats", invokeAction: true);
Assert.Equal(1, state.RefactorNotifyService.OnBeforeSymbolRenamedCount);
// Make sure the rename didn't proceed
Assert.Equal(0, state.RefactorNotifyService.OnAfterSymbolRenamedCount);
await state.AssertNoTag();
var expectedCode = @"
class Cat
{
public Cat()
{
}
}";
Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText());
state.AssertNotificationMessage();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingAlertsAboutThirdPartyRequestsForCancellationAfterRename()
{
var code = @"
class Cat$$
{
public Cat()
{
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp, onAfterGlobalSymbolRenamedReturnValue: false);
state.EditorOperations.InsertText("s");
await state.AssertTag("Cat", "Cats", invokeAction: true);
Assert.Equal(1, state.RefactorNotifyService.OnBeforeSymbolRenamedCount);
Assert.Equal(1, state.RefactorNotifyService.OnAfterSymbolRenamedCount);
state.AssertNotificationMessage();
// Make sure the rename completed
var expectedCode = @"
class Cats
{
public Cats()
{
}
}";
Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText());
await state.AssertNoTag();
}
[WpfFact, WorkItem(530469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530469")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotWhenStartedFromTextualWordInTrivia()
{
var code = @"
Module Program
Sub Main()
Dim [x$$ = 1
End Sub
End Module";
using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic);
state.EditorOperations.InsertText("]");
await state.AssertNoTag();
}
[WpfFact, WorkItem(530495, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530495")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotWhenCaseCorrectingReference()
{
var code = @"
Module Program
Sub Main()
$$main()
End Sub
End Module";
using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic);
state.EditorOperations.Delete();
await state.AssertTag("main", "ain");
state.EditorOperations.InsertText("M");
await state.AssertNoTag();
}
[WpfFact, WorkItem(599508, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/599508")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotWhenNewIdentifierReferenceBinds()
{
var code = @"
Module Program
Sub Main()
$$[|main|]()
End Sub
Sub Goo()
End Sub
End Module";
using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic);
var textSpan = state.HostDocument.SelectedSpans.Single();
state.EditorOperations.ReplaceText(new Span(textSpan.Start, textSpan.Length), "Go");
await state.AssertTag("main", "Go");
state.EditorOperations.InsertText("o");
await state.AssertNoTag();
}
[WpfFact, WorkItem(530400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530400")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotWhenDeclaringEnumMembers()
{
var code = @"
Enum E
$$
End Enum";
using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic);
state.EditorOperations.InsertText(" a");
state.EditorOperations.InsertText("b");
await state.AssertNoTag();
}
[WpfFact, WorkItem(1028072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1028072")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public void RenameTrackingDoesNotThrowAggregateException()
{
var waitForResult = false;
var notRenamable = Task.FromResult(RenameTrackingTaggerProvider.TriggerIdentifierKind.NotRenamable);
Assert.False(RenameTrackingTaggerProvider.IsRenamableIdentifier(notRenamable, waitForResult, CancellationToken.None));
var source = new TaskCompletionSource<RenameTrackingTaggerProvider.TriggerIdentifierKind>();
Assert.False(RenameTrackingTaggerProvider.IsRenamableIdentifier(source.Task, waitForResult, CancellationToken.None));
source.TrySetResult(RenameTrackingTaggerProvider.TriggerIdentifierKind.RenamableReference);
Assert.True(RenameTrackingTaggerProvider.IsRenamableIdentifier(source.Task, waitForResult, CancellationToken.None));
source = new TaskCompletionSource<RenameTrackingTaggerProvider.TriggerIdentifierKind>();
source.TrySetCanceled();
Assert.False(RenameTrackingTaggerProvider.IsRenamableIdentifier(source.Task, waitForResult, CancellationToken.None));
Assert.False(RenameTrackingTaggerProvider.WaitForIsRenamableIdentifier(source.Task, CancellationToken.None));
source = new TaskCompletionSource<RenameTrackingTaggerProvider.TriggerIdentifierKind>();
source.TrySetException(new OperationCanceledException());
Assert.False(RenameTrackingTaggerProvider.IsRenamableIdentifier(source.Task, waitForResult, CancellationToken.None));
Assert.False(RenameTrackingTaggerProvider.WaitForIsRenamableIdentifier(source.Task, CancellationToken.None));
Assert.False(RenameTrackingTaggerProvider.WaitForIsRenamableIdentifier(source.Task, new CancellationTokenSource().Token));
source = new TaskCompletionSource<RenameTrackingTaggerProvider.TriggerIdentifierKind>();
Assert.Throws<OperationCanceledException>(() => RenameTrackingTaggerProvider.WaitForIsRenamableIdentifier(source.Task, new CancellationToken(canceled: true)));
var thrownException = new Exception();
source.TrySetException(thrownException);
var caughtException = Assert.Throws<Exception>(() => RenameTrackingTaggerProvider.WaitForIsRenamableIdentifier(source.Task, CancellationToken.None));
Assert.Same(thrownException, caughtException);
}
[WpfFact, WorkItem(1063943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1063943")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotFromReferenceWithWrongNumberOfArguments()
{
var code = @"
class C
{
void M(int x)
{
M$$();
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("eow");
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task CancelRenameTracking()
{
var code = @"
class C$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("at");
await state.AssertTag("C", "Cat");
state.SendEscape();
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingNotWhenDeclaringEnumMembersEvenAfterCancellation()
{
var code = @"
Enum E
$$
End Enum";
using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic);
state.EditorOperations.InsertText(" a");
state.EditorOperations.InsertText("b");
await state.AssertNoTag();
state.SendEscape();
state.EditorOperations.InsertText("c");
await state.AssertNoTag();
}
[WpfFact]
[WorkItem(540, "https://github.com/dotnet/roslyn/issues/540")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingDoesNotProvideDiagnosticAfterCancellation()
{
var code = @"
class C$$
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("at");
await state.AssertTag("C", "Cat");
Assert.NotNull(await state.TryGetCodeActionAsync());
state.SendEscape();
await state.AssertNoTag();
Assert.Null(await state.TryGetCodeActionAsync());
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTracking_Nameof_FromMethodGroupReference()
{
var code = @"
class C
{
void M()
{
nameof(M$$).ToString();
}
void M(int x)
{
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("at");
await state.AssertTag("M", "Mat", invokeAction: true);
// Make sure the rename completed
var expectedCode = @"
class C
{
void Mat()
{
nameof(Mat).ToString();
}
void Mat(int x)
{
}
}";
Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText());
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTracking_Nameof_FromMethodDefinition_NoOverloads()
{
var code = @"
class C
{
void M$$()
{
nameof(M).ToString();
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("at");
await state.AssertTag("M", "Mat", invokeAction: true);
// Make sure the rename completed
var expectedCode = @"
class C
{
void Mat()
{
nameof(Mat).ToString();
}
}";
Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText());
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTracking_Nameof_FromMethodDefinition_WithOverloads()
{
var code = @"
class C
{
void M$$()
{
nameof(M).ToString();
}
void M(int x)
{
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("at");
await state.AssertTag("M", "Mat", invokeAction: true);
// Make sure the rename completed
var expectedCode = @"
class C
{
void Mat()
{
nameof(M).ToString();
}
void M(int x)
{
}
}";
Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText());
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTracking_Nameof_FromReferenceToMetadata_NoTag()
{
var code = @"
class C
{
void M()
{
var x = nameof(ToString$$);
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("z");
await state.AssertNoTag();
}
[WpfFact]
[WorkItem(762964, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/762964")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTracking_NoTagWhenFirstEditChangesReferenceToAnotherSymbol()
{
var code = @"
class C
{
void M()
{
int abc = 7;
int ab = 8;
int z = abc$$;
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.Backspace();
await state.AssertNoTag();
}
[WpfFact]
[WorkItem(2605, "https://github.com/dotnet/roslyn/issues/2605")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTracking_CannotRenameToVarInCSharp()
{
var code = @"
class C
{
void M()
{
C$$ c;
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.Backspace();
state.EditorOperations.InsertText("va");
await state.AssertTag("C", "va");
Assert.NotNull(await state.TryGetCodeActionAsync());
state.EditorOperations.InsertText("r");
await state.AssertNoTag();
Assert.Null(await state.TryGetCodeActionAsync());
state.EditorOperations.InsertText("p");
await state.AssertTag("C", "varp");
Assert.NotNull(await state.TryGetCodeActionAsync());
}
[WpfFact]
[WorkItem(2605, "https://github.com/dotnet/roslyn/issues/2605")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTracking_CannotRenameFromVarInCSharp()
{
var code = @"
class C
{
void M()
{
var$$ c = new C();
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.Backspace();
await state.AssertNoTag();
Assert.Null(await state.TryGetCodeActionAsync());
}
[WpfFact]
[WorkItem(2605, "https://github.com/dotnet/roslyn/issues/2605")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTracking_CanRenameToVarInVisualBasic()
{
var code = @"
Class C
Sub M()
Dim x as C$$
End Sub
End Class";
using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic);
state.EditorOperations.Backspace();
state.EditorOperations.InsertText("var");
await state.AssertTag("C", "var");
Assert.NotNull(await state.TryGetCodeActionAsync());
}
[WpfFact]
[WorkItem(2605, "https://github.com/dotnet/roslyn/issues/2605")]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTracking_CannotRenameToDynamicInCSharp()
{
var code = @"
class C
{
void M()
{
C$$ c;
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.Backspace();
state.EditorOperations.InsertText("dynami");
await state.AssertTag("C", "dynami");
Assert.NotNull(await state.TryGetCodeActionAsync());
state.EditorOperations.InsertText("c");
await state.AssertNoTag();
Assert.Null(await state.TryGetCodeActionAsync());
state.EditorOperations.InsertText("s");
await state.AssertTag("C", "dynamics");
Assert.NotNull(await state.TryGetCodeActionAsync());
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameImplicitTupleField()
{
var code = @"
class C
{
void M()
{
(int, int) x = (1, 2);
var y = x.Item1$$;
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.Backspace();
state.EditorOperations.Backspace();
await state.AssertNoTag();
Assert.Null(await state.TryGetCodeActionAsync());
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameImplicitTupleFieldVB()
{
var code = @"
class C
Sub M()
Dim x as (Integer, Integer) = (1, 2)
Dim y = x.Item1$$
End Sub
End Class
";
using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic);
state.EditorOperations.Backspace();
state.EditorOperations.Backspace();
await state.AssertNoTag();
Assert.Null(await state.TryGetCodeActionAsync());
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameImplicitTupleFieldExtended()
{
var code = @"
class C
{
void M()
{
(int, int, int, int, int, int, int, int, int, int) x = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
var y = x.Item9$$;
}
}
";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.Backspace();
state.EditorOperations.Backspace();
await state.AssertNoTag();
Assert.Null(await state.TryGetCodeActionAsync());
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameImplicitTupleFieldExtendedVB()
{
var code = @"
Class C
Sub M()
Dim x as (Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer) = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Dim y = x.Item9$$
End Sub
End Class
";
using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic);
state.EditorOperations.Backspace();
state.EditorOperations.Backspace();
await state.AssertNoTag();
Assert.Null(await state.TryGetCodeActionAsync());
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
[WorkItem(371205, "https://devdiv.visualstudio.com/DevDiv/_workitems?_a=edit&id=371205")]
public async Task RenameTrackingNotOnExplicitTupleReturnDeclaration_CSharp()
{
var code = @"
class C
{
void M()
{
(int abc$$, int) x = (1, 2);
var y = x.abc;
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.Backspace();
state.EditorOperations.Backspace();
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
[WorkItem(371205, "https://devdiv.visualstudio.com/DevDiv/_workitems?_a=edit&id=371205")]
public async Task RenameTrackingNotOnExplicitTupleReturnDeclaration_VB()
{
var code = @"
class C
Sub M()
Dim x as (abc$$ as integer, int Item2 as integer) = (1, 2)
Dim y = x.abc
End Sub
End Class";
using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic);
state.EditorOperations.Backspace();
state.EditorOperations.Backspace();
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
[WorkItem(371205, "https://devdiv.visualstudio.com/DevDiv/_workitems?_a=edit&id=371205")]
public async Task RenameTrackingNotOnExplicitTupleFieldReference_CSharp()
{
var code = @"
class C
{
void M()
{
(int abc, int) x = (1, 2);
var y = x.abc$$;
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.Backspace();
state.EditorOperations.Backspace();
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
[WorkItem(371205, "https://devdiv.visualstudio.com/DevDiv/_workitems?_a=edit&id=371205")]
public async Task RenameTrackingNotOnExplicitTupleFieldReference_VB()
{
var code = @"
class C
Sub M()
Dim x as (abc as integer, int Item2 as integer) = (1, 2)
Dim y = x.abc$$
End Sub
End Class";
using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic);
state.EditorOperations.Backspace();
state.EditorOperations.Backspace();
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
[WorkItem(371205, "https://devdiv.visualstudio.com/DevDiv/_workitems?_a=edit&id=371205")]
public async Task RenameTrackingNotOnExplicitTupleElementsInDeclarations_CSharp()
{
var code = @"
class C
{
void M()
{
var t = (x$$: 1, y: 2);
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("2");
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
[WorkItem(371205, "https://devdiv.visualstudio.com/DevDiv/_workitems?_a=edit&id=371205")]
public async Task RenameTrackingNotOnExplicitTupleElementsInDeclarations_VB()
{
var code = @"
Class C
Sub M()
Dim t = (x$$:=1, y:=2)
End Sub
End Class";
using var state = RenameTrackingTestState.Create(code, LanguageNames.VisualBasic);
state.EditorOperations.InsertText("2");
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
[WorkItem(14159, "https://github.com/dotnet/roslyn/issues/14159")]
public async Task RenameTrackingNotOnWellKnownValueTupleType()
{
var workspaceXml = @"
<Workspace>
<Project Language=""C#"" CommonReferences=""true"" LanguageVersion=""7"">
<Document>
using System;
class C
{
void M()
{
var x = new ValueTuple$$<int>();
}
}
namespace System
{
public struct ValueTuple<T1>
{
public T1 Item1;
}
}
</Document>
</Project>
</Workspace>";
using var state = RenameTrackingTestState.CreateFromWorkspaceXml(workspaceXml, LanguageNames.CSharp);
state.EditorOperations.InsertText("2");
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
[WorkItem(14159, "https://github.com/dotnet/roslyn/issues/14159")]
public async Task RenameTrackingOnThingsCalledValueTupleThatAreNotTheWellKnownType()
{
var workspaceXml = @"
<Workspace>
<Project Language=""C#"" CommonReferences=""true"" LanguageVersion=""7"">
<Document>
class C
{
void M()
{
var x = new ValueTuple$$<int>();
}
}
public struct ValueTuple<T1>
{
public T1 Item1;
}
</Document>
</Project>
</Workspace>";
using var state = RenameTrackingTestState.CreateFromWorkspaceXml(workspaceXml, LanguageNames.CSharp);
state.EditorOperations.InsertText("2");
await state.AssertTag("ValueTuple", "ValueTuple2");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTrackingOnDeconstruct()
{
var code = @"
class C
{
void Deconstruct$$(out int x1, out int x2) { x1 = 1; x2 = 2; }
void M()
{
var (y1, y2) = this;
}
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("2");
await state.AssertTag("Deconstruct", "Deconstruct2");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTracking_UnmanagedConstraint_Keyword()
{
var code = @"
class C<T> where T : $$unmanaged
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
await state.AssertNoTag();
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.RenameTracking)]
public async Task RenameTracking_UnmanagedConstraint_Type()
{
var code = @"
interface unmanaged
{
}
class C<T> where T : $$unmanaged
{
}";
using var state = RenameTrackingTestState.Create(code, LanguageNames.CSharp);
state.EditorOperations.InsertText("my");
await state.AssertTag("unmanaged", "myunmanaged", invokeAction: true);
// Make sure the rename completed
var expectedCode = @"
interface myunmanaged
{
}
class C<T> where T : myunmanaged
{
}";
Assert.Equal(expectedCode, state.HostDocument.GetTextBuffer().CurrentSnapshot.GetText());
await state.AssertNoTag();
}
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/EditorFeatures/CSharpTest/CodeActions/SyncNamespace/SyncNamespaceTests_ChangeNamespace.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.SyncNamespace
{
public partial class SyncNamespaceTests : CSharpSyncNamespaceTestsBase
{
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_InvalidFolderName1()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar";
// No change namespace action because the folder name is not valid identifier
var (folder, filePath) = CreateDocumentFilePath(new[] { "3B", "C" }, "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestChangeNamespaceAsync(code, expectedSourceOriginal: null);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_InvalidFolderName2()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar";
// No change namespace action because the folder name is not valid identifier
var (folder, filePath) = CreateDocumentFilePath(new[] { "B.3C", "D" }, "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestChangeNamespaceAsync(code, expectedSourceOriginal: null);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_SingleDocumentNoReference()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_SingleDocumentNoReference_FileScopedNamespace()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace};
class Class1
{{
}}
</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C;
class Class1
{
}
";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_SingleDocumentLocalReference()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
delegate void D1;
interface Class1
{{
void M1();
}}
class Class2 : {declaredNamespace}.Class1
{{
{declaredNamespace}.D1 d;
void {declaredNamespace}.Class1.M1(){{}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
delegate void D1;
interface Class1
{
void M1();
}
class Class2 : Class1
{
D1 d;
void Class1.M1() { }
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithCrefReference()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""{declaredNamespace}.Class1""/>
/// See <see cref=""global::{declaredNamespace}.Class1""/>
/// See <see cref=""global::{declaredNamespace}.Class1.M1""/>
/// </summary>
public class Class1
{{
public void M1() {{ }}
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
using {declaredNamespace};
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""{declaredNamespace}.Class1""/>
/// See <see cref=""global::{declaredNamespace}.Class1""/>
/// See <see cref=""global::{declaredNamespace}.Class1.M1""/>
/// </summary>
class RefClass
{{
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""Class1""/>
/// See <see cref=""global::A.B.C.Class1""/>
/// See <see cref=""global::A.B.C.Class1.M1""/>
/// </summary>
public class Class1
{
public void M1() { }
}
}";
var expectedSourceReference =
@"
namespace Foo
{
using A.B.C;
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""A.B.C.Class1""/>
/// See <see cref=""global::A.B.C.Class1""/>
/// See <see cref=""global::A.B.C.Class1.M1""/>
/// </summary>
class RefClass
{
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithCrefReferencesInVB()
{
var defaultNamespace = "A.B.C";
var declaredNamespace = "A.B.C.D";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""{declaredNamespace}.Class1""/>
/// </summary>
public class Class1
{{
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Imports {declaredNamespace}
''' <summary>
''' See <see cref=""Class1""/>
''' See <see cref=""{declaredNamespace}.Class1""/>
''' </summary>
Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""Class1""/>
/// </summary>
public class Class1
{
}
}";
var expectedSourceReference =
@"
Imports A.B.C
''' <summary>
''' See <see cref=""Class1""/>
''' See <see cref=""Class1""/>
''' </summary>
Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_ReferencingTypesDeclaredInOtherDocument()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
private Class2 c2;
private Class3 c3;
private Class4 c4;
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class Class2 {{}}
namespace Bar
{{
class Class3 {{}}
namespace Baz
{{
class Class4 {{}}
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"using Foo;
using Foo.Bar;
using Foo.Bar.Baz;
namespace A.B.C
{
class Class1
{
private Class2 c2;
private Class3 c3;
private Class4 c4;
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_ReferencingQualifiedTypesDeclaredInOtherDocument()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
private Foo.Class2 c2;
private Foo.Bar.Class3 c3;
private Foo.Bar.Baz.Class4 c4;
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class Class2 {{}}
namespace Bar
{{
class Class3 {{}}
namespace Baz
{{
class Class4 {{}}
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"using Foo;
using Foo.Bar;
using Foo.Bar.Baz;
namespace A.B.C
{
class Class1
{
private Class2 c2;
private Class3 c3;
private Class4 c4;
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithReferencesInOtherDocument()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
class Class2
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
using Foo.Bar.Baz;
namespace Foo
{{
class RefClass
{{
private Class1 c1;
void M1()
{{
Bar.Baz.Class2 c2 = null;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
}
class Class2
{
}
}";
var expectedSourceReference =
@"
using A.B.C;
namespace Foo
{
class RefClass
{
private Class1 c1;
void M1()
{
Class2 c2 = null;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithQualifiedReferencesInOtherDocument()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
interface Interface1
{{
void M1(Interface1 c1);
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
using {declaredNamespace};
class RefClass : Interface1
{{
void {declaredNamespace}.Interface1.M1(Interface1 c1){{}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
interface Interface1
{
void M1(Interface1 c1);
}
}";
var expectedSourceReference =
@"
namespace Foo
{
using A.B.C;
class RefClass : Interface1
{
void Interface1.M1(Interface1 c1){}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_ChangeUsingsInMultipleContainers()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace NS1
{{
using Foo.Bar.Baz;
class Class2
{{
Class1 c2;
}}
namespace NS2
{{
using Foo.Bar.Baz;
class Class2
{{
Class1 c1;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
}
}";
var expectedSourceReference =
@"
namespace NS1
{
using A.B.C;
class Class2
{
Class1 c2;
}
namespace NS2
{
class Class2
{
Class1 c1;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithAliasReferencesInOtherDocument()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
class Class2
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
using System;
using Class1Alias = Foo.Bar.Baz.Class1;
namespace Foo
{{
class RefClass
{{
private Class1Alias c1;
void M1()
{{
Bar.Baz.Class2 c2 = null;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
}
class Class2
{
}
}";
var expectedSourceReference =
@"
using System;
using A.B.C;
using Class1Alias = A.B.C.Class1;
namespace Foo
{
class RefClass
{
private Class1Alias c1;
void M1()
{
Class2 c2 = null;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_SingleDocumentNoRef()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
using System;
// Comments before declaration.
namespace [||]{declaredNamespace}
{{ // Comments after opening brace
class Class1
{{
}}
// Comments before closing brace
}} // Comments after declaration.
</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"using System;
// Comments before declaration.
// Comments after opening brace
class Class1
{
}
// Comments before closing brace
// Comments after declaration.
";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_SingleDocumentLocalRef()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
delegate void D1;
interface Class1
{{
void M1();
}}
class Class2 : {declaredNamespace}.Class1
{{
global::{declaredNamespace}.D1 d;
void {declaredNamespace}.Class1.M1() {{ }}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"delegate void D1;
interface Class1
{
void M1();
}
class Class2 : Class1
{
global::D1 d;
void Class1.M1() { }
}
";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithReferencesInOtherDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
class Class2
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
using Foo.Bar.Baz;
namespace Foo
{{
class RefClass
{{
private Class1 c1;
void M1()
{{
Bar.Baz.Class2 c2 = null;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"class Class1
{
}
class Class2
{
}
";
var expectedSourceReference =
@"namespace Foo
{
class RefClass
{
private Class1 c1;
void M1()
{
Class2 c2 = null;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithQualifiedReferencesInOtherDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
interface Interface1
{{
void M1(Interface1 c1);
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
using {declaredNamespace};
class RefClass : Interface1
{{
void {declaredNamespace}.Interface1.M1(Interface1 c1){{}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"interface Interface1
{
void M1(Interface1 c1);
}
";
var expectedSourceReference =
@"
namespace Foo
{
class RefClass : Interface1
{
void Interface1.M1(Interface1 c1){}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithReferenceAndConflictDeclarationInOtherDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class MyClass
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
using {declaredNamespace};
class RefClass
{{
Foo.Bar.Baz.MyClass c;
}}
class MyClass
{{
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"class MyClass
{
}
";
var expectedSourceReference =
@"
namespace Foo
{
class RefClass
{
global::MyClass c;
}
class MyClass
{
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_ReferencingTypesDeclaredInOtherDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
private Class2 c2;
private Class3 c3;
private Class4 c4;
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class Class2 {{}}
namespace Bar
{{
class Class3 {{}}
namespace Baz
{{
class Class4 {{}}
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"using Foo;
using Foo.Bar;
using Foo.Bar.Baz;
class Class1
{
private Class2 c2;
private Class3 c3;
private Class4 c4;
}
";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_ChangeUsingsInMultipleContainers()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace NS1
{{
using Foo.Bar.Baz;
class Class2
{{
Class1 c2;
}}
namespace NS2
{{
using Foo.Bar.Baz;
class Class2
{{
Class1 c1;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"class Class1
{
}
";
var expectedSourceReference =
@"
namespace NS1
{
class Class2
{
Class1 c2;
}
namespace NS2
{
class Class2
{
Class1 c1;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithAliasReferencesInOtherDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
class Class2
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
using System;
using Class1Alias = Foo.Bar.Baz.Class1;
namespace Foo
{{
class RefClass
{{
private Class1Alias c1;
void M1()
{{
Bar.Baz.Class2 c2 = null;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"class Class1
{
}
class Class2
{
}
";
var expectedSourceReference =
@"using System;
using Class1Alias = Class1;
namespace Foo
{
class RefClass
{
private Class1Alias c1;
void M1()
{
Class2 c2 = null;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_SingleDocumentNoRef()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
using System;
class [||]Class1
{{
}}
</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"using System;
namespace A.B.C
{
class Class1
{
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_SingleDocumentLocalRef()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
delegate void [||]D1;
interface Class1
{{
void M1();
}}
class Class2 : Class1
{{
D1 d;
void Class1.M1() {{ }}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
delegate void D1;
interface Class1
{
void M1();
}
class Class2 : Class1
{
D1 d;
void Class1.M1() { }
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_WithReferencesInOtherDocument()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
class [||]Class1
{{
}}
class Class2
{{
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class RefClass
{{
private Class1 c1;
void M1()
{{
Class2 c2 = null;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
}
class Class2
{
}
}";
var expectedSourceReference =
@"
using A.B.C;
namespace Foo
{
class RefClass
{
private Class1 c1;
void M1()
{
Class2 c2 = null;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_WithQualifiedReferencesInOtherDocument()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
interface [||]Interface1
{{
void M1(Interface1 c1);
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class RefClass : Interface1
{{
void Interface1.M1(Interface1 c1){{}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
interface Interface1
{
void M1(Interface1 c1);
}
}";
var expectedSourceReference =
@"
using A.B.C;
namespace Foo
{
class RefClass : Interface1
{
void Interface1.M1(Interface1 c1){}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_ReferencingQualifiedTypesDeclaredInOtherDocument()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
class [||]Class1
{{
private A.Class2 c2;
private A.B.Class3 c3;
private A.B.C.Class4 c4;
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace A
{{
class Class2 {{}}
namespace B
{{
class Class3 {{}}
namespace C
{{
class Class4 {{}}
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
private Class2 c2;
private Class3 c3;
private Class4 c4;
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_ChangeUsingsInMultipleContainers()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
class [||]Class1
{{
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace NS1
{{
using System;
class Class2
{{
Class1 c2;
}}
namespace NS2
{{
using System;
class Class2
{{
Class1 c1;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
}
}";
var expectedSourceReference =
@"
namespace NS1
{
using System;
using A.B.C;
class Class2
{
Class1 c2;
}
namespace NS2
{
using System;
class Class2
{
Class1 c1;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_WithAliasReferencesInOtherDocument()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
class [||]Class1
{{
}}
class Class2
{{
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
using Class1Alias = Class1;
namespace Foo
{{
using System;
class RefClass
{{
private Class1Alias c1;
void M1()
{{
Class2 c2 = null;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
}
class Class2
{
}
}";
var expectedSourceReference =
@"
using A.B.C;
using Class1Alias = Class1;
namespace Foo
{
using System;
class RefClass
{
private Class1Alias c1;
void M1()
{
Class2 c2 = null;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithReferencesInVBDocument()
{
var defaultNamespace = "A.B.C";
var declaredNamespace = "A.B.C.D";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
public class Class1
{{
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Imports {declaredNamespace}
Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
public class Class1
{
}
}";
var expectedSourceReference =
@"
Imports A.B.C
Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithQualifiedReferencesInVBDocument()
{
var defaultNamespace = "A.B.C";
var declaredNamespace = "A.B.C.D";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
public class Class1
{{
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Public Class VBClass
Public ReadOnly Property C1 As A.B.C.D.Class1
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
public class Class1
{
}
}";
var expectedSourceReference =
@"Public Class VBClass
Public ReadOnly Property C1 As A.B.C.Class1
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_WithReferencesInVBDocument()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
public class [||]Class1
{{
}}
</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
public class Class1
{
}
}";
var expectedSourceReference =
@"
Imports A.B.C
Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_WithCredReferences()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
/// <summary>
/// See <see cref=""Class1""/>
/// </summary>
class [||]Class1
{{
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
/// <summary>
/// See <see cref=""Class1""/>
/// </summary>
class Bar
{{
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
/// <summary>
/// See <see cref=""Class1""/>
/// </summary>
class Class1
{
}
}";
var expectedSourceReference =
@"
using A.B.C;
namespace Foo
{
/// <summary>
/// See <see cref=""Class1""/>
/// </summary>
class Bar
{
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithReferencesInVBDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
public class Class1
{{
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Imports {declaredNamespace}
Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"public class Class1
{
}
";
var expectedSourceReference =
@"Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithReferenceAndConflictDeclarationInVBDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
public class MyClass
{{
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Namespace Foo
Public Class VBClass
Public ReadOnly Property C1 As Foo.Bar.Baz.MyClass
End Class
Public Class MyClass
End Class
End Namespace</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"public class MyClass
{
}
";
var expectedSourceReference =
@"Namespace Foo
Public Class VBClass
Public ReadOnly Property C1 As Global.MyClass
End Class
Public Class MyClass
End Class
End Namespace";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithCredReferences()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""{declaredNamespace}.Class1""/>
/// </summary>
public class Class1
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
using {declaredNamespace};
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""{declaredNamespace}.Class1""/>
/// </summary>
class RefClass
{{
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""Class1""/>
/// </summary>
public class Class1
{
}
";
var expectedSourceReference =
@"
namespace Foo
{
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""Class1""/>
/// </summary>
class RefClass
{
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(33890, "https://github.com/dotnet/roslyn/issues/33890")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_ExtensionMethodInReducedForm()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{defaultNamespace}
{{
public static class Extensions
{{
public static bool Foo(this Class1 c1) => true;
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace {defaultNamespace}
{{
using System;
public class Class1
{{
public bool Bar(Class1 c1) => c1.Foo();
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
$@"namespace A.B.C
{{
public static class Extensions
{{
public static bool Foo(this Class1 c1) => true;
}}
}}";
var expectedSourceReference =
$@"
namespace {defaultNamespace}
{{
using System;
using A.B.C;
public class Class1
{{
public bool Bar(Class1 c1) => c1.Foo();
}}
}}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(33890, "https://github.com/dotnet/roslyn/issues/33890")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_ExternsionMethodInRegularForm()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]A
{{
public static class Extensions
{{
public static bool Foo(this Class1 c1) => true;
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
using System;
namespace A
{{
public class Class1
{{
public bool Bar(Class1 c1) => Extensions.Foo(c1);
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
$@"namespace A.B.C
{{
public static class Extensions
{{
public static bool Foo(this Class1 c1) => true;
}}
}}";
var expectedSourceReference =
$@"
using System;
using A.B.C;
namespace A
{{
public class Class1
{{
public bool Bar(Class1 c1) => Extensions.Foo(c1);
}}
}}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(33890, "https://github.com/dotnet/roslyn/issues/33890")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_ContainsBothTypeAndExternsionMethod()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]A
{{
public static class Extensions
{{
public static bool Foo(this Class1 c1) => true;
}}
public class Class2
{{ }}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
using System;
namespace A
{{
public class Class1
{{
public bool Bar(Class1 c1, Class2 c2) => c2 == null ? c1.Foo() : true;
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
public static class Extensions
{
public static bool Foo(this Class1 c1) => true;
}
public class Class2
{ }
}";
var expectedSourceReference =
@"
using System;
using A.B.C;
namespace A
{
public class Class1
{
public bool Bar(Class1 c1, Class2 c2) => c2 == null ? c1.Foo() : true;
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(33890, "https://github.com/dotnet/roslyn/issues/33890")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithExtensionMethodReferencesInVBDocument()
{
var defaultNamespace = "A.B.C";
var declaredNamespace = "A.B.C.D";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
using System;
namespace [||]{declaredNamespace}
{{
public static class Extensions
{{
public static bool Foo(this String s) => true;
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Imports {declaredNamespace}
Public Class VBClass
Public Function Foo(s As string) As Boolean
Return s.Foo()
End Function
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
$@"
using System;
namespace {defaultNamespace}
{{
public static class Extensions
{{
public static bool Foo(this string s) => true;
}}
}}";
var expectedSourceReference =
$@"
Imports {defaultNamespace}
Public Class VBClass
Public Function Foo(s As string) As Boolean
Return s.Foo()
End Function
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(37891, "https://github.com/dotnet/roslyn/issues/37891")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithMemberAccessReferencesInOtherDocument()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var documentPath1 = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{documentPath1.folder}"" FilePath=""{documentPath1.filePath}"">
namespace [||]{declaredNamespace}
{{
enum Enum1
{{
A,
B,
C
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class RefClass
{{
Enum1 M1()
{{
return {declaredNamespace}.Enum1.A;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
enum Enum1
{
A,
B,
C
}
}";
var expectedSourceReference =
@"
using A.B.C;
namespace Foo
{
class RefClass
{
Enum1 M1()
{
return Enum1.A;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(37891, "https://github.com/dotnet/roslyn/issues/37891")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithMemberAccessReferencesInOtherDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var documentPath1 = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{documentPath1.folder}"" FilePath=""{documentPath1.filePath}"">
namespace [||]{declaredNamespace}
{{
enum Enum1
{{
A,
B,
C
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class RefClass
{{
Enum1 M1()
{{
return {declaredNamespace}.Enum1.A;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"enum Enum1
{
A,
B,
C
}
";
var expectedSourceReference =
@"namespace Foo
{
class RefClass
{
Enum1 M1()
{
return Enum1.A;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(37891, "https://github.com/dotnet/roslyn/issues/37891")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithMemberAccessReferencesInVBDocument()
{
var defaultNamespace = "A.B.C";
var declaredNamespace = "A.B.C.D";
var documentPath1 = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{documentPath1.folder}"" FilePath=""{documentPath1.filePath}"">
namespace [||]{declaredNamespace}
{{
public enum Enum1
{{
A,
B,
C
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Public Class VBClass
Sub M()
Dim x = A.B.C.D.Enum1.A
End Sub
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
public enum Enum1
{
A,
B,
C
}
}";
var expectedSourceReference =
@"Public Class VBClass
Sub M()
Dim x = A.B.C.Enum1.A
End Sub
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(37891, "https://github.com/dotnet/roslyn/issues/37891")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithMemberAccessReferencesInVBDocument()
{
var defaultNamespace = "";
var declaredNamespace = "A.B.C.D";
var documentPath1 = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{documentPath1.folder}"" FilePath=""{documentPath1.filePath}"">
namespace [||]{declaredNamespace}
{{
public enum Enum1
{{
A,
B,
C
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Public Class VBClass
Sub M()
Dim x = A.B.C.D.Enum1.A
End Sub
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"public enum Enum1
{
A,
B,
C
}
";
var expectedSourceReference =
@"Public Class VBClass
Sub M()
Dim x = Enum1.A
End Sub
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.SyncNamespace
{
public partial class SyncNamespaceTests : CSharpSyncNamespaceTestsBase
{
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_InvalidFolderName1()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar";
// No change namespace action because the folder name is not valid identifier
var (folder, filePath) = CreateDocumentFilePath(new[] { "3B", "C" }, "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestChangeNamespaceAsync(code, expectedSourceOriginal: null);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_InvalidFolderName2()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar";
// No change namespace action because the folder name is not valid identifier
var (folder, filePath) = CreateDocumentFilePath(new[] { "B.3C", "D" }, "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestChangeNamespaceAsync(code, expectedSourceOriginal: null);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_SingleDocumentNoReference()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_SingleDocumentNoReference_FileScopedNamespace()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace};
class Class1
{{
}}
</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C;
class Class1
{
}
";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_SingleDocumentLocalReference()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
delegate void D1;
interface Class1
{{
void M1();
}}
class Class2 : {declaredNamespace}.Class1
{{
{declaredNamespace}.D1 d;
void {declaredNamespace}.Class1.M1(){{}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
delegate void D1;
interface Class1
{
void M1();
}
class Class2 : Class1
{
D1 d;
void Class1.M1() { }
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithCrefReference()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""{declaredNamespace}.Class1""/>
/// See <see cref=""global::{declaredNamespace}.Class1""/>
/// See <see cref=""global::{declaredNamespace}.Class1.M1""/>
/// </summary>
public class Class1
{{
public void M1() {{ }}
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
using {declaredNamespace};
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""{declaredNamespace}.Class1""/>
/// See <see cref=""global::{declaredNamespace}.Class1""/>
/// See <see cref=""global::{declaredNamespace}.Class1.M1""/>
/// </summary>
class RefClass
{{
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""Class1""/>
/// See <see cref=""global::A.B.C.Class1""/>
/// See <see cref=""global::A.B.C.Class1.M1""/>
/// </summary>
public class Class1
{
public void M1() { }
}
}";
var expectedSourceReference =
@"
namespace Foo
{
using A.B.C;
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""A.B.C.Class1""/>
/// See <see cref=""global::A.B.C.Class1""/>
/// See <see cref=""global::A.B.C.Class1.M1""/>
/// </summary>
class RefClass
{
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithCrefReferencesInVB()
{
var defaultNamespace = "A.B.C";
var declaredNamespace = "A.B.C.D";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""{declaredNamespace}.Class1""/>
/// </summary>
public class Class1
{{
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Imports {declaredNamespace}
''' <summary>
''' See <see cref=""Class1""/>
''' See <see cref=""{declaredNamespace}.Class1""/>
''' </summary>
Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""Class1""/>
/// </summary>
public class Class1
{
}
}";
var expectedSourceReference =
@"
Imports A.B.C
''' <summary>
''' See <see cref=""Class1""/>
''' See <see cref=""Class1""/>
''' </summary>
Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_ReferencingTypesDeclaredInOtherDocument()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
private Class2 c2;
private Class3 c3;
private Class4 c4;
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class Class2 {{}}
namespace Bar
{{
class Class3 {{}}
namespace Baz
{{
class Class4 {{}}
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"using Foo;
using Foo.Bar;
using Foo.Bar.Baz;
namespace A.B.C
{
class Class1
{
private Class2 c2;
private Class3 c3;
private Class4 c4;
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_ReferencingQualifiedTypesDeclaredInOtherDocument()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
private Foo.Class2 c2;
private Foo.Bar.Class3 c3;
private Foo.Bar.Baz.Class4 c4;
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class Class2 {{}}
namespace Bar
{{
class Class3 {{}}
namespace Baz
{{
class Class4 {{}}
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"using Foo;
using Foo.Bar;
using Foo.Bar.Baz;
namespace A.B.C
{
class Class1
{
private Class2 c2;
private Class3 c3;
private Class4 c4;
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithReferencesInOtherDocument()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
class Class2
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
using Foo.Bar.Baz;
namespace Foo
{{
class RefClass
{{
private Class1 c1;
void M1()
{{
Bar.Baz.Class2 c2 = null;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
}
class Class2
{
}
}";
var expectedSourceReference =
@"
using A.B.C;
namespace Foo
{
class RefClass
{
private Class1 c1;
void M1()
{
Class2 c2 = null;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithQualifiedReferencesInOtherDocument()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
interface Interface1
{{
void M1(Interface1 c1);
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
using {declaredNamespace};
class RefClass : Interface1
{{
void {declaredNamespace}.Interface1.M1(Interface1 c1){{}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
interface Interface1
{
void M1(Interface1 c1);
}
}";
var expectedSourceReference =
@"
namespace Foo
{
using A.B.C;
class RefClass : Interface1
{
void Interface1.M1(Interface1 c1){}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_ChangeUsingsInMultipleContainers()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace NS1
{{
using Foo.Bar.Baz;
class Class2
{{
Class1 c2;
}}
namespace NS2
{{
using Foo.Bar.Baz;
class Class2
{{
Class1 c1;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
}
}";
var expectedSourceReference =
@"
namespace NS1
{
using A.B.C;
class Class2
{
Class1 c2;
}
namespace NS2
{
class Class2
{
Class1 c1;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithAliasReferencesInOtherDocument()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
class Class2
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
using System;
using Class1Alias = Foo.Bar.Baz.Class1;
namespace Foo
{{
class RefClass
{{
private Class1Alias c1;
void M1()
{{
Bar.Baz.Class2 c2 = null;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
}
class Class2
{
}
}";
var expectedSourceReference =
@"
using System;
using A.B.C;
using Class1Alias = A.B.C.Class1;
namespace Foo
{
class RefClass
{
private Class1Alias c1;
void M1()
{
Class2 c2 = null;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_SingleDocumentNoRef()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
using System;
// Comments before declaration.
namespace [||]{declaredNamespace}
{{ // Comments after opening brace
class Class1
{{
}}
// Comments before closing brace
}} // Comments after declaration.
</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"using System;
// Comments before declaration.
// Comments after opening brace
class Class1
{
}
// Comments before closing brace
// Comments after declaration.
";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_SingleDocumentLocalRef()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
delegate void D1;
interface Class1
{{
void M1();
}}
class Class2 : {declaredNamespace}.Class1
{{
global::{declaredNamespace}.D1 d;
void {declaredNamespace}.Class1.M1() {{ }}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"delegate void D1;
interface Class1
{
void M1();
}
class Class2 : Class1
{
global::D1 d;
void Class1.M1() { }
}
";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithReferencesInOtherDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
class Class2
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
using Foo.Bar.Baz;
namespace Foo
{{
class RefClass
{{
private Class1 c1;
void M1()
{{
Bar.Baz.Class2 c2 = null;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"class Class1
{
}
class Class2
{
}
";
var expectedSourceReference =
@"namespace Foo
{
class RefClass
{
private Class1 c1;
void M1()
{
Class2 c2 = null;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithQualifiedReferencesInOtherDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
interface Interface1
{{
void M1(Interface1 c1);
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
using {declaredNamespace};
class RefClass : Interface1
{{
void {declaredNamespace}.Interface1.M1(Interface1 c1){{}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"interface Interface1
{
void M1(Interface1 c1);
}
";
var expectedSourceReference =
@"
namespace Foo
{
class RefClass : Interface1
{
void Interface1.M1(Interface1 c1){}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithReferenceAndConflictDeclarationInOtherDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class MyClass
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
using {declaredNamespace};
class RefClass
{{
Foo.Bar.Baz.MyClass c;
}}
class MyClass
{{
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"class MyClass
{
}
";
var expectedSourceReference =
@"
namespace Foo
{
class RefClass
{
global::MyClass c;
}
class MyClass
{
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_ReferencingTypesDeclaredInOtherDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
private Class2 c2;
private Class3 c3;
private Class4 c4;
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class Class2 {{}}
namespace Bar
{{
class Class3 {{}}
namespace Baz
{{
class Class4 {{}}
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"using Foo;
using Foo.Bar;
using Foo.Bar.Baz;
class Class1
{
private Class2 c2;
private Class3 c3;
private Class4 c4;
}
";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_ChangeUsingsInMultipleContainers()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace NS1
{{
using Foo.Bar.Baz;
class Class2
{{
Class1 c2;
}}
namespace NS2
{{
using Foo.Bar.Baz;
class Class2
{{
Class1 c1;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"class Class1
{
}
";
var expectedSourceReference =
@"
namespace NS1
{
class Class2
{
Class1 c2;
}
namespace NS2
{
class Class2
{
Class1 c1;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithAliasReferencesInOtherDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
class Class1
{{
}}
class Class2
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
using System;
using Class1Alias = Foo.Bar.Baz.Class1;
namespace Foo
{{
class RefClass
{{
private Class1Alias c1;
void M1()
{{
Bar.Baz.Class2 c2 = null;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"class Class1
{
}
class Class2
{
}
";
var expectedSourceReference =
@"using System;
using Class1Alias = Class1;
namespace Foo
{
class RefClass
{
private Class1Alias c1;
void M1()
{
Class2 c2 = null;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_SingleDocumentNoRef()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
using System;
class [||]Class1
{{
}}
</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"using System;
namespace A.B.C
{
class Class1
{
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_SingleDocumentLocalRef()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
delegate void [||]D1;
interface Class1
{{
void M1();
}}
class Class2 : Class1
{{
D1 d;
void Class1.M1() {{ }}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
delegate void D1;
interface Class1
{
void M1();
}
class Class2 : Class1
{
D1 d;
void Class1.M1() { }
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_WithReferencesInOtherDocument()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
class [||]Class1
{{
}}
class Class2
{{
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class RefClass
{{
private Class1 c1;
void M1()
{{
Class2 c2 = null;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
}
class Class2
{
}
}";
var expectedSourceReference =
@"
using A.B.C;
namespace Foo
{
class RefClass
{
private Class1 c1;
void M1()
{
Class2 c2 = null;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_WithQualifiedReferencesInOtherDocument()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
interface [||]Interface1
{{
void M1(Interface1 c1);
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class RefClass : Interface1
{{
void Interface1.M1(Interface1 c1){{}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
interface Interface1
{
void M1(Interface1 c1);
}
}";
var expectedSourceReference =
@"
using A.B.C;
namespace Foo
{
class RefClass : Interface1
{
void Interface1.M1(Interface1 c1){}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_ReferencingQualifiedTypesDeclaredInOtherDocument()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
class [||]Class1
{{
private A.Class2 c2;
private A.B.Class3 c3;
private A.B.C.Class4 c4;
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace A
{{
class Class2 {{}}
namespace B
{{
class Class3 {{}}
namespace C
{{
class Class4 {{}}
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
private Class2 c2;
private Class3 c3;
private Class4 c4;
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_ChangeUsingsInMultipleContainers()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
class [||]Class1
{{
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace NS1
{{
using System;
class Class2
{{
Class1 c2;
}}
namespace NS2
{{
using System;
class Class2
{{
Class1 c1;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
}
}";
var expectedSourceReference =
@"
namespace NS1
{
using System;
using A.B.C;
class Class2
{
Class1 c2;
}
namespace NS2
{
using System;
class Class2
{
Class1 c1;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_WithAliasReferencesInOtherDocument()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
class [||]Class1
{{
}}
class Class2
{{
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
using Class1Alias = Class1;
namespace Foo
{{
using System;
class RefClass
{{
private Class1Alias c1;
void M1()
{{
Class2 c2 = null;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
class Class1
{
}
class Class2
{
}
}";
var expectedSourceReference =
@"
using A.B.C;
using Class1Alias = Class1;
namespace Foo
{
using System;
class RefClass
{
private Class1Alias c1;
void M1()
{
Class2 c2 = null;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithReferencesInVBDocument()
{
var defaultNamespace = "A.B.C";
var declaredNamespace = "A.B.C.D";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
public class Class1
{{
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Imports {declaredNamespace}
Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
public class Class1
{
}
}";
var expectedSourceReference =
@"
Imports A.B.C
Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithQualifiedReferencesInVBDocument()
{
var defaultNamespace = "A.B.C";
var declaredNamespace = "A.B.C.D";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
public class Class1
{{
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Public Class VBClass
Public ReadOnly Property C1 As A.B.C.D.Class1
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
public class Class1
{
}
}";
var expectedSourceReference =
@"Public Class VBClass
Public ReadOnly Property C1 As A.B.C.Class1
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_WithReferencesInVBDocument()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
public class [||]Class1
{{
}}
</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
public class Class1
{
}
}";
var expectedSourceReference =
@"
Imports A.B.C
Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeFromGlobalNamespace_WithCredReferences()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
/// <summary>
/// See <see cref=""Class1""/>
/// </summary>
class [||]Class1
{{
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
/// <summary>
/// See <see cref=""Class1""/>
/// </summary>
class Bar
{{
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
/// <summary>
/// See <see cref=""Class1""/>
/// </summary>
class Class1
{
}
}";
var expectedSourceReference =
@"
using A.B.C;
namespace Foo
{
/// <summary>
/// See <see cref=""Class1""/>
/// </summary>
class Bar
{
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithReferencesInVBDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
public class Class1
{{
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Imports {declaredNamespace}
Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"public class Class1
{
}
";
var expectedSourceReference =
@"Public Class VBClass
Public ReadOnly Property C1 As Class1
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithReferenceAndConflictDeclarationInVBDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
public class MyClass
{{
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Namespace Foo
Public Class VBClass
Public ReadOnly Property C1 As Foo.Bar.Baz.MyClass
End Class
Public Class MyClass
End Class
End Namespace</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"public class MyClass
{
}
";
var expectedSourceReference =
@"Namespace Foo
Public Class VBClass
Public ReadOnly Property C1 As Global.MyClass
End Class
Public Class MyClass
End Class
End Namespace";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithCredReferences()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{declaredNamespace}
{{
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""{declaredNamespace}.Class1""/>
/// </summary>
public class Class1
{{
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
using {declaredNamespace};
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""{declaredNamespace}.Class1""/>
/// </summary>
class RefClass
{{
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""Class1""/>
/// </summary>
public class Class1
{
}
";
var expectedSourceReference =
@"
namespace Foo
{
/// <summary>
/// See <see cref=""Class1""/>
/// See <see cref=""Class1""/>
/// </summary>
class RefClass
{
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(33890, "https://github.com/dotnet/roslyn/issues/33890")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_ExtensionMethodInReducedForm()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]{defaultNamespace}
{{
public static class Extensions
{{
public static bool Foo(this Class1 c1) => true;
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace {defaultNamespace}
{{
using System;
public class Class1
{{
public bool Bar(Class1 c1) => c1.Foo();
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
$@"namespace A.B.C
{{
public static class Extensions
{{
public static bool Foo(this Class1 c1) => true;
}}
}}";
var expectedSourceReference =
$@"
namespace {defaultNamespace}
{{
using System;
using A.B.C;
public class Class1
{{
public bool Bar(Class1 c1) => c1.Foo();
}}
}}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(33890, "https://github.com/dotnet/roslyn/issues/33890")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_ExternsionMethodInRegularForm()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]A
{{
public static class Extensions
{{
public static bool Foo(this Class1 c1) => true;
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
using System;
namespace A
{{
public class Class1
{{
public bool Bar(Class1 c1) => Extensions.Foo(c1);
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
$@"namespace A.B.C
{{
public static class Extensions
{{
public static bool Foo(this Class1 c1) => true;
}}
}}";
var expectedSourceReference =
$@"
using System;
using A.B.C;
namespace A
{{
public class Class1
{{
public bool Bar(Class1 c1) => Extensions.Foo(c1);
}}
}}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(33890, "https://github.com/dotnet/roslyn/issues/33890")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_ContainsBothTypeAndExternsionMethod()
{
var defaultNamespace = "A";
var (folder, filePath) = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]A
{{
public static class Extensions
{{
public static bool Foo(this Class1 c1) => true;
}}
public class Class2
{{ }}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
using System;
namespace A
{{
public class Class1
{{
public bool Bar(Class1 c1, Class2 c2) => c2 == null ? c1.Foo() : true;
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
public static class Extensions
{
public static bool Foo(this Class1 c1) => true;
}
public class Class2
{ }
}";
var expectedSourceReference =
@"
using System;
using A.B.C;
namespace A
{
public class Class1
{
public bool Bar(Class1 c1, Class2 c2) => c2 == null ? c1.Foo() : true;
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(33890, "https://github.com/dotnet/roslyn/issues/33890")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithExtensionMethodReferencesInVBDocument()
{
var defaultNamespace = "A.B.C";
var declaredNamespace = "A.B.C.D";
var (folder, filePath) = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
using System;
namespace [||]{declaredNamespace}
{{
public static class Extensions
{{
public static bool Foo(this String s) => true;
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Imports {declaredNamespace}
Public Class VBClass
Public Function Foo(s As string) As Boolean
Return s.Foo()
End Function
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
$@"
using System;
namespace {defaultNamespace}
{{
public static class Extensions
{{
public static bool Foo(this string s) => true;
}}
}}";
var expectedSourceReference =
$@"
Imports {defaultNamespace}
Public Class VBClass
Public Function Foo(s As string) As Boolean
Return s.Foo()
End Function
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(37891, "https://github.com/dotnet/roslyn/issues/37891")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithMemberAccessReferencesInOtherDocument()
{
var defaultNamespace = "A";
var declaredNamespace = "Foo.Bar.Baz";
var documentPath1 = CreateDocumentFilePath(new[] { "B", "C" }, "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{documentPath1.folder}"" FilePath=""{documentPath1.filePath}"">
namespace [||]{declaredNamespace}
{{
enum Enum1
{{
A,
B,
C
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class RefClass
{{
Enum1 M1()
{{
return {declaredNamespace}.Enum1.A;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
enum Enum1
{
A,
B,
C
}
}";
var expectedSourceReference =
@"
using A.B.C;
namespace Foo
{
class RefClass
{
Enum1 M1()
{
return Enum1.A;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(37891, "https://github.com/dotnet/roslyn/issues/37891")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithMemberAccessReferencesInOtherDocument()
{
var defaultNamespace = "";
var declaredNamespace = "Foo.Bar.Baz";
var documentPath1 = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var documentPath2 = CreateDocumentFilePath(Array.Empty<string>(), "File2.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{documentPath1.folder}"" FilePath=""{documentPath1.filePath}"">
namespace [||]{declaredNamespace}
{{
enum Enum1
{{
A,
B,
C
}}
}}</Document>
<Document Folders=""{documentPath2.folder}"" FilePath=""{documentPath2.filePath}"">
namespace Foo
{{
class RefClass
{{
Enum1 M1()
{{
return {declaredNamespace}.Enum1.A;
}}
}}
}}</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"enum Enum1
{
A,
B,
C
}
";
var expectedSourceReference =
@"namespace Foo
{
class RefClass
{
Enum1 M1()
{
return Enum1.A;
}
}
}";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(37891, "https://github.com/dotnet/roslyn/issues/37891")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeNamespace_WithMemberAccessReferencesInVBDocument()
{
var defaultNamespace = "A.B.C";
var declaredNamespace = "A.B.C.D";
var documentPath1 = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{documentPath1.folder}"" FilePath=""{documentPath1.filePath}"">
namespace [||]{declaredNamespace}
{{
public enum Enum1
{{
A,
B,
C
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Public Class VBClass
Sub M()
Dim x = A.B.C.D.Enum1.A
End Sub
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"namespace A.B.C
{
public enum Enum1
{
A,
B,
C
}
}";
var expectedSourceReference =
@"Public Class VBClass
Sub M()
Dim x = A.B.C.Enum1.A
End Sub
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
[WorkItem(37891, "https://github.com/dotnet/roslyn/issues/37891")]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task ChangeToGlobalNamespace_WithMemberAccessReferencesInVBDocument()
{
var defaultNamespace = "";
var declaredNamespace = "A.B.C.D";
var documentPath1 = CreateDocumentFilePath(Array.Empty<string>(), "File1.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""{defaultNamespace}"" CommonReferences=""true"">
<Document Folders=""{documentPath1.folder}"" FilePath=""{documentPath1.filePath}"">
namespace [||]{declaredNamespace}
{{
public enum Enum1
{{
A,
B,
C
}}
}}</Document>
</Project>
<Project Language=""Visual Basic"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
Public Class VBClass
Sub M()
Dim x = A.B.C.D.Enum1.A
End Sub
End Class</Document>
</Project>
</Workspace>";
var expectedSourceOriginal =
@"public enum Enum1
{
A,
B,
C
}
";
var expectedSourceReference =
@"Public Class VBClass
Sub M()
Dim x = Enum1.A
End Sub
End Class";
await TestChangeNamespaceAsync(code, expectedSourceOriginal, expectedSourceReference);
}
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Features/Core/Portable/Common/GlyphTags.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Tags;
namespace Microsoft.CodeAnalysis
{
internal static class GlyphTags
{
public static ImmutableArray<string> GetTags(Glyph glyph)
=> glyph switch
{
Glyph.Assembly => WellKnownTagArrays.Assembly,
Glyph.BasicFile => WellKnownTagArrays.VisualBasicFile,
Glyph.BasicProject => WellKnownTagArrays.VisualBasicProject,
Glyph.ClassPublic => WellKnownTagArrays.ClassPublic,
Glyph.ClassProtected => WellKnownTagArrays.ClassProtected,
Glyph.ClassPrivate => WellKnownTagArrays.ClassPrivate,
Glyph.ClassInternal => WellKnownTagArrays.ClassInternal,
Glyph.CSharpFile => WellKnownTagArrays.CSharpFile,
Glyph.CSharpProject => WellKnownTagArrays.CSharpProject,
Glyph.ConstantPublic => WellKnownTagArrays.ConstantPublic,
Glyph.ConstantProtected => WellKnownTagArrays.ConstantProtected,
Glyph.ConstantPrivate => WellKnownTagArrays.ConstantPrivate,
Glyph.ConstantInternal => WellKnownTagArrays.ConstantInternal,
Glyph.DelegatePublic => WellKnownTagArrays.DelegatePublic,
Glyph.DelegateProtected => WellKnownTagArrays.DelegateProtected,
Glyph.DelegatePrivate => WellKnownTagArrays.DelegatePrivate,
Glyph.DelegateInternal => WellKnownTagArrays.DelegateInternal,
Glyph.EnumPublic => WellKnownTagArrays.EnumPublic,
Glyph.EnumProtected => WellKnownTagArrays.EnumProtected,
Glyph.EnumPrivate => WellKnownTagArrays.EnumPrivate,
Glyph.EnumInternal => WellKnownTagArrays.EnumInternal,
Glyph.EnumMemberPublic => WellKnownTagArrays.EnumMemberPublic,
Glyph.EnumMemberProtected => WellKnownTagArrays.EnumMemberProtected,
Glyph.EnumMemberPrivate => WellKnownTagArrays.EnumMemberPrivate,
Glyph.EnumMemberInternal => WellKnownTagArrays.EnumMemberInternal,
Glyph.Error => WellKnownTagArrays.Error,
Glyph.EventPublic => WellKnownTagArrays.EventPublic,
Glyph.EventProtected => WellKnownTagArrays.EventProtected,
Glyph.EventPrivate => WellKnownTagArrays.EventPrivate,
Glyph.EventInternal => WellKnownTagArrays.EventInternal,
Glyph.ExtensionMethodPublic => WellKnownTagArrays.ExtensionMethodPublic,
Glyph.ExtensionMethodProtected => WellKnownTagArrays.ExtensionMethodProtected,
Glyph.ExtensionMethodPrivate => WellKnownTagArrays.ExtensionMethodPrivate,
Glyph.ExtensionMethodInternal => WellKnownTagArrays.ExtensionMethodInternal,
Glyph.FieldPublic => WellKnownTagArrays.FieldPublic,
Glyph.FieldProtected => WellKnownTagArrays.FieldProtected,
Glyph.FieldPrivate => WellKnownTagArrays.FieldPrivate,
Glyph.FieldInternal => WellKnownTagArrays.FieldInternal,
Glyph.InterfacePublic => WellKnownTagArrays.InterfacePublic,
Glyph.InterfaceProtected => WellKnownTagArrays.InterfaceProtected,
Glyph.InterfacePrivate => WellKnownTagArrays.InterfacePrivate,
Glyph.InterfaceInternal => WellKnownTagArrays.InterfaceInternal,
Glyph.Intrinsic => WellKnownTagArrays.Intrinsic,
Glyph.Keyword => WellKnownTagArrays.Keyword,
Glyph.Label => WellKnownTagArrays.Label,
Glyph.Local => WellKnownTagArrays.Local,
Glyph.Namespace => WellKnownTagArrays.Namespace,
Glyph.MethodPublic => WellKnownTagArrays.MethodPublic,
Glyph.MethodProtected => WellKnownTagArrays.MethodProtected,
Glyph.MethodPrivate => WellKnownTagArrays.MethodPrivate,
Glyph.MethodInternal => WellKnownTagArrays.MethodInternal,
Glyph.ModulePublic => WellKnownTagArrays.ModulePublic,
Glyph.ModuleProtected => WellKnownTagArrays.ModuleProtected,
Glyph.ModulePrivate => WellKnownTagArrays.ModulePrivate,
Glyph.ModuleInternal => WellKnownTagArrays.ModuleInternal,
Glyph.OpenFolder => WellKnownTagArrays.Folder,
Glyph.Operator => WellKnownTagArrays.Operator,
Glyph.Parameter => WellKnownTagArrays.Parameter,
Glyph.PropertyPublic => WellKnownTagArrays.PropertyPublic,
Glyph.PropertyProtected => WellKnownTagArrays.PropertyProtected,
Glyph.PropertyPrivate => WellKnownTagArrays.PropertyPrivate,
Glyph.PropertyInternal => WellKnownTagArrays.PropertyInternal,
Glyph.RangeVariable => WellKnownTagArrays.RangeVariable,
Glyph.Reference => WellKnownTagArrays.Reference,
Glyph.StructurePublic => WellKnownTagArrays.StructurePublic,
Glyph.StructureProtected => WellKnownTagArrays.StructureProtected,
Glyph.StructurePrivate => WellKnownTagArrays.StructurePrivate,
Glyph.StructureInternal => WellKnownTagArrays.StructureInternal,
Glyph.TypeParameter => WellKnownTagArrays.TypeParameter,
Glyph.Snippet => WellKnownTagArrays.Snippet,
Glyph.CompletionWarning => WellKnownTagArrays.Warning,
Glyph.StatusInformation => WellKnownTagArrays.StatusInformation,
_ => ImmutableArray<string>.Empty,
};
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Tags;
namespace Microsoft.CodeAnalysis
{
internal static class GlyphTags
{
public static ImmutableArray<string> GetTags(Glyph glyph)
=> glyph switch
{
Glyph.Assembly => WellKnownTagArrays.Assembly,
Glyph.BasicFile => WellKnownTagArrays.VisualBasicFile,
Glyph.BasicProject => WellKnownTagArrays.VisualBasicProject,
Glyph.ClassPublic => WellKnownTagArrays.ClassPublic,
Glyph.ClassProtected => WellKnownTagArrays.ClassProtected,
Glyph.ClassPrivate => WellKnownTagArrays.ClassPrivate,
Glyph.ClassInternal => WellKnownTagArrays.ClassInternal,
Glyph.CSharpFile => WellKnownTagArrays.CSharpFile,
Glyph.CSharpProject => WellKnownTagArrays.CSharpProject,
Glyph.ConstantPublic => WellKnownTagArrays.ConstantPublic,
Glyph.ConstantProtected => WellKnownTagArrays.ConstantProtected,
Glyph.ConstantPrivate => WellKnownTagArrays.ConstantPrivate,
Glyph.ConstantInternal => WellKnownTagArrays.ConstantInternal,
Glyph.DelegatePublic => WellKnownTagArrays.DelegatePublic,
Glyph.DelegateProtected => WellKnownTagArrays.DelegateProtected,
Glyph.DelegatePrivate => WellKnownTagArrays.DelegatePrivate,
Glyph.DelegateInternal => WellKnownTagArrays.DelegateInternal,
Glyph.EnumPublic => WellKnownTagArrays.EnumPublic,
Glyph.EnumProtected => WellKnownTagArrays.EnumProtected,
Glyph.EnumPrivate => WellKnownTagArrays.EnumPrivate,
Glyph.EnumInternal => WellKnownTagArrays.EnumInternal,
Glyph.EnumMemberPublic => WellKnownTagArrays.EnumMemberPublic,
Glyph.EnumMemberProtected => WellKnownTagArrays.EnumMemberProtected,
Glyph.EnumMemberPrivate => WellKnownTagArrays.EnumMemberPrivate,
Glyph.EnumMemberInternal => WellKnownTagArrays.EnumMemberInternal,
Glyph.Error => WellKnownTagArrays.Error,
Glyph.EventPublic => WellKnownTagArrays.EventPublic,
Glyph.EventProtected => WellKnownTagArrays.EventProtected,
Glyph.EventPrivate => WellKnownTagArrays.EventPrivate,
Glyph.EventInternal => WellKnownTagArrays.EventInternal,
Glyph.ExtensionMethodPublic => WellKnownTagArrays.ExtensionMethodPublic,
Glyph.ExtensionMethodProtected => WellKnownTagArrays.ExtensionMethodProtected,
Glyph.ExtensionMethodPrivate => WellKnownTagArrays.ExtensionMethodPrivate,
Glyph.ExtensionMethodInternal => WellKnownTagArrays.ExtensionMethodInternal,
Glyph.FieldPublic => WellKnownTagArrays.FieldPublic,
Glyph.FieldProtected => WellKnownTagArrays.FieldProtected,
Glyph.FieldPrivate => WellKnownTagArrays.FieldPrivate,
Glyph.FieldInternal => WellKnownTagArrays.FieldInternal,
Glyph.InterfacePublic => WellKnownTagArrays.InterfacePublic,
Glyph.InterfaceProtected => WellKnownTagArrays.InterfaceProtected,
Glyph.InterfacePrivate => WellKnownTagArrays.InterfacePrivate,
Glyph.InterfaceInternal => WellKnownTagArrays.InterfaceInternal,
Glyph.Intrinsic => WellKnownTagArrays.Intrinsic,
Glyph.Keyword => WellKnownTagArrays.Keyword,
Glyph.Label => WellKnownTagArrays.Label,
Glyph.Local => WellKnownTagArrays.Local,
Glyph.Namespace => WellKnownTagArrays.Namespace,
Glyph.MethodPublic => WellKnownTagArrays.MethodPublic,
Glyph.MethodProtected => WellKnownTagArrays.MethodProtected,
Glyph.MethodPrivate => WellKnownTagArrays.MethodPrivate,
Glyph.MethodInternal => WellKnownTagArrays.MethodInternal,
Glyph.ModulePublic => WellKnownTagArrays.ModulePublic,
Glyph.ModuleProtected => WellKnownTagArrays.ModuleProtected,
Glyph.ModulePrivate => WellKnownTagArrays.ModulePrivate,
Glyph.ModuleInternal => WellKnownTagArrays.ModuleInternal,
Glyph.OpenFolder => WellKnownTagArrays.Folder,
Glyph.Operator => WellKnownTagArrays.Operator,
Glyph.Parameter => WellKnownTagArrays.Parameter,
Glyph.PropertyPublic => WellKnownTagArrays.PropertyPublic,
Glyph.PropertyProtected => WellKnownTagArrays.PropertyProtected,
Glyph.PropertyPrivate => WellKnownTagArrays.PropertyPrivate,
Glyph.PropertyInternal => WellKnownTagArrays.PropertyInternal,
Glyph.RangeVariable => WellKnownTagArrays.RangeVariable,
Glyph.Reference => WellKnownTagArrays.Reference,
Glyph.StructurePublic => WellKnownTagArrays.StructurePublic,
Glyph.StructureProtected => WellKnownTagArrays.StructureProtected,
Glyph.StructurePrivate => WellKnownTagArrays.StructurePrivate,
Glyph.StructureInternal => WellKnownTagArrays.StructureInternal,
Glyph.TypeParameter => WellKnownTagArrays.TypeParameter,
Glyph.Snippet => WellKnownTagArrays.Snippet,
Glyph.CompletionWarning => WellKnownTagArrays.Warning,
Glyph.StatusInformation => WellKnownTagArrays.StatusInformation,
_ => ImmutableArray<string>.Empty,
};
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Compilers/Core/Portable/InternalUtilities/FileNameUtilities.cs | // Licensed to the .NET Foundation under one or more 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;
namespace Roslyn.Utilities
{
/// <summary>
/// Implements a few file name utilities that are needed by the compiler.
/// In general the compiler is not supposed to understand the format of the paths.
/// In rare cases it needs to check if a string is a valid file name or change the extension
/// (embedded resources, netmodules, output name).
/// The APIs are intentionally limited to cover just these rare cases. Do not add more APIs.
/// </summary>
internal static class FileNameUtilities
{
internal const char DirectorySeparatorChar = '\\';
internal const char AltDirectorySeparatorChar = '/';
internal const char VolumeSeparatorChar = ':';
/// <summary>
/// Returns true if the string represents an unqualified file name.
/// The name may contain any characters but directory and volume separators.
/// </summary>
/// <param name="path">Path.</param>
/// <returns>
/// True if <paramref name="path"/> is a simple file name, false if it is null or includes a directory specification.
/// </returns>
internal static bool IsFileName([NotNullWhen(returnValue: true)] string? path)
{
return IndexOfFileName(path) == 0;
}
/// <summary>
/// Returns the offset in <paramref name="path"/> where the dot that starts an extension is, or -1 if the path doesn't have an extension.
/// </summary>
/// <remarks>
/// Returns 0 for path ".goo".
/// Returns -1 for path "goo.".
/// </remarks>
private static int IndexOfExtension(string? path) =>
path is null
? -1
: IndexOfExtension(path.AsSpan());
private static int IndexOfExtension(ReadOnlySpan<char> path)
{
int length = path.Length;
int i = length;
while (--i >= 0)
{
char c = path[i];
if (c == '.')
{
if (i != length - 1)
{
return i;
}
return -1;
}
if (c == DirectorySeparatorChar || c == AltDirectorySeparatorChar || c == VolumeSeparatorChar)
{
break;
}
}
return -1;
}
/// <summary>
/// Returns an extension of the specified path string.
/// </summary>
/// <remarks>
/// The same functionality as <see cref="System.IO.Path.GetExtension(string)"/> but doesn't throw an exception
/// if there are invalid characters in the path.
/// </remarks>
[return: NotNullIfNotNull(parameterName: "path")]
internal static string? GetExtension(string? path)
{
if (path == null)
{
return null;
}
int index = IndexOfExtension(path);
return (index >= 0) ? path.Substring(index) : string.Empty;
}
internal static ReadOnlyMemory<char> GetExtension(ReadOnlyMemory<char> path)
{
int index = IndexOfExtension(path.Span);
return (index >= 0) ? path.Slice(index) : default;
}
/// <summary>
/// Removes extension from path.
/// </summary>
/// <remarks>
/// Returns "goo" for path "goo.".
/// Returns "goo.." for path "goo...".
/// </remarks>
[return: NotNullIfNotNull(parameterName: "path")]
private static string? RemoveExtension(string? path)
{
if (path == null)
{
return null;
}
int index = IndexOfExtension(path);
if (index >= 0)
{
return path.Substring(0, index);
}
// trim last ".", if present
if (path.Length > 0 && path[path.Length - 1] == '.')
{
return path.Substring(0, path.Length - 1);
}
return path;
}
/// <summary>
/// Returns path with the extension changed to <paramref name="extension"/>.
/// </summary>
/// <returns>
/// Equivalent of <see cref="System.IO.Path.ChangeExtension(string, string)"/>
///
/// If <paramref name="path"/> is null, returns null.
/// If path does not end with an extension, the new extension is appended to the path.
/// If extension is null, equivalent to <see cref="RemoveExtension"/>.
/// </returns>
[return: NotNullIfNotNull(parameterName: "path")]
internal static string? ChangeExtension(string? path, string? extension)
{
if (path == null)
{
return null;
}
var pathWithoutExtension = RemoveExtension(path);
if (extension == null || path.Length == 0)
{
return pathWithoutExtension;
}
if (extension.Length == 0 || extension[0] != '.')
{
return pathWithoutExtension + "." + extension;
}
return pathWithoutExtension + extension;
}
/// <summary>
/// Returns the position in given path where the file name starts.
/// </summary>
/// <returns>-1 if path is null.</returns>
internal static int IndexOfFileName(string? path)
{
if (path == null)
{
return -1;
}
for (int i = path.Length - 1; i >= 0; i--)
{
char ch = path[i];
if (ch == DirectorySeparatorChar || ch == AltDirectorySeparatorChar || ch == VolumeSeparatorChar)
{
return i + 1;
}
}
return 0;
}
/// <summary>
/// Get file name from path.
/// </summary>
/// <remarks>Unlike <see cref="System.IO.Path.GetFileName(string)"/> doesn't check for invalid path characters.</remarks>
[return: NotNullIfNotNull(parameterName: "path")]
internal static string? GetFileName(string? path, bool includeExtension = true)
{
int fileNameStart = IndexOfFileName(path);
var fileName = (fileNameStart <= 0) ? path : path!.Substring(fileNameStart);
return includeExtension ? fileName : RemoveExtension(fileName);
}
}
}
| // Licensed to the .NET Foundation under one or more 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;
namespace Roslyn.Utilities
{
/// <summary>
/// Implements a few file name utilities that are needed by the compiler.
/// In general the compiler is not supposed to understand the format of the paths.
/// In rare cases it needs to check if a string is a valid file name or change the extension
/// (embedded resources, netmodules, output name).
/// The APIs are intentionally limited to cover just these rare cases. Do not add more APIs.
/// </summary>
internal static class FileNameUtilities
{
internal const char DirectorySeparatorChar = '\\';
internal const char AltDirectorySeparatorChar = '/';
internal const char VolumeSeparatorChar = ':';
/// <summary>
/// Returns true if the string represents an unqualified file name.
/// The name may contain any characters but directory and volume separators.
/// </summary>
/// <param name="path">Path.</param>
/// <returns>
/// True if <paramref name="path"/> is a simple file name, false if it is null or includes a directory specification.
/// </returns>
internal static bool IsFileName([NotNullWhen(returnValue: true)] string? path)
{
return IndexOfFileName(path) == 0;
}
/// <summary>
/// Returns the offset in <paramref name="path"/> where the dot that starts an extension is, or -1 if the path doesn't have an extension.
/// </summary>
/// <remarks>
/// Returns 0 for path ".goo".
/// Returns -1 for path "goo.".
/// </remarks>
private static int IndexOfExtension(string? path) =>
path is null
? -1
: IndexOfExtension(path.AsSpan());
private static int IndexOfExtension(ReadOnlySpan<char> path)
{
int length = path.Length;
int i = length;
while (--i >= 0)
{
char c = path[i];
if (c == '.')
{
if (i != length - 1)
{
return i;
}
return -1;
}
if (c == DirectorySeparatorChar || c == AltDirectorySeparatorChar || c == VolumeSeparatorChar)
{
break;
}
}
return -1;
}
/// <summary>
/// Returns an extension of the specified path string.
/// </summary>
/// <remarks>
/// The same functionality as <see cref="System.IO.Path.GetExtension(string)"/> but doesn't throw an exception
/// if there are invalid characters in the path.
/// </remarks>
[return: NotNullIfNotNull(parameterName: "path")]
internal static string? GetExtension(string? path)
{
if (path == null)
{
return null;
}
int index = IndexOfExtension(path);
return (index >= 0) ? path.Substring(index) : string.Empty;
}
internal static ReadOnlyMemory<char> GetExtension(ReadOnlyMemory<char> path)
{
int index = IndexOfExtension(path.Span);
return (index >= 0) ? path.Slice(index) : default;
}
/// <summary>
/// Removes extension from path.
/// </summary>
/// <remarks>
/// Returns "goo" for path "goo.".
/// Returns "goo.." for path "goo...".
/// </remarks>
[return: NotNullIfNotNull(parameterName: "path")]
private static string? RemoveExtension(string? path)
{
if (path == null)
{
return null;
}
int index = IndexOfExtension(path);
if (index >= 0)
{
return path.Substring(0, index);
}
// trim last ".", if present
if (path.Length > 0 && path[path.Length - 1] == '.')
{
return path.Substring(0, path.Length - 1);
}
return path;
}
/// <summary>
/// Returns path with the extension changed to <paramref name="extension"/>.
/// </summary>
/// <returns>
/// Equivalent of <see cref="System.IO.Path.ChangeExtension(string, string)"/>
///
/// If <paramref name="path"/> is null, returns null.
/// If path does not end with an extension, the new extension is appended to the path.
/// If extension is null, equivalent to <see cref="RemoveExtension"/>.
/// </returns>
[return: NotNullIfNotNull(parameterName: "path")]
internal static string? ChangeExtension(string? path, string? extension)
{
if (path == null)
{
return null;
}
var pathWithoutExtension = RemoveExtension(path);
if (extension == null || path.Length == 0)
{
return pathWithoutExtension;
}
if (extension.Length == 0 || extension[0] != '.')
{
return pathWithoutExtension + "." + extension;
}
return pathWithoutExtension + extension;
}
/// <summary>
/// Returns the position in given path where the file name starts.
/// </summary>
/// <returns>-1 if path is null.</returns>
internal static int IndexOfFileName(string? path)
{
if (path == null)
{
return -1;
}
for (int i = path.Length - 1; i >= 0; i--)
{
char ch = path[i];
if (ch == DirectorySeparatorChar || ch == AltDirectorySeparatorChar || ch == VolumeSeparatorChar)
{
return i + 1;
}
}
return 0;
}
/// <summary>
/// Get file name from path.
/// </summary>
/// <remarks>Unlike <see cref="System.IO.Path.GetFileName(string)"/> doesn't check for invalid path characters.</remarks>
[return: NotNullIfNotNull(parameterName: "path")]
internal static string? GetFileName(string? path, bool includeExtension = true)
{
int fileNameStart = IndexOfFileName(path);
var fileName = (fileNameStart <= 0) ? path : path!.Substring(fileNameStart);
return includeExtension ? fileName : RemoveExtension(fileName);
}
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Features/LanguageServer/Protocol/Handler/SemanticTokens/SemanticTokensHelpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens
{
internal class SemanticTokensHelpers
{
internal static readonly string[] RoslynCustomTokenTypes =
{
ClassificationTypeNames.ClassName,
ClassificationTypeNames.ConstantName,
ClassificationTypeNames.ControlKeyword,
ClassificationTypeNames.DelegateName,
ClassificationTypeNames.EnumMemberName,
ClassificationTypeNames.EnumName,
ClassificationTypeNames.EventName,
ClassificationTypeNames.ExcludedCode,
ClassificationTypeNames.ExtensionMethodName,
ClassificationTypeNames.FieldName,
ClassificationTypeNames.InterfaceName,
ClassificationTypeNames.LabelName,
ClassificationTypeNames.LocalName,
ClassificationTypeNames.MethodName,
ClassificationTypeNames.ModuleName,
ClassificationTypeNames.NamespaceName,
ClassificationTypeNames.OperatorOverloaded,
ClassificationTypeNames.ParameterName,
ClassificationTypeNames.PropertyName,
// Preprocessor
ClassificationTypeNames.PreprocessorKeyword,
ClassificationTypeNames.PreprocessorText,
ClassificationTypeNames.Punctuation,
ClassificationTypeNames.RecordClassName,
ClassificationTypeNames.RecordStructName,
// Regex
ClassificationTypeNames.RegexAlternation,
ClassificationTypeNames.RegexAnchor,
ClassificationTypeNames.RegexCharacterClass,
ClassificationTypeNames.RegexComment,
ClassificationTypeNames.RegexGrouping,
ClassificationTypeNames.RegexOtherEscape,
ClassificationTypeNames.RegexQuantifier,
ClassificationTypeNames.RegexSelfEscapedCharacter,
ClassificationTypeNames.RegexText,
ClassificationTypeNames.StringEscapeCharacter,
ClassificationTypeNames.StructName,
ClassificationTypeNames.Text,
ClassificationTypeNames.TypeParameterName,
ClassificationTypeNames.VerbatimStringLiteral,
ClassificationTypeNames.WhiteSpace,
// XML
ClassificationTypeNames.XmlDocCommentAttributeName,
ClassificationTypeNames.XmlDocCommentAttributeQuotes,
ClassificationTypeNames.XmlDocCommentAttributeValue,
ClassificationTypeNames.XmlDocCommentCDataSection,
ClassificationTypeNames.XmlDocCommentComment,
ClassificationTypeNames.XmlDocCommentDelimiter,
ClassificationTypeNames.XmlDocCommentEntityReference,
ClassificationTypeNames.XmlDocCommentName,
ClassificationTypeNames.XmlDocCommentProcessingInstruction,
ClassificationTypeNames.XmlDocCommentText,
ClassificationTypeNames.XmlLiteralAttributeName,
ClassificationTypeNames.XmlLiteralAttributeQuotes,
ClassificationTypeNames.XmlLiteralAttributeValue,
ClassificationTypeNames.XmlLiteralCDataSection,
ClassificationTypeNames.XmlLiteralComment,
ClassificationTypeNames.XmlLiteralDelimiter,
ClassificationTypeNames.XmlLiteralEmbeddedExpression,
ClassificationTypeNames.XmlLiteralEntityReference,
ClassificationTypeNames.XmlLiteralName,
ClassificationTypeNames.XmlLiteralProcessingInstruction,
ClassificationTypeNames.XmlLiteralText
};
// TO-DO: Expand this mapping once support for custom token types is added:
// https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1085998
private static readonly Dictionary<string, string> s_classificationTypeToSemanticTokenTypeMap =
new Dictionary<string, string>
{
[ClassificationTypeNames.Comment] = LSP.SemanticTokenTypes.Comment,
[ClassificationTypeNames.Identifier] = LSP.SemanticTokenTypes.Variable,
[ClassificationTypeNames.Keyword] = LSP.SemanticTokenTypes.Keyword,
[ClassificationTypeNames.NumericLiteral] = LSP.SemanticTokenTypes.Number,
[ClassificationTypeNames.Operator] = LSP.SemanticTokenTypes.Operator,
[ClassificationTypeNames.StringLiteral] = LSP.SemanticTokenTypes.String,
};
/// <summary>
/// Returns the semantic tokens data for a given document with an optional range.
/// </summary>
internal static async Task<int[]> ComputeSemanticTokensDataAsync(
Document document,
Dictionary<string, int> tokenTypesToIndex,
LSP.Range? range,
CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
// By default we calculate the tokens for the full document span, although the user
// can pass in a range if they wish.
var textSpan = range == null ? root.FullSpan : ProtocolConversions.RangeToTextSpan(range, text);
var classifiedSpans = await Classifier.GetClassifiedSpansAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
Contract.ThrowIfNull(classifiedSpans, "classifiedSpans is null");
// Multi-line tokens are not supported by VS (tracked by https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1265495).
// Roslyn's classifier however can return multi-line classified spans, so we must break these up into single-line spans.
var updatedClassifiedSpans = ConvertMultiLineToSingleLineSpans(text, classifiedSpans.ToArray());
// TO-DO: We should implement support for streaming if LSP adds support for it:
// https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1276300
return ComputeTokens(text.Lines, updatedClassifiedSpans, tokenTypesToIndex);
}
private static ClassifiedSpan[] ConvertMultiLineToSingleLineSpans(SourceText text, ClassifiedSpan[] classifiedSpans)
{
using var _ = ArrayBuilder<ClassifiedSpan>.GetInstance(out var updatedClassifiedSpans);
for (var spanIndex = 0; spanIndex < classifiedSpans.Length; spanIndex++)
{
var span = classifiedSpans[spanIndex];
text.GetLinesAndOffsets(span.TextSpan, out var startLine, out var startOffset, out var endLine, out var endOffSet);
// If the start and end of the classified span are not on the same line, we're dealing with a multi-line span.
// Since VS doesn't support multi-line spans/tokens, we need to break the span up into single-line spans.
if (startLine != endLine)
{
spanIndex = ConvertToSingleLineSpan(
text, classifiedSpans, updatedClassifiedSpans, spanIndex, span.ClassificationType,
startLine, startOffset, endLine, endOffSet);
}
else
{
// This is already a single-line span, so no modification is necessary.
updatedClassifiedSpans.Add(span);
}
}
return updatedClassifiedSpans.ToArray();
static int ConvertToSingleLineSpan(
SourceText text,
ClassifiedSpan[] originalClassifiedSpans,
ArrayBuilder<ClassifiedSpan> updatedClassifiedSpans,
int spanIndex,
string classificationType,
int startLine,
int startOffset,
int endLine,
int endOffSet)
{
var numLinesInSpan = endLine - startLine + 1;
Contract.ThrowIfTrue(numLinesInSpan < 1);
var updatedSpanIndex = spanIndex;
for (var currentLine = 0; currentLine < numLinesInSpan; currentLine++)
{
TextSpan? textSpan;
// Case 1: First line of span
if (currentLine == 0)
{
var absoluteStartOffset = text.Lines[startLine].Start + startOffset;
var spanLength = text.Lines[startLine].End - absoluteStartOffset;
textSpan = new TextSpan(absoluteStartOffset, spanLength);
}
// Case 2: Any of the span's middle lines
else if (currentLine != numLinesInSpan - 1)
{
textSpan = text.Lines[startLine + currentLine].Span;
}
// Case 3: Last line of span
else
{
textSpan = new TextSpan(text.Lines[endLine].Start, endOffSet);
}
var updatedClassifiedSpan = new ClassifiedSpan(textSpan.Value, classificationType);
updatedClassifiedSpans.Add(updatedClassifiedSpan);
// Since spans are expected to be ordered, when breaking up a multi-line span, we may have to insert
// other spans in-between. For example, we may encounter this case when breaking up a multi-line verbatim
// string literal containing escape characters:
// var x = @"one ""
// two";
// The check below ensures we correctly return the spans in the correct order, i.e. 'one', '""', 'two'.
while (updatedSpanIndex + 1 < originalClassifiedSpans.Length &&
textSpan.Value.Contains(originalClassifiedSpans[updatedSpanIndex + 1].TextSpan))
{
updatedClassifiedSpans.Add(originalClassifiedSpans[updatedSpanIndex + 1]);
updatedSpanIndex++;
}
}
return updatedSpanIndex;
}
}
private static int[] ComputeTokens(
TextLineCollection lines,
ClassifiedSpan[] classifiedSpans,
Dictionary<string, int> tokenTypesToIndex)
{
using var _ = ArrayBuilder<int>.GetInstance(classifiedSpans.Length, out var data);
// We keep track of the last line number and last start character since tokens are
// reported relative to each other.
var lastLineNumber = 0;
var lastStartCharacter = 0;
for (var currentClassifiedSpanIndex = 0; currentClassifiedSpanIndex < classifiedSpans.Length; currentClassifiedSpanIndex++)
{
currentClassifiedSpanIndex = ComputeNextToken(
lines, ref lastLineNumber, ref lastStartCharacter, classifiedSpans,
currentClassifiedSpanIndex, tokenTypesToIndex,
out var deltaLine, out var startCharacterDelta, out var tokenLength,
out var tokenType, out var tokenModifiers);
data.AddRange(deltaLine, startCharacterDelta, tokenLength, tokenType, tokenModifiers);
}
return data.ToArray();
}
private static int ComputeNextToken(
TextLineCollection lines,
ref int lastLineNumber,
ref int lastStartCharacter,
ClassifiedSpan[] classifiedSpans,
int currentClassifiedSpanIndex,
Dictionary<string, int> tokenTypesToIndex,
out int deltaLineOut,
out int startCharacterDeltaOut,
out int tokenLengthOut,
out int tokenTypeOut,
out int tokenModifiersOut)
{
// Each semantic token is represented in LSP by five numbers:
// 1. Token line number delta, relative to the previous token
// 2. Token start character delta, relative to the previous token
// 3. Token length
// 4. Token type (index) - looked up in SemanticTokensLegend.tokenTypes
// 5. Token modifiers - each set bit will be looked up in SemanticTokensLegend.tokenModifiers
var classifiedSpan = classifiedSpans[currentClassifiedSpanIndex];
var originalTextSpan = classifiedSpan.TextSpan;
var linePosition = lines.GetLinePositionSpan(originalTextSpan).Start;
var lineNumber = linePosition.Line;
// 1. Token line number delta, relative to the previous token
var deltaLine = lineNumber - lastLineNumber;
Contract.ThrowIfTrue(deltaLine < 0, $"deltaLine is less than 0: {deltaLine}");
// 2. Token start character delta, relative to the previous token
// (Relative to 0 or the previous token’s start if they're on the same line)
var deltaStartCharacter = linePosition.Character;
if (lastLineNumber == lineNumber)
{
deltaStartCharacter -= lastStartCharacter;
}
lastLineNumber = lineNumber;
lastStartCharacter = linePosition.Character;
// 3. Token length
var tokenLength = originalTextSpan.Length;
// We currently only have one modifier (static). The logic below will need to change in the future if other
// modifiers are added in the future.
var modifierBits = TokenModifiers.None;
var tokenTypeIndex = 0;
// Classified spans with the same text span should be combined into one token.
while (classifiedSpans[currentClassifiedSpanIndex].TextSpan == originalTextSpan)
{
var classificationType = classifiedSpans[currentClassifiedSpanIndex].ClassificationType;
if (classificationType == ClassificationTypeNames.StaticSymbol)
{
// 4. Token modifiers - each set bit will be looked up in SemanticTokensLegend.tokenModifiers
modifierBits = TokenModifiers.Static;
}
else if (classificationType == ClassificationTypeNames.ReassignedVariable)
{
// 5. Token modifiers - each set bit will be looked up in SemanticTokensLegend.tokenModifiers
modifierBits = TokenModifiers.ReassignedVariable;
}
else
{
// 6. Token type - looked up in SemanticTokensLegend.tokenTypes (language server defined mapping
// from integer to LSP token types).
tokenTypeIndex = GetTokenTypeIndex(classificationType, tokenTypesToIndex);
}
// Break out of the loop if we have no more classified spans left, or if the next classified span has
// a different text span than our current text span.
if (currentClassifiedSpanIndex + 1 >= classifiedSpans.Length || classifiedSpans[currentClassifiedSpanIndex + 1].TextSpan != originalTextSpan)
{
break;
}
currentClassifiedSpanIndex++;
}
deltaLineOut = deltaLine;
startCharacterDeltaOut = deltaStartCharacter;
tokenLengthOut = tokenLength;
tokenTypeOut = tokenTypeIndex;
tokenModifiersOut = (int)modifierBits;
return currentClassifiedSpanIndex;
}
private static int GetTokenTypeIndex(string classificationType, Dictionary<string, int> tokenTypesToIndex)
{
if (!s_classificationTypeToSemanticTokenTypeMap.TryGetValue(classificationType, out var tokenTypeStr))
{
tokenTypeStr = classificationType;
}
Contract.ThrowIfFalse(tokenTypesToIndex.TryGetValue(tokenTypeStr, out var tokenTypeIndex), "No matching token type index found.");
return tokenTypeIndex;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens
{
internal class SemanticTokensHelpers
{
internal static readonly string[] RoslynCustomTokenTypes =
{
ClassificationTypeNames.ClassName,
ClassificationTypeNames.ConstantName,
ClassificationTypeNames.ControlKeyword,
ClassificationTypeNames.DelegateName,
ClassificationTypeNames.EnumMemberName,
ClassificationTypeNames.EnumName,
ClassificationTypeNames.EventName,
ClassificationTypeNames.ExcludedCode,
ClassificationTypeNames.ExtensionMethodName,
ClassificationTypeNames.FieldName,
ClassificationTypeNames.InterfaceName,
ClassificationTypeNames.LabelName,
ClassificationTypeNames.LocalName,
ClassificationTypeNames.MethodName,
ClassificationTypeNames.ModuleName,
ClassificationTypeNames.NamespaceName,
ClassificationTypeNames.OperatorOverloaded,
ClassificationTypeNames.ParameterName,
ClassificationTypeNames.PropertyName,
// Preprocessor
ClassificationTypeNames.PreprocessorKeyword,
ClassificationTypeNames.PreprocessorText,
ClassificationTypeNames.Punctuation,
ClassificationTypeNames.RecordClassName,
ClassificationTypeNames.RecordStructName,
// Regex
ClassificationTypeNames.RegexAlternation,
ClassificationTypeNames.RegexAnchor,
ClassificationTypeNames.RegexCharacterClass,
ClassificationTypeNames.RegexComment,
ClassificationTypeNames.RegexGrouping,
ClassificationTypeNames.RegexOtherEscape,
ClassificationTypeNames.RegexQuantifier,
ClassificationTypeNames.RegexSelfEscapedCharacter,
ClassificationTypeNames.RegexText,
ClassificationTypeNames.StringEscapeCharacter,
ClassificationTypeNames.StructName,
ClassificationTypeNames.Text,
ClassificationTypeNames.TypeParameterName,
ClassificationTypeNames.VerbatimStringLiteral,
ClassificationTypeNames.WhiteSpace,
// XML
ClassificationTypeNames.XmlDocCommentAttributeName,
ClassificationTypeNames.XmlDocCommentAttributeQuotes,
ClassificationTypeNames.XmlDocCommentAttributeValue,
ClassificationTypeNames.XmlDocCommentCDataSection,
ClassificationTypeNames.XmlDocCommentComment,
ClassificationTypeNames.XmlDocCommentDelimiter,
ClassificationTypeNames.XmlDocCommentEntityReference,
ClassificationTypeNames.XmlDocCommentName,
ClassificationTypeNames.XmlDocCommentProcessingInstruction,
ClassificationTypeNames.XmlDocCommentText,
ClassificationTypeNames.XmlLiteralAttributeName,
ClassificationTypeNames.XmlLiteralAttributeQuotes,
ClassificationTypeNames.XmlLiteralAttributeValue,
ClassificationTypeNames.XmlLiteralCDataSection,
ClassificationTypeNames.XmlLiteralComment,
ClassificationTypeNames.XmlLiteralDelimiter,
ClassificationTypeNames.XmlLiteralEmbeddedExpression,
ClassificationTypeNames.XmlLiteralEntityReference,
ClassificationTypeNames.XmlLiteralName,
ClassificationTypeNames.XmlLiteralProcessingInstruction,
ClassificationTypeNames.XmlLiteralText
};
// TO-DO: Expand this mapping once support for custom token types is added:
// https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1085998
private static readonly Dictionary<string, string> s_classificationTypeToSemanticTokenTypeMap =
new Dictionary<string, string>
{
[ClassificationTypeNames.Comment] = LSP.SemanticTokenTypes.Comment,
[ClassificationTypeNames.Identifier] = LSP.SemanticTokenTypes.Variable,
[ClassificationTypeNames.Keyword] = LSP.SemanticTokenTypes.Keyword,
[ClassificationTypeNames.NumericLiteral] = LSP.SemanticTokenTypes.Number,
[ClassificationTypeNames.Operator] = LSP.SemanticTokenTypes.Operator,
[ClassificationTypeNames.StringLiteral] = LSP.SemanticTokenTypes.String,
};
/// <summary>
/// Returns the semantic tokens data for a given document with an optional range.
/// </summary>
internal static async Task<int[]> ComputeSemanticTokensDataAsync(
Document document,
Dictionary<string, int> tokenTypesToIndex,
LSP.Range? range,
CancellationToken cancellationToken)
{
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
// By default we calculate the tokens for the full document span, although the user
// can pass in a range if they wish.
var textSpan = range == null ? root.FullSpan : ProtocolConversions.RangeToTextSpan(range, text);
var classifiedSpans = await Classifier.GetClassifiedSpansAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
Contract.ThrowIfNull(classifiedSpans, "classifiedSpans is null");
// Multi-line tokens are not supported by VS (tracked by https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1265495).
// Roslyn's classifier however can return multi-line classified spans, so we must break these up into single-line spans.
var updatedClassifiedSpans = ConvertMultiLineToSingleLineSpans(text, classifiedSpans.ToArray());
// TO-DO: We should implement support for streaming if LSP adds support for it:
// https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1276300
return ComputeTokens(text.Lines, updatedClassifiedSpans, tokenTypesToIndex);
}
private static ClassifiedSpan[] ConvertMultiLineToSingleLineSpans(SourceText text, ClassifiedSpan[] classifiedSpans)
{
using var _ = ArrayBuilder<ClassifiedSpan>.GetInstance(out var updatedClassifiedSpans);
for (var spanIndex = 0; spanIndex < classifiedSpans.Length; spanIndex++)
{
var span = classifiedSpans[spanIndex];
text.GetLinesAndOffsets(span.TextSpan, out var startLine, out var startOffset, out var endLine, out var endOffSet);
// If the start and end of the classified span are not on the same line, we're dealing with a multi-line span.
// Since VS doesn't support multi-line spans/tokens, we need to break the span up into single-line spans.
if (startLine != endLine)
{
spanIndex = ConvertToSingleLineSpan(
text, classifiedSpans, updatedClassifiedSpans, spanIndex, span.ClassificationType,
startLine, startOffset, endLine, endOffSet);
}
else
{
// This is already a single-line span, so no modification is necessary.
updatedClassifiedSpans.Add(span);
}
}
return updatedClassifiedSpans.ToArray();
static int ConvertToSingleLineSpan(
SourceText text,
ClassifiedSpan[] originalClassifiedSpans,
ArrayBuilder<ClassifiedSpan> updatedClassifiedSpans,
int spanIndex,
string classificationType,
int startLine,
int startOffset,
int endLine,
int endOffSet)
{
var numLinesInSpan = endLine - startLine + 1;
Contract.ThrowIfTrue(numLinesInSpan < 1);
var updatedSpanIndex = spanIndex;
for (var currentLine = 0; currentLine < numLinesInSpan; currentLine++)
{
TextSpan? textSpan;
// Case 1: First line of span
if (currentLine == 0)
{
var absoluteStartOffset = text.Lines[startLine].Start + startOffset;
var spanLength = text.Lines[startLine].End - absoluteStartOffset;
textSpan = new TextSpan(absoluteStartOffset, spanLength);
}
// Case 2: Any of the span's middle lines
else if (currentLine != numLinesInSpan - 1)
{
textSpan = text.Lines[startLine + currentLine].Span;
}
// Case 3: Last line of span
else
{
textSpan = new TextSpan(text.Lines[endLine].Start, endOffSet);
}
var updatedClassifiedSpan = new ClassifiedSpan(textSpan.Value, classificationType);
updatedClassifiedSpans.Add(updatedClassifiedSpan);
// Since spans are expected to be ordered, when breaking up a multi-line span, we may have to insert
// other spans in-between. For example, we may encounter this case when breaking up a multi-line verbatim
// string literal containing escape characters:
// var x = @"one ""
// two";
// The check below ensures we correctly return the spans in the correct order, i.e. 'one', '""', 'two'.
while (updatedSpanIndex + 1 < originalClassifiedSpans.Length &&
textSpan.Value.Contains(originalClassifiedSpans[updatedSpanIndex + 1].TextSpan))
{
updatedClassifiedSpans.Add(originalClassifiedSpans[updatedSpanIndex + 1]);
updatedSpanIndex++;
}
}
return updatedSpanIndex;
}
}
private static int[] ComputeTokens(
TextLineCollection lines,
ClassifiedSpan[] classifiedSpans,
Dictionary<string, int> tokenTypesToIndex)
{
using var _ = ArrayBuilder<int>.GetInstance(classifiedSpans.Length, out var data);
// We keep track of the last line number and last start character since tokens are
// reported relative to each other.
var lastLineNumber = 0;
var lastStartCharacter = 0;
for (var currentClassifiedSpanIndex = 0; currentClassifiedSpanIndex < classifiedSpans.Length; currentClassifiedSpanIndex++)
{
currentClassifiedSpanIndex = ComputeNextToken(
lines, ref lastLineNumber, ref lastStartCharacter, classifiedSpans,
currentClassifiedSpanIndex, tokenTypesToIndex,
out var deltaLine, out var startCharacterDelta, out var tokenLength,
out var tokenType, out var tokenModifiers);
data.AddRange(deltaLine, startCharacterDelta, tokenLength, tokenType, tokenModifiers);
}
return data.ToArray();
}
private static int ComputeNextToken(
TextLineCollection lines,
ref int lastLineNumber,
ref int lastStartCharacter,
ClassifiedSpan[] classifiedSpans,
int currentClassifiedSpanIndex,
Dictionary<string, int> tokenTypesToIndex,
out int deltaLineOut,
out int startCharacterDeltaOut,
out int tokenLengthOut,
out int tokenTypeOut,
out int tokenModifiersOut)
{
// Each semantic token is represented in LSP by five numbers:
// 1. Token line number delta, relative to the previous token
// 2. Token start character delta, relative to the previous token
// 3. Token length
// 4. Token type (index) - looked up in SemanticTokensLegend.tokenTypes
// 5. Token modifiers - each set bit will be looked up in SemanticTokensLegend.tokenModifiers
var classifiedSpan = classifiedSpans[currentClassifiedSpanIndex];
var originalTextSpan = classifiedSpan.TextSpan;
var linePosition = lines.GetLinePositionSpan(originalTextSpan).Start;
var lineNumber = linePosition.Line;
// 1. Token line number delta, relative to the previous token
var deltaLine = lineNumber - lastLineNumber;
Contract.ThrowIfTrue(deltaLine < 0, $"deltaLine is less than 0: {deltaLine}");
// 2. Token start character delta, relative to the previous token
// (Relative to 0 or the previous token’s start if they're on the same line)
var deltaStartCharacter = linePosition.Character;
if (lastLineNumber == lineNumber)
{
deltaStartCharacter -= lastStartCharacter;
}
lastLineNumber = lineNumber;
lastStartCharacter = linePosition.Character;
// 3. Token length
var tokenLength = originalTextSpan.Length;
// We currently only have one modifier (static). The logic below will need to change in the future if other
// modifiers are added in the future.
var modifierBits = TokenModifiers.None;
var tokenTypeIndex = 0;
// Classified spans with the same text span should be combined into one token.
while (classifiedSpans[currentClassifiedSpanIndex].TextSpan == originalTextSpan)
{
var classificationType = classifiedSpans[currentClassifiedSpanIndex].ClassificationType;
if (classificationType == ClassificationTypeNames.StaticSymbol)
{
// 4. Token modifiers - each set bit will be looked up in SemanticTokensLegend.tokenModifiers
modifierBits = TokenModifiers.Static;
}
else if (classificationType == ClassificationTypeNames.ReassignedVariable)
{
// 5. Token modifiers - each set bit will be looked up in SemanticTokensLegend.tokenModifiers
modifierBits = TokenModifiers.ReassignedVariable;
}
else
{
// 6. Token type - looked up in SemanticTokensLegend.tokenTypes (language server defined mapping
// from integer to LSP token types).
tokenTypeIndex = GetTokenTypeIndex(classificationType, tokenTypesToIndex);
}
// Break out of the loop if we have no more classified spans left, or if the next classified span has
// a different text span than our current text span.
if (currentClassifiedSpanIndex + 1 >= classifiedSpans.Length || classifiedSpans[currentClassifiedSpanIndex + 1].TextSpan != originalTextSpan)
{
break;
}
currentClassifiedSpanIndex++;
}
deltaLineOut = deltaLine;
startCharacterDeltaOut = deltaStartCharacter;
tokenLengthOut = tokenLength;
tokenTypeOut = tokenTypeIndex;
tokenModifiersOut = (int)modifierBits;
return currentClassifiedSpanIndex;
}
private static int GetTokenTypeIndex(string classificationType, Dictionary<string, int> tokenTypesToIndex)
{
if (!s_classificationTypeToSemanticTokenTypeMap.TryGetValue(classificationType, out var tokenTypeStr))
{
tokenTypeStr = classificationType;
}
Contract.ThrowIfFalse(tokenTypesToIndex.TryGetValue(tokenTypeStr, out var tokenTypeIndex), "No matching token type index found.");
return tokenTypeIndex;
}
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/VisualBasicMetadataContext.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
Friend Structure VisualBasicMetadataContext
Friend ReadOnly Compilation As VisualBasicCompilation
Friend ReadOnly EvaluationContext As EvaluationContext
Friend Sub New(compilation As VisualBasicCompilation, Optional evaluationContext As EvaluationContext = Nothing)
Me.Compilation = compilation
Me.EvaluationContext = evaluationContext
End Sub
End Structure
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
Friend Structure VisualBasicMetadataContext
Friend ReadOnly Compilation As VisualBasicCompilation
Friend ReadOnly EvaluationContext As EvaluationContext
Friend Sub New(compilation As VisualBasicCompilation, Optional evaluationContext As EvaluationContext = Nothing)
Me.Compilation = compilation
Me.EvaluationContext = evaluationContext
End Sub
End Structure
End Namespace
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Extensions/SyntaxTreeExtensions.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 System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Partial Friend Module SyntaxTreeExtensions
''' <summary>
''' check whether given token is the last token of a statement that ends with end of line trivia or an elastic trivia
''' </summary>
<Extension()>
Public Function IsLastTokenOfStatementWithEndOfLine(token As SyntaxToken) As Boolean
If Not token.HasTrailingTrivia Then
Return False
End If
' easy case
Dim trailing = token.TrailingTrivia
If trailing.Count = 1 Then
Dim trivia = trailing.First()
If trivia.Kind = SyntaxKind.EndOfLineTrivia Then
Return token.IsLastTokenOfStatement()
End If
Return False
End If
' little bit more expansive case
For Each trivia In trailing
If trivia.Kind = SyntaxKind.EndOfLineTrivia Then
Return token.IsLastTokenOfStatement()
End If
Next
Return False
End Function
''' <summary>
''' check whether given token is the last token of a statement by walking up the spine
''' </summary>
<Extension()>
Public Function IsLastTokenOfStatement(
token As SyntaxToken,
Optional checkColonTrivia As Boolean = False,
<Out> Optional ByRef statement As StatementSyntax = Nothing) As Boolean
Dim current = token.Parent
While current IsNot Nothing
If current.FullSpan.End <> token.FullSpan.End Then
Return False
End If
If TypeOf current Is StatementSyntax Then
statement = DirectCast(current, StatementSyntax)
Dim colonTrivia = GetTrailingColonTrivia(DirectCast(current, StatementSyntax))
If Not PartOfSingleLineLambda(current) AndAlso Not PartOfMultilineLambdaFooter(current) Then
If checkColonTrivia Then
If colonTrivia Is Nothing Then
Return current.GetLastToken(includeZeroWidth:=True) = token
End If
Else
Return current.GetLastToken(includeZeroWidth:=True) = token
End If
End If
End If
current = current.Parent
End While
Return False
End Function
<PerformanceSensitive("https://github.com/dotnet/roslyn/issues/30819", AllowImplicitBoxing:=False)>
Private Function GetTrailingColonTrivia(statement As StatementSyntax) As SyntaxTrivia?
If Not statement.HasTrailingTrivia Then
Return Nothing
End If
Return statement _
.GetTrailingTrivia() _
.FirstOrNull(Function(t) t.Kind = SyntaxKind.ColonTrivia)
End Function
Private Function PartOfSingleLineLambda(node As SyntaxNode) As Boolean
While node IsNot Nothing
If TypeOf node Is MultiLineLambdaExpressionSyntax Then Return False
If TypeOf node Is SingleLineLambdaExpressionSyntax Then Return True
node = node.Parent
End While
Return False
End Function
<PerformanceSensitive("https://github.com/dotnet/roslyn/issues/30819", AllowCaptures:=False)>
Private Function PartOfMultilineLambdaFooter(node As SyntaxNode) As Boolean
For Each n In node.AncestorsAndSelf
Dim multiLine = TryCast(n, MultiLineLambdaExpressionSyntax)
If multiLine Is Nothing Then
Continue For
End If
If (multiLine.EndSubOrFunctionStatement Is node) Then
Return True
End If
Next
Return False
End Function
''' <summary>
''' Finds the token being touched by this position. Unlike the normal FindTrivia helper, this helper will prefer
''' trivia to the left rather than the right if the position is on the border.
''' </summary>
''' <param name="syntaxTree">The syntaxTree to search.</param>
''' <param name="position">The position to find trivia.</param>
<Extension()>
Public Function FindTriviaToLeft(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As SyntaxTrivia
Return FindTriviaToLeft(syntaxTree.GetRoot(cancellationToken), position)
End Function
Private Function FindTriviaToLeft(nodeOrToken As SyntaxNodeOrToken, position As Integer) As SyntaxTrivia
recurse:
For Each child In nodeOrToken.ChildNodesAndTokens().Reverse()
If (child.FullSpan.Start < position) AndAlso (position <= child.FullSpan.End) Then
If child.IsNode Then
nodeOrToken = child
GoTo recurse
Else
For Each trivia In child.GetTrailingTrivia.Reverse
If (trivia.SpanStart < position) AndAlso (position <= child.FullSpan.End) Then
Return trivia
End If
Next
For Each trivia In child.GetLeadingTrivia.Reverse
If (trivia.SpanStart < position) AndAlso (position <= child.FullSpan.End) Then
Return trivia
End If
Next
End If
End If
Next
Return Nothing
End Function
<Extension()>
Public Function IsInNonUserCode(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean
Return _
syntaxTree.IsEntirelyWithinComment(position, cancellationToken) OrElse
syntaxTree.IsEntirelyWithinStringOrCharOrNumericLiteral(position, cancellationToken) OrElse
syntaxTree.IsInInactiveRegion(position, cancellationToken) OrElse
syntaxTree.IsWithinPartialMethodDeclaration(position, cancellationToken)
End Function
<Extension()>
Public Function IsWithinPartialMethodDeclaration(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean
Dim token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken)
Dim declaration = token.GetAncestor(Of MethodStatementSyntax)
If declaration IsNot Nothing AndAlso declaration.Modifiers.Any(SyntaxKind.PartialKeyword) Then
Return True
End If
Dim block = token.GetAncestor(Of MethodBlockSyntax)
If block IsNot Nothing AndAlso block.BlockStatement.Modifiers.Any(SyntaxKind.PartialKeyword) Then
Return True
End If
Return False
End Function
<Extension()>
Public Function IsEntirelyWithinComment(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean
Dim trivia = syntaxTree.FindTriviaToLeft(position, cancellationToken)
If trivia.IsKind(SyntaxKind.CommentTrivia, SyntaxKind.DocumentationCommentTrivia) AndAlso trivia.SpanStart <> position Then
Return True
End If
Return False
End Function
<Extension()>
Public Function IsEntirelyWithinStringLiteral(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean
Dim token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives:=True, includeDocumentationComments:=True)
If token.IsKind(SyntaxKind.StringLiteralToken) Then
Return token.SpanStart < position AndAlso position < token.Span.End OrElse AtEndOfIncompleteStringOrCharLiteral(token, position, """")
End If
Return False
End Function
<Extension()>
Public Function IsEntirelyWithinStringOrCharOrNumericLiteral(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean
Dim token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives:=True, includeDocumentationComments:=True)
If Not token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.CharacterLiteralToken, SyntaxKind.DecimalLiteralToken, SyntaxKind.IntegerLiteralToken,
SyntaxKind.DateLiteralToken, SyntaxKind.FloatingLiteralToken) Then
Return False
End If
' Check if it's within a completed token.
If token.SpanStart < position AndAlso position < token.Span.End Then
Return True
End If
' If it is a numeric literal, all checks are done and we're okay.
If token.IsKind(SyntaxKind.IntegerLiteralToken, SyntaxKind.DecimalLiteralToken,
SyntaxKind.DateLiteralToken, SyntaxKind.FloatingLiteralToken) Then
Return False
End If
' For char or string literals, check if we're at the end of an incomplete literal.
Dim lastChar = If(token.IsKind(SyntaxKind.CharacterLiteralToken), "'", """")
Return AtEndOfIncompleteStringOrCharLiteral(token, position, lastChar)
End Function
Private Function AtEndOfIncompleteStringOrCharLiteral(token As SyntaxToken, position As Integer, lastChar As String) As Boolean
' Check if it's a token that was started, but not ended
Dim startLength = 1
If token.IsKind(SyntaxKind.CharacterLiteralToken) Then
startLength = 2
End If
Return _
position = token.Span.End AndAlso
(token.Span.Length = startLength OrElse
(token.Span.Length > startLength AndAlso Not token.ToString().EndsWith(lastChar, StringComparison.Ordinal)))
End Function
<Extension()>
Public Function IsInInactiveRegion(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean
Contract.ThrowIfNull(syntaxTree)
' cases:
' $ is EOF
' #IF false Then
' |
' #IF false Then
' |$
' #IF false Then
' |
' #IF false Then
' |$
If syntaxTree.FindTriviaToLeft(position, cancellationToken).Kind = SyntaxKind.DisabledTextTrivia Then
Return True
End If
' TODO : insert point at the same line as preprocessor?
Return False
End Function
<Extension()>
Public Function IsInSkippedText(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean
Dim trivia = syntaxTree.FindTriviaToLeft(position, cancellationToken)
Return trivia.IsKind(SyntaxKind.SkippedTokensTrivia)
End Function
Private Function IsGlobalStatementContext(token As SyntaxToken, position As Integer) As Boolean
If Not token.IsLastTokenOfStatement() Then
Return False
End If
' NB: Checks whether the caret is placed after a colon or an end of line.
' Otherwise the typed expression would still be a part of the previous statement.
If Not token.HasTrailingTrivia OrElse token.HasAncestor(Of IncompleteMemberSyntax) Then
Return False
End If
For Each trivia In token.TrailingTrivia
If trivia.Span.Start > position Then
Return False
ElseIf trivia.IsKind(SyntaxKind.ColonTrivia) Then
Return True
ElseIf trivia.IsKind(SyntaxKind.EndOfLineTrivia) Then
Return True
End If
Next
Return False
End Function
<Extension()>
Public Function IsGlobalStatementContext(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean
If Not syntaxTree.IsScript() Then
Return False
End If
Dim token As SyntaxToken = syntaxTree.FindTokenOnLeftOfPosition(
position, cancellationToken, includeDirectives:=True).GetPreviousTokenIfTouchingWord(position)
If token.IsKind(SyntaxKind.None) Then
Dim compilationUnit = TryCast(syntaxTree.GetRoot(cancellationToken), CompilationUnitSyntax)
Return compilationUnit Is Nothing OrElse compilationUnit.Imports.Count = 0
End If
Return IsGlobalStatementContext(token, position)
End Function
<Extension()>
Public Function IsRightOfDot(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean
Dim token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken)
If token.Kind = SyntaxKind.None Then
Return False
End If
token = token.GetPreviousTokenIfTouchingWord(position)
Return token.Kind = SyntaxKind.DotToken
End Function
<Extension()>
Public Function IsRightOfIntegerLiteral(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean
Dim token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken)
Return token.Kind = SyntaxKind.IntegerLiteralToken
End Function
<Extension()>
Public Function IsInPreprocessorDirectiveContext(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean
Dim directive As DirectiveTriviaSyntax = Nothing
Return IsInPreprocessorDirectiveContext(syntaxTree, position, cancellationToken, directive)
End Function
Friend Function IsInPreprocessorDirectiveContext(
syntaxTree As SyntaxTree,
position As Integer,
cancellationToken As CancellationToken,
ByRef directive As DirectiveTriviaSyntax) As Boolean
Dim token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives:=True, includeDocumentationComments:=True)
directive = token.GetAncestor(Of DirectiveTriviaSyntax)()
' Directives contain the EOL, so if the position is within the full span of the
' directive, then it is on that line, the only exception is if the directive is on the
' last line, the position at the end if technically not contained by the directive but
' its also not on a new line, so it should be considered part of the preprocessor
' context.
If directive Is Nothing Then
Return False
End If
Return directive.FullSpan.Contains(position) OrElse
directive.FullSpan.End = syntaxTree.GetRoot(cancellationToken).FullSpan.End
End Function
<Extension()>
Public Function GetFirstStatementOnLine(syntaxTree As SyntaxTree, lineNumber As Integer, cancellationToken As CancellationToken) As StatementSyntax
Dim line = syntaxTree.GetText(cancellationToken).Lines(lineNumber)
Dim token = syntaxTree.GetRoot(cancellationToken).FindToken(line.Start)
Dim statement = token.Parent.FirstAncestorOrSelf(Of StatementSyntax)()
If statement IsNot Nothing AndAlso
syntaxTree.GetText(cancellationToken).Lines.IndexOf(statement.SpanStart) = lineNumber Then
Return statement
End If
Return Nothing
End Function
<Extension()>
Public Function GetFirstEnclosingStatement(node As SyntaxNode) As StatementSyntax
Return node.AncestorsAndSelf().Where(Function(n) TypeOf n Is StatementSyntax).OfType(Of StatementSyntax).FirstOrDefault()
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 System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Partial Friend Module SyntaxTreeExtensions
''' <summary>
''' check whether given token is the last token of a statement that ends with end of line trivia or an elastic trivia
''' </summary>
<Extension()>
Public Function IsLastTokenOfStatementWithEndOfLine(token As SyntaxToken) As Boolean
If Not token.HasTrailingTrivia Then
Return False
End If
' easy case
Dim trailing = token.TrailingTrivia
If trailing.Count = 1 Then
Dim trivia = trailing.First()
If trivia.Kind = SyntaxKind.EndOfLineTrivia Then
Return token.IsLastTokenOfStatement()
End If
Return False
End If
' little bit more expansive case
For Each trivia In trailing
If trivia.Kind = SyntaxKind.EndOfLineTrivia Then
Return token.IsLastTokenOfStatement()
End If
Next
Return False
End Function
''' <summary>
''' check whether given token is the last token of a statement by walking up the spine
''' </summary>
<Extension()>
Public Function IsLastTokenOfStatement(
token As SyntaxToken,
Optional checkColonTrivia As Boolean = False,
<Out> Optional ByRef statement As StatementSyntax = Nothing) As Boolean
Dim current = token.Parent
While current IsNot Nothing
If current.FullSpan.End <> token.FullSpan.End Then
Return False
End If
If TypeOf current Is StatementSyntax Then
statement = DirectCast(current, StatementSyntax)
Dim colonTrivia = GetTrailingColonTrivia(DirectCast(current, StatementSyntax))
If Not PartOfSingleLineLambda(current) AndAlso Not PartOfMultilineLambdaFooter(current) Then
If checkColonTrivia Then
If colonTrivia Is Nothing Then
Return current.GetLastToken(includeZeroWidth:=True) = token
End If
Else
Return current.GetLastToken(includeZeroWidth:=True) = token
End If
End If
End If
current = current.Parent
End While
Return False
End Function
<PerformanceSensitive("https://github.com/dotnet/roslyn/issues/30819", AllowImplicitBoxing:=False)>
Private Function GetTrailingColonTrivia(statement As StatementSyntax) As SyntaxTrivia?
If Not statement.HasTrailingTrivia Then
Return Nothing
End If
Return statement _
.GetTrailingTrivia() _
.FirstOrNull(Function(t) t.Kind = SyntaxKind.ColonTrivia)
End Function
Private Function PartOfSingleLineLambda(node As SyntaxNode) As Boolean
While node IsNot Nothing
If TypeOf node Is MultiLineLambdaExpressionSyntax Then Return False
If TypeOf node Is SingleLineLambdaExpressionSyntax Then Return True
node = node.Parent
End While
Return False
End Function
<PerformanceSensitive("https://github.com/dotnet/roslyn/issues/30819", AllowCaptures:=False)>
Private Function PartOfMultilineLambdaFooter(node As SyntaxNode) As Boolean
For Each n In node.AncestorsAndSelf
Dim multiLine = TryCast(n, MultiLineLambdaExpressionSyntax)
If multiLine Is Nothing Then
Continue For
End If
If (multiLine.EndSubOrFunctionStatement Is node) Then
Return True
End If
Next
Return False
End Function
''' <summary>
''' Finds the token being touched by this position. Unlike the normal FindTrivia helper, this helper will prefer
''' trivia to the left rather than the right if the position is on the border.
''' </summary>
''' <param name="syntaxTree">The syntaxTree to search.</param>
''' <param name="position">The position to find trivia.</param>
<Extension()>
Public Function FindTriviaToLeft(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As SyntaxTrivia
Return FindTriviaToLeft(syntaxTree.GetRoot(cancellationToken), position)
End Function
Private Function FindTriviaToLeft(nodeOrToken As SyntaxNodeOrToken, position As Integer) As SyntaxTrivia
recurse:
For Each child In nodeOrToken.ChildNodesAndTokens().Reverse()
If (child.FullSpan.Start < position) AndAlso (position <= child.FullSpan.End) Then
If child.IsNode Then
nodeOrToken = child
GoTo recurse
Else
For Each trivia In child.GetTrailingTrivia.Reverse
If (trivia.SpanStart < position) AndAlso (position <= child.FullSpan.End) Then
Return trivia
End If
Next
For Each trivia In child.GetLeadingTrivia.Reverse
If (trivia.SpanStart < position) AndAlso (position <= child.FullSpan.End) Then
Return trivia
End If
Next
End If
End If
Next
Return Nothing
End Function
<Extension()>
Public Function IsInNonUserCode(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean
Return _
syntaxTree.IsEntirelyWithinComment(position, cancellationToken) OrElse
syntaxTree.IsEntirelyWithinStringOrCharOrNumericLiteral(position, cancellationToken) OrElse
syntaxTree.IsInInactiveRegion(position, cancellationToken) OrElse
syntaxTree.IsWithinPartialMethodDeclaration(position, cancellationToken)
End Function
<Extension()>
Public Function IsWithinPartialMethodDeclaration(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean
Dim token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken)
Dim declaration = token.GetAncestor(Of MethodStatementSyntax)
If declaration IsNot Nothing AndAlso declaration.Modifiers.Any(SyntaxKind.PartialKeyword) Then
Return True
End If
Dim block = token.GetAncestor(Of MethodBlockSyntax)
If block IsNot Nothing AndAlso block.BlockStatement.Modifiers.Any(SyntaxKind.PartialKeyword) Then
Return True
End If
Return False
End Function
<Extension()>
Public Function IsEntirelyWithinComment(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean
Dim trivia = syntaxTree.FindTriviaToLeft(position, cancellationToken)
If trivia.IsKind(SyntaxKind.CommentTrivia, SyntaxKind.DocumentationCommentTrivia) AndAlso trivia.SpanStart <> position Then
Return True
End If
Return False
End Function
<Extension()>
Public Function IsEntirelyWithinStringLiteral(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean
Dim token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives:=True, includeDocumentationComments:=True)
If token.IsKind(SyntaxKind.StringLiteralToken) Then
Return token.SpanStart < position AndAlso position < token.Span.End OrElse AtEndOfIncompleteStringOrCharLiteral(token, position, """")
End If
Return False
End Function
<Extension()>
Public Function IsEntirelyWithinStringOrCharOrNumericLiteral(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean
Dim token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives:=True, includeDocumentationComments:=True)
If Not token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.CharacterLiteralToken, SyntaxKind.DecimalLiteralToken, SyntaxKind.IntegerLiteralToken,
SyntaxKind.DateLiteralToken, SyntaxKind.FloatingLiteralToken) Then
Return False
End If
' Check if it's within a completed token.
If token.SpanStart < position AndAlso position < token.Span.End Then
Return True
End If
' If it is a numeric literal, all checks are done and we're okay.
If token.IsKind(SyntaxKind.IntegerLiteralToken, SyntaxKind.DecimalLiteralToken,
SyntaxKind.DateLiteralToken, SyntaxKind.FloatingLiteralToken) Then
Return False
End If
' For char or string literals, check if we're at the end of an incomplete literal.
Dim lastChar = If(token.IsKind(SyntaxKind.CharacterLiteralToken), "'", """")
Return AtEndOfIncompleteStringOrCharLiteral(token, position, lastChar)
End Function
Private Function AtEndOfIncompleteStringOrCharLiteral(token As SyntaxToken, position As Integer, lastChar As String) As Boolean
' Check if it's a token that was started, but not ended
Dim startLength = 1
If token.IsKind(SyntaxKind.CharacterLiteralToken) Then
startLength = 2
End If
Return _
position = token.Span.End AndAlso
(token.Span.Length = startLength OrElse
(token.Span.Length > startLength AndAlso Not token.ToString().EndsWith(lastChar, StringComparison.Ordinal)))
End Function
<Extension()>
Public Function IsInInactiveRegion(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean
Contract.ThrowIfNull(syntaxTree)
' cases:
' $ is EOF
' #IF false Then
' |
' #IF false Then
' |$
' #IF false Then
' |
' #IF false Then
' |$
If syntaxTree.FindTriviaToLeft(position, cancellationToken).Kind = SyntaxKind.DisabledTextTrivia Then
Return True
End If
' TODO : insert point at the same line as preprocessor?
Return False
End Function
<Extension()>
Public Function IsInSkippedText(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean
Dim trivia = syntaxTree.FindTriviaToLeft(position, cancellationToken)
Return trivia.IsKind(SyntaxKind.SkippedTokensTrivia)
End Function
Private Function IsGlobalStatementContext(token As SyntaxToken, position As Integer) As Boolean
If Not token.IsLastTokenOfStatement() Then
Return False
End If
' NB: Checks whether the caret is placed after a colon or an end of line.
' Otherwise the typed expression would still be a part of the previous statement.
If Not token.HasTrailingTrivia OrElse token.HasAncestor(Of IncompleteMemberSyntax) Then
Return False
End If
For Each trivia In token.TrailingTrivia
If trivia.Span.Start > position Then
Return False
ElseIf trivia.IsKind(SyntaxKind.ColonTrivia) Then
Return True
ElseIf trivia.IsKind(SyntaxKind.EndOfLineTrivia) Then
Return True
End If
Next
Return False
End Function
<Extension()>
Public Function IsGlobalStatementContext(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean
If Not syntaxTree.IsScript() Then
Return False
End If
Dim token As SyntaxToken = syntaxTree.FindTokenOnLeftOfPosition(
position, cancellationToken, includeDirectives:=True).GetPreviousTokenIfTouchingWord(position)
If token.IsKind(SyntaxKind.None) Then
Dim compilationUnit = TryCast(syntaxTree.GetRoot(cancellationToken), CompilationUnitSyntax)
Return compilationUnit Is Nothing OrElse compilationUnit.Imports.Count = 0
End If
Return IsGlobalStatementContext(token, position)
End Function
<Extension()>
Public Function IsRightOfDot(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean
Dim token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken)
If token.Kind = SyntaxKind.None Then
Return False
End If
token = token.GetPreviousTokenIfTouchingWord(position)
Return token.Kind = SyntaxKind.DotToken
End Function
<Extension()>
Public Function IsRightOfIntegerLiteral(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean
Dim token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken)
Return token.Kind = SyntaxKind.IntegerLiteralToken
End Function
<Extension()>
Public Function IsInPreprocessorDirectiveContext(syntaxTree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As Boolean
Dim directive As DirectiveTriviaSyntax = Nothing
Return IsInPreprocessorDirectiveContext(syntaxTree, position, cancellationToken, directive)
End Function
Friend Function IsInPreprocessorDirectiveContext(
syntaxTree As SyntaxTree,
position As Integer,
cancellationToken As CancellationToken,
ByRef directive As DirectiveTriviaSyntax) As Boolean
Dim token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives:=True, includeDocumentationComments:=True)
directive = token.GetAncestor(Of DirectiveTriviaSyntax)()
' Directives contain the EOL, so if the position is within the full span of the
' directive, then it is on that line, the only exception is if the directive is on the
' last line, the position at the end if technically not contained by the directive but
' its also not on a new line, so it should be considered part of the preprocessor
' context.
If directive Is Nothing Then
Return False
End If
Return directive.FullSpan.Contains(position) OrElse
directive.FullSpan.End = syntaxTree.GetRoot(cancellationToken).FullSpan.End
End Function
<Extension()>
Public Function GetFirstStatementOnLine(syntaxTree As SyntaxTree, lineNumber As Integer, cancellationToken As CancellationToken) As StatementSyntax
Dim line = syntaxTree.GetText(cancellationToken).Lines(lineNumber)
Dim token = syntaxTree.GetRoot(cancellationToken).FindToken(line.Start)
Dim statement = token.Parent.FirstAncestorOrSelf(Of StatementSyntax)()
If statement IsNot Nothing AndAlso
syntaxTree.GetText(cancellationToken).Lines.IndexOf(statement.SpanStart) = lineNumber Then
Return statement
End If
Return Nothing
End Function
<Extension()>
Public Function GetFirstEnclosingStatement(node As SyntaxNode) As StatementSyntax
Return node.AncestorsAndSelf().Where(Function(n) TypeOf n Is StatementSyntax).OfType(Of StatementSyntax).FirstOrDefault()
End Function
End Module
End Namespace
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/EditorFeatures/Core.Wpf/NavigateTo/NavigateToItemProvider.cs | // Licensed to the .NET Foundation under one or more 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.Threading;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.NavigateTo;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Language.NavigateTo.Interfaces;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo
{
internal partial class NavigateToItemProvider : INavigateToItemProvider2
{
private readonly Workspace _workspace;
private readonly IAsynchronousOperationListener _asyncListener;
private readonly INavigateToItemDisplayFactory _displayFactory;
private readonly IThreadingContext _threadingContext;
private CancellationTokenSource _cancellationTokenSource = new();
public NavigateToItemProvider(
Workspace workspace,
IAsynchronousOperationListener asyncListener,
IThreadingContext threadingContext)
{
Contract.ThrowIfNull(workspace);
Contract.ThrowIfNull(asyncListener);
_workspace = workspace;
_asyncListener = asyncListener;
_displayFactory = new NavigateToItemDisplayFactory();
_threadingContext = threadingContext;
}
ISet<string> INavigateToItemProvider2.KindsProvided => KindsProvided;
public ImmutableHashSet<string> KindsProvided
=> NavigateToUtilities.GetKindsProvided(_workspace.CurrentSolution);
public bool CanFilter
{
get
{
foreach (var project in _workspace.CurrentSolution.Projects)
{
var navigateToSearchService = project.GetLanguageService<INavigateToSearchService>();
if (navigateToSearchService is null)
{
// If we reach here, it means the current project does not support Navigate To, which is
// functionally equivalent to supporting filtering.
continue;
}
if (!navigateToSearchService.CanFilter)
{
return false;
}
}
// All projects either support filtering or do not support Navigate To at all
return true;
}
}
public void StopSearch()
{
_cancellationTokenSource.Cancel();
_cancellationTokenSource = new CancellationTokenSource();
}
public void Dispose()
{
this.StopSearch();
(_displayFactory as IDisposable)?.Dispose();
}
public void StartSearch(INavigateToCallback callback, string searchValue)
=> StartSearch(callback, searchValue, KindsProvided);
public void StartSearch(INavigateToCallback callback, string searchValue, INavigateToFilterParameters filter)
=> StartSearch(callback, searchValue, filter.Kinds.ToImmutableHashSet(StringComparer.Ordinal));
private void StartSearch(INavigateToCallback callback, string searchValue, IImmutableSet<string> kinds)
{
this.StopSearch();
if (string.IsNullOrWhiteSpace(searchValue))
{
callback.Done();
return;
}
if (kinds == null || kinds.Count == 0)
{
kinds = KindsProvided;
}
var searchCurrentDocument = (callback.Options as INavigateToOptions2)?.SearchCurrentDocument ?? false;
var roslynCallback = new NavigateToItemProviderCallback(_displayFactory, callback);
var searcher = NavigateToSearcher.Create(
_workspace.CurrentSolution,
_asyncListener,
roslynCallback,
searchValue,
searchCurrentDocument,
kinds,
_threadingContext.DisposalToken);
_ = searcher.SearchAsync(_cancellationTokenSource.Token);
}
}
}
| // Licensed to the .NET Foundation under one or more 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.Threading;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.NavigateTo;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Language.NavigateTo.Interfaces;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo
{
internal partial class NavigateToItemProvider : INavigateToItemProvider2
{
private readonly Workspace _workspace;
private readonly IAsynchronousOperationListener _asyncListener;
private readonly INavigateToItemDisplayFactory _displayFactory;
private readonly IThreadingContext _threadingContext;
private CancellationTokenSource _cancellationTokenSource = new();
public NavigateToItemProvider(
Workspace workspace,
IAsynchronousOperationListener asyncListener,
IThreadingContext threadingContext)
{
Contract.ThrowIfNull(workspace);
Contract.ThrowIfNull(asyncListener);
_workspace = workspace;
_asyncListener = asyncListener;
_displayFactory = new NavigateToItemDisplayFactory();
_threadingContext = threadingContext;
}
ISet<string> INavigateToItemProvider2.KindsProvided => KindsProvided;
public ImmutableHashSet<string> KindsProvided
=> NavigateToUtilities.GetKindsProvided(_workspace.CurrentSolution);
public bool CanFilter
{
get
{
foreach (var project in _workspace.CurrentSolution.Projects)
{
var navigateToSearchService = project.GetLanguageService<INavigateToSearchService>();
if (navigateToSearchService is null)
{
// If we reach here, it means the current project does not support Navigate To, which is
// functionally equivalent to supporting filtering.
continue;
}
if (!navigateToSearchService.CanFilter)
{
return false;
}
}
// All projects either support filtering or do not support Navigate To at all
return true;
}
}
public void StopSearch()
{
_cancellationTokenSource.Cancel();
_cancellationTokenSource = new CancellationTokenSource();
}
public void Dispose()
{
this.StopSearch();
(_displayFactory as IDisposable)?.Dispose();
}
public void StartSearch(INavigateToCallback callback, string searchValue)
=> StartSearch(callback, searchValue, KindsProvided);
public void StartSearch(INavigateToCallback callback, string searchValue, INavigateToFilterParameters filter)
=> StartSearch(callback, searchValue, filter.Kinds.ToImmutableHashSet(StringComparer.Ordinal));
private void StartSearch(INavigateToCallback callback, string searchValue, IImmutableSet<string> kinds)
{
this.StopSearch();
if (string.IsNullOrWhiteSpace(searchValue))
{
callback.Done();
return;
}
if (kinds == null || kinds.Count == 0)
{
kinds = KindsProvided;
}
var searchCurrentDocument = (callback.Options as INavigateToOptions2)?.SearchCurrentDocument ?? false;
var roslynCallback = new NavigateToItemProviderCallback(_displayFactory, callback);
var searcher = NavigateToSearcher.Create(
_workspace.CurrentSolution,
_asyncListener,
roslynCallback,
searchValue,
searchCurrentDocument,
kinds,
_threadingContext.DisposalToken);
_ = searcher.SearchAsync(_cancellationTokenSource.Token);
}
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Compilers/VisualBasic/Test/Semantic/Semantics/EraseStatementTests.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.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Public Class EraseStatementTests
Inherits BasicTestBase
<Fact>
<CompilerTrait(CompilerFeature.IOperation)>
Public Sub Simple()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim x(1) As Integer
Dim y As System.Array = New Integer(1) {}
Dim z As Object = New Integer(1) {}
Erase x
Erase y, z
System.Console.WriteLine(x Is Nothing)
System.Console.WriteLine(y Is Nothing)
System.Console.WriteLine(z Is Nothing)
End Sub
End Module
</file>
</compilation>
Dim verifier = CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
True
True
True
]]>)
Dim compilation = verifier.Compilation
Dim tree = compilation.SyntaxTrees.Single()
Dim node = tree.GetRoot().DescendantNodes().OfType(Of EraseStatementSyntax)().Last()
Assert.Equal("Erase y, z", node.ToString())
compilation.VerifyOperationTree(node, expectedOperationTree:=
<![CDATA[
IOperation: (OperationKind.None, Type: null) (Syntax: 'Erase y, z')
Children(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Array, IsImplicit) (Syntax: 'y')
Left:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Array) (Syntax: 'y')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Array, Constant: null, IsImplicit) (Syntax: 'y')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsImplicit) (Syntax: 'y')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'z')
Left:
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Object) (Syntax: 'z')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'z')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsImplicit) (Syntax: 'z')
]]>.Value)
End Sub
<Fact>
Public Sub Flow()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim x() As Integer
x(0).ToString()
End Sub
Sub Test()
Dim y() As Integer
Erase y
y(0).ToString()
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime.
x(0).ToString()
~
</expected>)
End Sub
<Fact>
Public Sub Errors1()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim x As String = ""
Erase x
Dim y As String = ""
Dim z As Integer = 1
Erase y, z
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertTheseDiagnostics(compilation,
<expected>
BC30049: 'Erase' statement requires an array.
Erase x
~
BC30049: 'Erase' statement requires an array.
Erase y, z
~
BC30049: 'Erase' statement requires an array.
Erase y, z
~
</expected>)
End Sub
<Fact>
Public Sub Errors2()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Erase x1
Erase x2
Erase y
Erase z
End Sub
ReadOnly Property x1 As String
Get
Return Nothing
End Get
End Property
ReadOnly Property x2 As Integer()
Get
Return Nothing
End Get
End Property
Property y As Integer()
WriteOnly Property z As Integer()
Set(value As Integer())
End Set
End Property
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertTheseDiagnostics(compilation,
<expected>
BC30049: 'Erase' statement requires an array.
Erase x1
~~
BC30526: Property 'x2' is 'ReadOnly'.
Erase x2
~~
</expected>)
End Sub
<Fact>
Public Sub Errors3()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Erase x
End Sub
Function x() As Integer()
Return Nothing
End Function
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertTheseDiagnostics(compilation,
<expected>
BC30068: Expression is a value and therefore cannot be the target of an assignment.
Erase x
~
</expected>)
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.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Public Class EraseStatementTests
Inherits BasicTestBase
<Fact>
<CompilerTrait(CompilerFeature.IOperation)>
Public Sub Simple()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim x(1) As Integer
Dim y As System.Array = New Integer(1) {}
Dim z As Object = New Integer(1) {}
Erase x
Erase y, z
System.Console.WriteLine(x Is Nothing)
System.Console.WriteLine(y Is Nothing)
System.Console.WriteLine(z Is Nothing)
End Sub
End Module
</file>
</compilation>
Dim verifier = CompileAndVerify(compilationDef,
expectedOutput:=
<![CDATA[
True
True
True
]]>)
Dim compilation = verifier.Compilation
Dim tree = compilation.SyntaxTrees.Single()
Dim node = tree.GetRoot().DescendantNodes().OfType(Of EraseStatementSyntax)().Last()
Assert.Equal("Erase y, z", node.ToString())
compilation.VerifyOperationTree(node, expectedOperationTree:=
<![CDATA[
IOperation: (OperationKind.None, Type: null) (Syntax: 'Erase y, z')
Children(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Array, IsImplicit) (Syntax: 'y')
Left:
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Array) (Syntax: 'y')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Array, Constant: null, IsImplicit) (Syntax: 'y')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsImplicit) (Syntax: 'y')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'z')
Left:
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Object) (Syntax: 'z')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'z')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsImplicit) (Syntax: 'z')
]]>.Value)
End Sub
<Fact>
Public Sub Flow()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim x() As Integer
x(0).ToString()
End Sub
Sub Test()
Dim y() As Integer
Erase y
y(0).ToString()
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertTheseDiagnostics(compilation,
<expected>
BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime.
x(0).ToString()
~
</expected>)
End Sub
<Fact>
Public Sub Errors1()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim x As String = ""
Erase x
Dim y As String = ""
Dim z As Integer = 1
Erase y, z
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertTheseDiagnostics(compilation,
<expected>
BC30049: 'Erase' statement requires an array.
Erase x
~
BC30049: 'Erase' statement requires an array.
Erase y, z
~
BC30049: 'Erase' statement requires an array.
Erase y, z
~
</expected>)
End Sub
<Fact>
Public Sub Errors2()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Erase x1
Erase x2
Erase y
Erase z
End Sub
ReadOnly Property x1 As String
Get
Return Nothing
End Get
End Property
ReadOnly Property x2 As Integer()
Get
Return Nothing
End Get
End Property
Property y As Integer()
WriteOnly Property z As Integer()
Set(value As Integer())
End Set
End Property
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertTheseDiagnostics(compilation,
<expected>
BC30049: 'Erase' statement requires an array.
Erase x1
~~
BC30526: Property 'x2' is 'ReadOnly'.
Erase x2
~~
</expected>)
End Sub
<Fact>
Public Sub Errors3()
Dim compilationDef =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Erase x
End Sub
Function x() As Integer()
Return Nothing
End Function
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertTheseDiagnostics(compilation,
<expected>
BC30068: Expression is a value and therefore cannot be the target of an assignment.
Erase x
~
</expected>)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Compilers/VisualBasic/Portable/Lowering/IteratorRewriter/IteratorRewriter.IteratorMethodToClassRewriter.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend NotInheritable Class IteratorRewriter
Inherits StateMachineRewriter(Of FieldSymbol)
Private Class IteratorMethodToClassRewriter
Inherits StateMachineMethodToClassRewriter
''' <summary>
''' The field of the generated iterator class that underlies the Current property.
''' </summary>
Private ReadOnly _current As FieldSymbol
Private _exitLabel As LabelSymbol
Private _methodValue As LocalSymbol
Private _tryNestingLevel As Integer
Friend Sub New(method As MethodSymbol,
F As SyntheticBoundNodeFactory,
state As FieldSymbol,
current As FieldSymbol,
hoistedVariables As IReadOnlySet(Of Symbol),
localProxies As Dictionary(Of Symbol, FieldSymbol),
SynthesizedLocalOrdinals As SynthesizedLocalOrdinalsDispenser,
slotAllocatorOpt As VariableSlotAllocator,
nextFreeHoistedLocalSlot As Integer,
diagnostics As BindingDiagnosticBag)
MyBase.New(F, state, hoistedVariables, localProxies, SynthesizedLocalOrdinals, slotAllocatorOpt, nextFreeHoistedLocalSlot, diagnostics)
Me._current = current
End Sub
Public Sub GenerateMoveNextAndDispose(Body As BoundStatement,
moveNextMethod As SynthesizedMethod,
disposeMethod As SynthesizedMethod)
' Generate the body for MoveNext()
F.CurrentMethod = moveNextMethod
Dim initialStateInfo = AddState()
Dim initialState As Integer = initialStateInfo.Number
Dim initialLabel As GeneratedLabelSymbol = initialStateInfo.ResumeLabel
Me._methodValue = Me.F.SynthesizedLocal(F.CurrentMethod.ReturnType, SynthesizedLocalKind.StateMachineReturnValue, F.Syntax)
Dim newBody = DirectCast(Visit(Body), BoundStatement)
' Select Me.state
' Case 0:
' GoTo state_0
' Case 1:
' GoTo state_1
' 'etc
' Case Else:
' return false
' }
' state_0:
' state = -1
' [[rewritten body]]
F.CloseMethod(
F.Block(
ImmutableArray.Create(Me._methodValue, Me.CachedState),
SyntheticBoundNodeFactory.HiddenSequencePoint(),
F.Assignment(Me.F.Local(Me.CachedState, True), F.Field(F.Me, Me.StateField, False)),
Dispatch(),
GenerateReturn(finished:=True),
F.Label(initialLabel),
F.Assignment(F.Field(F.Me, Me.StateField, True), Me.F.AssignmentExpression(Me.F.Local(Me.CachedState, True), Me.F.Literal(StateMachineStates.NotStartedStateMachine))),
newBody,
HandleReturn()
))
Me._exitLabel = Nothing
Me._methodValue = Nothing
' Generate the body for Dispose().
F.CurrentMethod = disposeMethod
Dim breakLabel = F.GenerateLabel("break")
Dim sections = (From ft In FinalizerStateMap
Where ft.Value <> -1
Group ft.Key By ft.Value Into Group
Select F.SwitchSection(
New List(Of Integer)(Group),
F.Assignment(F.Field(F.Me, Me.StateField, True), F.Literal(Value)),
F.Goto(breakLabel))).ToArray()
If (sections.Length > 0) Then
F.CloseMethod(F.Block(
F.Select(
F.Field(F.Me, Me.StateField, False),
sections),
F.Assignment(F.Field(F.Me, Me.StateField, True), F.Literal(StateMachineStates.NotStartedStateMachine)),
F.Label(breakLabel),
F.ExpressionStatement(F.Call(F.Me, moveNextMethod)),
F.Return()
))
Else
F.CloseMethod(F.Return())
End If
End Sub
Private Function HandleReturn() As BoundStatement
If Me._exitLabel Is Nothing Then
' did not see indirect returns
Return F.StatementList()
Else
' _methodValue = False
' exitlabel:
' Return _methodValue
Return F.Block(
SyntheticBoundNodeFactory.HiddenSequencePoint(),
F.Assignment(F.Local(Me._methodValue, True), F.Literal(True)),
F.Label(Me._exitLabel),
F.Return(Me.F.Local(Me._methodValue, False))
)
End If
End Function
Protected Overrides Function GenerateReturn(finished As Boolean) As BoundStatement
Dim result = F.Literal(Not finished)
If Me._tryNestingLevel = 0 Then
' direct return
Return F.Return(result)
Else
' indirect return
If Me._exitLabel Is Nothing Then
Me._exitLabel = F.GenerateLabel("exitLabel")
End If
Return Me.F.Block(
Me.F.Assignment(Me.F.Local(Me._methodValue, True), result),
Me.F.Goto(Me._exitLabel)
)
End If
End Function
Public Overrides Function VisitTryStatement(node As BoundTryStatement) As BoundNode
Me._tryNestingLevel += 1
Dim result = MyBase.VisitTryStatement(node)
Me._tryNestingLevel -= 1
Return result
End Function
Protected Overrides ReadOnly Property IsInExpressionLambda As Boolean
Get
Return False
End Get
End Property
Protected Overrides ReadOnly Property ResumeLabelName As String
Get
Return "iteratorLabel"
End Get
End Property
#Region "Visitors"
Public Overrides Function VisitReturnStatement(node As BoundReturnStatement) As BoundNode
Return GenerateReturn(finished:=True)
End Function
Public Overrides Function VisitYieldStatement(node As BoundYieldStatement) As BoundNode
' Yield expression
' is translated to -
' Me.current = expression
' Me.state = <next_state>
' return true
' <next_state_label>:
' Me.state = -1
Dim newState = AddState()
Return F.SequencePoint(
node.Syntax,
F.Block(
F.Assignment(F.Field(F.Me, Me._current, True), DirectCast(Visit(node.Expression), BoundExpression)),
F.Assignment(F.Field(F.Me, Me.StateField, True), F.AssignmentExpression(F.Local(Me.CachedState, True), F.Literal(newState.Number))),
GenerateReturn(finished:=False),
F.Label(newState.ResumeLabel),
F.Assignment(F.Field(F.Me, Me.StateField, True), F.AssignmentExpression(F.Local(Me.CachedState, True), F.Literal(StateMachineStates.NotStartedStateMachine)))
)
)
End Function
#End Region 'Visitors
Friend Overrides Sub AddProxyFieldsForStateMachineScope(proxy As FieldSymbol, proxyFields As ArrayBuilder(Of FieldSymbol))
proxyFields.Add(proxy)
End Sub
Protected Overrides Function MaterializeProxy(origExpression As BoundExpression, proxy As FieldSymbol) As BoundNode
Dim syntax As SyntaxNode = Me.F.Syntax
Dim framePointer As BoundExpression = Me.FramePointer(syntax, proxy.ContainingType)
Dim proxyFieldParented = proxy.AsMember(DirectCast(framePointer.Type, NamedTypeSymbol))
Return Me.F.Field(framePointer, proxyFieldParented, origExpression.IsLValue)
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.CodeGen
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend NotInheritable Class IteratorRewriter
Inherits StateMachineRewriter(Of FieldSymbol)
Private Class IteratorMethodToClassRewriter
Inherits StateMachineMethodToClassRewriter
''' <summary>
''' The field of the generated iterator class that underlies the Current property.
''' </summary>
Private ReadOnly _current As FieldSymbol
Private _exitLabel As LabelSymbol
Private _methodValue As LocalSymbol
Private _tryNestingLevel As Integer
Friend Sub New(method As MethodSymbol,
F As SyntheticBoundNodeFactory,
state As FieldSymbol,
current As FieldSymbol,
hoistedVariables As IReadOnlySet(Of Symbol),
localProxies As Dictionary(Of Symbol, FieldSymbol),
SynthesizedLocalOrdinals As SynthesizedLocalOrdinalsDispenser,
slotAllocatorOpt As VariableSlotAllocator,
nextFreeHoistedLocalSlot As Integer,
diagnostics As BindingDiagnosticBag)
MyBase.New(F, state, hoistedVariables, localProxies, SynthesizedLocalOrdinals, slotAllocatorOpt, nextFreeHoistedLocalSlot, diagnostics)
Me._current = current
End Sub
Public Sub GenerateMoveNextAndDispose(Body As BoundStatement,
moveNextMethod As SynthesizedMethod,
disposeMethod As SynthesizedMethod)
' Generate the body for MoveNext()
F.CurrentMethod = moveNextMethod
Dim initialStateInfo = AddState()
Dim initialState As Integer = initialStateInfo.Number
Dim initialLabel As GeneratedLabelSymbol = initialStateInfo.ResumeLabel
Me._methodValue = Me.F.SynthesizedLocal(F.CurrentMethod.ReturnType, SynthesizedLocalKind.StateMachineReturnValue, F.Syntax)
Dim newBody = DirectCast(Visit(Body), BoundStatement)
' Select Me.state
' Case 0:
' GoTo state_0
' Case 1:
' GoTo state_1
' 'etc
' Case Else:
' return false
' }
' state_0:
' state = -1
' [[rewritten body]]
F.CloseMethod(
F.Block(
ImmutableArray.Create(Me._methodValue, Me.CachedState),
SyntheticBoundNodeFactory.HiddenSequencePoint(),
F.Assignment(Me.F.Local(Me.CachedState, True), F.Field(F.Me, Me.StateField, False)),
Dispatch(),
GenerateReturn(finished:=True),
F.Label(initialLabel),
F.Assignment(F.Field(F.Me, Me.StateField, True), Me.F.AssignmentExpression(Me.F.Local(Me.CachedState, True), Me.F.Literal(StateMachineStates.NotStartedStateMachine))),
newBody,
HandleReturn()
))
Me._exitLabel = Nothing
Me._methodValue = Nothing
' Generate the body for Dispose().
F.CurrentMethod = disposeMethod
Dim breakLabel = F.GenerateLabel("break")
Dim sections = (From ft In FinalizerStateMap
Where ft.Value <> -1
Group ft.Key By ft.Value Into Group
Select F.SwitchSection(
New List(Of Integer)(Group),
F.Assignment(F.Field(F.Me, Me.StateField, True), F.Literal(Value)),
F.Goto(breakLabel))).ToArray()
If (sections.Length > 0) Then
F.CloseMethod(F.Block(
F.Select(
F.Field(F.Me, Me.StateField, False),
sections),
F.Assignment(F.Field(F.Me, Me.StateField, True), F.Literal(StateMachineStates.NotStartedStateMachine)),
F.Label(breakLabel),
F.ExpressionStatement(F.Call(F.Me, moveNextMethod)),
F.Return()
))
Else
F.CloseMethod(F.Return())
End If
End Sub
Private Function HandleReturn() As BoundStatement
If Me._exitLabel Is Nothing Then
' did not see indirect returns
Return F.StatementList()
Else
' _methodValue = False
' exitlabel:
' Return _methodValue
Return F.Block(
SyntheticBoundNodeFactory.HiddenSequencePoint(),
F.Assignment(F.Local(Me._methodValue, True), F.Literal(True)),
F.Label(Me._exitLabel),
F.Return(Me.F.Local(Me._methodValue, False))
)
End If
End Function
Protected Overrides Function GenerateReturn(finished As Boolean) As BoundStatement
Dim result = F.Literal(Not finished)
If Me._tryNestingLevel = 0 Then
' direct return
Return F.Return(result)
Else
' indirect return
If Me._exitLabel Is Nothing Then
Me._exitLabel = F.GenerateLabel("exitLabel")
End If
Return Me.F.Block(
Me.F.Assignment(Me.F.Local(Me._methodValue, True), result),
Me.F.Goto(Me._exitLabel)
)
End If
End Function
Public Overrides Function VisitTryStatement(node As BoundTryStatement) As BoundNode
Me._tryNestingLevel += 1
Dim result = MyBase.VisitTryStatement(node)
Me._tryNestingLevel -= 1
Return result
End Function
Protected Overrides ReadOnly Property IsInExpressionLambda As Boolean
Get
Return False
End Get
End Property
Protected Overrides ReadOnly Property ResumeLabelName As String
Get
Return "iteratorLabel"
End Get
End Property
#Region "Visitors"
Public Overrides Function VisitReturnStatement(node As BoundReturnStatement) As BoundNode
Return GenerateReturn(finished:=True)
End Function
Public Overrides Function VisitYieldStatement(node As BoundYieldStatement) As BoundNode
' Yield expression
' is translated to -
' Me.current = expression
' Me.state = <next_state>
' return true
' <next_state_label>:
' Me.state = -1
Dim newState = AddState()
Return F.SequencePoint(
node.Syntax,
F.Block(
F.Assignment(F.Field(F.Me, Me._current, True), DirectCast(Visit(node.Expression), BoundExpression)),
F.Assignment(F.Field(F.Me, Me.StateField, True), F.AssignmentExpression(F.Local(Me.CachedState, True), F.Literal(newState.Number))),
GenerateReturn(finished:=False),
F.Label(newState.ResumeLabel),
F.Assignment(F.Field(F.Me, Me.StateField, True), F.AssignmentExpression(F.Local(Me.CachedState, True), F.Literal(StateMachineStates.NotStartedStateMachine)))
)
)
End Function
#End Region 'Visitors
Friend Overrides Sub AddProxyFieldsForStateMachineScope(proxy As FieldSymbol, proxyFields As ArrayBuilder(Of FieldSymbol))
proxyFields.Add(proxy)
End Sub
Protected Overrides Function MaterializeProxy(origExpression As BoundExpression, proxy As FieldSymbol) As BoundNode
Dim syntax As SyntaxNode = Me.F.Syntax
Dim framePointer As BoundExpression = Me.FramePointer(syntax, proxy.ContainingType)
Dim proxyFieldParented = proxy.AsMember(DirectCast(framePointer.Type, NamedTypeSymbol))
Return Me.F.Field(framePointer, proxyFieldParented, origExpression.IsLValue)
End Function
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Features/Core/Portable/IntroduceVariable/IIntroduceVariableService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.CodeActions;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.IntroduceVariable
{
internal interface IIntroduceVariableService : ILanguageService
{
Task<CodeAction> IntroduceVariableAsync(Document document, TextSpan textSpan, 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.CodeActions;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.IntroduceVariable
{
internal interface IIntroduceVariableService : ILanguageService
{
Task<CodeAction> IntroduceVariableAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/VisualStudio/Core/Impl/CodeModel/PrototypeFlags.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Implementation.CodeModel
{
/// <summary>
/// Map vsCMPrototype flags to sane names
/// </summary>
internal enum PrototypeFlags
{
Signature = EnvDTE.vsCMPrototype.vsCMPrototypeUniqueSignature,
FullName = EnvDTE.vsCMPrototype.vsCMPrototypeFullname,
NoName = EnvDTE.vsCMPrototype.vsCMPrototypeNoName,
TypeName = EnvDTE.vsCMPrototype.vsCMPrototypeClassName,
BaseName = 0,
NameMask = (FullName | NoName | TypeName | BaseName),
ParameterTypes = EnvDTE.vsCMPrototype.vsCMPrototypeParamTypes,
ParameterNames = EnvDTE.vsCMPrototype.vsCMPrototypeParamNames,
ParameterDefaultValues = EnvDTE.vsCMPrototype.vsCMPrototypeParamDefaultValues,
ParametersMask = (ParameterTypes | ParameterNames | ParameterDefaultValues),
Type = EnvDTE.vsCMPrototype.vsCMPrototypeType,
Initializer = EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Implementation.CodeModel
{
/// <summary>
/// Map vsCMPrototype flags to sane names
/// </summary>
internal enum PrototypeFlags
{
Signature = EnvDTE.vsCMPrototype.vsCMPrototypeUniqueSignature,
FullName = EnvDTE.vsCMPrototype.vsCMPrototypeFullname,
NoName = EnvDTE.vsCMPrototype.vsCMPrototypeNoName,
TypeName = EnvDTE.vsCMPrototype.vsCMPrototypeClassName,
BaseName = 0,
NameMask = (FullName | NoName | TypeName | BaseName),
ParameterTypes = EnvDTE.vsCMPrototype.vsCMPrototypeParamTypes,
ParameterNames = EnvDTE.vsCMPrototype.vsCMPrototypeParamNames,
ParameterDefaultValues = EnvDTE.vsCMPrototype.vsCMPrototypeParamDefaultValues,
ParametersMask = (ParameterTypes | ParameterNames | ParameterDefaultValues),
Type = EnvDTE.vsCMPrototype.vsCMPrototypeType,
Initializer = EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/VisualStudio/LiveShare/Impl/CustomProtocol/LspRequestExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.VisualStudio.LanguageServices.Implementation.LanguageService;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
using LS = Microsoft.VisualStudio.LiveShare.LanguageServices;
namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Protocol
{
public static class LspRequestExtensions
{
public static LS.LspRequest<TIn, TOut> ToLSRequest<TIn, TOut>(this LSP.LspRequest<TIn, TOut> lspRequest)
=> new LS.LspRequest<TIn, TOut>(lspRequest.Name);
public static LSP.ClientCapabilities GetClientCapabilities(this LS.RequestContext requestContext)
=> requestContext.ClientCapabilities?.ToObject<LSP.ClientCapabilities>() ?? new LSP.VSInternalClientCapabilities();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.VisualStudio.LanguageServices.Implementation.LanguageService;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
using LS = Microsoft.VisualStudio.LiveShare.LanguageServices;
namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Protocol
{
public static class LspRequestExtensions
{
public static LS.LspRequest<TIn, TOut> ToLSRequest<TIn, TOut>(this LSP.LspRequest<TIn, TOut> lspRequest)
=> new LS.LspRequest<TIn, TOut>(lspRequest.Name);
public static LSP.ClientCapabilities GetClientCapabilities(this LS.RequestContext requestContext)
=> requestContext.ClientCapabilities?.ToObject<LSP.ClientCapabilities>() ?? new LSP.VSInternalClientCapabilities();
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Compilers/Server/VBCSCompilerTests/TouchedFileLoggingTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using static Roslyn.Test.Utilities.SharedResourceHelpers;
using System.Reflection;
using Microsoft.CodeAnalysis.CompilerServer;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.VisualBasic;
namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests
{
public class TouchedFileLoggingTests : TestBase
{
private static readonly string s_libDirectory = Environment.GetEnvironmentVariable("LIB");
private readonly string _baseDirectory = TempRoot.Root;
private const string HelloWorldCS = @"using System;
class C
{
public static void Main(string[] args)
{
Console.WriteLine(""Hello, world"");
}
}";
private const string HelloWorldVB = @"Imports System
Class C
Shared Sub Main(args As String())
Console.WriteLine(""Hello, world"")
End Sub
End Class
";
[ConditionalFact(typeof(DesktopOnly))]
public void CSharpTrivialMetadataCaching()
{
var filelist = new List<string>();
// Do the following compilation twice.
// The compiler server API should hold on to the mscorlib bits
// in memory, but the file tracker should still map that it was
// touched.
for (int i = 0; i < 2; i++)
{
var source1 = Temp.CreateFile().WriteAllText(HelloWorldCS).Path;
var touchedDir = Temp.CreateDirectory();
var touchedBase = Path.Combine(touchedDir.Path, "touched");
var clientDirectory = AppContext.BaseDirectory;
filelist.Add(source1);
var outWriter = new StringWriter();
var cmd = new CSharpCompilerServer(
CompilerServerHost.SharedAssemblyReferenceProvider,
responseFile: null,
new[] { "/nologo", "/touchedfiles:" + touchedBase, source1 },
new BuildPaths(clientDirectory, _baseDirectory, RuntimeEnvironment.GetRuntimeDirectory(), Path.GetTempPath()),
s_libDirectory,
new TestAnalyzerAssemblyLoader());
List<string> expectedReads;
List<string> expectedWrites;
BuildTouchedFiles(cmd,
Path.ChangeExtension(source1, "exe"),
out expectedReads,
out expectedWrites);
var exitCode = cmd.Run(outWriter);
Assert.Equal(string.Empty, outWriter.ToString().Trim());
Assert.Equal(0, exitCode);
AssertTouchedFilesEqual(expectedReads,
expectedWrites,
touchedBase);
}
foreach (String f in filelist)
{
CleanupAllGeneratedFiles(f);
}
}
[ConditionalFact(typeof(DesktopOnly))]
public void VisualBasicTrivialMetadataCaching()
{
var filelist = new List<string>();
// Do the following compilation twice.
// The compiler server API should hold on to the mscorlib bits
// in memory, but the file tracker should still map that it was
// touched.
for (int i = 0; i < 2; i++)
{
var source1 = Temp.CreateFile().WriteAllText(HelloWorldVB).Path;
var touchedDir = Temp.CreateDirectory();
var touchedBase = Path.Combine(touchedDir.Path, "touched");
var clientDirectory = AppContext.BaseDirectory;
filelist.Add(source1);
var outWriter = new StringWriter();
var cmd = new VisualBasicCompilerServer(
CompilerServerHost.SharedAssemblyReferenceProvider,
responseFile: null,
new[] { "/nologo", "/touchedfiles:" + touchedBase, source1 },
new BuildPaths(clientDirectory, _baseDirectory, RuntimeEnvironment.GetRuntimeDirectory(), Path.GetTempPath()),
s_libDirectory,
new TestAnalyzerAssemblyLoader());
List<string> expectedReads;
List<string> expectedWrites;
BuildTouchedFiles(cmd,
Path.ChangeExtension(source1, "exe"),
out expectedReads,
out expectedWrites);
var exitCode = cmd.Run(outWriter);
Assert.Equal(string.Empty, outWriter.ToString().Trim());
Assert.Equal(0, exitCode);
AssertTouchedFilesEqual(expectedReads,
expectedWrites,
touchedBase);
}
foreach (string f in filelist)
{
CleanupAllGeneratedFiles(f);
}
}
/// <summary>
/// Builds the expected base of touched files.
/// Adds a hook for temporary file creation as well,
/// so this method must be called before the execution of
/// Csc.Run.
/// </summary>
private static void BuildTouchedFiles(CommonCompiler cmd,
string outputPath,
out List<string> expectedReads,
out List<string> expectedWrites)
{
expectedReads = new List<string>();
expectedReads.AddRange(cmd.Arguments.MetadataReferences.Select(r => r.Reference));
if (cmd.Arguments is VisualBasicCommandLineArguments { DefaultCoreLibraryReference: { } reference })
{
expectedReads.Add(reference.Reference);
}
foreach (var file in cmd.Arguments.SourceFiles)
{
expectedReads.Add(file.Path);
}
var writes = new List<string>();
writes.Add(outputPath);
expectedWrites = writes;
}
private static void AssertTouchedFilesEqual(
List<string> expectedReads,
List<string> expectedWrites,
string touchedFilesBase)
{
var touchedReadPath = touchedFilesBase + ".read";
var touchedWritesPath = touchedFilesBase + ".write";
var expected = expectedReads.Select(s => s.ToUpperInvariant()).OrderBy(s => s);
Assert.Equal(string.Join("\r\n", expected),
File.ReadAllText(touchedReadPath).Trim());
expected = expectedWrites.Select(s => s.ToUpperInvariant()).OrderBy(s => s);
Assert.Equal(string.Join("\r\n", expected),
File.ReadAllText(touchedWritesPath).Trim());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using static Roslyn.Test.Utilities.SharedResourceHelpers;
using System.Reflection;
using Microsoft.CodeAnalysis.CompilerServer;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.VisualBasic;
namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests
{
public class TouchedFileLoggingTests : TestBase
{
private static readonly string s_libDirectory = Environment.GetEnvironmentVariable("LIB");
private readonly string _baseDirectory = TempRoot.Root;
private const string HelloWorldCS = @"using System;
class C
{
public static void Main(string[] args)
{
Console.WriteLine(""Hello, world"");
}
}";
private const string HelloWorldVB = @"Imports System
Class C
Shared Sub Main(args As String())
Console.WriteLine(""Hello, world"")
End Sub
End Class
";
[ConditionalFact(typeof(DesktopOnly))]
public void CSharpTrivialMetadataCaching()
{
var filelist = new List<string>();
// Do the following compilation twice.
// The compiler server API should hold on to the mscorlib bits
// in memory, but the file tracker should still map that it was
// touched.
for (int i = 0; i < 2; i++)
{
var source1 = Temp.CreateFile().WriteAllText(HelloWorldCS).Path;
var touchedDir = Temp.CreateDirectory();
var touchedBase = Path.Combine(touchedDir.Path, "touched");
var clientDirectory = AppContext.BaseDirectory;
filelist.Add(source1);
var outWriter = new StringWriter();
var cmd = new CSharpCompilerServer(
CompilerServerHost.SharedAssemblyReferenceProvider,
responseFile: null,
new[] { "/nologo", "/touchedfiles:" + touchedBase, source1 },
new BuildPaths(clientDirectory, _baseDirectory, RuntimeEnvironment.GetRuntimeDirectory(), Path.GetTempPath()),
s_libDirectory,
new TestAnalyzerAssemblyLoader());
List<string> expectedReads;
List<string> expectedWrites;
BuildTouchedFiles(cmd,
Path.ChangeExtension(source1, "exe"),
out expectedReads,
out expectedWrites);
var exitCode = cmd.Run(outWriter);
Assert.Equal(string.Empty, outWriter.ToString().Trim());
Assert.Equal(0, exitCode);
AssertTouchedFilesEqual(expectedReads,
expectedWrites,
touchedBase);
}
foreach (String f in filelist)
{
CleanupAllGeneratedFiles(f);
}
}
[ConditionalFact(typeof(DesktopOnly))]
public void VisualBasicTrivialMetadataCaching()
{
var filelist = new List<string>();
// Do the following compilation twice.
// The compiler server API should hold on to the mscorlib bits
// in memory, but the file tracker should still map that it was
// touched.
for (int i = 0; i < 2; i++)
{
var source1 = Temp.CreateFile().WriteAllText(HelloWorldVB).Path;
var touchedDir = Temp.CreateDirectory();
var touchedBase = Path.Combine(touchedDir.Path, "touched");
var clientDirectory = AppContext.BaseDirectory;
filelist.Add(source1);
var outWriter = new StringWriter();
var cmd = new VisualBasicCompilerServer(
CompilerServerHost.SharedAssemblyReferenceProvider,
responseFile: null,
new[] { "/nologo", "/touchedfiles:" + touchedBase, source1 },
new BuildPaths(clientDirectory, _baseDirectory, RuntimeEnvironment.GetRuntimeDirectory(), Path.GetTempPath()),
s_libDirectory,
new TestAnalyzerAssemblyLoader());
List<string> expectedReads;
List<string> expectedWrites;
BuildTouchedFiles(cmd,
Path.ChangeExtension(source1, "exe"),
out expectedReads,
out expectedWrites);
var exitCode = cmd.Run(outWriter);
Assert.Equal(string.Empty, outWriter.ToString().Trim());
Assert.Equal(0, exitCode);
AssertTouchedFilesEqual(expectedReads,
expectedWrites,
touchedBase);
}
foreach (string f in filelist)
{
CleanupAllGeneratedFiles(f);
}
}
/// <summary>
/// Builds the expected base of touched files.
/// Adds a hook for temporary file creation as well,
/// so this method must be called before the execution of
/// Csc.Run.
/// </summary>
private static void BuildTouchedFiles(CommonCompiler cmd,
string outputPath,
out List<string> expectedReads,
out List<string> expectedWrites)
{
expectedReads = new List<string>();
expectedReads.AddRange(cmd.Arguments.MetadataReferences.Select(r => r.Reference));
if (cmd.Arguments is VisualBasicCommandLineArguments { DefaultCoreLibraryReference: { } reference })
{
expectedReads.Add(reference.Reference);
}
foreach (var file in cmd.Arguments.SourceFiles)
{
expectedReads.Add(file.Path);
}
var writes = new List<string>();
writes.Add(outputPath);
expectedWrites = writes;
}
private static void AssertTouchedFilesEqual(
List<string> expectedReads,
List<string> expectedWrites,
string touchedFilesBase)
{
var touchedReadPath = touchedFilesBase + ".read";
var touchedWritesPath = touchedFilesBase + ".write";
var expected = expectedReads.Select(s => s.ToUpperInvariant()).OrderBy(s => s);
Assert.Equal(string.Join("\r\n", expected),
File.ReadAllText(touchedReadPath).Trim());
expected = expectedWrites.Select(s => s.ToUpperInvariant()).OrderBy(s => s);
Assert.Equal(string.Join("\r\n", expected),
File.ReadAllText(touchedWritesPath).Trim());
}
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/EditorFeatures/DiagnosticsTestUtilities/ChangeSignature/ChangeSignatureTestState.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.ChangeSignature;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.VisualBasic;
using Roslyn.Test.Utilities;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature
{
internal sealed class ChangeSignatureTestState : IDisposable
{
private static readonly TestComposition s_composition = EditorTestCompositions.EditorFeatures.AddParts(typeof(TestChangeSignatureOptionsService));
private readonly TestHostDocument _testDocument;
public TestWorkspace Workspace { get; }
public Document InvocationDocument { get; }
public AbstractChangeSignatureService ChangeSignatureService { get; }
public static ChangeSignatureTestState Create(string markup, string languageName, ParseOptions parseOptions = null, OptionsCollection options = null)
{
var workspace = languageName switch
{
"XML" => TestWorkspace.Create(markup, composition: s_composition),
LanguageNames.CSharp => TestWorkspace.CreateCSharp(markup, composition: s_composition, parseOptions: (CSharpParseOptions)parseOptions),
LanguageNames.VisualBasic => TestWorkspace.CreateVisualBasic(markup, composition: s_composition, parseOptions: parseOptions, compilationOptions: new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)),
_ => throw new ArgumentException("Invalid language name.")
};
if (options != null)
{
workspace.ApplyOptions(options);
}
return new ChangeSignatureTestState(workspace);
}
public static ChangeSignatureTestState Create(XElement workspaceXml)
{
var workspace = TestWorkspace.Create(workspaceXml, composition: s_composition);
return new ChangeSignatureTestState(workspace);
}
public ChangeSignatureTestState(TestWorkspace workspace)
{
Workspace = workspace;
_testDocument = Workspace.Documents.SingleOrDefault(d => d.CursorPosition.HasValue);
if (_testDocument == null)
{
throw new ArgumentException("markup does not contain a cursor position", nameof(workspace));
}
InvocationDocument = Workspace.CurrentSolution.GetDocument(_testDocument.Id);
ChangeSignatureService = InvocationDocument.GetLanguageService<AbstractChangeSignatureService>();
}
public TestChangeSignatureOptionsService TestChangeSignatureOptionsService
{
get
{
return (TestChangeSignatureOptionsService)InvocationDocument.Project.Solution.Workspace.Services.GetRequiredService<IChangeSignatureOptionsService>();
}
}
public async Task<ChangeSignatureResult> ChangeSignatureAsync()
{
var context = await ChangeSignatureService.GetChangeSignatureContextAsync(InvocationDocument, _testDocument.CursorPosition.Value, restrictToDeclarations: false, CancellationToken.None).ConfigureAwait(false);
var options = AbstractChangeSignatureService.GetChangeSignatureOptions(context);
return await ChangeSignatureService.ChangeSignatureWithContextAsync(context, options, CancellationToken.None);
}
public async Task<ParameterConfiguration> GetParameterConfigurationAsync()
{
var context = await ChangeSignatureService.GetChangeSignatureContextAsync(InvocationDocument, _testDocument.CursorPosition.Value, restrictToDeclarations: false, CancellationToken.None);
if (context is ChangeSignatureAnalysisSucceededContext changeSignatureAnalyzedSucceedContext)
{
return changeSignatureAnalyzedSucceedContext.ParameterConfiguration;
}
throw Roslyn.Utilities.ExceptionUtilities.UnexpectedValue(((CannotChangeSignatureAnalyzedContext)context).CannotChangeSignatureReason.ToString());
}
public void Dispose()
{
if (Workspace != null)
{
Workspace.Dispose();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.ChangeSignature;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.VisualBasic;
using Roslyn.Test.Utilities;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature
{
internal sealed class ChangeSignatureTestState : IDisposable
{
private static readonly TestComposition s_composition = EditorTestCompositions.EditorFeatures.AddParts(typeof(TestChangeSignatureOptionsService));
private readonly TestHostDocument _testDocument;
public TestWorkspace Workspace { get; }
public Document InvocationDocument { get; }
public AbstractChangeSignatureService ChangeSignatureService { get; }
public static ChangeSignatureTestState Create(string markup, string languageName, ParseOptions parseOptions = null, OptionsCollection options = null)
{
var workspace = languageName switch
{
"XML" => TestWorkspace.Create(markup, composition: s_composition),
LanguageNames.CSharp => TestWorkspace.CreateCSharp(markup, composition: s_composition, parseOptions: (CSharpParseOptions)parseOptions),
LanguageNames.VisualBasic => TestWorkspace.CreateVisualBasic(markup, composition: s_composition, parseOptions: parseOptions, compilationOptions: new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)),
_ => throw new ArgumentException("Invalid language name.")
};
if (options != null)
{
workspace.ApplyOptions(options);
}
return new ChangeSignatureTestState(workspace);
}
public static ChangeSignatureTestState Create(XElement workspaceXml)
{
var workspace = TestWorkspace.Create(workspaceXml, composition: s_composition);
return new ChangeSignatureTestState(workspace);
}
public ChangeSignatureTestState(TestWorkspace workspace)
{
Workspace = workspace;
_testDocument = Workspace.Documents.SingleOrDefault(d => d.CursorPosition.HasValue);
if (_testDocument == null)
{
throw new ArgumentException("markup does not contain a cursor position", nameof(workspace));
}
InvocationDocument = Workspace.CurrentSolution.GetDocument(_testDocument.Id);
ChangeSignatureService = InvocationDocument.GetLanguageService<AbstractChangeSignatureService>();
}
public TestChangeSignatureOptionsService TestChangeSignatureOptionsService
{
get
{
return (TestChangeSignatureOptionsService)InvocationDocument.Project.Solution.Workspace.Services.GetRequiredService<IChangeSignatureOptionsService>();
}
}
public async Task<ChangeSignatureResult> ChangeSignatureAsync()
{
var context = await ChangeSignatureService.GetChangeSignatureContextAsync(InvocationDocument, _testDocument.CursorPosition.Value, restrictToDeclarations: false, CancellationToken.None).ConfigureAwait(false);
var options = AbstractChangeSignatureService.GetChangeSignatureOptions(context);
return await ChangeSignatureService.ChangeSignatureWithContextAsync(context, options, CancellationToken.None);
}
public async Task<ParameterConfiguration> GetParameterConfigurationAsync()
{
var context = await ChangeSignatureService.GetChangeSignatureContextAsync(InvocationDocument, _testDocument.CursorPosition.Value, restrictToDeclarations: false, CancellationToken.None);
if (context is ChangeSignatureAnalysisSucceededContext changeSignatureAnalyzedSucceedContext)
{
return changeSignatureAnalyzedSucceedContext.ParameterConfiguration;
}
throw Roslyn.Utilities.ExceptionUtilities.UnexpectedValue(((CannotChangeSignatureAnalyzedContext)context).CannotChangeSignatureReason.ToString());
}
public void Dispose()
{
if (Workspace != null)
{
Workspace.Dispose();
}
}
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Analyzers/Core/Analyzers/UseObjectInitializer/AbstractUseObjectInitializerDiagnosticAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.UseObjectInitializer
{
internal abstract partial class AbstractUseObjectInitializerDiagnosticAnalyzer<
TSyntaxKind,
TExpressionSyntax,
TStatementSyntax,
TObjectCreationExpressionSyntax,
TMemberAccessExpressionSyntax,
TAssignmentStatementSyntax,
TVariableDeclaratorSyntax>
: AbstractBuiltInCodeStyleDiagnosticAnalyzer
where TSyntaxKind : struct
where TExpressionSyntax : SyntaxNode
where TStatementSyntax : SyntaxNode
where TObjectCreationExpressionSyntax : TExpressionSyntax
where TMemberAccessExpressionSyntax : TExpressionSyntax
where TAssignmentStatementSyntax : TStatementSyntax
where TVariableDeclaratorSyntax : SyntaxNode
{
protected abstract bool FadeOutOperatorToken { get; }
protected AbstractUseObjectInitializerDiagnosticAnalyzer()
: base(IDEDiagnosticIds.UseObjectInitializerDiagnosticId,
EnforceOnBuildValues.UseObjectInitializer,
CodeStyleOptions2.PreferObjectInitializer,
new LocalizableResourceString(nameof(AnalyzersResources.Simplify_object_initialization), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)),
new LocalizableResourceString(nameof(AnalyzersResources.Object_initialization_can_be_simplified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)))
{
}
protected override void InitializeWorker(AnalysisContext context)
{
var syntaxKinds = GetSyntaxFacts().SyntaxKinds;
context.RegisterCompilationStartAction(context =>
{
if (!AreObjectInitializersSupported(context.Compilation))
{
return;
}
context.RegisterSyntaxNodeAction(
AnalyzeNode, syntaxKinds.Convert<TSyntaxKind>(syntaxKinds.ObjectCreationExpression));
});
}
protected abstract bool AreObjectInitializersSupported(Compilation compilation);
protected abstract bool IsValidContainingStatement(TStatementSyntax node);
private void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
var objectCreationExpression = (TObjectCreationExpressionSyntax)context.Node;
var language = objectCreationExpression.Language;
var option = context.GetOption(CodeStyleOptions2.PreferObjectInitializer, language);
if (!option.Value)
{
// not point in analyzing if the option is off.
return;
}
var syntaxFacts = GetSyntaxFacts();
var matches = ObjectCreationExpressionAnalyzer<TExpressionSyntax, TStatementSyntax, TObjectCreationExpressionSyntax, TMemberAccessExpressionSyntax, TAssignmentStatementSyntax, TVariableDeclaratorSyntax>.Analyze(
context.SemanticModel, syntaxFacts, objectCreationExpression, context.CancellationToken);
if (matches == null || matches.Value.Length == 0)
{
return;
}
var containingStatement = objectCreationExpression.FirstAncestorOrSelf<TStatementSyntax>();
if (containingStatement == null)
{
return;
}
if (!IsValidContainingStatement(containingStatement))
{
return;
}
var nodes = ImmutableArray.Create<SyntaxNode>(containingStatement).AddRange(matches.Value.Select(m => m.Statement));
if (syntaxFacts.ContainsInterleavedDirective(nodes, context.CancellationToken))
{
return;
}
var locations = ImmutableArray.Create(objectCreationExpression.GetLocation());
var severity = option.Notification.Severity;
context.ReportDiagnostic(DiagnosticHelper.Create(
Descriptor,
objectCreationExpression.GetLocation(),
severity,
additionalLocations: locations,
properties: null));
FadeOutCode(context, matches.Value, locations);
}
private void FadeOutCode(
SyntaxNodeAnalysisContext context,
ImmutableArray<Match<TExpressionSyntax, TStatementSyntax, TMemberAccessExpressionSyntax, TAssignmentStatementSyntax>> matches,
ImmutableArray<Location> locations)
{
var syntaxTree = context.Node.SyntaxTree;
var fadeOutCode = context.GetOption(
CodeStyleOptions2.PreferObjectInitializer_FadeOutCode, context.Node.Language);
if (!fadeOutCode)
{
return;
}
var syntaxFacts = GetSyntaxFacts();
foreach (var match in matches)
{
var end = FadeOutOperatorToken
? syntaxFacts.GetOperatorTokenOfMemberAccessExpression(match.MemberAccessExpression).Span.End
: syntaxFacts.GetExpressionOfMemberAccessExpression(match.MemberAccessExpression)!.Span.End;
var location1 = Location.Create(syntaxTree, TextSpan.FromBounds(
match.MemberAccessExpression.SpanStart, end));
if (match.Statement.Span.End > match.Initializer.FullSpan.End)
{
context.ReportDiagnostic(DiagnosticHelper.CreateWithLocationTags(
Descriptor,
location1,
ReportDiagnostic.Default,
additionalLocations: locations,
additionalUnnecessaryLocations: ImmutableArray.Create(
syntaxTree.GetLocation(TextSpan.FromBounds(match.Initializer.FullSpan.End, match.Statement.Span.End)))));
}
else
{
context.ReportDiagnostic(Diagnostic.Create(
Descriptor, location1, additionalLocations: locations));
}
}
}
protected abstract ISyntaxFacts GetSyntaxFacts();
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.UseObjectInitializer
{
internal abstract partial class AbstractUseObjectInitializerDiagnosticAnalyzer<
TSyntaxKind,
TExpressionSyntax,
TStatementSyntax,
TObjectCreationExpressionSyntax,
TMemberAccessExpressionSyntax,
TAssignmentStatementSyntax,
TVariableDeclaratorSyntax>
: AbstractBuiltInCodeStyleDiagnosticAnalyzer
where TSyntaxKind : struct
where TExpressionSyntax : SyntaxNode
where TStatementSyntax : SyntaxNode
where TObjectCreationExpressionSyntax : TExpressionSyntax
where TMemberAccessExpressionSyntax : TExpressionSyntax
where TAssignmentStatementSyntax : TStatementSyntax
where TVariableDeclaratorSyntax : SyntaxNode
{
protected abstract bool FadeOutOperatorToken { get; }
protected AbstractUseObjectInitializerDiagnosticAnalyzer()
: base(IDEDiagnosticIds.UseObjectInitializerDiagnosticId,
EnforceOnBuildValues.UseObjectInitializer,
CodeStyleOptions2.PreferObjectInitializer,
new LocalizableResourceString(nameof(AnalyzersResources.Simplify_object_initialization), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)),
new LocalizableResourceString(nameof(AnalyzersResources.Object_initialization_can_be_simplified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)))
{
}
protected override void InitializeWorker(AnalysisContext context)
{
var syntaxKinds = GetSyntaxFacts().SyntaxKinds;
context.RegisterCompilationStartAction(context =>
{
if (!AreObjectInitializersSupported(context.Compilation))
{
return;
}
context.RegisterSyntaxNodeAction(
AnalyzeNode, syntaxKinds.Convert<TSyntaxKind>(syntaxKinds.ObjectCreationExpression));
});
}
protected abstract bool AreObjectInitializersSupported(Compilation compilation);
protected abstract bool IsValidContainingStatement(TStatementSyntax node);
private void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
var objectCreationExpression = (TObjectCreationExpressionSyntax)context.Node;
var language = objectCreationExpression.Language;
var option = context.GetOption(CodeStyleOptions2.PreferObjectInitializer, language);
if (!option.Value)
{
// not point in analyzing if the option is off.
return;
}
var syntaxFacts = GetSyntaxFacts();
var matches = ObjectCreationExpressionAnalyzer<TExpressionSyntax, TStatementSyntax, TObjectCreationExpressionSyntax, TMemberAccessExpressionSyntax, TAssignmentStatementSyntax, TVariableDeclaratorSyntax>.Analyze(
context.SemanticModel, syntaxFacts, objectCreationExpression, context.CancellationToken);
if (matches == null || matches.Value.Length == 0)
{
return;
}
var containingStatement = objectCreationExpression.FirstAncestorOrSelf<TStatementSyntax>();
if (containingStatement == null)
{
return;
}
if (!IsValidContainingStatement(containingStatement))
{
return;
}
var nodes = ImmutableArray.Create<SyntaxNode>(containingStatement).AddRange(matches.Value.Select(m => m.Statement));
if (syntaxFacts.ContainsInterleavedDirective(nodes, context.CancellationToken))
{
return;
}
var locations = ImmutableArray.Create(objectCreationExpression.GetLocation());
var severity = option.Notification.Severity;
context.ReportDiagnostic(DiagnosticHelper.Create(
Descriptor,
objectCreationExpression.GetLocation(),
severity,
additionalLocations: locations,
properties: null));
FadeOutCode(context, matches.Value, locations);
}
private void FadeOutCode(
SyntaxNodeAnalysisContext context,
ImmutableArray<Match<TExpressionSyntax, TStatementSyntax, TMemberAccessExpressionSyntax, TAssignmentStatementSyntax>> matches,
ImmutableArray<Location> locations)
{
var syntaxTree = context.Node.SyntaxTree;
var fadeOutCode = context.GetOption(
CodeStyleOptions2.PreferObjectInitializer_FadeOutCode, context.Node.Language);
if (!fadeOutCode)
{
return;
}
var syntaxFacts = GetSyntaxFacts();
foreach (var match in matches)
{
var end = FadeOutOperatorToken
? syntaxFacts.GetOperatorTokenOfMemberAccessExpression(match.MemberAccessExpression).Span.End
: syntaxFacts.GetExpressionOfMemberAccessExpression(match.MemberAccessExpression)!.Span.End;
var location1 = Location.Create(syntaxTree, TextSpan.FromBounds(
match.MemberAccessExpression.SpanStart, end));
if (match.Statement.Span.End > match.Initializer.FullSpan.End)
{
context.ReportDiagnostic(DiagnosticHelper.CreateWithLocationTags(
Descriptor,
location1,
ReportDiagnostic.Default,
additionalLocations: locations,
additionalUnnecessaryLocations: ImmutableArray.Create(
syntaxTree.GetLocation(TextSpan.FromBounds(match.Initializer.FullSpan.End, match.Statement.Span.End)))));
}
else
{
context.ReportDiagnostic(Diagnostic.Create(
Descriptor, location1, additionalLocations: locations));
}
}
}
protected abstract ISyntaxFacts GetSyntaxFacts();
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/VisualStudio/Xaml/Impl/Features/Completion/XamlCommitCharacters.cs | // Licensed to the .NET Foundation under one or more 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;
namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Completion
{
public readonly struct XamlCommitCharacters
{
/// <summary>
/// Commit characters.
/// </summary>
public ImmutableArray<char> Characters { get; }
/// <summary>
/// Commit characters that will not be inserted when commit
/// </summary>
public ImmutableArray<char> NonInsertCharacters { get; }
private XamlCommitCharacters(ImmutableArray<char> characters, ImmutableArray<char> nonInsertCharacters)
{
Characters = characters;
NonInsertCharacters = nonInsertCharacters;
}
public static XamlCommitCharacters Create(ImmutableArray<char> characters, ImmutableArray<char> nonInsertCharacters)
=> new(characters, nonInsertCharacters);
public static XamlCommitCharacters Create(ImmutableArray<char> characters, params char[] nonInsertCharacters)
=> new(characters, nonInsertCharacters?.ToImmutableArray() ?? ImmutableArray<char>.Empty);
public static XamlCommitCharacters Create(char[] characters, params char[] nonInsertCharacters)
=> Create(characters.ToImmutableArray(), nonInsertCharacters);
}
}
| // Licensed to the .NET Foundation under one or more 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;
namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Completion
{
public readonly struct XamlCommitCharacters
{
/// <summary>
/// Commit characters.
/// </summary>
public ImmutableArray<char> Characters { get; }
/// <summary>
/// Commit characters that will not be inserted when commit
/// </summary>
public ImmutableArray<char> NonInsertCharacters { get; }
private XamlCommitCharacters(ImmutableArray<char> characters, ImmutableArray<char> nonInsertCharacters)
{
Characters = characters;
NonInsertCharacters = nonInsertCharacters;
}
public static XamlCommitCharacters Create(ImmutableArray<char> characters, ImmutableArray<char> nonInsertCharacters)
=> new(characters, nonInsertCharacters);
public static XamlCommitCharacters Create(ImmutableArray<char> characters, params char[] nonInsertCharacters)
=> new(characters, nonInsertCharacters?.ToImmutableArray() ?? ImmutableArray<char>.Empty);
public static XamlCommitCharacters Create(char[] characters, params char[] nonInsertCharacters)
=> Create(characters.ToImmutableArray(), nonInsertCharacters);
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Workspaces/Core/Portable/xlf/WorkspacesResources.fr.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="fr" original="../WorkspacesResources.resx">
<body>
<trans-unit id="A_project_may_not_reference_itself">
<source>A project may not reference itself.</source>
<target state="translated">Un projet ne peut pas se référencer lui-même.</target>
<note />
</trans-unit>
<trans-unit id="Adding_analyzer_config_documents_is_not_supported">
<source>Adding analyzer config documents is not supported.</source>
<target state="translated">L'ajout de documents de configuration de l'analyseur n'est pas pris en charge.</target>
<note />
</trans-unit>
<trans-unit id="An_error_occurred_while_reading_the_specified_configuration_file_colon_0">
<source>An error occurred while reading the specified configuration file: {0}</source>
<target state="translated">Une erreur s'est produite lors de la lecture du fichier de configuration spécifié : {0}</target>
<note />
</trans-unit>
<trans-unit id="CSharp_files">
<source>C# files</source>
<target state="translated">Fichiers C#</target>
<note />
</trans-unit>
<trans-unit id="Cannot_apply_action_that_is_not_in_0">
<source>Cannot apply action that is not in '{0}'</source>
<target state="translated">Impossible d'appliquer l'action qui n'est pas dans '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Changing_analyzer_config_documents_is_not_supported">
<source>Changing analyzer config documents is not supported.</source>
<target state="translated">L'apport de changements aux documents de configuration de l'analyseur n'est pas pris en charge.</target>
<note />
</trans-unit>
<trans-unit id="Changing_document_0_is_not_supported">
<source>Changing document '{0}' is not supported.</source>
<target state="translated">Le changement du document '{0}' n'est pas pris en charge.</target>
<note />
</trans-unit>
<trans-unit id="CodeAction_{0}_did_not_produce_a_changed_solution">
<source>CodeAction '{0}' did not produce a changed solution</source>
<target state="translated">Le CodeAction '{0}' n'a pas produit de solution contenant des changements</target>
<note>"CodeAction" is a specific type, and {0} represents the title shown by the action.</note>
</trans-unit>
<trans-unit id="Core_EditorConfig_Options">
<source>Core EditorConfig Options</source>
<target state="translated">Options EditorConfig principales</target>
<note />
</trans-unit>
<trans-unit id="DateTimeKind_must_be_Utc">
<source>DateTimeKind must be Utc</source>
<target state="translated">DateTimeKind doit être UTC</target>
<note />
</trans-unit>
<trans-unit id="Destination_type_must_be_a_0_1_2_or_3_but_given_one_is_4">
<source>Destination type must be a {0}, {1}, {2} or {3}, but given one is {4}.</source>
<target state="translated">Le type de destination doit être {0}, {1}, {2} ou {3}, mais le type spécifié est {4}.</target>
<note />
</trans-unit>
<trans-unit id="Document_does_not_support_syntax_trees">
<source>Document does not support syntax trees</source>
<target state="translated">Le document ne prend pas en charge les arborescences de syntaxe</target>
<note />
</trans-unit>
<trans-unit id="Error_reading_content_of_source_file_0_1">
<source>Error reading content of source file '{0}' -- '{1}'.</source>
<target state="translated">Erreur durant la lecture du contenu du fichier source '{0}' -- '{1}'.</target>
<note />
</trans-unit>
<trans-unit id="Indentation_and_spacing">
<source>Indentation and spacing</source>
<target state="translated">Indentation et espacement</target>
<note />
</trans-unit>
<trans-unit id="New_line_preferences">
<source>New line preferences</source>
<target state="translated">Préférences de nouvelle ligne</target>
<note />
</trans-unit>
<trans-unit id="Only_submission_project_can_reference_submission_projects">
<source>Only submission project can reference submission projects.</source>
<target state="translated">Seul un projet de soumission peut référencer des projets de soumission.</target>
<note />
</trans-unit>
<trans-unit id="Options_did_not_come_from_specified_Solution">
<source>Options did not come from specified Solution</source>
<target state="translated">Les options ne proviennent pas de la solution spécifiée</target>
<note />
</trans-unit>
<trans-unit id="Predefined_conversion_from_0_to_1">
<source>Predefined conversion from {0} to {1}.</source>
<target state="translated">Conversion prédéfinie de {0} en {1}.</target>
<note />
</trans-unit>
<trans-unit id="Project_does_not_contain_specified_reference">
<source>Project does not contain specified reference</source>
<target state="translated">Le projet ne contient pas la référence spécifiée</target>
<note />
</trans-unit>
<trans-unit id="Refactoring_Only">
<source>Refactoring Only</source>
<target state="translated">Refactorisation uniquement</target>
<note />
</trans-unit>
<trans-unit id="Remove_the_line_below_if_you_want_to_inherit_dot_editorconfig_settings_from_higher_directories">
<source>Remove the line below if you want to inherit .editorconfig settings from higher directories</source>
<target state="translated">Supprimer la ligne ci-dessous si vous voulez hériter les paramètres .editorconfig des répertoires supérieurs</target>
<note />
</trans-unit>
<trans-unit id="Removing_analyzer_config_documents_is_not_supported">
<source>Removing analyzer config documents is not supported.</source>
<target state="translated">La suppression de documents de configuration de l'analyseur n'est pas prise en charge.</target>
<note />
</trans-unit>
<trans-unit id="Rename_0_to_1">
<source>Rename '{0}' to '{1}'</source>
<target state="translated">Renommer '{0}' en '{1}'</target>
<note />
</trans-unit>
<trans-unit id="Solution_does_not_contain_specified_reference">
<source>Solution does not contain specified reference</source>
<target state="translated">La solution ne contient pas la référence spécifiée</target>
<note />
</trans-unit>
<trans-unit id="Symbol_0_is_not_from_source">
<source>Symbol "{0}" is not from source.</source>
<target state="translated">Le symbole "{0}" ne provient pas de la source.</target>
<note />
</trans-unit>
<trans-unit id="Documentation_comment_id_must_start_with_E_F_M_N_P_or_T">
<source>Documentation comment id must start with E, F, M, N, P or T</source>
<target state="translated">L'ID du commentaire de documentation doit commencer par E, F, M, N, P ou T</target>
<note />
</trans-unit>
<trans-unit id="Cycle_detected_in_extensions">
<source>Cycle detected in extensions</source>
<target state="translated">Cycle détecté dans les extensions</target>
<note />
</trans-unit>
<trans-unit id="Destination_type_must_be_a_0_but_given_one_is_1">
<source>Destination type must be a {0}, but given one is {1}.</source>
<target state="translated">Le type de destination doit être un {0}, mais le type donné est {1}.</target>
<note />
</trans-unit>
<trans-unit id="Destination_type_must_be_a_0_or_a_1_but_given_one_is_2">
<source>Destination type must be a {0} or a {1}, but given one is {2}.</source>
<target state="translated">Le type de destination doit être un {0} ou un {1}, mais le type donné est {2}.</target>
<note />
</trans-unit>
<trans-unit id="Destination_type_must_be_a_0_1_or_2_but_given_one_is_3">
<source>Destination type must be a {0}, {1} or {2}, but given one is {3}.</source>
<target state="translated">Le type de destination doit être un {0}, {1} ou {2}, mais le type donné est {3}.</target>
<note />
</trans-unit>
<trans-unit id="Could_not_find_location_to_generation_symbol_into">
<source>Could not find location to generation symbol into.</source>
<target state="translated">L'emplacement dans lequel générer le symbole est introuvable.</target>
<note />
</trans-unit>
<trans-unit id="No_location_provided_to_add_statements_to">
<source>No location provided to add statements to.</source>
<target state="translated">Aucun emplacement n'a été fourni pour l'ajout d'instructions.</target>
<note />
</trans-unit>
<trans-unit id="Destination_location_was_not_in_source">
<source>Destination location was not in source.</source>
<target state="translated">L'emplacement de destination n'était pas dans la source.</target>
<note />
</trans-unit>
<trans-unit id="Destination_location_was_from_a_different_tree">
<source>Destination location was from a different tree.</source>
<target state="translated">L'emplacement de destination provient d'une arborescence différente.</target>
<note />
</trans-unit>
<trans-unit id="Node_is_of_the_wrong_type">
<source>Node is of the wrong type.</source>
<target state="translated">Le type de nœud est incorrect.</target>
<note />
</trans-unit>
<trans-unit id="Location_must_be_null_or_from_source">
<source>Location must be null or from source.</source>
<target state="translated">L'emplacement doit être null ou dans la source.</target>
<note />
</trans-unit>
<trans-unit id="Duplicate_source_file_0_in_project_1">
<source>Duplicate source file '{0}' in project '{1}'</source>
<target state="translated">Dupliquer le fichier source '{0}' dans le projet '{1}'</target>
<note />
</trans-unit>
<trans-unit id="Removing_projects_is_not_supported">
<source>Removing projects is not supported.</source>
<target state="translated">La suppression de projets n'est pas prise en charge.</target>
<note />
</trans-unit>
<trans-unit id="Adding_projects_is_not_supported">
<source>Adding projects is not supported.</source>
<target state="translated">L'ajout de projets n'est pas pris en charge.</target>
<note />
</trans-unit>
<trans-unit id="Symbols_project_could_not_be_found_in_the_provided_solution">
<source>Symbol's project could not be found in the provided solution</source>
<target state="translated">Le projet de symbole est introuvable dans la solution fournie</target>
<note />
</trans-unit>
<trans-unit id="Sync_namespace_to_folder_structure">
<source>Sync namespace to folder structure</source>
<target state="translated">Synchroniser l'espace de noms avec la structure de dossier</target>
<note />
</trans-unit>
<trans-unit id="The_contents_of_a_SourceGeneratedDocument_may_not_be_changed">
<source>The contents of a SourceGeneratedDocument may not be changed.</source>
<target state="translated">Le contenu de SourceGeneratedDocument ne doit pas être changé.</target>
<note>{locked:SourceGeneratedDocument}</note>
</trans-unit>
<trans-unit id="The_project_already_contains_the_specified_reference">
<source>The project already contains the specified reference.</source>
<target state="translated">Le projet contient déjà la référence spécifiée.</target>
<note />
</trans-unit>
<trans-unit id="The_solution_already_contains_the_specified_reference">
<source>The solution already contains the specified reference.</source>
<target state="translated">La solution contient déjà la référence spécifiée.</target>
<note />
</trans-unit>
<trans-unit id="Unknown">
<source>Unknown</source>
<target state="translated">Inconnue</target>
<note />
</trans-unit>
<trans-unit id="Visual_Basic_files">
<source>Visual Basic files</source>
<target state="translated">Fichiers Visual Basic</target>
<note />
</trans-unit>
<trans-unit id="Warning_adding_imports_will_bring_an_extension_method_into_scope_with_the_same_name_as_member_access">
<source>Adding imports will bring an extension method into scope with the same name as '{0}'</source>
<target state="translated">L'ajout d'importations place une méthode d'extension dans l'étendue avec le même nom que « {0} »</target>
<note />
</trans-unit>
<trans-unit id="Workspace_error">
<source>Workspace error</source>
<target state="translated">Erreur de l'espace de travail</target>
<note />
</trans-unit>
<trans-unit id="Workspace_is_not_empty">
<source>Workspace is not empty.</source>
<target state="translated">L'espace de travail n'est pas vide.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_in_a_different_project">
<source>{0} is in a different project.</source>
<target state="translated">{0} est dans un autre projet.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_not_part_of_the_workspace">
<source>'{0}' is not part of the workspace.</source>
<target state="translated">'{0}' ne fait pas partie de l'espace de travail.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_already_part_of_the_workspace">
<source>'{0}' is already part of the workspace.</source>
<target state="translated">'{0}' fait déjà partie de l'espace de travail.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_not_referenced">
<source>'{0}' is not referenced.</source>
<target state="translated">'{0}' n'est pas référencé.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_already_referenced">
<source>'{0}' is already referenced.</source>
<target state="translated">'{0}' est déjà référencé.</target>
<note />
</trans-unit>
<trans-unit id="Adding_project_reference_from_0_to_1_will_cause_a_circular_reference">
<source>Adding project reference from '{0}' to '{1}' will cause a circular reference.</source>
<target state="translated">L'ajout d'une référence de projet de '{0}' à '{1}' provoquera une référence circulaire.</target>
<note />
</trans-unit>
<trans-unit id="Metadata_is_not_referenced">
<source>Metadata is not referenced.</source>
<target state="translated">Les métadonnées ne sont pas référencées.</target>
<note />
</trans-unit>
<trans-unit id="Metadata_is_already_referenced">
<source>Metadata is already referenced.</source>
<target state="translated">Les métadonnées sont déjà référencées.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_not_present">
<source>{0} is not present.</source>
<target state="translated">{0} n'est pas présent.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_already_present">
<source>{0} is already present.</source>
<target state="translated">{0} est déjà présent.</target>
<note />
</trans-unit>
<trans-unit id="The_specified_document_is_not_a_version_of_this_document">
<source>The specified document is not a version of this document.</source>
<target state="translated">Le document spécifié n'est pas une version de ce document.</target>
<note />
</trans-unit>
<trans-unit id="The_language_0_is_not_supported">
<source>The language '{0}' is not supported.</source>
<target state="translated">Le langage '{0}' n'est pas pris en charge.</target>
<note />
</trans-unit>
<trans-unit id="The_solution_already_contains_the_specified_project">
<source>The solution already contains the specified project.</source>
<target state="translated">La solution contient déjà le projet spécifié.</target>
<note />
</trans-unit>
<trans-unit id="The_solution_does_not_contain_the_specified_project">
<source>The solution does not contain the specified project.</source>
<target state="translated">La solution ne contient pas le projet spécifié.</target>
<note />
</trans-unit>
<trans-unit id="The_project_already_references_the_target_project">
<source>The project already references the target project.</source>
<target state="translated">Le projet référence déjà le projet cible.</target>
<note />
</trans-unit>
<trans-unit id="The_solution_already_contains_the_specified_document">
<source>The solution already contains the specified document.</source>
<target state="translated">La solution contient déjà le document spécifié.</target>
<note />
</trans-unit>
<trans-unit id="Temporary_storage_cannot_be_written_more_than_once">
<source>Temporary storage cannot be written more than once.</source>
<target state="translated">Il est impossible d'écrire plusieurs fois dans le stockage temporaire.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_not_open">
<source>'{0}' is not open.</source>
<target state="translated">'{0}' n'est pas ouvert.</target>
<note />
</trans-unit>
<trans-unit id="A_language_name_cannot_be_specified_for_this_option">
<source>A language name cannot be specified for this option.</source>
<target state="translated">Impossible de spécifier un nom de langage pour cette option.</target>
<note />
</trans-unit>
<trans-unit id="A_language_name_must_be_specified_for_this_option">
<source>A language name must be specified for this option.</source>
<target state="translated">Un nom de langage doit être spécifié pour cette option.</target>
<note />
</trans-unit>
<trans-unit id="File_was_externally_modified_colon_0">
<source>File was externally modified: {0}.</source>
<target state="translated">Le fichier a été modifié en externe : {0}.</target>
<note />
</trans-unit>
<trans-unit id="Unrecognized_language_name">
<source>Unrecognized language name.</source>
<target state="translated">Nom de langage non reconnu.</target>
<note />
</trans-unit>
<trans-unit id="Can_t_resolve_metadata_reference_colon_0">
<source>Can't resolve metadata reference: '{0}'.</source>
<target state="translated">Impossible de résoudre la référence de métadonnées : '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="Can_t_resolve_analyzer_reference_colon_0">
<source>Can't resolve analyzer reference: '{0}'.</source>
<target state="translated">Impossible de résoudre la référence de l'analyseur : '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="Invalid_project_block_expected_after_Project">
<source>Invalid project block, expected "=" after Project.</source>
<target state="translated">Bloc de projet non valide, "=" attendu après Project.</target>
<note />
</trans-unit>
<trans-unit id="Invalid_project_block_expected_after_project_name">
<source>Invalid project block, expected "," after project name.</source>
<target state="translated">Bloc de projet non valide, "," attendu après le nom du projet.</target>
<note />
</trans-unit>
<trans-unit id="Invalid_project_block_expected_after_project_path">
<source>Invalid project block, expected "," after project path.</source>
<target state="translated">Bloc de projet non valide, "," attendu après le chemin d'accès au projet.</target>
<note />
</trans-unit>
<trans-unit id="Expected_0">
<source>Expected {0}.</source>
<target state="translated">{0} attendu.</target>
<note />
</trans-unit>
<trans-unit id="_0_must_be_a_non_null_and_non_empty_string">
<source>"{0}" must be a non-null and non-empty string.</source>
<target state="translated">"{0}" doit être une chaîne non null et non vide.</target>
<note />
</trans-unit>
<trans-unit id="Expected_header_colon_0">
<source>Expected header: "{0}".</source>
<target state="translated">En-tête attendu : "{0}".</target>
<note />
</trans-unit>
<trans-unit id="Expected_end_of_file">
<source>Expected end-of-file.</source>
<target state="translated">Fin de fichier attendue.</target>
<note />
</trans-unit>
<trans-unit id="Expected_0_line">
<source>Expected {0} line.</source>
<target state="translated">Ligne {0} attendue.</target>
<note />
</trans-unit>
<trans-unit id="This_submission_already_references_another_submission_project">
<source>This submission already references another submission project.</source>
<target state="translated">Cette soumission référence déjà un autre projet de soumission.</target>
<note />
</trans-unit>
<trans-unit id="_0_still_contains_open_documents">
<source>{0} still contains open documents.</source>
<target state="translated">{0} contient encore des documents ouverts.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_still_open">
<source>{0} is still open.</source>
<target state="translated">{0} est toujours ouvert.</target>
<note />
</trans-unit>
<trans-unit id="Arrays_with_more_than_one_dimension_cannot_be_serialized">
<source>Arrays with more than one dimension cannot be serialized.</source>
<target state="translated">Impossible de sérialiser les tableaux de plus d'une dimension.</target>
<note />
</trans-unit>
<trans-unit id="Value_too_large_to_be_represented_as_a_30_bit_unsigned_integer">
<source>Value too large to be represented as a 30 bit unsigned integer.</source>
<target state="translated">La valeur est trop grande pour être représentée comme un entier non signé 30 bits.</target>
<note />
</trans-unit>
<trans-unit id="Specified_path_must_be_absolute">
<source>Specified path must be absolute.</source>
<target state="translated">Le chemin d'accès spécifié doit être absolu.</target>
<note />
</trans-unit>
<trans-unit id="Name_can_be_simplified">
<source>Name can be simplified.</source>
<target state="translated">Le nom peut être simplifié.</target>
<note />
</trans-unit>
<trans-unit id="Unknown_identifier">
<source>Unknown identifier.</source>
<target state="translated">Identificateur inconnu.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_generate_code_for_unsupported_operator_0">
<source>Cannot generate code for unsupported operator '{0}'</source>
<target state="translated">Impossible de générer du code pour l'opérateur non pris en charge '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Invalid_number_of_parameters_for_binary_operator">
<source>Invalid number of parameters for binary operator.</source>
<target state="translated">Nombre de paramètres non valide pour l'opérateur binaire.</target>
<note />
</trans-unit>
<trans-unit id="Invalid_number_of_parameters_for_unary_operator">
<source>Invalid number of parameters for unary operator.</source>
<target state="translated">Nombre de paramètres non valide pour l'opérateur unaire.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language">
<source>Cannot open project '{0}' because the file extension '{1}' is not associated with a language.</source>
<target state="translated">Impossible d'ouvrir le projet '{0}', car l'extension de fichier '{1}' n'est pas associée à un langage.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_open_project_0_because_the_language_1_is_not_supported">
<source>Cannot open project '{0}' because the language '{1}' is not supported.</source>
<target state="translated">Impossible d'ouvrir le projet '{0}', car le langage '{1}' n'est pas pris en charge.</target>
<note />
</trans-unit>
<trans-unit id="Invalid_project_file_path_colon_0">
<source>Invalid project file path: '{0}'</source>
<target state="translated">Chemin d'accès au fichier de projet non valide : '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Invalid_solution_file_path_colon_0">
<source>Invalid solution file path: '{0}'</source>
<target state="translated">Chemin d'accès au fichier de solution non valide : '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Project_file_not_found_colon_0">
<source>Project file not found: '{0}'</source>
<target state="translated">Fichier de projet introuvable : '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Solution_file_not_found_colon_0">
<source>Solution file not found: '{0}'</source>
<target state="translated">Fichier solution introuvable : '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Unmerged_change_from_project_0">
<source>Unmerged change from project '{0}'</source>
<target state="translated">Modification non fusionnée à partir du projet '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Added_colon">
<source>Added:</source>
<target state="translated">Ajouté :</target>
<note />
</trans-unit>
<trans-unit id="After_colon">
<source>After:</source>
<target state="translated">Après :</target>
<note />
</trans-unit>
<trans-unit id="Before_colon">
<source>Before:</source>
<target state="translated">Avant :</target>
<note />
</trans-unit>
<trans-unit id="Removed_colon">
<source>Removed:</source>
<target state="translated">Supprimé :</target>
<note />
</trans-unit>
<trans-unit id="Invalid_CodePage_value_colon_0">
<source>Invalid CodePage value: {0}</source>
<target state="translated">Valeur de CodePage non valide : {0}</target>
<note />
</trans-unit>
<trans-unit id="Adding_additional_documents_is_not_supported">
<source>Adding additional documents is not supported.</source>
<target state="translated">L'ajout de documents supplémentaires n'est pas pris en charge.</target>
<note />
</trans-unit>
<trans-unit id="Adding_analyzer_references_is_not_supported">
<source>Adding analyzer references is not supported.</source>
<target state="translated">L'ajout de références de l'analyseur n'est pas pris en charge.</target>
<note />
</trans-unit>
<trans-unit id="Adding_documents_is_not_supported">
<source>Adding documents is not supported.</source>
<target state="translated">L'ajout de documents n'est pas pris en charge.</target>
<note />
</trans-unit>
<trans-unit id="Adding_metadata_references_is_not_supported">
<source>Adding metadata references is not supported.</source>
<target state="translated">L'ajout de références de métadonnées n'est pas pris en charge.</target>
<note />
</trans-unit>
<trans-unit id="Adding_project_references_is_not_supported">
<source>Adding project references is not supported.</source>
<target state="translated">L'ajout de références de projet n'est pas pris en charge.</target>
<note />
</trans-unit>
<trans-unit id="Changing_additional_documents_is_not_supported">
<source>Changing additional documents is not supported.</source>
<target state="translated">La modification de documents supplémentaires n'est pas prise en charge.</target>
<note />
</trans-unit>
<trans-unit id="Changing_documents_is_not_supported">
<source>Changing documents is not supported.</source>
<target state="translated">La modification de documents n'est pas prise en charge.</target>
<note />
</trans-unit>
<trans-unit id="Changing_project_properties_is_not_supported">
<source>Changing project properties is not supported.</source>
<target state="translated">La modification des propriétés de projet n'est pas prise en charge.</target>
<note />
</trans-unit>
<trans-unit id="Removing_additional_documents_is_not_supported">
<source>Removing additional documents is not supported.</source>
<target state="translated">La suppression de documents supplémentaires n'est pas prise en charge.</target>
<note />
</trans-unit>
<trans-unit id="Removing_analyzer_references_is_not_supported">
<source>Removing analyzer references is not supported.</source>
<target state="translated">La suppression de références de l'analyseur n'est pas prise en charge.</target>
<note />
</trans-unit>
<trans-unit id="Removing_documents_is_not_supported">
<source>Removing documents is not supported.</source>
<target state="translated">La suppression de documents n'est pas prise en charge.</target>
<note />
</trans-unit>
<trans-unit id="Removing_metadata_references_is_not_supported">
<source>Removing metadata references is not supported.</source>
<target state="translated">La suppression de références de métadonnées n'est pas prise en charge.</target>
<note />
</trans-unit>
<trans-unit id="Removing_project_references_is_not_supported">
<source>Removing project references is not supported.</source>
<target state="translated">La suppression de références de projet n'est pas prise en charge.</target>
<note />
</trans-unit>
<trans-unit id="Service_of_type_0_is_required_to_accomplish_the_task_but_is_not_available_from_the_workspace">
<source>Service of type '{0}' is required to accomplish the task but is not available from the workspace.</source>
<target state="translated">Le service de type '{0}' est nécessaire pour accomplir la tâche mais n'est pas disponible dans l'espace de travail.</target>
<note />
</trans-unit>
<trans-unit id="At_least_one_diagnostic_must_be_supplied">
<source>At least one diagnostic must be supplied.</source>
<target state="translated">Au moins un diagnostic doit être fourni.</target>
<note />
</trans-unit>
<trans-unit id="Diagnostic_must_have_span_0">
<source>Diagnostic must have span '{0}'</source>
<target state="translated">Le diagnostic doit avoir l'étendue '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Cannot_deserialize_type_0">
<source>Cannot deserialize type '{0}'.</source>
<target state="translated">Impossible de désérialiser le type '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_serialize_type_0">
<source>Cannot serialize type '{0}'.</source>
<target state="translated">Impossible de sérialiser le type '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="The_type_0_is_not_understood_by_the_serialization_binder">
<source>The type '{0}' is not understood by the serialization binder.</source>
<target state="translated">Le type '{0}' n'est pas pris en charge par le binder de sérialisation.</target>
<note />
</trans-unit>
<trans-unit id="Label_for_node_0_is_invalid_it_must_be_within_bracket_0_1">
<source>Label for node '{0}' is invalid, it must be within [0, {1}).</source>
<target state="translated">L’étiquette pour le nœud « {0} » n’est pas valide. Elle doit être comprise dans l’intervalle suivant [0, {1}).</target>
<note />
</trans-unit>
<trans-unit id="Matching_nodes_0_and_1_must_have_the_same_label">
<source>Matching nodes '{0}' and '{1}' must have the same label.</source>
<target state="translated">Les nœuds correspondants « {0} » et « {1} » doivent avoir la même étiquette.</target>
<note />
</trans-unit>
<trans-unit id="Node_0_must_be_contained_in_the_new_tree">
<source>Node '{0}' must be contained in the new tree.</source>
<target state="translated">Le nœud « {0} » doit figurer dans la nouvelle arborescence.</target>
<note />
</trans-unit>
<trans-unit id="Node_0_must_be_contained_in_the_old_tree">
<source>Node '{0}' must be contained in the old tree.</source>
<target state="translated">Le nœud « {0} » doit figurer dans l’ancienne arborescence.</target>
<note />
</trans-unit>
<trans-unit id="The_member_0_is_not_declared_within_the_declaration_of_the_symbol">
<source>The member '{0}' is not declared within the declaration of the symbol.</source>
<target state="translated">Le membre « {0} » n’est pas déclaré dans la déclaration du symbole.</target>
<note />
</trans-unit>
<trans-unit id="The_position_is_not_within_the_symbol_s_declaration">
<source>The position is not within the symbol's declaration</source>
<target state="translated">La position ne se trouve pas dans la déclaration du symbole</target>
<note />
</trans-unit>
<trans-unit id="The_symbol_0_cannot_be_located_within_the_current_solution">
<source>The symbol '{0}' cannot be located within the current solution.</source>
<target state="translated">Le symbole « {0} » ne peut pas se trouver dans la solution actuelle.</target>
<note />
</trans-unit>
<trans-unit id="Changing_compilation_options_is_not_supported">
<source>Changing compilation options is not supported.</source>
<target state="translated">La modification des options de compilation n’est pas prise en charge.</target>
<note />
</trans-unit>
<trans-unit id="Changing_parse_options_is_not_supported">
<source>Changing parse options is not supported.</source>
<target state="translated">La modification des options d’analyse n’est pas prise en charge.</target>
<note />
</trans-unit>
<trans-unit id="The_node_is_not_part_of_the_tree">
<source>The node is not part of the tree.</source>
<target state="translated">Le nœud ne fait pas partie de l'arborescence.</target>
<note />
</trans-unit>
<trans-unit id="This_workspace_does_not_support_opening_and_closing_documents">
<source>This workspace does not support opening and closing documents.</source>
<target state="translated">Cet espace de travail ne prend pas en charge l'ouverture et la fermeture de documents.</target>
<note />
</trans-unit>
<trans-unit id="Exceptions_colon">
<source>Exceptions:</source>
<target state="translated">Exceptions :</target>
<note />
</trans-unit>
<trans-unit id="_0_returned_an_uninitialized_ImmutableArray">
<source>'{0}' returned an uninitialized ImmutableArray</source>
<target state="translated">'{0}' a retourné un ImmutableArray non initialisé</target>
<note />
</trans-unit>
<trans-unit id="Failure">
<source>Failure</source>
<target state="translated">Échec</target>
<note />
</trans-unit>
<trans-unit id="Warning">
<source>Warning</source>
<target state="translated">Avertissement</target>
<note />
</trans-unit>
<trans-unit id="Enable">
<source>Enable</source>
<target state="translated">Activer</target>
<note />
</trans-unit>
<trans-unit id="Enable_and_ignore_future_errors">
<source>Enable and ignore future errors</source>
<target state="translated">Activer et ignorer les futures erreurs</target>
<note />
</trans-unit>
<trans-unit id="_0_encountered_an_error_and_has_been_disabled">
<source>'{0}' encountered an error and has been disabled.</source>
<target state="translated">'{0}' a rencontré une erreur et a été désactivé.</target>
<note />
</trans-unit>
<trans-unit id="Show_Stack_Trace">
<source>Show Stack Trace</source>
<target state="translated">Afficher l'arborescence des appels de procédure</target>
<note />
</trans-unit>
<trans-unit id="Stream_is_too_long">
<source>Stream is too long.</source>
<target state="translated">Le flux est trop long.</target>
<note />
</trans-unit>
<trans-unit id="Deserialization_reader_for_0_read_incorrect_number_of_values">
<source>Deserialization reader for '{0}' read incorrect number of values.</source>
<target state="translated">Le lecteur de désérialisation pour '{0}' a lu un nombre incorrect de valeurs.</target>
<note />
</trans-unit>
<trans-unit id="Async_Method">
<source>Async Method</source>
<target state="translated">Méthode async</target>
<note>{locked: async}{locked: method} These are keywords (unless the order of words or capitalization should be handled differently)</note>
</trans-unit>
<trans-unit id="Error">
<source>Error</source>
<target state="translated">Erreur</target>
<note />
</trans-unit>
<trans-unit id="None">
<source>None</source>
<target state="translated">Aucun(e)</target>
<note />
</trans-unit>
<trans-unit id="Suggestion">
<source>Suggestion</source>
<target state="translated">Suggestion</target>
<note />
</trans-unit>
<trans-unit id="File_0_size_of_1_exceeds_maximum_allowed_size_of_2">
<source>File '{0}' size of {1} exceeds maximum allowed size of {2}</source>
<target state="translated">Le fichier '{0}' de {1} dépasse la taille maximale autorisée de {2}</target>
<note />
</trans-unit>
<trans-unit id="Changing_document_property_is_not_supported">
<source>Changing document properties is not supported</source>
<target state="translated">Le changement des propriétés du document n'est pas pris en charge</target>
<note />
</trans-unit>
<trans-unit id="dot_NET_Coding_Conventions">
<source>.NET Coding Conventions</source>
<target state="translated">Conventions de codage .NET</target>
<note />
</trans-unit>
<trans-unit id="Variables_captured_colon">
<source>Variables captured:</source>
<target state="translated">Variables capturées :</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="fr" original="../WorkspacesResources.resx">
<body>
<trans-unit id="A_project_may_not_reference_itself">
<source>A project may not reference itself.</source>
<target state="translated">Un projet ne peut pas se référencer lui-même.</target>
<note />
</trans-unit>
<trans-unit id="Adding_analyzer_config_documents_is_not_supported">
<source>Adding analyzer config documents is not supported.</source>
<target state="translated">L'ajout de documents de configuration de l'analyseur n'est pas pris en charge.</target>
<note />
</trans-unit>
<trans-unit id="An_error_occurred_while_reading_the_specified_configuration_file_colon_0">
<source>An error occurred while reading the specified configuration file: {0}</source>
<target state="translated">Une erreur s'est produite lors de la lecture du fichier de configuration spécifié : {0}</target>
<note />
</trans-unit>
<trans-unit id="CSharp_files">
<source>C# files</source>
<target state="translated">Fichiers C#</target>
<note />
</trans-unit>
<trans-unit id="Cannot_apply_action_that_is_not_in_0">
<source>Cannot apply action that is not in '{0}'</source>
<target state="translated">Impossible d'appliquer l'action qui n'est pas dans '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Changing_analyzer_config_documents_is_not_supported">
<source>Changing analyzer config documents is not supported.</source>
<target state="translated">L'apport de changements aux documents de configuration de l'analyseur n'est pas pris en charge.</target>
<note />
</trans-unit>
<trans-unit id="Changing_document_0_is_not_supported">
<source>Changing document '{0}' is not supported.</source>
<target state="translated">Le changement du document '{0}' n'est pas pris en charge.</target>
<note />
</trans-unit>
<trans-unit id="CodeAction_{0}_did_not_produce_a_changed_solution">
<source>CodeAction '{0}' did not produce a changed solution</source>
<target state="translated">Le CodeAction '{0}' n'a pas produit de solution contenant des changements</target>
<note>"CodeAction" is a specific type, and {0} represents the title shown by the action.</note>
</trans-unit>
<trans-unit id="Core_EditorConfig_Options">
<source>Core EditorConfig Options</source>
<target state="translated">Options EditorConfig principales</target>
<note />
</trans-unit>
<trans-unit id="DateTimeKind_must_be_Utc">
<source>DateTimeKind must be Utc</source>
<target state="translated">DateTimeKind doit être UTC</target>
<note />
</trans-unit>
<trans-unit id="Destination_type_must_be_a_0_1_2_or_3_but_given_one_is_4">
<source>Destination type must be a {0}, {1}, {2} or {3}, but given one is {4}.</source>
<target state="translated">Le type de destination doit être {0}, {1}, {2} ou {3}, mais le type spécifié est {4}.</target>
<note />
</trans-unit>
<trans-unit id="Document_does_not_support_syntax_trees">
<source>Document does not support syntax trees</source>
<target state="translated">Le document ne prend pas en charge les arborescences de syntaxe</target>
<note />
</trans-unit>
<trans-unit id="Error_reading_content_of_source_file_0_1">
<source>Error reading content of source file '{0}' -- '{1}'.</source>
<target state="translated">Erreur durant la lecture du contenu du fichier source '{0}' -- '{1}'.</target>
<note />
</trans-unit>
<trans-unit id="Indentation_and_spacing">
<source>Indentation and spacing</source>
<target state="translated">Indentation et espacement</target>
<note />
</trans-unit>
<trans-unit id="New_line_preferences">
<source>New line preferences</source>
<target state="translated">Préférences de nouvelle ligne</target>
<note />
</trans-unit>
<trans-unit id="Only_submission_project_can_reference_submission_projects">
<source>Only submission project can reference submission projects.</source>
<target state="translated">Seul un projet de soumission peut référencer des projets de soumission.</target>
<note />
</trans-unit>
<trans-unit id="Options_did_not_come_from_specified_Solution">
<source>Options did not come from specified Solution</source>
<target state="translated">Les options ne proviennent pas de la solution spécifiée</target>
<note />
</trans-unit>
<trans-unit id="Predefined_conversion_from_0_to_1">
<source>Predefined conversion from {0} to {1}.</source>
<target state="translated">Conversion prédéfinie de {0} en {1}.</target>
<note />
</trans-unit>
<trans-unit id="Project_does_not_contain_specified_reference">
<source>Project does not contain specified reference</source>
<target state="translated">Le projet ne contient pas la référence spécifiée</target>
<note />
</trans-unit>
<trans-unit id="Refactoring_Only">
<source>Refactoring Only</source>
<target state="translated">Refactorisation uniquement</target>
<note />
</trans-unit>
<trans-unit id="Remove_the_line_below_if_you_want_to_inherit_dot_editorconfig_settings_from_higher_directories">
<source>Remove the line below if you want to inherit .editorconfig settings from higher directories</source>
<target state="translated">Supprimer la ligne ci-dessous si vous voulez hériter les paramètres .editorconfig des répertoires supérieurs</target>
<note />
</trans-unit>
<trans-unit id="Removing_analyzer_config_documents_is_not_supported">
<source>Removing analyzer config documents is not supported.</source>
<target state="translated">La suppression de documents de configuration de l'analyseur n'est pas prise en charge.</target>
<note />
</trans-unit>
<trans-unit id="Rename_0_to_1">
<source>Rename '{0}' to '{1}'</source>
<target state="translated">Renommer '{0}' en '{1}'</target>
<note />
</trans-unit>
<trans-unit id="Solution_does_not_contain_specified_reference">
<source>Solution does not contain specified reference</source>
<target state="translated">La solution ne contient pas la référence spécifiée</target>
<note />
</trans-unit>
<trans-unit id="Symbol_0_is_not_from_source">
<source>Symbol "{0}" is not from source.</source>
<target state="translated">Le symbole "{0}" ne provient pas de la source.</target>
<note />
</trans-unit>
<trans-unit id="Documentation_comment_id_must_start_with_E_F_M_N_P_or_T">
<source>Documentation comment id must start with E, F, M, N, P or T</source>
<target state="translated">L'ID du commentaire de documentation doit commencer par E, F, M, N, P ou T</target>
<note />
</trans-unit>
<trans-unit id="Cycle_detected_in_extensions">
<source>Cycle detected in extensions</source>
<target state="translated">Cycle détecté dans les extensions</target>
<note />
</trans-unit>
<trans-unit id="Destination_type_must_be_a_0_but_given_one_is_1">
<source>Destination type must be a {0}, but given one is {1}.</source>
<target state="translated">Le type de destination doit être un {0}, mais le type donné est {1}.</target>
<note />
</trans-unit>
<trans-unit id="Destination_type_must_be_a_0_or_a_1_but_given_one_is_2">
<source>Destination type must be a {0} or a {1}, but given one is {2}.</source>
<target state="translated">Le type de destination doit être un {0} ou un {1}, mais le type donné est {2}.</target>
<note />
</trans-unit>
<trans-unit id="Destination_type_must_be_a_0_1_or_2_but_given_one_is_3">
<source>Destination type must be a {0}, {1} or {2}, but given one is {3}.</source>
<target state="translated">Le type de destination doit être un {0}, {1} ou {2}, mais le type donné est {3}.</target>
<note />
</trans-unit>
<trans-unit id="Could_not_find_location_to_generation_symbol_into">
<source>Could not find location to generation symbol into.</source>
<target state="translated">L'emplacement dans lequel générer le symbole est introuvable.</target>
<note />
</trans-unit>
<trans-unit id="No_location_provided_to_add_statements_to">
<source>No location provided to add statements to.</source>
<target state="translated">Aucun emplacement n'a été fourni pour l'ajout d'instructions.</target>
<note />
</trans-unit>
<trans-unit id="Destination_location_was_not_in_source">
<source>Destination location was not in source.</source>
<target state="translated">L'emplacement de destination n'était pas dans la source.</target>
<note />
</trans-unit>
<trans-unit id="Destination_location_was_from_a_different_tree">
<source>Destination location was from a different tree.</source>
<target state="translated">L'emplacement de destination provient d'une arborescence différente.</target>
<note />
</trans-unit>
<trans-unit id="Node_is_of_the_wrong_type">
<source>Node is of the wrong type.</source>
<target state="translated">Le type de nœud est incorrect.</target>
<note />
</trans-unit>
<trans-unit id="Location_must_be_null_or_from_source">
<source>Location must be null or from source.</source>
<target state="translated">L'emplacement doit être null ou dans la source.</target>
<note />
</trans-unit>
<trans-unit id="Duplicate_source_file_0_in_project_1">
<source>Duplicate source file '{0}' in project '{1}'</source>
<target state="translated">Dupliquer le fichier source '{0}' dans le projet '{1}'</target>
<note />
</trans-unit>
<trans-unit id="Removing_projects_is_not_supported">
<source>Removing projects is not supported.</source>
<target state="translated">La suppression de projets n'est pas prise en charge.</target>
<note />
</trans-unit>
<trans-unit id="Adding_projects_is_not_supported">
<source>Adding projects is not supported.</source>
<target state="translated">L'ajout de projets n'est pas pris en charge.</target>
<note />
</trans-unit>
<trans-unit id="Symbols_project_could_not_be_found_in_the_provided_solution">
<source>Symbol's project could not be found in the provided solution</source>
<target state="translated">Le projet de symbole est introuvable dans la solution fournie</target>
<note />
</trans-unit>
<trans-unit id="Sync_namespace_to_folder_structure">
<source>Sync namespace to folder structure</source>
<target state="translated">Synchroniser l'espace de noms avec la structure de dossier</target>
<note />
</trans-unit>
<trans-unit id="The_contents_of_a_SourceGeneratedDocument_may_not_be_changed">
<source>The contents of a SourceGeneratedDocument may not be changed.</source>
<target state="translated">Le contenu de SourceGeneratedDocument ne doit pas être changé.</target>
<note>{locked:SourceGeneratedDocument}</note>
</trans-unit>
<trans-unit id="The_project_already_contains_the_specified_reference">
<source>The project already contains the specified reference.</source>
<target state="translated">Le projet contient déjà la référence spécifiée.</target>
<note />
</trans-unit>
<trans-unit id="The_solution_already_contains_the_specified_reference">
<source>The solution already contains the specified reference.</source>
<target state="translated">La solution contient déjà la référence spécifiée.</target>
<note />
</trans-unit>
<trans-unit id="Unknown">
<source>Unknown</source>
<target state="translated">Inconnue</target>
<note />
</trans-unit>
<trans-unit id="Visual_Basic_files">
<source>Visual Basic files</source>
<target state="translated">Fichiers Visual Basic</target>
<note />
</trans-unit>
<trans-unit id="Warning_adding_imports_will_bring_an_extension_method_into_scope_with_the_same_name_as_member_access">
<source>Adding imports will bring an extension method into scope with the same name as '{0}'</source>
<target state="translated">L'ajout d'importations place une méthode d'extension dans l'étendue avec le même nom que « {0} »</target>
<note />
</trans-unit>
<trans-unit id="Workspace_error">
<source>Workspace error</source>
<target state="translated">Erreur de l'espace de travail</target>
<note />
</trans-unit>
<trans-unit id="Workspace_is_not_empty">
<source>Workspace is not empty.</source>
<target state="translated">L'espace de travail n'est pas vide.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_in_a_different_project">
<source>{0} is in a different project.</source>
<target state="translated">{0} est dans un autre projet.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_not_part_of_the_workspace">
<source>'{0}' is not part of the workspace.</source>
<target state="translated">'{0}' ne fait pas partie de l'espace de travail.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_already_part_of_the_workspace">
<source>'{0}' is already part of the workspace.</source>
<target state="translated">'{0}' fait déjà partie de l'espace de travail.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_not_referenced">
<source>'{0}' is not referenced.</source>
<target state="translated">'{0}' n'est pas référencé.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_already_referenced">
<source>'{0}' is already referenced.</source>
<target state="translated">'{0}' est déjà référencé.</target>
<note />
</trans-unit>
<trans-unit id="Adding_project_reference_from_0_to_1_will_cause_a_circular_reference">
<source>Adding project reference from '{0}' to '{1}' will cause a circular reference.</source>
<target state="translated">L'ajout d'une référence de projet de '{0}' à '{1}' provoquera une référence circulaire.</target>
<note />
</trans-unit>
<trans-unit id="Metadata_is_not_referenced">
<source>Metadata is not referenced.</source>
<target state="translated">Les métadonnées ne sont pas référencées.</target>
<note />
</trans-unit>
<trans-unit id="Metadata_is_already_referenced">
<source>Metadata is already referenced.</source>
<target state="translated">Les métadonnées sont déjà référencées.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_not_present">
<source>{0} is not present.</source>
<target state="translated">{0} n'est pas présent.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_already_present">
<source>{0} is already present.</source>
<target state="translated">{0} est déjà présent.</target>
<note />
</trans-unit>
<trans-unit id="The_specified_document_is_not_a_version_of_this_document">
<source>The specified document is not a version of this document.</source>
<target state="translated">Le document spécifié n'est pas une version de ce document.</target>
<note />
</trans-unit>
<trans-unit id="The_language_0_is_not_supported">
<source>The language '{0}' is not supported.</source>
<target state="translated">Le langage '{0}' n'est pas pris en charge.</target>
<note />
</trans-unit>
<trans-unit id="The_solution_already_contains_the_specified_project">
<source>The solution already contains the specified project.</source>
<target state="translated">La solution contient déjà le projet spécifié.</target>
<note />
</trans-unit>
<trans-unit id="The_solution_does_not_contain_the_specified_project">
<source>The solution does not contain the specified project.</source>
<target state="translated">La solution ne contient pas le projet spécifié.</target>
<note />
</trans-unit>
<trans-unit id="The_project_already_references_the_target_project">
<source>The project already references the target project.</source>
<target state="translated">Le projet référence déjà le projet cible.</target>
<note />
</trans-unit>
<trans-unit id="The_solution_already_contains_the_specified_document">
<source>The solution already contains the specified document.</source>
<target state="translated">La solution contient déjà le document spécifié.</target>
<note />
</trans-unit>
<trans-unit id="Temporary_storage_cannot_be_written_more_than_once">
<source>Temporary storage cannot be written more than once.</source>
<target state="translated">Il est impossible d'écrire plusieurs fois dans le stockage temporaire.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_not_open">
<source>'{0}' is not open.</source>
<target state="translated">'{0}' n'est pas ouvert.</target>
<note />
</trans-unit>
<trans-unit id="A_language_name_cannot_be_specified_for_this_option">
<source>A language name cannot be specified for this option.</source>
<target state="translated">Impossible de spécifier un nom de langage pour cette option.</target>
<note />
</trans-unit>
<trans-unit id="A_language_name_must_be_specified_for_this_option">
<source>A language name must be specified for this option.</source>
<target state="translated">Un nom de langage doit être spécifié pour cette option.</target>
<note />
</trans-unit>
<trans-unit id="File_was_externally_modified_colon_0">
<source>File was externally modified: {0}.</source>
<target state="translated">Le fichier a été modifié en externe : {0}.</target>
<note />
</trans-unit>
<trans-unit id="Unrecognized_language_name">
<source>Unrecognized language name.</source>
<target state="translated">Nom de langage non reconnu.</target>
<note />
</trans-unit>
<trans-unit id="Can_t_resolve_metadata_reference_colon_0">
<source>Can't resolve metadata reference: '{0}'.</source>
<target state="translated">Impossible de résoudre la référence de métadonnées : '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="Can_t_resolve_analyzer_reference_colon_0">
<source>Can't resolve analyzer reference: '{0}'.</source>
<target state="translated">Impossible de résoudre la référence de l'analyseur : '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="Invalid_project_block_expected_after_Project">
<source>Invalid project block, expected "=" after Project.</source>
<target state="translated">Bloc de projet non valide, "=" attendu après Project.</target>
<note />
</trans-unit>
<trans-unit id="Invalid_project_block_expected_after_project_name">
<source>Invalid project block, expected "," after project name.</source>
<target state="translated">Bloc de projet non valide, "," attendu après le nom du projet.</target>
<note />
</trans-unit>
<trans-unit id="Invalid_project_block_expected_after_project_path">
<source>Invalid project block, expected "," after project path.</source>
<target state="translated">Bloc de projet non valide, "," attendu après le chemin d'accès au projet.</target>
<note />
</trans-unit>
<trans-unit id="Expected_0">
<source>Expected {0}.</source>
<target state="translated">{0} attendu.</target>
<note />
</trans-unit>
<trans-unit id="_0_must_be_a_non_null_and_non_empty_string">
<source>"{0}" must be a non-null and non-empty string.</source>
<target state="translated">"{0}" doit être une chaîne non null et non vide.</target>
<note />
</trans-unit>
<trans-unit id="Expected_header_colon_0">
<source>Expected header: "{0}".</source>
<target state="translated">En-tête attendu : "{0}".</target>
<note />
</trans-unit>
<trans-unit id="Expected_end_of_file">
<source>Expected end-of-file.</source>
<target state="translated">Fin de fichier attendue.</target>
<note />
</trans-unit>
<trans-unit id="Expected_0_line">
<source>Expected {0} line.</source>
<target state="translated">Ligne {0} attendue.</target>
<note />
</trans-unit>
<trans-unit id="This_submission_already_references_another_submission_project">
<source>This submission already references another submission project.</source>
<target state="translated">Cette soumission référence déjà un autre projet de soumission.</target>
<note />
</trans-unit>
<trans-unit id="_0_still_contains_open_documents">
<source>{0} still contains open documents.</source>
<target state="translated">{0} contient encore des documents ouverts.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_still_open">
<source>{0} is still open.</source>
<target state="translated">{0} est toujours ouvert.</target>
<note />
</trans-unit>
<trans-unit id="Arrays_with_more_than_one_dimension_cannot_be_serialized">
<source>Arrays with more than one dimension cannot be serialized.</source>
<target state="translated">Impossible de sérialiser les tableaux de plus d'une dimension.</target>
<note />
</trans-unit>
<trans-unit id="Value_too_large_to_be_represented_as_a_30_bit_unsigned_integer">
<source>Value too large to be represented as a 30 bit unsigned integer.</source>
<target state="translated">La valeur est trop grande pour être représentée comme un entier non signé 30 bits.</target>
<note />
</trans-unit>
<trans-unit id="Specified_path_must_be_absolute">
<source>Specified path must be absolute.</source>
<target state="translated">Le chemin d'accès spécifié doit être absolu.</target>
<note />
</trans-unit>
<trans-unit id="Name_can_be_simplified">
<source>Name can be simplified.</source>
<target state="translated">Le nom peut être simplifié.</target>
<note />
</trans-unit>
<trans-unit id="Unknown_identifier">
<source>Unknown identifier.</source>
<target state="translated">Identificateur inconnu.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_generate_code_for_unsupported_operator_0">
<source>Cannot generate code for unsupported operator '{0}'</source>
<target state="translated">Impossible de générer du code pour l'opérateur non pris en charge '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Invalid_number_of_parameters_for_binary_operator">
<source>Invalid number of parameters for binary operator.</source>
<target state="translated">Nombre de paramètres non valide pour l'opérateur binaire.</target>
<note />
</trans-unit>
<trans-unit id="Invalid_number_of_parameters_for_unary_operator">
<source>Invalid number of parameters for unary operator.</source>
<target state="translated">Nombre de paramètres non valide pour l'opérateur unaire.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language">
<source>Cannot open project '{0}' because the file extension '{1}' is not associated with a language.</source>
<target state="translated">Impossible d'ouvrir le projet '{0}', car l'extension de fichier '{1}' n'est pas associée à un langage.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_open_project_0_because_the_language_1_is_not_supported">
<source>Cannot open project '{0}' because the language '{1}' is not supported.</source>
<target state="translated">Impossible d'ouvrir le projet '{0}', car le langage '{1}' n'est pas pris en charge.</target>
<note />
</trans-unit>
<trans-unit id="Invalid_project_file_path_colon_0">
<source>Invalid project file path: '{0}'</source>
<target state="translated">Chemin d'accès au fichier de projet non valide : '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Invalid_solution_file_path_colon_0">
<source>Invalid solution file path: '{0}'</source>
<target state="translated">Chemin d'accès au fichier de solution non valide : '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Project_file_not_found_colon_0">
<source>Project file not found: '{0}'</source>
<target state="translated">Fichier de projet introuvable : '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Solution_file_not_found_colon_0">
<source>Solution file not found: '{0}'</source>
<target state="translated">Fichier solution introuvable : '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Unmerged_change_from_project_0">
<source>Unmerged change from project '{0}'</source>
<target state="translated">Modification non fusionnée à partir du projet '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Added_colon">
<source>Added:</source>
<target state="translated">Ajouté :</target>
<note />
</trans-unit>
<trans-unit id="After_colon">
<source>After:</source>
<target state="translated">Après :</target>
<note />
</trans-unit>
<trans-unit id="Before_colon">
<source>Before:</source>
<target state="translated">Avant :</target>
<note />
</trans-unit>
<trans-unit id="Removed_colon">
<source>Removed:</source>
<target state="translated">Supprimé :</target>
<note />
</trans-unit>
<trans-unit id="Invalid_CodePage_value_colon_0">
<source>Invalid CodePage value: {0}</source>
<target state="translated">Valeur de CodePage non valide : {0}</target>
<note />
</trans-unit>
<trans-unit id="Adding_additional_documents_is_not_supported">
<source>Adding additional documents is not supported.</source>
<target state="translated">L'ajout de documents supplémentaires n'est pas pris en charge.</target>
<note />
</trans-unit>
<trans-unit id="Adding_analyzer_references_is_not_supported">
<source>Adding analyzer references is not supported.</source>
<target state="translated">L'ajout de références de l'analyseur n'est pas pris en charge.</target>
<note />
</trans-unit>
<trans-unit id="Adding_documents_is_not_supported">
<source>Adding documents is not supported.</source>
<target state="translated">L'ajout de documents n'est pas pris en charge.</target>
<note />
</trans-unit>
<trans-unit id="Adding_metadata_references_is_not_supported">
<source>Adding metadata references is not supported.</source>
<target state="translated">L'ajout de références de métadonnées n'est pas pris en charge.</target>
<note />
</trans-unit>
<trans-unit id="Adding_project_references_is_not_supported">
<source>Adding project references is not supported.</source>
<target state="translated">L'ajout de références de projet n'est pas pris en charge.</target>
<note />
</trans-unit>
<trans-unit id="Changing_additional_documents_is_not_supported">
<source>Changing additional documents is not supported.</source>
<target state="translated">La modification de documents supplémentaires n'est pas prise en charge.</target>
<note />
</trans-unit>
<trans-unit id="Changing_documents_is_not_supported">
<source>Changing documents is not supported.</source>
<target state="translated">La modification de documents n'est pas prise en charge.</target>
<note />
</trans-unit>
<trans-unit id="Changing_project_properties_is_not_supported">
<source>Changing project properties is not supported.</source>
<target state="translated">La modification des propriétés de projet n'est pas prise en charge.</target>
<note />
</trans-unit>
<trans-unit id="Removing_additional_documents_is_not_supported">
<source>Removing additional documents is not supported.</source>
<target state="translated">La suppression de documents supplémentaires n'est pas prise en charge.</target>
<note />
</trans-unit>
<trans-unit id="Removing_analyzer_references_is_not_supported">
<source>Removing analyzer references is not supported.</source>
<target state="translated">La suppression de références de l'analyseur n'est pas prise en charge.</target>
<note />
</trans-unit>
<trans-unit id="Removing_documents_is_not_supported">
<source>Removing documents is not supported.</source>
<target state="translated">La suppression de documents n'est pas prise en charge.</target>
<note />
</trans-unit>
<trans-unit id="Removing_metadata_references_is_not_supported">
<source>Removing metadata references is not supported.</source>
<target state="translated">La suppression de références de métadonnées n'est pas prise en charge.</target>
<note />
</trans-unit>
<trans-unit id="Removing_project_references_is_not_supported">
<source>Removing project references is not supported.</source>
<target state="translated">La suppression de références de projet n'est pas prise en charge.</target>
<note />
</trans-unit>
<trans-unit id="Service_of_type_0_is_required_to_accomplish_the_task_but_is_not_available_from_the_workspace">
<source>Service of type '{0}' is required to accomplish the task but is not available from the workspace.</source>
<target state="translated">Le service de type '{0}' est nécessaire pour accomplir la tâche mais n'est pas disponible dans l'espace de travail.</target>
<note />
</trans-unit>
<trans-unit id="At_least_one_diagnostic_must_be_supplied">
<source>At least one diagnostic must be supplied.</source>
<target state="translated">Au moins un diagnostic doit être fourni.</target>
<note />
</trans-unit>
<trans-unit id="Diagnostic_must_have_span_0">
<source>Diagnostic must have span '{0}'</source>
<target state="translated">Le diagnostic doit avoir l'étendue '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Cannot_deserialize_type_0">
<source>Cannot deserialize type '{0}'.</source>
<target state="translated">Impossible de désérialiser le type '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_serialize_type_0">
<source>Cannot serialize type '{0}'.</source>
<target state="translated">Impossible de sérialiser le type '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="The_type_0_is_not_understood_by_the_serialization_binder">
<source>The type '{0}' is not understood by the serialization binder.</source>
<target state="translated">Le type '{0}' n'est pas pris en charge par le binder de sérialisation.</target>
<note />
</trans-unit>
<trans-unit id="Label_for_node_0_is_invalid_it_must_be_within_bracket_0_1">
<source>Label for node '{0}' is invalid, it must be within [0, {1}).</source>
<target state="translated">L’étiquette pour le nœud « {0} » n’est pas valide. Elle doit être comprise dans l’intervalle suivant [0, {1}).</target>
<note />
</trans-unit>
<trans-unit id="Matching_nodes_0_and_1_must_have_the_same_label">
<source>Matching nodes '{0}' and '{1}' must have the same label.</source>
<target state="translated">Les nœuds correspondants « {0} » et « {1} » doivent avoir la même étiquette.</target>
<note />
</trans-unit>
<trans-unit id="Node_0_must_be_contained_in_the_new_tree">
<source>Node '{0}' must be contained in the new tree.</source>
<target state="translated">Le nœud « {0} » doit figurer dans la nouvelle arborescence.</target>
<note />
</trans-unit>
<trans-unit id="Node_0_must_be_contained_in_the_old_tree">
<source>Node '{0}' must be contained in the old tree.</source>
<target state="translated">Le nœud « {0} » doit figurer dans l’ancienne arborescence.</target>
<note />
</trans-unit>
<trans-unit id="The_member_0_is_not_declared_within_the_declaration_of_the_symbol">
<source>The member '{0}' is not declared within the declaration of the symbol.</source>
<target state="translated">Le membre « {0} » n’est pas déclaré dans la déclaration du symbole.</target>
<note />
</trans-unit>
<trans-unit id="The_position_is_not_within_the_symbol_s_declaration">
<source>The position is not within the symbol's declaration</source>
<target state="translated">La position ne se trouve pas dans la déclaration du symbole</target>
<note />
</trans-unit>
<trans-unit id="The_symbol_0_cannot_be_located_within_the_current_solution">
<source>The symbol '{0}' cannot be located within the current solution.</source>
<target state="translated">Le symbole « {0} » ne peut pas se trouver dans la solution actuelle.</target>
<note />
</trans-unit>
<trans-unit id="Changing_compilation_options_is_not_supported">
<source>Changing compilation options is not supported.</source>
<target state="translated">La modification des options de compilation n’est pas prise en charge.</target>
<note />
</trans-unit>
<trans-unit id="Changing_parse_options_is_not_supported">
<source>Changing parse options is not supported.</source>
<target state="translated">La modification des options d’analyse n’est pas prise en charge.</target>
<note />
</trans-unit>
<trans-unit id="The_node_is_not_part_of_the_tree">
<source>The node is not part of the tree.</source>
<target state="translated">Le nœud ne fait pas partie de l'arborescence.</target>
<note />
</trans-unit>
<trans-unit id="This_workspace_does_not_support_opening_and_closing_documents">
<source>This workspace does not support opening and closing documents.</source>
<target state="translated">Cet espace de travail ne prend pas en charge l'ouverture et la fermeture de documents.</target>
<note />
</trans-unit>
<trans-unit id="Exceptions_colon">
<source>Exceptions:</source>
<target state="translated">Exceptions :</target>
<note />
</trans-unit>
<trans-unit id="_0_returned_an_uninitialized_ImmutableArray">
<source>'{0}' returned an uninitialized ImmutableArray</source>
<target state="translated">'{0}' a retourné un ImmutableArray non initialisé</target>
<note />
</trans-unit>
<trans-unit id="Failure">
<source>Failure</source>
<target state="translated">Échec</target>
<note />
</trans-unit>
<trans-unit id="Warning">
<source>Warning</source>
<target state="translated">Avertissement</target>
<note />
</trans-unit>
<trans-unit id="Enable">
<source>Enable</source>
<target state="translated">Activer</target>
<note />
</trans-unit>
<trans-unit id="Enable_and_ignore_future_errors">
<source>Enable and ignore future errors</source>
<target state="translated">Activer et ignorer les futures erreurs</target>
<note />
</trans-unit>
<trans-unit id="_0_encountered_an_error_and_has_been_disabled">
<source>'{0}' encountered an error and has been disabled.</source>
<target state="translated">'{0}' a rencontré une erreur et a été désactivé.</target>
<note />
</trans-unit>
<trans-unit id="Show_Stack_Trace">
<source>Show Stack Trace</source>
<target state="translated">Afficher l'arborescence des appels de procédure</target>
<note />
</trans-unit>
<trans-unit id="Stream_is_too_long">
<source>Stream is too long.</source>
<target state="translated">Le flux est trop long.</target>
<note />
</trans-unit>
<trans-unit id="Deserialization_reader_for_0_read_incorrect_number_of_values">
<source>Deserialization reader for '{0}' read incorrect number of values.</source>
<target state="translated">Le lecteur de désérialisation pour '{0}' a lu un nombre incorrect de valeurs.</target>
<note />
</trans-unit>
<trans-unit id="Async_Method">
<source>Async Method</source>
<target state="translated">Méthode async</target>
<note>{locked: async}{locked: method} These are keywords (unless the order of words or capitalization should be handled differently)</note>
</trans-unit>
<trans-unit id="Error">
<source>Error</source>
<target state="translated">Erreur</target>
<note />
</trans-unit>
<trans-unit id="None">
<source>None</source>
<target state="translated">Aucun(e)</target>
<note />
</trans-unit>
<trans-unit id="Suggestion">
<source>Suggestion</source>
<target state="translated">Suggestion</target>
<note />
</trans-unit>
<trans-unit id="File_0_size_of_1_exceeds_maximum_allowed_size_of_2">
<source>File '{0}' size of {1} exceeds maximum allowed size of {2}</source>
<target state="translated">Le fichier '{0}' de {1} dépasse la taille maximale autorisée de {2}</target>
<note />
</trans-unit>
<trans-unit id="Changing_document_property_is_not_supported">
<source>Changing document properties is not supported</source>
<target state="translated">Le changement des propriétés du document n'est pas pris en charge</target>
<note />
</trans-unit>
<trans-unit id="dot_NET_Coding_Conventions">
<source>.NET Coding Conventions</source>
<target state="translated">Conventions de codage .NET</target>
<note />
</trans-unit>
<trans-unit id="Variables_captured_colon">
<source>Variables captured:</source>
<target state="translated">Variables capturées :</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Compilers/CSharp/Test/Symbol/Symbols/Metadata/PE/LoadingIndexers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Metadata.PE;
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.Symbols.Metadata.PE
{
// CONSIDER: it might be worthwhile to promote some of these sample types to a test resource DLL
public class LoadingIndexers : CSharpTestBase
{
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void LoadReadWriteIndexer()
{
string ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('Item')}
.method public hidebysig specialname instance int32
get_Item(int32 x) cil managed
{
ldc.i4.0
ret
}
.method public hidebysig specialname instance void
set_Item(int32 x,
int32 'value') cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance int32 Item(int32)
{
.get instance int32 C::get_Item(int32)
.set instance void C::set_Item(int32, int32)
}
}
";
CompileWithCustomILSource("", ilSource, compilation =>
{
var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C");
Assert.Equal("Item", @class.DefaultMemberName);
var indexer = @class.GetIndexer<PEPropertySymbol>("Item");
CheckIndexer(indexer, true, true, "System.Int32 C.this[System.Int32 x] { get; set; }");
});
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void LoadWriteOnlyIndexer()
{
string ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('Item')}
.method public hidebysig specialname instance void
set_Item(int32 x,
int32 'value') cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance int32 Item(int32)
{
.set instance void C::set_Item(int32, int32)
}
}
";
CompileWithCustomILSource("", ilSource, compilation =>
{
var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C");
Assert.Equal("Item", @class.DefaultMemberName);
var indexer = @class.GetIndexer<PEPropertySymbol>("Item");
CheckIndexer(indexer, false, true, "System.Int32 C.this[System.Int32 x] { set; }");
});
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void LoadReadOnlyIndexer()
{
string ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('Item')}
.method public hidebysig specialname instance int32
get_Item(int32 x) cil managed
{
ldc.i4.0
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance int32 Item(int32)
{
.get instance int32 C::get_Item(int32)
}
}
";
CompileWithCustomILSource("", ilSource, compilation =>
{
var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C");
Assert.Equal("Item", @class.DefaultMemberName);
var indexer = @class.GetIndexer<PEPropertySymbol>("Item");
CheckIndexer(indexer, true, false, "System.Int32 C.this[System.Int32 x] { get; }");
});
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void LoadIndexerWithAlternateName()
{
string ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('NotItem')}
.method public hidebysig specialname instance int32
get_NotItem(int32 x) cil managed
{
ldc.i4.0
ret
}
.method public hidebysig specialname instance void
set_NotItem(int32 x,
int32 'value') cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance int32 NotItem(int32)
{
.get instance int32 C::get_NotItem(int32)
.set instance void C::set_NotItem(int32, int32)
}
}
";
CompileWithCustomILSource("", ilSource, compilation =>
{
var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C");
Assert.Equal("NotItem", @class.DefaultMemberName);
var indexer = @class.GetIndexer<PEPropertySymbol>("NotItem");
CheckIndexer(indexer, true, true, "System.Int32 C.this[System.Int32 x] { get; set; }");
});
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void LoadIndexerWithAccessorAsDefaultMember()
{
string ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('get_NotItem')}
.method public hidebysig specialname instance int32
get_NotItem(int32 x) cil managed
{
ldc.i4.0
ret
}
.method public hidebysig specialname instance void
set_NotItem(int32 x,
int32 'value') cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance int32 NotItem(int32)
{
.get instance int32 C::get_NotItem(int32)
.set instance void C::set_NotItem(int32, int32)
}
}
";
CompileWithCustomILSource("", ilSource, compilation =>
{
var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C");
Assert.Equal("get_NotItem", @class.DefaultMemberName);
var indexer = @class.GetIndexer<PEPropertySymbol>("NotItem");
CheckIndexer(indexer, true, true, "System.Int32 C.this[System.Int32 x] { get; set; }");
});
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void LoadComplexIndexers()
{
string ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('Accessor1')}
.method public hidebysig specialname instance int32
Accessor1(int32 x, int64 y) cil managed
{
ldc.i4.0
ret
}
.method public hidebysig specialname instance void
Accessor2(int32 x, int64 y,
int32 'value') cil managed
{
ret
}
.method public hidebysig specialname instance void
Accessor3(int32 x, int64 y,
int32 'value') cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance int32 Indexer1(int32, int64)
{
.get instance int32 C::Accessor1(int32, int64)
.set instance void C::Accessor2(int32, int64, int32)
}
.property instance int32 Indexer2(int32, int64)
{
.get instance int32 C::Accessor1(int32, int64)
.set instance void C::Accessor3(int32, int64, int32)
}
}
";
CompileWithCustomILSource("", ilSource, compilation =>
{
var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C");
Assert.Equal("Accessor1", @class.DefaultMemberName);
var indexer1 = @class.GetIndexer<PEPropertySymbol>("Indexer1");
CheckIndexer(indexer1, true, true, "System.Int32 C.this[System.Int32 x, System.Int64 y] { get; set; }", suppressAssociatedPropertyCheck: true);
var indexer2 = @class.GetIndexer<PEPropertySymbol>("Indexer2");
CheckIndexer(indexer2, true, true, "System.Int32 C.this[System.Int32 x, System.Int64 y] { get; set; }", suppressAssociatedPropertyCheck: true);
});
}
[ClrOnlyFact]
public void LoadNonIndexer_NoDefaultMember()
{
string ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.method public hidebysig specialname instance int32
get_Item(int32 x) cil managed
{
ldc.i4.0
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance int32 Item(int32)
{
.get instance int32 C::get_Item(int32)
}
}
";
CompileWithCustomILSource("", ilSource, compilation =>
{
var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C");
Assert.Equal("", @class.DefaultMemberName); //placeholder value to avoid refetching
var property = @class.GetMember<PEPropertySymbol>("Item");
CheckNonIndexer(property, true, false, "System.Int32 C.Item[System.Int32 x] { get; }");
});
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void LoadNonIndexer_NotDefaultMember()
{
string ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('NotItem')}
.method public hidebysig specialname instance int32
get_Item(int32 x) cil managed
{
ldc.i4.0
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance int32 Item(int32)
{
.get instance int32 C::get_Item(int32)
}
}
";
CompileWithCustomILSource("", ilSource, compilation =>
{
var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C");
Assert.Equal("NotItem", @class.DefaultMemberName);
var property = @class.GetMember<PEPropertySymbol>("Item");
CheckNonIndexer(property, true, false, "System.Int32 C.Item[System.Int32 x] { get; }");
});
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void LoadNonGenericIndexers()
{
string ilSource = @"
.class public auto ansi beforefieldinit NonGeneric
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('get_Item')}
.method public hidebysig newslot specialname virtual
instance int32 get_Item(int64 x) cil managed
{
ldnull
throw
}
.method public hidebysig newslot specialname virtual
instance void set_Item(int64 x, int32 'value') cil managed
{
ldnull
throw
}
.method public hidebysig newslot specialname virtual
static int32 get_Item(int64 x) cil managed
{
ldnull
throw
}
.method public hidebysig newslot specialname virtual
static void set_Item(int64 x, int32 'value') cil managed
{
ldnull
throw
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldnull
throw
}
.property instance int32 Instance(int64)
{
.get instance int32 NonGeneric::get_Item(int64)
.set instance void NonGeneric::set_Item(int64, int32)
}
.property int32 Static(int64)
{
.get int32 NonGeneric::get_Item(int64)
.set void NonGeneric::set_Item(int64, int32)
}
} // end of class NonGeneric
";
CompileWithCustomILSource("", ilSource, compilation =>
CheckInstanceAndStaticIndexers(compilation, "NonGeneric", "System.Int32 NonGeneric.this[System.Int64 x] { get; set; }"));
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void LoadGenericIndexers()
{
string ilSource = @"
.class public auto ansi beforefieldinit Generic`2<T,U>
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('get_Item')}
.method public hidebysig newslot specialname virtual
instance !T get_Item(!U u) cil managed
{
ldnull
throw
}
.method public hidebysig newslot specialname virtual
instance void set_Item(!U u, !T 'value') cil managed
{
ldnull
throw
}
.method public hidebysig newslot specialname virtual
static !T get_Item(!U u) cil managed
{
ldnull
throw
}
.method public hidebysig newslot specialname virtual
static void set_Item(!U u, !T 'value') cil managed
{
ldnull
throw
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldnull
throw
}
.property instance !T Instance(!U)
{
.get instance !T Generic`2::get_Item(!U)
.set instance void Generic`2::set_Item(!U, !T)
}
.property !T Static(!U)
{
.get !T Generic`2::get_Item(!U)
.set void Generic`2::set_Item(!U, !T)
}
} // end of class Generic`2
";
CompileWithCustomILSource("", ilSource, compilation =>
CheckInstanceAndStaticIndexers(compilation, "Generic", "T Generic<T, U>.this[U u] { get; set; }"));
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void LoadClosedGenericIndexers()
{
string ilSource = @"
.class public auto ansi beforefieldinit ClosedGeneric
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('get_Item')}
.method public hidebysig newslot specialname virtual
instance class [mscorlib]System.Collections.Generic.List`1<int32>
get_Item(class [mscorlib]System.Action`1<int16> u) cil managed
{
ldnull
throw
}
.method public hidebysig newslot specialname virtual
instance void set_Item(class [mscorlib]System.Action`1<int16> u,
class [mscorlib]System.Collections.Generic.List`1<int32> 'value') cil managed
{
ldnull
throw
}
.method public hidebysig newslot specialname virtual
static class [mscorlib]System.Collections.Generic.List`1<int32>
get_Item(class [mscorlib]System.Action`1<int16> u) cil managed
{
ldnull
throw
}
.method public hidebysig newslot specialname virtual
static void set_Item(class [mscorlib]System.Action`1<int16> u,
class [mscorlib]System.Collections.Generic.List`1<int32> 'value') cil managed
{
ldnull
throw
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldnull
throw
}
.property instance class [mscorlib]System.Collections.Generic.List`1<int32>
Instance(class [mscorlib]System.Action`1<int16>)
{
.get instance class [mscorlib]System.Collections.Generic.List`1<int32> ClosedGeneric::get_Item(class [mscorlib]System.Action`1<int16>)
.set instance void ClosedGeneric::set_Item(class [mscorlib]System.Action`1<int16>,
class [mscorlib]System.Collections.Generic.List`1<int32>)
}
.property class [mscorlib]System.Collections.Generic.List`1<int32>
Static(class [mscorlib]System.Action`1<int16>)
{
.get class [mscorlib]System.Collections.Generic.List`1<int32> ClosedGeneric::get_Item(class [mscorlib]System.Action`1<int16>)
.set void ClosedGeneric::set_Item(class [mscorlib]System.Action`1<int16>,
class [mscorlib]System.Collections.Generic.List`1<int32>)
}
} // end of class ClosedGeneric
";
CompileWithCustomILSource("", ilSource, compilation =>
CheckInstanceAndStaticIndexers(compilation, "ClosedGeneric", "System.Collections.Generic.List<System.Int32> ClosedGeneric.this[System.Action<System.Int16> u] { get; set; }"));
}
[Fact]
public void LoadIndexerWithRefParam()
{
var assembly = MetadataTestHelpers.GetSymbolForReference(TestReferences.SymbolsTests.Indexers);
var @class = assembly.GlobalNamespace.GetMember<NamedTypeSymbol>("RefIndexer");
var indexer = (PropertySymbol)@class.GetMembers().Where(m => m.Kind == SymbolKind.Property).Single();
Assert.Equal(RefKind.Ref, indexer.Parameters.Single().RefKind);
Assert.True(indexer.MustCallMethodsDirectly);
}
private static void CheckInstanceAndStaticIndexers(CSharpCompilation compilation, string className, string indexerDisplayString)
{
var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>(className);
var instanceIndexer = @class.GetIndexer<PEPropertySymbol>("Instance");
Assert.False(instanceIndexer.IsStatic);
CheckIndexer(instanceIndexer, true, true, indexerDisplayString);
var staticIndexer = @class.GetIndexer<PEPropertySymbol>("Static"); //not allowed in C#
Assert.True(staticIndexer.IsStatic);
CheckIndexer(staticIndexer, true, true, indexerDisplayString);
}
/// <summary>
/// The accessor and the property have signatures.
/// </summary>
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void LoadAccessorPropertySignatureMismatch()
{
string ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('get_Item')}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.method public hidebysig specialname instance int32
get_Item(string s) cil managed
{
ldc.i4.0
ret
}
.property instance int32 ParameterCount(string, char)
{
.get instance int32 C::get_Item(string)
}
.method public hidebysig specialname instance int32
get_Item(string s, string c) cil managed
{
ldc.i4.0
ret
}
.property instance int32 ParameterTypes(string, char)
{
.get instance int32 C::get_Item(string, string)
}
.method public hidebysig specialname instance int32
get_Item(string s, char modopt(int32) c) cil managed
{
ldc.i4.0
ret
}
.property instance int32 ReturnType(string, char)
{
.get instance char C::get_Item(string, string)
}
.property instance int32 ParameterModopt(string, char)
{
.get instance int32 C::get_Item(string, char modopt(int32))
}
.method public hidebysig specialname instance char
get_Item(string s, string c) cil managed
{
ldc.i4.0
ret
}
.method public hidebysig specialname instance int32 modopt(int32)
get_Item(string s, char c) cil managed
{
ldc.i4.0
ret
}
.property instance int32 ReturnTypeModopt(string, char)
{
.get instance int32 modopt(int32) C::get_Item(string, char)
}
} // end of class C
";
CompileWithCustomILSource("", ilSource, compilation =>
{
var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C");
var parameterCountIndexer = @class.GetIndexer<PEPropertySymbol>("ParameterCount");
Assert.True(parameterCountIndexer.IsIndexer);
Assert.True(parameterCountIndexer.MustCallMethodsDirectly);
Assert.NotEqual(parameterCountIndexer.ParameterCount, parameterCountIndexer.GetMethod.ParameterCount);
var parameterTypesIndexer = @class.GetIndexer<PEPropertySymbol>("ParameterTypes");
Assert.True(parameterTypesIndexer.IsIndexer);
Assert.True(parameterTypesIndexer.MustCallMethodsDirectly);
Assert.NotEqual(parameterTypesIndexer.Parameters.Last().Type, parameterTypesIndexer.GetMethod.Parameters.Last().Type);
var returnTypeIndexer = @class.GetIndexer<PEPropertySymbol>("ReturnType");
Assert.True(returnTypeIndexer.IsIndexer);
Assert.True(returnTypeIndexer.MustCallMethodsDirectly);
Assert.NotEqual(returnTypeIndexer.Type, returnTypeIndexer.GetMethod.ReturnType);
var parameterModoptIndexer = @class.GetIndexer<PEPropertySymbol>("ParameterModopt");
Assert.True(parameterModoptIndexer.IsIndexer);
Assert.False(parameterModoptIndexer.MustCallMethodsDirectly); //NB: we allow this amount of variation (modopt is on, rather than in parameter type)
Assert.NotEqual(parameterModoptIndexer.Parameters.Last().TypeWithAnnotations.CustomModifiers.Length, parameterModoptIndexer.GetMethod.Parameters.Last().TypeWithAnnotations.CustomModifiers.Length);
var returnTypeModoptIndexer = @class.GetIndexer<PEPropertySymbol>("ReturnTypeModopt");
Assert.True(returnTypeModoptIndexer.IsIndexer);
Assert.False(returnTypeModoptIndexer.MustCallMethodsDirectly); //NB: we allow this amount of variation (modopt is on, rather than in return type)
Assert.NotEqual(returnTypeModoptIndexer.TypeWithAnnotations.CustomModifiers.Length, returnTypeModoptIndexer.GetMethod.ReturnTypeWithAnnotations.CustomModifiers.Length);
});
}
[ClrOnlyFact]
public void LoadParameterNames()
{
string ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.method public hidebysig specialname instance int32
get_Item(int32 x) cil managed
{
ldc.i4.0
ret
}
// NB: getter and setter have different parameter names
.method public hidebysig specialname instance void
set_Item(int32 y,
int32 'value') cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance int32 ReadWrite(int32)
{
.get instance int32 C::get_Item(int32)
.set instance void C::set_Item(int32, int32)
}
.property instance int32 ReadOnly(int32)
{
.get instance int32 C::get_Item(int32)
}
.property instance int32 WriteOnly(int32)
{
.set instance void C::set_Item(int32, int32)
}
}
";
CompileWithCustomILSource("", ilSource, compilation =>
{
var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C");
var property1 = @class.GetMember<PEPropertySymbol>("ReadWrite");
var property1ParamName = property1.Parameters.Single().Name;
// NOTE: prefer setter
Assert.NotEqual(property1ParamName, property1.GetMethod.Parameters.Single().Name);
Assert.Equal(property1ParamName, property1.SetMethod.Parameters.First().Name);
var property2 = @class.GetMember<PEPropertySymbol>("ReadOnly");
var property2ParamName = property2.Parameters.Single().Name;
Assert.Equal(property2ParamName, property2.GetMethod.Parameters.Single().Name);
var property3 = @class.GetMember<PEPropertySymbol>("WriteOnly");
var property3ParamName = property3.Parameters.Single().Name;
Assert.Equal(property3ParamName, property3.SetMethod.Parameters.First().Name);
});
}
/// <remarks>
/// Only testing parameter count mismatch. There isn't specific handling for other
/// types of bogus properties - just setter param name if setter available and getter
/// param name if getter available (i.e. same as success case).
/// </remarks>
[ClrOnlyFact]
public void LoadBogusParameterNames()
{
string ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.method public hidebysig specialname instance int32
get_Item(int32 x, int32 y) cil managed
{
ldc.i4.0
ret
}
// accessor has too many parameters
.property instance int32 TooMany(int32)
{
.get instance int32 C::get_Item(int32, int32)
}
// accessor has too few parameters
.property instance int32 TooFew(int32, int32, int32)
{
.get instance int32 C::get_Item(int32, int32)
}
}
";
CompileWithCustomILSource("", ilSource, compilation =>
{
var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C");
var accessor = @class.GetMember<MethodSymbol>("get_Item");
var accessParam0Name = accessor.Parameters[0].Name;
var accessParam1Name = accessor.Parameters[1].Name;
var property1 = @class.GetMember<PEPropertySymbol>("TooMany");
Assert.Equal(accessParam0Name, property1.Parameters[0].Name);
var property2 = @class.GetMember<PEPropertySymbol>("TooFew");
var property2Params = property2.Parameters;
Assert.Equal(accessParam0Name, property2Params[0].Name);
Assert.Equal(accessParam1Name, property2Params[1].Name);
Assert.Equal("value", property2Params[2].Name); //filler name
});
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void LoadParamArrayAttribute()
{
string ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('accessor')}
.method public hidebysig specialname instance int32
accessor(int32[] a) cil managed
{
.param [1]
.custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = {}
ldc.i4.0
ret
}
.method public hidebysig specialname instance void
accessor(int32[] a,
int32 'value') cil managed
{
.param [1]
.custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = {}
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance int32 ReadWrite(int32[])
{
.get instance int32 C::accessor(int32[])
.set instance void C::accessor(int32[], int32)
}
.property instance int32 ReadOnly(int32[])
{
.get instance int32 C::accessor(int32[])
}
.property instance int32 WriteOnly(int32[])
{
.set instance void C::accessor(int32[], int32)
}
} // end of class C
";
CompileWithCustomILSource("", ilSource, compilation =>
{
var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C");
var readWrite = @class.GetIndexer<PEPropertySymbol>("ReadWrite");
Assert.True(readWrite.IsIndexer);
Assert.False(readWrite.MustCallMethodsDirectly);
Assert.True(readWrite.Parameters.Last().IsParams);
var readOnly = @class.GetIndexer<PEPropertySymbol>("ReadOnly");
Assert.True(readOnly.IsIndexer);
Assert.False(readOnly.MustCallMethodsDirectly);
Assert.True(readOnly.Parameters.Last().IsParams);
var writeOnly = @class.GetIndexer<PEPropertySymbol>("WriteOnly");
Assert.True(writeOnly.IsIndexer);
Assert.False(writeOnly.MustCallMethodsDirectly);
Assert.True(writeOnly.Parameters.Last().IsParams);
});
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void LoadBogusParamArrayAttribute()
{
string ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('params')}
.method public hidebysig specialname instance int32
params(int32[] a) cil managed
{
.param [1]
.custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = {}
ldc.i4.0
ret
}
.method public hidebysig specialname instance int32
noParams(int32[] a) cil managed
{
ldc.i4.0
ret
}
.method public hidebysig specialname instance void
params(int32[] a,
int32 'value') cil managed
{
.param [1]
.custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = {}
ret
}
.method public hidebysig specialname instance void
noParams(int32[] a,
int32 'value') cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance int32 OnlyGetter(int32[])
{
.get instance int32 C::params(int32[])
.set instance void C::noParams(int32[], int32)
}
.property instance int32 OnlySetter(int32[])
{
.get instance int32 C::noParams(int32[])
.set instance void C::params(int32[], int32)
}
} // end of class C
";
CompileWithCustomILSource("", ilSource, compilation =>
{
var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C");
var readWrite = @class.GetIndexer<PEPropertySymbol>("OnlyGetter");
Assert.True(readWrite.IsIndexer);
Assert.True(readWrite.MustCallMethodsDirectly);
Assert.False(readWrite.Parameters.Last().IsParams); //favour setter
var readOnly = @class.GetIndexer<PEPropertySymbol>("OnlySetter");
Assert.True(readWrite.IsIndexer);
Assert.True(readOnly.MustCallMethodsDirectly);
Assert.True(readOnly.Parameters.Last().IsParams); //favour setter
});
}
private static void CheckIndexer(PropertySymbol indexer, bool expectGetter, bool expectSetter, string indexerDisplayString, bool suppressAssociatedPropertyCheck = false)
{
CheckParameterizedProperty(indexer, expectGetter, expectSetter, indexerDisplayString, true, suppressAssociatedPropertyCheck);
}
private static void CheckNonIndexer(PropertySymbol property, bool expectGetter, bool expectSetter, string propertyDisplayString)
{
CheckParameterizedProperty(property, expectGetter, expectSetter, propertyDisplayString, false, true);
}
private static void CheckParameterizedProperty(PropertySymbol property, bool expectGetter, bool expectSetter, string propertyDisplayString, bool expectIndexer, bool suppressAssociatedPropertyCheck)
{
Assert.Equal(SymbolKind.Property, property.Kind);
Assert.Equal(expectIndexer, property.IsIndexer);
Assert.NotEqual(expectIndexer, property.MustCallMethodsDirectly);
Assert.Equal(propertyDisplayString, property.ToTestDisplayString());
if (expectGetter)
{
CheckAccessorShape(property.GetMethod, true, property, expectIndexer, suppressAssociatedPropertyCheck);
}
else
{
Assert.Null(property.GetMethod);
}
if (expectSetter)
{
CheckAccessorShape(property.SetMethod, false, property, expectIndexer, suppressAssociatedPropertyCheck);
}
else
{
Assert.Null(property.SetMethod);
}
}
private static void CheckAccessorShape(MethodSymbol accessor, bool accessorIsGetMethod, PropertySymbol property, bool propertyIsIndexer, bool suppressAssociatedPropertyCheck)
{
Assert.NotNull(accessor);
if (propertyIsIndexer)
{
if (!suppressAssociatedPropertyCheck)
{
Assert.Same(property, accessor.AssociatedSymbol);
}
}
else
{
Assert.Null(accessor.AssociatedSymbol);
Assert.Equal(MethodKind.Ordinary, accessor.MethodKind);
}
if (accessorIsGetMethod)
{
Assert.Equal(propertyIsIndexer ? MethodKind.PropertyGet : MethodKind.Ordinary, accessor.MethodKind);
Assert.Equal(property.Type, accessor.ReturnType);
Assert.Equal(property.ParameterCount, accessor.ParameterCount);
}
else
{
Assert.Equal(propertyIsIndexer ? MethodKind.PropertySet : MethodKind.Ordinary, accessor.MethodKind);
Assert.Equal(SpecialType.System_Void, accessor.ReturnType.SpecialType);
Assert.Equal(property.Type, accessor.Parameters.Last().Type);
Assert.Equal(property.ParameterCount + 1, accessor.ParameterCount);
}
// NOTE: won't check last param of setter - that was handled above.
for (int i = 0; i < property.ParameterCount; i++)
{
Assert.Equal(property.Parameters[i].Type, accessor.Parameters[i].Type);
}
Assert.Equal(property.IsAbstract, accessor.IsAbstract);
Assert.Equal(property.IsOverride, @accessor.IsOverride);
Assert.Equal(property.IsVirtual, @accessor.IsVirtual);
Assert.Equal(property.IsSealed, @accessor.IsSealed);
Assert.Equal(property.IsExtern, @accessor.IsExtern);
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void LoadExplicitImplementation()
{
string ilSource = @"
.class interface public abstract auto ansi I
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('Item')}
.method public hidebysig newslot specialname abstract virtual
instance int32 get_Item(int32 x) cil managed
{
} // end of method I::get_Item
.method public hidebysig newslot specialname abstract virtual
instance void set_Item(int32 x,
int32 'value') cil managed
{
} // end of method I::set_Item
.property instance int32 Item(int32)
{
.get instance int32 I::get_Item(int32)
.set instance void I::set_Item(int32,
int32)
} // end of property I::Item
} // end of class I
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
implements I
{
.method private hidebysig newslot specialname virtual final
instance int32 I.get_Item(int32 x) cil managed
{
.override I::get_Item
ldnull
throw
}
.method private hidebysig newslot specialname virtual final
instance void I.set_Item(int32 x,
int32 'value') cil managed
{
.override I::set_Item
ldnull
throw
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance int32 I.Item(int32)
{
.get instance int32 C::I.get_Item(int32)
.set instance void C::I.set_Item(int32,
int32)
}
} // end of class C
";
CompileWithCustomILSource("", ilSource, compilation =>
{
var @interface = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("I");
var interfaceIndexer = @interface.Indexers.Single();
Assert.True(interfaceIndexer.IsIndexer);
var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C");
var classIndexer = (PropertySymbol)@class.GetMembers().Single(s => s.Kind == SymbolKind.Property);
Assert.False(classIndexer.IsIndexer);
Assert.Equal(classIndexer, @class.FindImplementationForInterfaceMember(interfaceIndexer));
Assert.Equal(interfaceIndexer, classIndexer.ExplicitInterfaceImplementations.Single());
});
}
[Fact]
public void LoadImplicitImplementation()
{
}
[Fact]
public void LoadOverriding()
{
}
[Fact]
public void LoadHiding()
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Metadata.PE;
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.Symbols.Metadata.PE
{
// CONSIDER: it might be worthwhile to promote some of these sample types to a test resource DLL
public class LoadingIndexers : CSharpTestBase
{
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void LoadReadWriteIndexer()
{
string ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('Item')}
.method public hidebysig specialname instance int32
get_Item(int32 x) cil managed
{
ldc.i4.0
ret
}
.method public hidebysig specialname instance void
set_Item(int32 x,
int32 'value') cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance int32 Item(int32)
{
.get instance int32 C::get_Item(int32)
.set instance void C::set_Item(int32, int32)
}
}
";
CompileWithCustomILSource("", ilSource, compilation =>
{
var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C");
Assert.Equal("Item", @class.DefaultMemberName);
var indexer = @class.GetIndexer<PEPropertySymbol>("Item");
CheckIndexer(indexer, true, true, "System.Int32 C.this[System.Int32 x] { get; set; }");
});
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void LoadWriteOnlyIndexer()
{
string ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('Item')}
.method public hidebysig specialname instance void
set_Item(int32 x,
int32 'value') cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance int32 Item(int32)
{
.set instance void C::set_Item(int32, int32)
}
}
";
CompileWithCustomILSource("", ilSource, compilation =>
{
var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C");
Assert.Equal("Item", @class.DefaultMemberName);
var indexer = @class.GetIndexer<PEPropertySymbol>("Item");
CheckIndexer(indexer, false, true, "System.Int32 C.this[System.Int32 x] { set; }");
});
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void LoadReadOnlyIndexer()
{
string ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('Item')}
.method public hidebysig specialname instance int32
get_Item(int32 x) cil managed
{
ldc.i4.0
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance int32 Item(int32)
{
.get instance int32 C::get_Item(int32)
}
}
";
CompileWithCustomILSource("", ilSource, compilation =>
{
var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C");
Assert.Equal("Item", @class.DefaultMemberName);
var indexer = @class.GetIndexer<PEPropertySymbol>("Item");
CheckIndexer(indexer, true, false, "System.Int32 C.this[System.Int32 x] { get; }");
});
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void LoadIndexerWithAlternateName()
{
string ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('NotItem')}
.method public hidebysig specialname instance int32
get_NotItem(int32 x) cil managed
{
ldc.i4.0
ret
}
.method public hidebysig specialname instance void
set_NotItem(int32 x,
int32 'value') cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance int32 NotItem(int32)
{
.get instance int32 C::get_NotItem(int32)
.set instance void C::set_NotItem(int32, int32)
}
}
";
CompileWithCustomILSource("", ilSource, compilation =>
{
var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C");
Assert.Equal("NotItem", @class.DefaultMemberName);
var indexer = @class.GetIndexer<PEPropertySymbol>("NotItem");
CheckIndexer(indexer, true, true, "System.Int32 C.this[System.Int32 x] { get; set; }");
});
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void LoadIndexerWithAccessorAsDefaultMember()
{
string ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('get_NotItem')}
.method public hidebysig specialname instance int32
get_NotItem(int32 x) cil managed
{
ldc.i4.0
ret
}
.method public hidebysig specialname instance void
set_NotItem(int32 x,
int32 'value') cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance int32 NotItem(int32)
{
.get instance int32 C::get_NotItem(int32)
.set instance void C::set_NotItem(int32, int32)
}
}
";
CompileWithCustomILSource("", ilSource, compilation =>
{
var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C");
Assert.Equal("get_NotItem", @class.DefaultMemberName);
var indexer = @class.GetIndexer<PEPropertySymbol>("NotItem");
CheckIndexer(indexer, true, true, "System.Int32 C.this[System.Int32 x] { get; set; }");
});
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void LoadComplexIndexers()
{
string ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('Accessor1')}
.method public hidebysig specialname instance int32
Accessor1(int32 x, int64 y) cil managed
{
ldc.i4.0
ret
}
.method public hidebysig specialname instance void
Accessor2(int32 x, int64 y,
int32 'value') cil managed
{
ret
}
.method public hidebysig specialname instance void
Accessor3(int32 x, int64 y,
int32 'value') cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance int32 Indexer1(int32, int64)
{
.get instance int32 C::Accessor1(int32, int64)
.set instance void C::Accessor2(int32, int64, int32)
}
.property instance int32 Indexer2(int32, int64)
{
.get instance int32 C::Accessor1(int32, int64)
.set instance void C::Accessor3(int32, int64, int32)
}
}
";
CompileWithCustomILSource("", ilSource, compilation =>
{
var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C");
Assert.Equal("Accessor1", @class.DefaultMemberName);
var indexer1 = @class.GetIndexer<PEPropertySymbol>("Indexer1");
CheckIndexer(indexer1, true, true, "System.Int32 C.this[System.Int32 x, System.Int64 y] { get; set; }", suppressAssociatedPropertyCheck: true);
var indexer2 = @class.GetIndexer<PEPropertySymbol>("Indexer2");
CheckIndexer(indexer2, true, true, "System.Int32 C.this[System.Int32 x, System.Int64 y] { get; set; }", suppressAssociatedPropertyCheck: true);
});
}
[ClrOnlyFact]
public void LoadNonIndexer_NoDefaultMember()
{
string ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.method public hidebysig specialname instance int32
get_Item(int32 x) cil managed
{
ldc.i4.0
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance int32 Item(int32)
{
.get instance int32 C::get_Item(int32)
}
}
";
CompileWithCustomILSource("", ilSource, compilation =>
{
var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C");
Assert.Equal("", @class.DefaultMemberName); //placeholder value to avoid refetching
var property = @class.GetMember<PEPropertySymbol>("Item");
CheckNonIndexer(property, true, false, "System.Int32 C.Item[System.Int32 x] { get; }");
});
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void LoadNonIndexer_NotDefaultMember()
{
string ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('NotItem')}
.method public hidebysig specialname instance int32
get_Item(int32 x) cil managed
{
ldc.i4.0
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance int32 Item(int32)
{
.get instance int32 C::get_Item(int32)
}
}
";
CompileWithCustomILSource("", ilSource, compilation =>
{
var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C");
Assert.Equal("NotItem", @class.DefaultMemberName);
var property = @class.GetMember<PEPropertySymbol>("Item");
CheckNonIndexer(property, true, false, "System.Int32 C.Item[System.Int32 x] { get; }");
});
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void LoadNonGenericIndexers()
{
string ilSource = @"
.class public auto ansi beforefieldinit NonGeneric
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('get_Item')}
.method public hidebysig newslot specialname virtual
instance int32 get_Item(int64 x) cil managed
{
ldnull
throw
}
.method public hidebysig newslot specialname virtual
instance void set_Item(int64 x, int32 'value') cil managed
{
ldnull
throw
}
.method public hidebysig newslot specialname virtual
static int32 get_Item(int64 x) cil managed
{
ldnull
throw
}
.method public hidebysig newslot specialname virtual
static void set_Item(int64 x, int32 'value') cil managed
{
ldnull
throw
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldnull
throw
}
.property instance int32 Instance(int64)
{
.get instance int32 NonGeneric::get_Item(int64)
.set instance void NonGeneric::set_Item(int64, int32)
}
.property int32 Static(int64)
{
.get int32 NonGeneric::get_Item(int64)
.set void NonGeneric::set_Item(int64, int32)
}
} // end of class NonGeneric
";
CompileWithCustomILSource("", ilSource, compilation =>
CheckInstanceAndStaticIndexers(compilation, "NonGeneric", "System.Int32 NonGeneric.this[System.Int64 x] { get; set; }"));
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void LoadGenericIndexers()
{
string ilSource = @"
.class public auto ansi beforefieldinit Generic`2<T,U>
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('get_Item')}
.method public hidebysig newslot specialname virtual
instance !T get_Item(!U u) cil managed
{
ldnull
throw
}
.method public hidebysig newslot specialname virtual
instance void set_Item(!U u, !T 'value') cil managed
{
ldnull
throw
}
.method public hidebysig newslot specialname virtual
static !T get_Item(!U u) cil managed
{
ldnull
throw
}
.method public hidebysig newslot specialname virtual
static void set_Item(!U u, !T 'value') cil managed
{
ldnull
throw
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldnull
throw
}
.property instance !T Instance(!U)
{
.get instance !T Generic`2::get_Item(!U)
.set instance void Generic`2::set_Item(!U, !T)
}
.property !T Static(!U)
{
.get !T Generic`2::get_Item(!U)
.set void Generic`2::set_Item(!U, !T)
}
} // end of class Generic`2
";
CompileWithCustomILSource("", ilSource, compilation =>
CheckInstanceAndStaticIndexers(compilation, "Generic", "T Generic<T, U>.this[U u] { get; set; }"));
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void LoadClosedGenericIndexers()
{
string ilSource = @"
.class public auto ansi beforefieldinit ClosedGeneric
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('get_Item')}
.method public hidebysig newslot specialname virtual
instance class [mscorlib]System.Collections.Generic.List`1<int32>
get_Item(class [mscorlib]System.Action`1<int16> u) cil managed
{
ldnull
throw
}
.method public hidebysig newslot specialname virtual
instance void set_Item(class [mscorlib]System.Action`1<int16> u,
class [mscorlib]System.Collections.Generic.List`1<int32> 'value') cil managed
{
ldnull
throw
}
.method public hidebysig newslot specialname virtual
static class [mscorlib]System.Collections.Generic.List`1<int32>
get_Item(class [mscorlib]System.Action`1<int16> u) cil managed
{
ldnull
throw
}
.method public hidebysig newslot specialname virtual
static void set_Item(class [mscorlib]System.Action`1<int16> u,
class [mscorlib]System.Collections.Generic.List`1<int32> 'value') cil managed
{
ldnull
throw
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldnull
throw
}
.property instance class [mscorlib]System.Collections.Generic.List`1<int32>
Instance(class [mscorlib]System.Action`1<int16>)
{
.get instance class [mscorlib]System.Collections.Generic.List`1<int32> ClosedGeneric::get_Item(class [mscorlib]System.Action`1<int16>)
.set instance void ClosedGeneric::set_Item(class [mscorlib]System.Action`1<int16>,
class [mscorlib]System.Collections.Generic.List`1<int32>)
}
.property class [mscorlib]System.Collections.Generic.List`1<int32>
Static(class [mscorlib]System.Action`1<int16>)
{
.get class [mscorlib]System.Collections.Generic.List`1<int32> ClosedGeneric::get_Item(class [mscorlib]System.Action`1<int16>)
.set void ClosedGeneric::set_Item(class [mscorlib]System.Action`1<int16>,
class [mscorlib]System.Collections.Generic.List`1<int32>)
}
} // end of class ClosedGeneric
";
CompileWithCustomILSource("", ilSource, compilation =>
CheckInstanceAndStaticIndexers(compilation, "ClosedGeneric", "System.Collections.Generic.List<System.Int32> ClosedGeneric.this[System.Action<System.Int16> u] { get; set; }"));
}
[Fact]
public void LoadIndexerWithRefParam()
{
var assembly = MetadataTestHelpers.GetSymbolForReference(TestReferences.SymbolsTests.Indexers);
var @class = assembly.GlobalNamespace.GetMember<NamedTypeSymbol>("RefIndexer");
var indexer = (PropertySymbol)@class.GetMembers().Where(m => m.Kind == SymbolKind.Property).Single();
Assert.Equal(RefKind.Ref, indexer.Parameters.Single().RefKind);
Assert.True(indexer.MustCallMethodsDirectly);
}
private static void CheckInstanceAndStaticIndexers(CSharpCompilation compilation, string className, string indexerDisplayString)
{
var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>(className);
var instanceIndexer = @class.GetIndexer<PEPropertySymbol>("Instance");
Assert.False(instanceIndexer.IsStatic);
CheckIndexer(instanceIndexer, true, true, indexerDisplayString);
var staticIndexer = @class.GetIndexer<PEPropertySymbol>("Static"); //not allowed in C#
Assert.True(staticIndexer.IsStatic);
CheckIndexer(staticIndexer, true, true, indexerDisplayString);
}
/// <summary>
/// The accessor and the property have signatures.
/// </summary>
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void LoadAccessorPropertySignatureMismatch()
{
string ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('get_Item')}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.method public hidebysig specialname instance int32
get_Item(string s) cil managed
{
ldc.i4.0
ret
}
.property instance int32 ParameterCount(string, char)
{
.get instance int32 C::get_Item(string)
}
.method public hidebysig specialname instance int32
get_Item(string s, string c) cil managed
{
ldc.i4.0
ret
}
.property instance int32 ParameterTypes(string, char)
{
.get instance int32 C::get_Item(string, string)
}
.method public hidebysig specialname instance int32
get_Item(string s, char modopt(int32) c) cil managed
{
ldc.i4.0
ret
}
.property instance int32 ReturnType(string, char)
{
.get instance char C::get_Item(string, string)
}
.property instance int32 ParameterModopt(string, char)
{
.get instance int32 C::get_Item(string, char modopt(int32))
}
.method public hidebysig specialname instance char
get_Item(string s, string c) cil managed
{
ldc.i4.0
ret
}
.method public hidebysig specialname instance int32 modopt(int32)
get_Item(string s, char c) cil managed
{
ldc.i4.0
ret
}
.property instance int32 ReturnTypeModopt(string, char)
{
.get instance int32 modopt(int32) C::get_Item(string, char)
}
} // end of class C
";
CompileWithCustomILSource("", ilSource, compilation =>
{
var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C");
var parameterCountIndexer = @class.GetIndexer<PEPropertySymbol>("ParameterCount");
Assert.True(parameterCountIndexer.IsIndexer);
Assert.True(parameterCountIndexer.MustCallMethodsDirectly);
Assert.NotEqual(parameterCountIndexer.ParameterCount, parameterCountIndexer.GetMethod.ParameterCount);
var parameterTypesIndexer = @class.GetIndexer<PEPropertySymbol>("ParameterTypes");
Assert.True(parameterTypesIndexer.IsIndexer);
Assert.True(parameterTypesIndexer.MustCallMethodsDirectly);
Assert.NotEqual(parameterTypesIndexer.Parameters.Last().Type, parameterTypesIndexer.GetMethod.Parameters.Last().Type);
var returnTypeIndexer = @class.GetIndexer<PEPropertySymbol>("ReturnType");
Assert.True(returnTypeIndexer.IsIndexer);
Assert.True(returnTypeIndexer.MustCallMethodsDirectly);
Assert.NotEqual(returnTypeIndexer.Type, returnTypeIndexer.GetMethod.ReturnType);
var parameterModoptIndexer = @class.GetIndexer<PEPropertySymbol>("ParameterModopt");
Assert.True(parameterModoptIndexer.IsIndexer);
Assert.False(parameterModoptIndexer.MustCallMethodsDirectly); //NB: we allow this amount of variation (modopt is on, rather than in parameter type)
Assert.NotEqual(parameterModoptIndexer.Parameters.Last().TypeWithAnnotations.CustomModifiers.Length, parameterModoptIndexer.GetMethod.Parameters.Last().TypeWithAnnotations.CustomModifiers.Length);
var returnTypeModoptIndexer = @class.GetIndexer<PEPropertySymbol>("ReturnTypeModopt");
Assert.True(returnTypeModoptIndexer.IsIndexer);
Assert.False(returnTypeModoptIndexer.MustCallMethodsDirectly); //NB: we allow this amount of variation (modopt is on, rather than in return type)
Assert.NotEqual(returnTypeModoptIndexer.TypeWithAnnotations.CustomModifiers.Length, returnTypeModoptIndexer.GetMethod.ReturnTypeWithAnnotations.CustomModifiers.Length);
});
}
[ClrOnlyFact]
public void LoadParameterNames()
{
string ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.method public hidebysig specialname instance int32
get_Item(int32 x) cil managed
{
ldc.i4.0
ret
}
// NB: getter and setter have different parameter names
.method public hidebysig specialname instance void
set_Item(int32 y,
int32 'value') cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance int32 ReadWrite(int32)
{
.get instance int32 C::get_Item(int32)
.set instance void C::set_Item(int32, int32)
}
.property instance int32 ReadOnly(int32)
{
.get instance int32 C::get_Item(int32)
}
.property instance int32 WriteOnly(int32)
{
.set instance void C::set_Item(int32, int32)
}
}
";
CompileWithCustomILSource("", ilSource, compilation =>
{
var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C");
var property1 = @class.GetMember<PEPropertySymbol>("ReadWrite");
var property1ParamName = property1.Parameters.Single().Name;
// NOTE: prefer setter
Assert.NotEqual(property1ParamName, property1.GetMethod.Parameters.Single().Name);
Assert.Equal(property1ParamName, property1.SetMethod.Parameters.First().Name);
var property2 = @class.GetMember<PEPropertySymbol>("ReadOnly");
var property2ParamName = property2.Parameters.Single().Name;
Assert.Equal(property2ParamName, property2.GetMethod.Parameters.Single().Name);
var property3 = @class.GetMember<PEPropertySymbol>("WriteOnly");
var property3ParamName = property3.Parameters.Single().Name;
Assert.Equal(property3ParamName, property3.SetMethod.Parameters.First().Name);
});
}
/// <remarks>
/// Only testing parameter count mismatch. There isn't specific handling for other
/// types of bogus properties - just setter param name if setter available and getter
/// param name if getter available (i.e. same as success case).
/// </remarks>
[ClrOnlyFact]
public void LoadBogusParameterNames()
{
string ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.method public hidebysig specialname instance int32
get_Item(int32 x, int32 y) cil managed
{
ldc.i4.0
ret
}
// accessor has too many parameters
.property instance int32 TooMany(int32)
{
.get instance int32 C::get_Item(int32, int32)
}
// accessor has too few parameters
.property instance int32 TooFew(int32, int32, int32)
{
.get instance int32 C::get_Item(int32, int32)
}
}
";
CompileWithCustomILSource("", ilSource, compilation =>
{
var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C");
var accessor = @class.GetMember<MethodSymbol>("get_Item");
var accessParam0Name = accessor.Parameters[0].Name;
var accessParam1Name = accessor.Parameters[1].Name;
var property1 = @class.GetMember<PEPropertySymbol>("TooMany");
Assert.Equal(accessParam0Name, property1.Parameters[0].Name);
var property2 = @class.GetMember<PEPropertySymbol>("TooFew");
var property2Params = property2.Parameters;
Assert.Equal(accessParam0Name, property2Params[0].Name);
Assert.Equal(accessParam1Name, property2Params[1].Name);
Assert.Equal("value", property2Params[2].Name); //filler name
});
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void LoadParamArrayAttribute()
{
string ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('accessor')}
.method public hidebysig specialname instance int32
accessor(int32[] a) cil managed
{
.param [1]
.custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = {}
ldc.i4.0
ret
}
.method public hidebysig specialname instance void
accessor(int32[] a,
int32 'value') cil managed
{
.param [1]
.custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = {}
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance int32 ReadWrite(int32[])
{
.get instance int32 C::accessor(int32[])
.set instance void C::accessor(int32[], int32)
}
.property instance int32 ReadOnly(int32[])
{
.get instance int32 C::accessor(int32[])
}
.property instance int32 WriteOnly(int32[])
{
.set instance void C::accessor(int32[], int32)
}
} // end of class C
";
CompileWithCustomILSource("", ilSource, compilation =>
{
var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C");
var readWrite = @class.GetIndexer<PEPropertySymbol>("ReadWrite");
Assert.True(readWrite.IsIndexer);
Assert.False(readWrite.MustCallMethodsDirectly);
Assert.True(readWrite.Parameters.Last().IsParams);
var readOnly = @class.GetIndexer<PEPropertySymbol>("ReadOnly");
Assert.True(readOnly.IsIndexer);
Assert.False(readOnly.MustCallMethodsDirectly);
Assert.True(readOnly.Parameters.Last().IsParams);
var writeOnly = @class.GetIndexer<PEPropertySymbol>("WriteOnly");
Assert.True(writeOnly.IsIndexer);
Assert.False(writeOnly.MustCallMethodsDirectly);
Assert.True(writeOnly.Parameters.Last().IsParams);
});
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void LoadBogusParamArrayAttribute()
{
string ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('params')}
.method public hidebysig specialname instance int32
params(int32[] a) cil managed
{
.param [1]
.custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = {}
ldc.i4.0
ret
}
.method public hidebysig specialname instance int32
noParams(int32[] a) cil managed
{
ldc.i4.0
ret
}
.method public hidebysig specialname instance void
params(int32[] a,
int32 'value') cil managed
{
.param [1]
.custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = {}
ret
}
.method public hidebysig specialname instance void
noParams(int32[] a,
int32 'value') cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance int32 OnlyGetter(int32[])
{
.get instance int32 C::params(int32[])
.set instance void C::noParams(int32[], int32)
}
.property instance int32 OnlySetter(int32[])
{
.get instance int32 C::noParams(int32[])
.set instance void C::params(int32[], int32)
}
} // end of class C
";
CompileWithCustomILSource("", ilSource, compilation =>
{
var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C");
var readWrite = @class.GetIndexer<PEPropertySymbol>("OnlyGetter");
Assert.True(readWrite.IsIndexer);
Assert.True(readWrite.MustCallMethodsDirectly);
Assert.False(readWrite.Parameters.Last().IsParams); //favour setter
var readOnly = @class.GetIndexer<PEPropertySymbol>("OnlySetter");
Assert.True(readWrite.IsIndexer);
Assert.True(readOnly.MustCallMethodsDirectly);
Assert.True(readOnly.Parameters.Last().IsParams); //favour setter
});
}
private static void CheckIndexer(PropertySymbol indexer, bool expectGetter, bool expectSetter, string indexerDisplayString, bool suppressAssociatedPropertyCheck = false)
{
CheckParameterizedProperty(indexer, expectGetter, expectSetter, indexerDisplayString, true, suppressAssociatedPropertyCheck);
}
private static void CheckNonIndexer(PropertySymbol property, bool expectGetter, bool expectSetter, string propertyDisplayString)
{
CheckParameterizedProperty(property, expectGetter, expectSetter, propertyDisplayString, false, true);
}
private static void CheckParameterizedProperty(PropertySymbol property, bool expectGetter, bool expectSetter, string propertyDisplayString, bool expectIndexer, bool suppressAssociatedPropertyCheck)
{
Assert.Equal(SymbolKind.Property, property.Kind);
Assert.Equal(expectIndexer, property.IsIndexer);
Assert.NotEqual(expectIndexer, property.MustCallMethodsDirectly);
Assert.Equal(propertyDisplayString, property.ToTestDisplayString());
if (expectGetter)
{
CheckAccessorShape(property.GetMethod, true, property, expectIndexer, suppressAssociatedPropertyCheck);
}
else
{
Assert.Null(property.GetMethod);
}
if (expectSetter)
{
CheckAccessorShape(property.SetMethod, false, property, expectIndexer, suppressAssociatedPropertyCheck);
}
else
{
Assert.Null(property.SetMethod);
}
}
private static void CheckAccessorShape(MethodSymbol accessor, bool accessorIsGetMethod, PropertySymbol property, bool propertyIsIndexer, bool suppressAssociatedPropertyCheck)
{
Assert.NotNull(accessor);
if (propertyIsIndexer)
{
if (!suppressAssociatedPropertyCheck)
{
Assert.Same(property, accessor.AssociatedSymbol);
}
}
else
{
Assert.Null(accessor.AssociatedSymbol);
Assert.Equal(MethodKind.Ordinary, accessor.MethodKind);
}
if (accessorIsGetMethod)
{
Assert.Equal(propertyIsIndexer ? MethodKind.PropertyGet : MethodKind.Ordinary, accessor.MethodKind);
Assert.Equal(property.Type, accessor.ReturnType);
Assert.Equal(property.ParameterCount, accessor.ParameterCount);
}
else
{
Assert.Equal(propertyIsIndexer ? MethodKind.PropertySet : MethodKind.Ordinary, accessor.MethodKind);
Assert.Equal(SpecialType.System_Void, accessor.ReturnType.SpecialType);
Assert.Equal(property.Type, accessor.Parameters.Last().Type);
Assert.Equal(property.ParameterCount + 1, accessor.ParameterCount);
}
// NOTE: won't check last param of setter - that was handled above.
for (int i = 0; i < property.ParameterCount; i++)
{
Assert.Equal(property.Parameters[i].Type, accessor.Parameters[i].Type);
}
Assert.Equal(property.IsAbstract, accessor.IsAbstract);
Assert.Equal(property.IsOverride, @accessor.IsOverride);
Assert.Equal(property.IsVirtual, @accessor.IsVirtual);
Assert.Equal(property.IsSealed, @accessor.IsSealed);
Assert.Equal(property.IsExtern, @accessor.IsExtern);
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void LoadExplicitImplementation()
{
string ilSource = @"
.class interface public abstract auto ansi I
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string)
= {string('Item')}
.method public hidebysig newslot specialname abstract virtual
instance int32 get_Item(int32 x) cil managed
{
} // end of method I::get_Item
.method public hidebysig newslot specialname abstract virtual
instance void set_Item(int32 x,
int32 'value') cil managed
{
} // end of method I::set_Item
.property instance int32 Item(int32)
{
.get instance int32 I::get_Item(int32)
.set instance void I::set_Item(int32,
int32)
} // end of property I::Item
} // end of class I
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
implements I
{
.method private hidebysig newslot specialname virtual final
instance int32 I.get_Item(int32 x) cil managed
{
.override I::get_Item
ldnull
throw
}
.method private hidebysig newslot specialname virtual final
instance void I.set_Item(int32 x,
int32 'value') cil managed
{
.override I::set_Item
ldnull
throw
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance int32 I.Item(int32)
{
.get instance int32 C::I.get_Item(int32)
.set instance void C::I.set_Item(int32,
int32)
}
} // end of class C
";
CompileWithCustomILSource("", ilSource, compilation =>
{
var @interface = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("I");
var interfaceIndexer = @interface.Indexers.Single();
Assert.True(interfaceIndexer.IsIndexer);
var @class = compilation.GlobalNamespace.GetMember<PENamedTypeSymbol>("C");
var classIndexer = (PropertySymbol)@class.GetMembers().Single(s => s.Kind == SymbolKind.Property);
Assert.False(classIndexer.IsIndexer);
Assert.Equal(classIndexer, @class.FindImplementationForInterfaceMember(interfaceIndexer));
Assert.Equal(interfaceIndexer, classIndexer.ExplicitInterfaceImplementations.Single());
});
}
[Fact]
public void LoadImplicitImplementation()
{
}
[Fact]
public void LoadOverriding()
{
}
[Fact]
public void LoadHiding()
{
}
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Collections/NormalizedTextSpanCollection.cs | // Licensed to the .NET Foundation under one or more 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.Text;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Shared
{
internal class NormalizedTextSpanCollection : ReadOnlyCollection<TextSpan>
{
/// <summary>
/// Initializes a new instance of <see cref="NormalizedTextSpanCollection"/> that is
/// empty.
/// </summary>
public NormalizedTextSpanCollection()
: base(new List<TextSpan>(0))
{
}
/// <summary>
/// Initializes a new instance of <see cref="NormalizedTextSpanCollection"/> that contains the specified span.
/// </summary>
/// <param name="span">TextSpan contained by the span set.</param>
public NormalizedTextSpanCollection(TextSpan span)
: base(ListFromSpan(span))
{
}
/// <summary>
/// Initializes a new instance of <see cref="NormalizedTextSpanCollection"/> that contains the specified list of spans.
/// </summary>
/// <param name="spans">The spans to be added.</param>
/// <remarks>
/// <para>The list of spans will be sorted and normalized (overlapping and adjoining spans will be combined).</para>
/// <para>This constructor runs in O(N log N) time, where N = spans.Count.</para></remarks>
/// <exception cref="ArgumentNullException"><paramref name="spans"/> is null.</exception>
public NormalizedTextSpanCollection(IEnumerable<TextSpan> spans)
: base(NormalizedTextSpanCollection.NormalizeSpans(spans))
{
// NormalizeSpans will throw if spans == null.
}
/// <summary>
/// Finds the union of two span sets.
/// </summary>
/// <param name="left">
/// The first span set.
/// </param>
/// <param name="right">
/// The second span set.
/// </param>
/// <returns>
/// The new span set that corresponds to the union of <paramref name="left"/> and <paramref name="right"/>.
/// </returns>
/// <remarks>This operator runs in O(N+M) time where N = left.Count, M = right.Count.</remarks>
/// <exception cref="ArgumentNullException">Either <paramref name="left"/> or <paramref name="right"/> is null.</exception>
public static NormalizedTextSpanCollection Union(NormalizedTextSpanCollection left, NormalizedTextSpanCollection right)
{
if (left == null)
{
throw new ArgumentNullException(nameof(left));
}
if (right == null)
{
throw new ArgumentNullException(nameof(right));
}
if (left.Count == 0)
{
return right;
}
if (right.Count == 0)
{
return left;
}
var spans = new OrderedSpanList();
var index1 = 0;
var index2 = 0;
var start = -1;
var end = int.MaxValue;
while (index1 < left.Count && index2 < right.Count)
{
var span1 = left[index1];
var span2 = right[index2];
if (span1.Start < span2.Start)
{
NormalizedTextSpanCollection.UpdateSpanUnion(span1, spans, ref start, ref end);
++index1;
}
else
{
NormalizedTextSpanCollection.UpdateSpanUnion(span2, spans, ref start, ref end);
++index2;
}
}
while (index1 < left.Count)
{
NormalizedTextSpanCollection.UpdateSpanUnion(left[index1], spans, ref start, ref end);
++index1;
}
while (index2 < right.Count)
{
NormalizedTextSpanCollection.UpdateSpanUnion(right[index2], spans, ref start, ref end);
++index2;
}
if (end != int.MaxValue)
{
spans.Add(TextSpan.FromBounds(start, end));
}
return new NormalizedTextSpanCollection(spans);
}
/// <summary>
/// Finds the overlap of two span sets.
/// </summary>
/// <param name="left">The first span set.</param>
/// <param name="right">The second span set.</param>
/// <returns>The new span set that corresponds to the overlap of <paramref name="left"/> and <paramref name="right"/>.</returns>
/// <remarks>This operator runs in O(N+M) time where N = left.Count, M = right.Count.</remarks>
/// <exception cref="ArgumentNullException"><paramref name="left"/> or <paramref name="right"/> is null.</exception>
public static NormalizedTextSpanCollection Overlap(NormalizedTextSpanCollection left, NormalizedTextSpanCollection right)
{
if (left == null)
{
throw new ArgumentNullException(nameof(left));
}
if (right == null)
{
throw new ArgumentNullException(nameof(right));
}
if (left.Count == 0)
{
return left;
}
if (right.Count == 0)
{
return right;
}
var spans = new OrderedSpanList();
for (int index1 = 0, index2 = 0; index1 < left.Count && index2 < right.Count;)
{
var span1 = left[index1];
var span2 = right[index2];
if (span1.OverlapsWith(span2))
{
spans.Add(span1.Overlap(span2)!.Value);
}
if (span1.End < span2.End)
{
++index1;
}
else if (span1.End == span2.End)
{
++index1;
++index2;
}
else
{
++index2;
}
}
return new NormalizedTextSpanCollection(spans);
}
/// <summary>
/// Finds the intersection of two span sets.
/// </summary>
/// <param name="left">The first span set.</param>
/// <param name="right">The second span set.</param>
/// <returns>The new span set that corresponds to the intersection of <paramref name="left"/> and <paramref name="right"/>.</returns>
/// <remarks>This operator runs in O(N+M) time where N = left.Count, M = right.Count.</remarks>
/// <exception cref="ArgumentNullException"><paramref name="left"/> is null.</exception>
/// <exception cref="ArgumentNullException"><paramref name="right"/> is null.</exception>
public static NormalizedTextSpanCollection Intersection(NormalizedTextSpanCollection left, NormalizedTextSpanCollection right)
{
if (left == null)
{
throw new ArgumentNullException(nameof(left));
}
if (right == null)
{
throw new ArgumentNullException(nameof(right));
}
if (left.Count == 0)
{
return left;
}
if (right.Count == 0)
{
return right;
}
var spans = new OrderedSpanList();
for (int index1 = 0, index2 = 0; (index1 < left.Count) && (index2 < right.Count);)
{
var span1 = left[index1];
var span2 = right[index2];
if (span1.IntersectsWith(span2))
{
spans.Add(span1.Intersection(span2)!.Value);
}
if (span1.End < span2.End)
{
++index1;
}
else
{
++index2;
}
}
return new NormalizedTextSpanCollection(spans);
}
/// <summary>
/// Finds the difference between two sets. The difference is defined as everything in the first span set that is not in the second span set.
/// </summary>
/// <param name="left">The first span set.</param>
/// <param name="right">The second span set.</param>
/// <returns>The new span set that corresponds to the difference between <paramref name="left"/> and <paramref name="right"/>.</returns>
/// <remarks>
/// Empty spans in the second set do not affect the first set at all. This method returns empty spans in the first set that are not contained by any set in
/// the second set.
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="left"/> is null.</exception>
/// <exception cref="ArgumentNullException"><paramref name="right"/> is null.</exception>
public static NormalizedTextSpanCollection Difference(NormalizedTextSpanCollection left, NormalizedTextSpanCollection right)
{
if (left == null)
{
throw new ArgumentNullException(nameof(left));
}
if (right == null)
{
throw new ArgumentNullException(nameof(right));
}
if (left.Count == 0)
{
return left;
}
if (right.Count == 0)
{
return left;
}
var spans = new OrderedSpanList();
var index1 = 0;
var index2 = 0;
var lastEnd = -1;
do
{
var span1 = left[index1];
var span2 = right[index2];
if ((span2.Length == 0) || (span1.Start >= span2.End))
{
++index2;
}
else if (span1.End <= span2.Start)
{
// lastEnd is set to the end of the previously encountered intersecting span
// from right when it ended before the end of span1 (so it must still be less
// than the end of span1).
Debug.Assert(lastEnd < span1.End);
spans.Add(TextSpan.FromBounds(Math.Max(lastEnd, span1.Start), span1.End));
++index1;
}
else
{
// The spans intersect, so add anything from span1 that extends to the left of span2.
if (span1.Start < span2.Start)
{
// lastEnd is set to the end of the previously encountered intersecting span
// on span2, so it must be less than the start of the current span on span2.
Debug.Assert(lastEnd < span2.Start);
spans.Add(TextSpan.FromBounds(Math.Max(lastEnd, span1.Start), span2.Start));
}
if (span1.End < span2.End)
{
++index1;
}
else if (span1.End == span2.End)
{
// Both spans ended at the same place so we're done with both.
++index1;
++index2;
}
else
{
// span2 ends before span1, so keep track of where it ended so that we don't
// try to add the excluded portion the next time we add a span.
lastEnd = span2.End;
++index2;
}
}
}
while ((index1 < left.Count) && (index2 < right.Count));
while (index1 < left.Count)
{
var span1 = left[index1++];
spans.Add(TextSpan.FromBounds(Math.Max(lastEnd, span1.Start), span1.End));
}
return new NormalizedTextSpanCollection(spans);
}
/// <summary>
/// Determines whether two span sets are the same.
/// </summary>
/// <param name="left">The first set.</param>
/// <param name="right">The second set.</param>
/// <returns><c>true</c> if the two sets are equivalent, otherwise <c>false</c>.</returns>
public static bool operator ==(NormalizedTextSpanCollection? left, NormalizedTextSpanCollection? right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (left is null || right is null)
{
return false;
}
if (left.Count != right.Count)
{
return false;
}
for (var i = 0; i < left.Count; ++i)
{
if (left[i] != right[i])
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether two span sets are not the same.
/// </summary>
/// <param name="left">The first set.</param>
/// <param name="right">The second set.</param>
/// <returns><c>true</c> if the two sets are not equivalent, otherwise <c>false</c>.</returns>
public static bool operator !=(NormalizedTextSpanCollection? left, NormalizedTextSpanCollection? right)
=> !(left == right);
/// <summary>
/// Determines whether this span set overlaps with another span set.
/// </summary>
/// <param name="set">The span set to test.</param>
/// <returns><c>true</c> if the span sets overlap, otherwise <c>false</c>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="set"/> is null.</exception>
public bool OverlapsWith(NormalizedTextSpanCollection set)
{
if (set == null)
{
throw new ArgumentNullException(nameof(set));
}
for (int index1 = 0, index2 = 0; (index1 < this.Count) && (index2 < set.Count);)
{
var span1 = this[index1];
var span2 = set[index2];
if (span1.OverlapsWith(span2))
{
return true;
}
if (span1.End < span2.End)
{
++index1;
}
else if (span1.End == span2.End)
{
++index1;
++index2;
}
else
{
++index2;
}
}
return false;
}
/// <summary>
/// Determines whether this span set overlaps with another span.
/// </summary>
/// <param name="span">The span to test.</param>
/// <returns><c>true</c> if this span set overlaps with the given span, otherwise <c>false</c>.</returns>
public bool OverlapsWith(TextSpan span)
{
// TODO: binary search
for (var index = 0; index < this.Count; ++index)
{
if (this[index].OverlapsWith(span))
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether this span set intersects with another span set.
/// </summary>
/// <param name="set">Set to test.</param>
/// <returns><c>true</c> if the span sets intersect, otherwise <c>false</c>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="set"/> is null.</exception>
public bool IntersectsWith(NormalizedTextSpanCollection set)
{
if (set == null)
{
throw new ArgumentNullException(nameof(set));
}
for (int index1 = 0, index2 = 0; (index1 < this.Count) && (index2 < set.Count);)
{
var span1 = this[index1];
var span2 = set[index2];
if (span1.IntersectsWith(span2))
{
return true;
}
if (span1.End < span2.End)
{
++index1;
}
else
{
++index2;
}
}
return false;
}
/// <summary>
/// Determines whether this span set intersects with another span.
/// </summary>
/// <returns><c>true</c> if this span set intersects with the given span, otherwise <c>false</c>.</returns>
public bool IntersectsWith(TextSpan span)
{
// TODO: binary search
for (var index = 0; index < this.Count; ++index)
{
if (this[index].IntersectsWith(span))
{
return true;
}
}
return false;
}
#region Overridden methods and operators
/// <summary>
/// Gets a unique hash code for the span set.
/// </summary>
/// <returns>A 32-bit hash code associated with the set.</returns>
public override int GetHashCode()
{
var hc = 0;
foreach (var s in this)
{
hc ^= s.GetHashCode();
}
return hc;
}
/// <summary>
/// Determines whether this span set is the same as another object.
/// </summary>
/// <param name="obj">The object to test.</param>
/// <returns><c>true</c> if the two objects are equal, otherwise <c>false</c>.</returns>
public override bool Equals(object? obj)
{
var set = obj as NormalizedTextSpanCollection;
return this == set;
}
/// <summary>
/// Provides a string representation of the set.
/// </summary>
/// <returns>The string representation of the set.</returns>
public override string ToString()
{
var value = new StringBuilder("{");
foreach (var s in this)
{
value.Append(s.ToString());
}
value.Append("}");
return value.ToString();
}
#endregion // Overridden methods and operators
#region Private Helpers
private static IList<TextSpan> ListFromSpan(TextSpan span)
{
IList<TextSpan> list = new List<TextSpan>(1);
list.Add(span);
return list;
}
/// <summary>
/// Private constructor for use when the span list is already normalized.
/// </summary>
/// <param name="normalizedSpans">An already normalized span list.</param>
private NormalizedTextSpanCollection(OrderedSpanList normalizedSpans)
: base(normalizedSpans)
{
}
private static void UpdateSpanUnion(TextSpan span, IList<TextSpan> spans, ref int start, ref int end)
{
if (end < span.Start)
{
spans.Add(TextSpan.FromBounds(start, end));
start = -1;
end = int.MaxValue;
}
if (end == int.MaxValue)
{
start = span.Start;
end = span.End;
}
else
{
end = Math.Max(end, span.End);
}
}
private static IList<TextSpan> NormalizeSpans(IEnumerable<TextSpan> spans)
{
if (spans == null)
{
throw new ArgumentNullException(nameof(spans));
}
var sorted = new List<TextSpan>(spans);
if (sorted.Count <= 1)
{
return sorted;
}
else
{
sorted.Sort(delegate (TextSpan s1, TextSpan s2) { return s1.Start.CompareTo(s2.Start); });
IList<TextSpan> normalized = new List<TextSpan>(sorted.Count);
var oldStart = sorted[0].Start;
var oldEnd = sorted[0].End;
for (var i = 1; i < sorted.Count; ++i)
{
var newStart = sorted[i].Start;
var newEnd = sorted[i].End;
if (oldEnd < newStart)
{
normalized.Add(TextSpan.FromBounds(oldStart, oldEnd));
oldStart = newStart;
oldEnd = newEnd;
}
else
{
oldEnd = Math.Max(oldEnd, newEnd);
}
}
normalized.Add(TextSpan.FromBounds(oldStart, oldEnd));
return normalized;
}
}
private class OrderedSpanList : List<TextSpan>
{
}
#endregion // Private Helpers
}
}
| // Licensed to the .NET Foundation under one or more 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.Text;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Shared
{
internal class NormalizedTextSpanCollection : ReadOnlyCollection<TextSpan>
{
/// <summary>
/// Initializes a new instance of <see cref="NormalizedTextSpanCollection"/> that is
/// empty.
/// </summary>
public NormalizedTextSpanCollection()
: base(new List<TextSpan>(0))
{
}
/// <summary>
/// Initializes a new instance of <see cref="NormalizedTextSpanCollection"/> that contains the specified span.
/// </summary>
/// <param name="span">TextSpan contained by the span set.</param>
public NormalizedTextSpanCollection(TextSpan span)
: base(ListFromSpan(span))
{
}
/// <summary>
/// Initializes a new instance of <see cref="NormalizedTextSpanCollection"/> that contains the specified list of spans.
/// </summary>
/// <param name="spans">The spans to be added.</param>
/// <remarks>
/// <para>The list of spans will be sorted and normalized (overlapping and adjoining spans will be combined).</para>
/// <para>This constructor runs in O(N log N) time, where N = spans.Count.</para></remarks>
/// <exception cref="ArgumentNullException"><paramref name="spans"/> is null.</exception>
public NormalizedTextSpanCollection(IEnumerable<TextSpan> spans)
: base(NormalizedTextSpanCollection.NormalizeSpans(spans))
{
// NormalizeSpans will throw if spans == null.
}
/// <summary>
/// Finds the union of two span sets.
/// </summary>
/// <param name="left">
/// The first span set.
/// </param>
/// <param name="right">
/// The second span set.
/// </param>
/// <returns>
/// The new span set that corresponds to the union of <paramref name="left"/> and <paramref name="right"/>.
/// </returns>
/// <remarks>This operator runs in O(N+M) time where N = left.Count, M = right.Count.</remarks>
/// <exception cref="ArgumentNullException">Either <paramref name="left"/> or <paramref name="right"/> is null.</exception>
public static NormalizedTextSpanCollection Union(NormalizedTextSpanCollection left, NormalizedTextSpanCollection right)
{
if (left == null)
{
throw new ArgumentNullException(nameof(left));
}
if (right == null)
{
throw new ArgumentNullException(nameof(right));
}
if (left.Count == 0)
{
return right;
}
if (right.Count == 0)
{
return left;
}
var spans = new OrderedSpanList();
var index1 = 0;
var index2 = 0;
var start = -1;
var end = int.MaxValue;
while (index1 < left.Count && index2 < right.Count)
{
var span1 = left[index1];
var span2 = right[index2];
if (span1.Start < span2.Start)
{
NormalizedTextSpanCollection.UpdateSpanUnion(span1, spans, ref start, ref end);
++index1;
}
else
{
NormalizedTextSpanCollection.UpdateSpanUnion(span2, spans, ref start, ref end);
++index2;
}
}
while (index1 < left.Count)
{
NormalizedTextSpanCollection.UpdateSpanUnion(left[index1], spans, ref start, ref end);
++index1;
}
while (index2 < right.Count)
{
NormalizedTextSpanCollection.UpdateSpanUnion(right[index2], spans, ref start, ref end);
++index2;
}
if (end != int.MaxValue)
{
spans.Add(TextSpan.FromBounds(start, end));
}
return new NormalizedTextSpanCollection(spans);
}
/// <summary>
/// Finds the overlap of two span sets.
/// </summary>
/// <param name="left">The first span set.</param>
/// <param name="right">The second span set.</param>
/// <returns>The new span set that corresponds to the overlap of <paramref name="left"/> and <paramref name="right"/>.</returns>
/// <remarks>This operator runs in O(N+M) time where N = left.Count, M = right.Count.</remarks>
/// <exception cref="ArgumentNullException"><paramref name="left"/> or <paramref name="right"/> is null.</exception>
public static NormalizedTextSpanCollection Overlap(NormalizedTextSpanCollection left, NormalizedTextSpanCollection right)
{
if (left == null)
{
throw new ArgumentNullException(nameof(left));
}
if (right == null)
{
throw new ArgumentNullException(nameof(right));
}
if (left.Count == 0)
{
return left;
}
if (right.Count == 0)
{
return right;
}
var spans = new OrderedSpanList();
for (int index1 = 0, index2 = 0; index1 < left.Count && index2 < right.Count;)
{
var span1 = left[index1];
var span2 = right[index2];
if (span1.OverlapsWith(span2))
{
spans.Add(span1.Overlap(span2)!.Value);
}
if (span1.End < span2.End)
{
++index1;
}
else if (span1.End == span2.End)
{
++index1;
++index2;
}
else
{
++index2;
}
}
return new NormalizedTextSpanCollection(spans);
}
/// <summary>
/// Finds the intersection of two span sets.
/// </summary>
/// <param name="left">The first span set.</param>
/// <param name="right">The second span set.</param>
/// <returns>The new span set that corresponds to the intersection of <paramref name="left"/> and <paramref name="right"/>.</returns>
/// <remarks>This operator runs in O(N+M) time where N = left.Count, M = right.Count.</remarks>
/// <exception cref="ArgumentNullException"><paramref name="left"/> is null.</exception>
/// <exception cref="ArgumentNullException"><paramref name="right"/> is null.</exception>
public static NormalizedTextSpanCollection Intersection(NormalizedTextSpanCollection left, NormalizedTextSpanCollection right)
{
if (left == null)
{
throw new ArgumentNullException(nameof(left));
}
if (right == null)
{
throw new ArgumentNullException(nameof(right));
}
if (left.Count == 0)
{
return left;
}
if (right.Count == 0)
{
return right;
}
var spans = new OrderedSpanList();
for (int index1 = 0, index2 = 0; (index1 < left.Count) && (index2 < right.Count);)
{
var span1 = left[index1];
var span2 = right[index2];
if (span1.IntersectsWith(span2))
{
spans.Add(span1.Intersection(span2)!.Value);
}
if (span1.End < span2.End)
{
++index1;
}
else
{
++index2;
}
}
return new NormalizedTextSpanCollection(spans);
}
/// <summary>
/// Finds the difference between two sets. The difference is defined as everything in the first span set that is not in the second span set.
/// </summary>
/// <param name="left">The first span set.</param>
/// <param name="right">The second span set.</param>
/// <returns>The new span set that corresponds to the difference between <paramref name="left"/> and <paramref name="right"/>.</returns>
/// <remarks>
/// Empty spans in the second set do not affect the first set at all. This method returns empty spans in the first set that are not contained by any set in
/// the second set.
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="left"/> is null.</exception>
/// <exception cref="ArgumentNullException"><paramref name="right"/> is null.</exception>
public static NormalizedTextSpanCollection Difference(NormalizedTextSpanCollection left, NormalizedTextSpanCollection right)
{
if (left == null)
{
throw new ArgumentNullException(nameof(left));
}
if (right == null)
{
throw new ArgumentNullException(nameof(right));
}
if (left.Count == 0)
{
return left;
}
if (right.Count == 0)
{
return left;
}
var spans = new OrderedSpanList();
var index1 = 0;
var index2 = 0;
var lastEnd = -1;
do
{
var span1 = left[index1];
var span2 = right[index2];
if ((span2.Length == 0) || (span1.Start >= span2.End))
{
++index2;
}
else if (span1.End <= span2.Start)
{
// lastEnd is set to the end of the previously encountered intersecting span
// from right when it ended before the end of span1 (so it must still be less
// than the end of span1).
Debug.Assert(lastEnd < span1.End);
spans.Add(TextSpan.FromBounds(Math.Max(lastEnd, span1.Start), span1.End));
++index1;
}
else
{
// The spans intersect, so add anything from span1 that extends to the left of span2.
if (span1.Start < span2.Start)
{
// lastEnd is set to the end of the previously encountered intersecting span
// on span2, so it must be less than the start of the current span on span2.
Debug.Assert(lastEnd < span2.Start);
spans.Add(TextSpan.FromBounds(Math.Max(lastEnd, span1.Start), span2.Start));
}
if (span1.End < span2.End)
{
++index1;
}
else if (span1.End == span2.End)
{
// Both spans ended at the same place so we're done with both.
++index1;
++index2;
}
else
{
// span2 ends before span1, so keep track of where it ended so that we don't
// try to add the excluded portion the next time we add a span.
lastEnd = span2.End;
++index2;
}
}
}
while ((index1 < left.Count) && (index2 < right.Count));
while (index1 < left.Count)
{
var span1 = left[index1++];
spans.Add(TextSpan.FromBounds(Math.Max(lastEnd, span1.Start), span1.End));
}
return new NormalizedTextSpanCollection(spans);
}
/// <summary>
/// Determines whether two span sets are the same.
/// </summary>
/// <param name="left">The first set.</param>
/// <param name="right">The second set.</param>
/// <returns><c>true</c> if the two sets are equivalent, otherwise <c>false</c>.</returns>
public static bool operator ==(NormalizedTextSpanCollection? left, NormalizedTextSpanCollection? right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (left is null || right is null)
{
return false;
}
if (left.Count != right.Count)
{
return false;
}
for (var i = 0; i < left.Count; ++i)
{
if (left[i] != right[i])
{
return false;
}
}
return true;
}
/// <summary>
/// Determines whether two span sets are not the same.
/// </summary>
/// <param name="left">The first set.</param>
/// <param name="right">The second set.</param>
/// <returns><c>true</c> if the two sets are not equivalent, otherwise <c>false</c>.</returns>
public static bool operator !=(NormalizedTextSpanCollection? left, NormalizedTextSpanCollection? right)
=> !(left == right);
/// <summary>
/// Determines whether this span set overlaps with another span set.
/// </summary>
/// <param name="set">The span set to test.</param>
/// <returns><c>true</c> if the span sets overlap, otherwise <c>false</c>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="set"/> is null.</exception>
public bool OverlapsWith(NormalizedTextSpanCollection set)
{
if (set == null)
{
throw new ArgumentNullException(nameof(set));
}
for (int index1 = 0, index2 = 0; (index1 < this.Count) && (index2 < set.Count);)
{
var span1 = this[index1];
var span2 = set[index2];
if (span1.OverlapsWith(span2))
{
return true;
}
if (span1.End < span2.End)
{
++index1;
}
else if (span1.End == span2.End)
{
++index1;
++index2;
}
else
{
++index2;
}
}
return false;
}
/// <summary>
/// Determines whether this span set overlaps with another span.
/// </summary>
/// <param name="span">The span to test.</param>
/// <returns><c>true</c> if this span set overlaps with the given span, otherwise <c>false</c>.</returns>
public bool OverlapsWith(TextSpan span)
{
// TODO: binary search
for (var index = 0; index < this.Count; ++index)
{
if (this[index].OverlapsWith(span))
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether this span set intersects with another span set.
/// </summary>
/// <param name="set">Set to test.</param>
/// <returns><c>true</c> if the span sets intersect, otherwise <c>false</c>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="set"/> is null.</exception>
public bool IntersectsWith(NormalizedTextSpanCollection set)
{
if (set == null)
{
throw new ArgumentNullException(nameof(set));
}
for (int index1 = 0, index2 = 0; (index1 < this.Count) && (index2 < set.Count);)
{
var span1 = this[index1];
var span2 = set[index2];
if (span1.IntersectsWith(span2))
{
return true;
}
if (span1.End < span2.End)
{
++index1;
}
else
{
++index2;
}
}
return false;
}
/// <summary>
/// Determines whether this span set intersects with another span.
/// </summary>
/// <returns><c>true</c> if this span set intersects with the given span, otherwise <c>false</c>.</returns>
public bool IntersectsWith(TextSpan span)
{
// TODO: binary search
for (var index = 0; index < this.Count; ++index)
{
if (this[index].IntersectsWith(span))
{
return true;
}
}
return false;
}
#region Overridden methods and operators
/// <summary>
/// Gets a unique hash code for the span set.
/// </summary>
/// <returns>A 32-bit hash code associated with the set.</returns>
public override int GetHashCode()
{
var hc = 0;
foreach (var s in this)
{
hc ^= s.GetHashCode();
}
return hc;
}
/// <summary>
/// Determines whether this span set is the same as another object.
/// </summary>
/// <param name="obj">The object to test.</param>
/// <returns><c>true</c> if the two objects are equal, otherwise <c>false</c>.</returns>
public override bool Equals(object? obj)
{
var set = obj as NormalizedTextSpanCollection;
return this == set;
}
/// <summary>
/// Provides a string representation of the set.
/// </summary>
/// <returns>The string representation of the set.</returns>
public override string ToString()
{
var value = new StringBuilder("{");
foreach (var s in this)
{
value.Append(s.ToString());
}
value.Append("}");
return value.ToString();
}
#endregion // Overridden methods and operators
#region Private Helpers
private static IList<TextSpan> ListFromSpan(TextSpan span)
{
IList<TextSpan> list = new List<TextSpan>(1);
list.Add(span);
return list;
}
/// <summary>
/// Private constructor for use when the span list is already normalized.
/// </summary>
/// <param name="normalizedSpans">An already normalized span list.</param>
private NormalizedTextSpanCollection(OrderedSpanList normalizedSpans)
: base(normalizedSpans)
{
}
private static void UpdateSpanUnion(TextSpan span, IList<TextSpan> spans, ref int start, ref int end)
{
if (end < span.Start)
{
spans.Add(TextSpan.FromBounds(start, end));
start = -1;
end = int.MaxValue;
}
if (end == int.MaxValue)
{
start = span.Start;
end = span.End;
}
else
{
end = Math.Max(end, span.End);
}
}
private static IList<TextSpan> NormalizeSpans(IEnumerable<TextSpan> spans)
{
if (spans == null)
{
throw new ArgumentNullException(nameof(spans));
}
var sorted = new List<TextSpan>(spans);
if (sorted.Count <= 1)
{
return sorted;
}
else
{
sorted.Sort(delegate (TextSpan s1, TextSpan s2) { return s1.Start.CompareTo(s2.Start); });
IList<TextSpan> normalized = new List<TextSpan>(sorted.Count);
var oldStart = sorted[0].Start;
var oldEnd = sorted[0].End;
for (var i = 1; i < sorted.Count; ++i)
{
var newStart = sorted[i].Start;
var newEnd = sorted[i].End;
if (oldEnd < newStart)
{
normalized.Add(TextSpan.FromBounds(oldStart, oldEnd));
oldStart = newStart;
oldEnd = newEnd;
}
else
{
oldEnd = Math.Max(oldEnd, newEnd);
}
}
normalized.Add(TextSpan.FromBounds(oldStart, oldEnd));
return normalized;
}
}
private class OrderedSpanList : List<TextSpan>
{
}
#endregion // Private Helpers
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Features/CSharp/Portable/ConvertIfToSwitch/CSharpConvertIfToSwitchCodeRefactoringProvider.Rewriting.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ConvertIfToSwitch
{
using static SyntaxFactory;
internal sealed partial class CSharpConvertIfToSwitchCodeRefactoringProvider
{
private static readonly Dictionary<BinaryOperatorKind, SyntaxKind> s_operatorMap = new Dictionary<BinaryOperatorKind, SyntaxKind>
{
{ BinaryOperatorKind.LessThan, SyntaxKind.LessThanToken },
{ BinaryOperatorKind.GreaterThan, SyntaxKind.GreaterThanToken },
{ BinaryOperatorKind.LessThanOrEqual, SyntaxKind.LessThanEqualsToken },
{ BinaryOperatorKind.GreaterThanOrEqual, SyntaxKind.GreaterThanEqualsToken },
};
public override SyntaxNode CreateSwitchExpressionStatement(SyntaxNode target, ImmutableArray<AnalyzedSwitchSection> sections, Feature feature)
{
return ReturnStatement(
SwitchExpression(
(ExpressionSyntax)target,
SeparatedList(sections.Select(section => AsSwitchExpressionArmSyntax(section, feature)))));
}
private static SwitchExpressionArmSyntax AsSwitchExpressionArmSyntax(AnalyzedSwitchSection section, Feature feature)
{
if (section.Labels.IsDefault)
return SwitchExpressionArm(DiscardPattern(), AsExpressionSyntax(section.Body));
var pattern = AsPatternSyntax(section.Labels[0].Pattern, feature);
var whenClause = AsWhenClause(section.Labels[0]);
Debug.Assert(whenClause == null || section.Labels.Length == 1, "We shouldn't have guards when we're combining multiple cases into a single arm");
for (var i = 1; i < section.Labels.Length; i++)
{
var label = section.Labels[i];
Debug.Assert(label.Guards.Length == 0, "We shouldn't have guards when we're combining multiple cases into a single arm");
var nextPattern = AsPatternSyntax(label.Pattern, feature);
pattern = BinaryPattern(SyntaxKind.OrPattern, pattern.Parenthesize(), nextPattern.Parenthesize());
}
return SwitchExpressionArm(pattern, whenClause, AsExpressionSyntax(section.Body));
}
private static ExpressionSyntax AsExpressionSyntax(IOperation operation)
=> operation switch
{
IReturnOperation { ReturnedValue: { } value } => (ExpressionSyntax)value.Syntax,
IThrowOperation { Exception: { } exception } => ThrowExpression((ExpressionSyntax)exception.Syntax),
IBlockOperation op => AsExpressionSyntax(op.Operations.Single()),
var v => throw ExceptionUtilities.UnexpectedValue(v.Kind)
};
public override SyntaxNode CreateSwitchStatement(IfStatementSyntax ifStatement, SyntaxNode expression, IEnumerable<SyntaxNode> sectionList)
{
var block = ifStatement.Statement as BlockSyntax;
return SwitchStatement(
switchKeyword: Token(SyntaxKind.SwitchKeyword).WithTriviaFrom(ifStatement.IfKeyword),
openParenToken: ifStatement.OpenParenToken,
expression: (ExpressionSyntax)expression,
closeParenToken: ifStatement.CloseParenToken.WithPrependedLeadingTrivia(ElasticMarker),
openBraceToken: block?.OpenBraceToken ?? Token(SyntaxKind.OpenBraceToken),
sections: List(sectionList.Cast<SwitchSectionSyntax>()),
closeBraceToken: block?.CloseBraceToken.WithoutLeadingTrivia() ?? Token(SyntaxKind.CloseBraceToken));
}
private static WhenClauseSyntax? AsWhenClause(AnalyzedSwitchLabel label)
=> AsWhenClause(label.Guards
.Select(e => e.WalkUpParentheses())
.AggregateOrDefault((prev, current) => BinaryExpression(SyntaxKind.LogicalAndExpression, prev, current)));
private static WhenClauseSyntax? AsWhenClause(ExpressionSyntax? expression)
=> expression is null ? null : WhenClause(expression);
public override SyntaxNode AsSwitchLabelSyntax(AnalyzedSwitchLabel label, Feature feature)
=> CasePatternSwitchLabel(
AsPatternSyntax(label.Pattern, feature),
AsWhenClause(label),
Token(SyntaxKind.ColonToken));
private static PatternSyntax AsPatternSyntax(AnalyzedPattern pattern, Feature feature)
=> pattern switch
{
AnalyzedPattern.And p => BinaryPattern(SyntaxKind.AndPattern, AsPatternSyntax(p.LeftPattern, feature).Parenthesize(), AsPatternSyntax(p.RightPattern, feature).Parenthesize()),
AnalyzedPattern.Constant p => ConstantPattern(p.ExpressionSyntax),
AnalyzedPattern.Source p => p.PatternSyntax,
AnalyzedPattern.Type p when feature.HasFlag(Feature.TypePattern) => TypePattern((TypeSyntax)p.IsExpressionSyntax.Right),
AnalyzedPattern.Type p => DeclarationPattern((TypeSyntax)p.IsExpressionSyntax.Right, DiscardDesignation()),
AnalyzedPattern.Relational p => RelationalPattern(Token(s_operatorMap[p.OperatorKind]), p.Value),
var p => throw ExceptionUtilities.UnexpectedValue(p)
};
public override IEnumerable<SyntaxNode> AsSwitchSectionStatements(IOperation operation)
{
var node = operation.Syntax;
Debug.Assert(operation.SemanticModel is not null);
var requiresBreak = operation.SemanticModel.AnalyzeControlFlow(node).EndPointIsReachable;
var requiresBlock = !operation.SemanticModel.AnalyzeDataFlow(node).VariablesDeclared.IsDefaultOrEmpty;
var statements = ArrayBuilder<SyntaxNode>.GetInstance();
if (node is BlockSyntax block)
{
if (block.Statements.Count == 0)
{
statements.Add(BreakStatement());
}
else if (requiresBlock)
{
statements.Add(requiresBreak ? block.AddStatements(BreakStatement()) : block);
}
else
{
statements.AddRange(block.Statements);
if (requiresBreak)
{
statements.Add(BreakStatement().WithLeadingTrivia(block.CloseBraceToken.LeadingTrivia));
}
}
}
else
{
statements.Add(node);
if (requiresBreak)
{
statements.Add(BreakStatement());
}
}
return statements.ToArrayAndFree();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ConvertIfToSwitch
{
using static SyntaxFactory;
internal sealed partial class CSharpConvertIfToSwitchCodeRefactoringProvider
{
private static readonly Dictionary<BinaryOperatorKind, SyntaxKind> s_operatorMap = new Dictionary<BinaryOperatorKind, SyntaxKind>
{
{ BinaryOperatorKind.LessThan, SyntaxKind.LessThanToken },
{ BinaryOperatorKind.GreaterThan, SyntaxKind.GreaterThanToken },
{ BinaryOperatorKind.LessThanOrEqual, SyntaxKind.LessThanEqualsToken },
{ BinaryOperatorKind.GreaterThanOrEqual, SyntaxKind.GreaterThanEqualsToken },
};
public override SyntaxNode CreateSwitchExpressionStatement(SyntaxNode target, ImmutableArray<AnalyzedSwitchSection> sections, Feature feature)
{
return ReturnStatement(
SwitchExpression(
(ExpressionSyntax)target,
SeparatedList(sections.Select(section => AsSwitchExpressionArmSyntax(section, feature)))));
}
private static SwitchExpressionArmSyntax AsSwitchExpressionArmSyntax(AnalyzedSwitchSection section, Feature feature)
{
if (section.Labels.IsDefault)
return SwitchExpressionArm(DiscardPattern(), AsExpressionSyntax(section.Body));
var pattern = AsPatternSyntax(section.Labels[0].Pattern, feature);
var whenClause = AsWhenClause(section.Labels[0]);
Debug.Assert(whenClause == null || section.Labels.Length == 1, "We shouldn't have guards when we're combining multiple cases into a single arm");
for (var i = 1; i < section.Labels.Length; i++)
{
var label = section.Labels[i];
Debug.Assert(label.Guards.Length == 0, "We shouldn't have guards when we're combining multiple cases into a single arm");
var nextPattern = AsPatternSyntax(label.Pattern, feature);
pattern = BinaryPattern(SyntaxKind.OrPattern, pattern.Parenthesize(), nextPattern.Parenthesize());
}
return SwitchExpressionArm(pattern, whenClause, AsExpressionSyntax(section.Body));
}
private static ExpressionSyntax AsExpressionSyntax(IOperation operation)
=> operation switch
{
IReturnOperation { ReturnedValue: { } value } => (ExpressionSyntax)value.Syntax,
IThrowOperation { Exception: { } exception } => ThrowExpression((ExpressionSyntax)exception.Syntax),
IBlockOperation op => AsExpressionSyntax(op.Operations.Single()),
var v => throw ExceptionUtilities.UnexpectedValue(v.Kind)
};
public override SyntaxNode CreateSwitchStatement(IfStatementSyntax ifStatement, SyntaxNode expression, IEnumerable<SyntaxNode> sectionList)
{
var block = ifStatement.Statement as BlockSyntax;
return SwitchStatement(
switchKeyword: Token(SyntaxKind.SwitchKeyword).WithTriviaFrom(ifStatement.IfKeyword),
openParenToken: ifStatement.OpenParenToken,
expression: (ExpressionSyntax)expression,
closeParenToken: ifStatement.CloseParenToken.WithPrependedLeadingTrivia(ElasticMarker),
openBraceToken: block?.OpenBraceToken ?? Token(SyntaxKind.OpenBraceToken),
sections: List(sectionList.Cast<SwitchSectionSyntax>()),
closeBraceToken: block?.CloseBraceToken.WithoutLeadingTrivia() ?? Token(SyntaxKind.CloseBraceToken));
}
private static WhenClauseSyntax? AsWhenClause(AnalyzedSwitchLabel label)
=> AsWhenClause(label.Guards
.Select(e => e.WalkUpParentheses())
.AggregateOrDefault((prev, current) => BinaryExpression(SyntaxKind.LogicalAndExpression, prev, current)));
private static WhenClauseSyntax? AsWhenClause(ExpressionSyntax? expression)
=> expression is null ? null : WhenClause(expression);
public override SyntaxNode AsSwitchLabelSyntax(AnalyzedSwitchLabel label, Feature feature)
=> CasePatternSwitchLabel(
AsPatternSyntax(label.Pattern, feature),
AsWhenClause(label),
Token(SyntaxKind.ColonToken));
private static PatternSyntax AsPatternSyntax(AnalyzedPattern pattern, Feature feature)
=> pattern switch
{
AnalyzedPattern.And p => BinaryPattern(SyntaxKind.AndPattern, AsPatternSyntax(p.LeftPattern, feature).Parenthesize(), AsPatternSyntax(p.RightPattern, feature).Parenthesize()),
AnalyzedPattern.Constant p => ConstantPattern(p.ExpressionSyntax),
AnalyzedPattern.Source p => p.PatternSyntax,
AnalyzedPattern.Type p when feature.HasFlag(Feature.TypePattern) => TypePattern((TypeSyntax)p.IsExpressionSyntax.Right),
AnalyzedPattern.Type p => DeclarationPattern((TypeSyntax)p.IsExpressionSyntax.Right, DiscardDesignation()),
AnalyzedPattern.Relational p => RelationalPattern(Token(s_operatorMap[p.OperatorKind]), p.Value),
var p => throw ExceptionUtilities.UnexpectedValue(p)
};
public override IEnumerable<SyntaxNode> AsSwitchSectionStatements(IOperation operation)
{
var node = operation.Syntax;
Debug.Assert(operation.SemanticModel is not null);
var requiresBreak = operation.SemanticModel.AnalyzeControlFlow(node).EndPointIsReachable;
var requiresBlock = !operation.SemanticModel.AnalyzeDataFlow(node).VariablesDeclared.IsDefaultOrEmpty;
var statements = ArrayBuilder<SyntaxNode>.GetInstance();
if (node is BlockSyntax block)
{
if (block.Statements.Count == 0)
{
statements.Add(BreakStatement());
}
else if (requiresBlock)
{
statements.Add(requiresBreak ? block.AddStatements(BreakStatement()) : block);
}
else
{
statements.AddRange(block.Statements);
if (requiresBreak)
{
statements.Add(BreakStatement().WithLeadingTrivia(block.CloseBraceToken.LeadingTrivia));
}
}
}
else
{
statements.Add(node);
if (requiresBreak)
{
statements.Add(BreakStatement());
}
}
return statements.ToArrayAndFree();
}
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SnippetCompletionProviderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Composition;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp.Completion.Providers;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Snippets;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders
{
public class SnippetCompletionProviderTests : AbstractCSharpCompletionProviderTests
{
internal override Type GetCompletionProviderType()
=> typeof(SnippetCompletionProvider);
protected override TestComposition GetComposition()
=> base.GetComposition().AddParts(typeof(MockSnippetInfoService));
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SnippetsInEmptyFile()
=> await VerifyItemExistsAsync(@"$$", MockSnippetInfoService.SnippetShortcut, sourceCodeKind: SourceCodeKind.Regular);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SnippetDescriptions()
=> await VerifyItemExistsAsync(@"$$", MockSnippetInfoService.SnippetShortcut, MockSnippetInfoService.SnippetTitle + Environment.NewLine + MockSnippetInfoService.SnippetDescription + Environment.NewLine + string.Format(FeaturesResources.Note_colon_Tab_twice_to_insert_the_0_snippet, MockSnippetInfoService.SnippetShortcut), SourceCodeKind.Regular);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SnippetsInNamespace()
=> await VerifyItemExistsAsync(@"namespace NS { $$ }", MockSnippetInfoService.SnippetShortcut, sourceCodeKind: SourceCodeKind.Regular);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SnippetsInClass()
=> await VerifyItemExistsAsync(@"namespace NS { class C { $$ } }", MockSnippetInfoService.SnippetShortcut, sourceCodeKind: SourceCodeKind.Regular);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SnippetsInMethod()
=> await VerifyItemExistsAsync(@"namespace NS { class C { void M() { $$ } } }", MockSnippetInfoService.SnippetShortcut, sourceCodeKind: SourceCodeKind.Regular);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SnippetsNotInLocalDeclarationIdentifier()
=> await VerifyItemIsAbsentAsync(@"namespace NS { class C { void M() { int $$ } } }", MockSnippetInfoService.SnippetShortcut, sourceCodeKind: SourceCodeKind.Regular);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SnippetsNotInEnum()
=> await VerifyItemIsAbsentAsync(@"namespace NS { enum E { $$ } }", MockSnippetInfoService.SnippetShortcut, sourceCodeKind: SourceCodeKind.Regular);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SnippetsInExpression()
=> await VerifyItemExistsAsync(@"namespace NS { class C { void M() { bool b = true && $$ } } }", MockSnippetInfoService.SnippetShortcut, sourceCodeKind: SourceCodeKind.Regular);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(608860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608860")]
public async Task SnippetsInPreProcessorContextWhenShortcutBeginsWithHash()
=> await VerifyItemExistsAsync(@"#$$", MockSnippetInfoService.PreProcessorSnippetShortcut.Substring(1), sourceCodeKind: SourceCodeKind.Regular);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(608860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608860")]
public async Task SnippetsNotInPreProcessorContextWhenShortcutDoesNotBeginWithHash()
=> await VerifyItemIsAbsentAsync(@"#$$", MockSnippetInfoService.SnippetShortcut, sourceCodeKind: SourceCodeKind.Regular);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(770156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770156")]
public async Task SnippetsNotInPreProcessorContextDirectiveNameAlreadyTyped()
=> await VerifyItemIsAbsentAsync(@"#region $$", MockSnippetInfoService.PreProcessorSnippetShortcut, sourceCodeKind: SourceCodeKind.Regular);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(839555, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/839555")]
public async Task ShowRegionSnippetWithHashRTyped()
=> await VerifyItemExistsAsync(@"#r$$", MockSnippetInfoService.PreProcessorSnippetShortcut.Substring(1), sourceCodeKind: SourceCodeKind.Regular);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SnippetsInLineSpanDirective()
=> await VerifyItemIsAbsentAsync(@"#line (1, 2) - (3, 4) $$", MockSnippetInfoService.PreProcessorSnippetShortcut, sourceCodeKind: SourceCodeKind.Regular);
[WorkItem(968256, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968256")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ShowSnippetsFromOtherContext()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if GOO
$$
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""GOO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
await VerifyItemInLinkedFilesAsync(markup, MockSnippetInfoService.SnippetShortcut, null);
}
[WorkItem(1140893, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1140893")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CommitWithEnterObeysOption()
{
await VerifySendEnterThroughToEnterAsync("$$", "SnippetShortcu", sendThroughEnterOption: EnterKeyRule.Always, expected: true);
await VerifySendEnterThroughToEnterAsync("$$", "SnippetShortcut", sendThroughEnterOption: EnterKeyRule.Always, expected: true);
await VerifySendEnterThroughToEnterAsync("$$", "SnippetShortcu", sendThroughEnterOption: EnterKeyRule.AfterFullyTypedWord, expected: false);
await VerifySendEnterThroughToEnterAsync("$$", "SnippetShortcut", sendThroughEnterOption: EnterKeyRule.AfterFullyTypedWord, expected: true);
await VerifySendEnterThroughToEnterAsync("$$", "SnippetShortcu", sendThroughEnterOption: EnterKeyRule.Never, expected: false);
await VerifySendEnterThroughToEnterAsync("$$", "SnippetShortcut", sendThroughEnterOption: EnterKeyRule.Never, expected: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(6405, "https://github.com/dotnet/roslyn/issues/6405")]
public async Task SnippetsNotInPreProcessorContextForScriptDirectives()
{
await VerifyItemIsAbsentAsync(@"#r f$$", MockSnippetInfoService.SnippetShortcut, sourceCodeKind: SourceCodeKind.Script);
await VerifyItemIsAbsentAsync(@"#load f$$", MockSnippetInfoService.SnippetShortcut, sourceCodeKind: SourceCodeKind.Script);
await VerifyItemIsAbsentAsync(@"#!$$", MockSnippetInfoService.SnippetShortcut, sourceCodeKind: SourceCodeKind.Script);
}
[ExportLanguageService(typeof(ISnippetInfoService), LanguageNames.CSharp, ServiceLayer.Test), Shared, PartNotDiscoverable]
private class MockSnippetInfoService : ISnippetInfoService
{
internal const string SnippetShortcut = nameof(SnippetShortcut);
internal const string SnippetDescription = nameof(SnippetDescription);
internal const string SnippetTitle = nameof(SnippetTitle);
internal const string SnippetPath = nameof(SnippetPath);
internal const string PreProcessorSnippetShortcut = "#PreProcessorSnippetShortcut";
internal const string PreProcessorSnippetDescription = nameof(PreProcessorSnippetDescription);
internal const string PreProcessorSnippetTitle = "#PreProcessorSnippetTitle";
internal const string PreProcessorSnippetPath = nameof(PreProcessorSnippetPath);
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public MockSnippetInfoService()
{
}
public IEnumerable<SnippetInfo> GetSnippetsIfAvailable()
{
return new List<SnippetInfo>
{
new SnippetInfo(SnippetShortcut, SnippetTitle, SnippetDescription, SnippetPath),
new SnippetInfo(PreProcessorSnippetShortcut, PreProcessorSnippetTitle, PreProcessorSnippetDescription, PreProcessorSnippetPath)
};
}
public bool SnippetShortcutExists_NonBlocking(string shortcut)
{
return string.Equals(shortcut, SnippetShortcut, StringComparison.OrdinalIgnoreCase) ||
string.Equals(shortcut, PreProcessorSnippetShortcut, StringComparison.OrdinalIgnoreCase);
}
public bool ShouldFormatSnippet(SnippetInfo snippetInfo)
=> false;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Composition;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp.Completion.Providers;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Snippets;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders
{
public class SnippetCompletionProviderTests : AbstractCSharpCompletionProviderTests
{
internal override Type GetCompletionProviderType()
=> typeof(SnippetCompletionProvider);
protected override TestComposition GetComposition()
=> base.GetComposition().AddParts(typeof(MockSnippetInfoService));
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SnippetsInEmptyFile()
=> await VerifyItemExistsAsync(@"$$", MockSnippetInfoService.SnippetShortcut, sourceCodeKind: SourceCodeKind.Regular);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SnippetDescriptions()
=> await VerifyItemExistsAsync(@"$$", MockSnippetInfoService.SnippetShortcut, MockSnippetInfoService.SnippetTitle + Environment.NewLine + MockSnippetInfoService.SnippetDescription + Environment.NewLine + string.Format(FeaturesResources.Note_colon_Tab_twice_to_insert_the_0_snippet, MockSnippetInfoService.SnippetShortcut), SourceCodeKind.Regular);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SnippetsInNamespace()
=> await VerifyItemExistsAsync(@"namespace NS { $$ }", MockSnippetInfoService.SnippetShortcut, sourceCodeKind: SourceCodeKind.Regular);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SnippetsInClass()
=> await VerifyItemExistsAsync(@"namespace NS { class C { $$ } }", MockSnippetInfoService.SnippetShortcut, sourceCodeKind: SourceCodeKind.Regular);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SnippetsInMethod()
=> await VerifyItemExistsAsync(@"namespace NS { class C { void M() { $$ } } }", MockSnippetInfoService.SnippetShortcut, sourceCodeKind: SourceCodeKind.Regular);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SnippetsNotInLocalDeclarationIdentifier()
=> await VerifyItemIsAbsentAsync(@"namespace NS { class C { void M() { int $$ } } }", MockSnippetInfoService.SnippetShortcut, sourceCodeKind: SourceCodeKind.Regular);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SnippetsNotInEnum()
=> await VerifyItemIsAbsentAsync(@"namespace NS { enum E { $$ } }", MockSnippetInfoService.SnippetShortcut, sourceCodeKind: SourceCodeKind.Regular);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SnippetsInExpression()
=> await VerifyItemExistsAsync(@"namespace NS { class C { void M() { bool b = true && $$ } } }", MockSnippetInfoService.SnippetShortcut, sourceCodeKind: SourceCodeKind.Regular);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(608860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608860")]
public async Task SnippetsInPreProcessorContextWhenShortcutBeginsWithHash()
=> await VerifyItemExistsAsync(@"#$$", MockSnippetInfoService.PreProcessorSnippetShortcut.Substring(1), sourceCodeKind: SourceCodeKind.Regular);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(608860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608860")]
public async Task SnippetsNotInPreProcessorContextWhenShortcutDoesNotBeginWithHash()
=> await VerifyItemIsAbsentAsync(@"#$$", MockSnippetInfoService.SnippetShortcut, sourceCodeKind: SourceCodeKind.Regular);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(770156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770156")]
public async Task SnippetsNotInPreProcessorContextDirectiveNameAlreadyTyped()
=> await VerifyItemIsAbsentAsync(@"#region $$", MockSnippetInfoService.PreProcessorSnippetShortcut, sourceCodeKind: SourceCodeKind.Regular);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(839555, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/839555")]
public async Task ShowRegionSnippetWithHashRTyped()
=> await VerifyItemExistsAsync(@"#r$$", MockSnippetInfoService.PreProcessorSnippetShortcut.Substring(1), sourceCodeKind: SourceCodeKind.Regular);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SnippetsInLineSpanDirective()
=> await VerifyItemIsAbsentAsync(@"#line (1, 2) - (3, 4) $$", MockSnippetInfoService.PreProcessorSnippetShortcut, sourceCodeKind: SourceCodeKind.Regular);
[WorkItem(968256, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968256")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ShowSnippetsFromOtherContext()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if GOO
$$
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""GOO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
await VerifyItemInLinkedFilesAsync(markup, MockSnippetInfoService.SnippetShortcut, null);
}
[WorkItem(1140893, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1140893")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CommitWithEnterObeysOption()
{
await VerifySendEnterThroughToEnterAsync("$$", "SnippetShortcu", sendThroughEnterOption: EnterKeyRule.Always, expected: true);
await VerifySendEnterThroughToEnterAsync("$$", "SnippetShortcut", sendThroughEnterOption: EnterKeyRule.Always, expected: true);
await VerifySendEnterThroughToEnterAsync("$$", "SnippetShortcu", sendThroughEnterOption: EnterKeyRule.AfterFullyTypedWord, expected: false);
await VerifySendEnterThroughToEnterAsync("$$", "SnippetShortcut", sendThroughEnterOption: EnterKeyRule.AfterFullyTypedWord, expected: true);
await VerifySendEnterThroughToEnterAsync("$$", "SnippetShortcu", sendThroughEnterOption: EnterKeyRule.Never, expected: false);
await VerifySendEnterThroughToEnterAsync("$$", "SnippetShortcut", sendThroughEnterOption: EnterKeyRule.Never, expected: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(6405, "https://github.com/dotnet/roslyn/issues/6405")]
public async Task SnippetsNotInPreProcessorContextForScriptDirectives()
{
await VerifyItemIsAbsentAsync(@"#r f$$", MockSnippetInfoService.SnippetShortcut, sourceCodeKind: SourceCodeKind.Script);
await VerifyItemIsAbsentAsync(@"#load f$$", MockSnippetInfoService.SnippetShortcut, sourceCodeKind: SourceCodeKind.Script);
await VerifyItemIsAbsentAsync(@"#!$$", MockSnippetInfoService.SnippetShortcut, sourceCodeKind: SourceCodeKind.Script);
}
[ExportLanguageService(typeof(ISnippetInfoService), LanguageNames.CSharp, ServiceLayer.Test), Shared, PartNotDiscoverable]
private class MockSnippetInfoService : ISnippetInfoService
{
internal const string SnippetShortcut = nameof(SnippetShortcut);
internal const string SnippetDescription = nameof(SnippetDescription);
internal const string SnippetTitle = nameof(SnippetTitle);
internal const string SnippetPath = nameof(SnippetPath);
internal const string PreProcessorSnippetShortcut = "#PreProcessorSnippetShortcut";
internal const string PreProcessorSnippetDescription = nameof(PreProcessorSnippetDescription);
internal const string PreProcessorSnippetTitle = "#PreProcessorSnippetTitle";
internal const string PreProcessorSnippetPath = nameof(PreProcessorSnippetPath);
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public MockSnippetInfoService()
{
}
public IEnumerable<SnippetInfo> GetSnippetsIfAvailable()
{
return new List<SnippetInfo>
{
new SnippetInfo(SnippetShortcut, SnippetTitle, SnippetDescription, SnippetPath),
new SnippetInfo(PreProcessorSnippetShortcut, PreProcessorSnippetTitle, PreProcessorSnippetDescription, PreProcessorSnippetPath)
};
}
public bool SnippetShortcutExists_NonBlocking(string shortcut)
{
return string.Equals(shortcut, SnippetShortcut, StringComparison.OrdinalIgnoreCase) ||
string.Equals(shortcut, PreProcessorSnippetShortcut, StringComparison.OrdinalIgnoreCase);
}
public bool ShouldFormatSnippet(SnippetInfo snippetInfo)
=> false;
}
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Compilers/Core/Portable/Desktop/AssemblyPortabilityPolicy.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.IO;
using System.Xml;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Policy to be used when matching assembly reference to an assembly definition across platforms.
/// </summary>
internal struct AssemblyPortabilityPolicy : IEquatable<AssemblyPortabilityPolicy>
{
// 7cec85d7bea7798e (System, System.Core)
public readonly bool SuppressSilverlightPlatformAssembliesPortability;
// 31bf3856ad364e35 (Microsoft.VisualBasic, System.ComponentModel.Composition)
public readonly bool SuppressSilverlightLibraryAssembliesPortability;
public AssemblyPortabilityPolicy(
bool suppressSilverlightPlatformAssembliesPortability,
bool suppressSilverlightLibraryAssembliesPortability)
{
this.SuppressSilverlightLibraryAssembliesPortability = suppressSilverlightLibraryAssembliesPortability;
this.SuppressSilverlightPlatformAssembliesPortability = suppressSilverlightPlatformAssembliesPortability;
}
public override bool Equals(object obj)
{
return obj is AssemblyPortabilityPolicy && Equals((AssemblyPortabilityPolicy)obj);
}
public bool Equals(AssemblyPortabilityPolicy other)
{
return this.SuppressSilverlightLibraryAssembliesPortability == other.SuppressSilverlightLibraryAssembliesPortability
&& this.SuppressSilverlightPlatformAssembliesPortability == other.SuppressSilverlightPlatformAssembliesPortability;
}
public override int GetHashCode()
{
return (this.SuppressSilverlightLibraryAssembliesPortability ? 1 : 0) |
(this.SuppressSilverlightPlatformAssembliesPortability ? 2 : 0);
}
private static bool ReadToChild(XmlReader reader, int depth, string elementName, string elementNamespace = "")
{
return reader.ReadToDescendant(elementName, elementNamespace) && reader.Depth == depth;
}
private static readonly XmlReaderSettings s_xmlSettings = new XmlReaderSettings()
{
DtdProcessing = DtdProcessing.Prohibit,
};
internal static AssemblyPortabilityPolicy LoadFromXml(Stream input)
{
// Note: Unlike Fusion XML reader the XmlReader doesn't allow whitespace in front of <?xml version=""1.0"" encoding=""utf-8"" ?>
const string ns = "urn:schemas-microsoft-com:asm.v1";
using (XmlReader xml = XmlReader.Create(input, s_xmlSettings))
{
if (!ReadToChild(xml, 0, "configuration") ||
!ReadToChild(xml, 1, "runtime") ||
!ReadToChild(xml, 2, "assemblyBinding", ns) ||
!ReadToChild(xml, 3, "supportPortability", ns))
{
return default(AssemblyPortabilityPolicy);
}
// 31bf3856ad364e35
bool suppressLibrary = false;
// 7cec85d7bea7798e
bool suppressPlatform = false;
do
{
// see CNodeFactory::ProcessSupportPortabilityTag in fusion\inc\nodefact.cpp for details
// - unrecognized attributes ignored.
// - syntax errors within tags causes this tag to be ignored (but not reject entire app.config)
// - multiple <supportPortability> tags ok (if two specify same PKT, all but (implementation defined) one ignored.)
string pkt = xml.GetAttribute("PKT");
string enableAttribute = xml.GetAttribute("enable");
bool? enable =
string.Equals(enableAttribute, "false", StringComparison.OrdinalIgnoreCase) ? false :
string.Equals(enableAttribute, "true", StringComparison.OrdinalIgnoreCase) ? true :
(bool?)null;
if (enable != null)
{
if (string.Equals(pkt, "31bf3856ad364e35", StringComparison.OrdinalIgnoreCase))
{
suppressLibrary = !enable.Value;
}
else if (string.Equals(pkt, "7cec85d7bea7798e", StringComparison.OrdinalIgnoreCase))
{
suppressPlatform = !enable.Value;
}
}
} while (xml.ReadToNextSibling("supportPortability", ns));
return new AssemblyPortabilityPolicy(suppressPlatform, suppressLibrary);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.IO;
using System.Xml;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Policy to be used when matching assembly reference to an assembly definition across platforms.
/// </summary>
internal struct AssemblyPortabilityPolicy : IEquatable<AssemblyPortabilityPolicy>
{
// 7cec85d7bea7798e (System, System.Core)
public readonly bool SuppressSilverlightPlatformAssembliesPortability;
// 31bf3856ad364e35 (Microsoft.VisualBasic, System.ComponentModel.Composition)
public readonly bool SuppressSilverlightLibraryAssembliesPortability;
public AssemblyPortabilityPolicy(
bool suppressSilverlightPlatformAssembliesPortability,
bool suppressSilverlightLibraryAssembliesPortability)
{
this.SuppressSilverlightLibraryAssembliesPortability = suppressSilverlightLibraryAssembliesPortability;
this.SuppressSilverlightPlatformAssembliesPortability = suppressSilverlightPlatformAssembliesPortability;
}
public override bool Equals(object obj)
{
return obj is AssemblyPortabilityPolicy && Equals((AssemblyPortabilityPolicy)obj);
}
public bool Equals(AssemblyPortabilityPolicy other)
{
return this.SuppressSilverlightLibraryAssembliesPortability == other.SuppressSilverlightLibraryAssembliesPortability
&& this.SuppressSilverlightPlatformAssembliesPortability == other.SuppressSilverlightPlatformAssembliesPortability;
}
public override int GetHashCode()
{
return (this.SuppressSilverlightLibraryAssembliesPortability ? 1 : 0) |
(this.SuppressSilverlightPlatformAssembliesPortability ? 2 : 0);
}
private static bool ReadToChild(XmlReader reader, int depth, string elementName, string elementNamespace = "")
{
return reader.ReadToDescendant(elementName, elementNamespace) && reader.Depth == depth;
}
private static readonly XmlReaderSettings s_xmlSettings = new XmlReaderSettings()
{
DtdProcessing = DtdProcessing.Prohibit,
};
internal static AssemblyPortabilityPolicy LoadFromXml(Stream input)
{
// Note: Unlike Fusion XML reader the XmlReader doesn't allow whitespace in front of <?xml version=""1.0"" encoding=""utf-8"" ?>
const string ns = "urn:schemas-microsoft-com:asm.v1";
using (XmlReader xml = XmlReader.Create(input, s_xmlSettings))
{
if (!ReadToChild(xml, 0, "configuration") ||
!ReadToChild(xml, 1, "runtime") ||
!ReadToChild(xml, 2, "assemblyBinding", ns) ||
!ReadToChild(xml, 3, "supportPortability", ns))
{
return default(AssemblyPortabilityPolicy);
}
// 31bf3856ad364e35
bool suppressLibrary = false;
// 7cec85d7bea7798e
bool suppressPlatform = false;
do
{
// see CNodeFactory::ProcessSupportPortabilityTag in fusion\inc\nodefact.cpp for details
// - unrecognized attributes ignored.
// - syntax errors within tags causes this tag to be ignored (but not reject entire app.config)
// - multiple <supportPortability> tags ok (if two specify same PKT, all but (implementation defined) one ignored.)
string pkt = xml.GetAttribute("PKT");
string enableAttribute = xml.GetAttribute("enable");
bool? enable =
string.Equals(enableAttribute, "false", StringComparison.OrdinalIgnoreCase) ? false :
string.Equals(enableAttribute, "true", StringComparison.OrdinalIgnoreCase) ? true :
(bool?)null;
if (enable != null)
{
if (string.Equals(pkt, "31bf3856ad364e35", StringComparison.OrdinalIgnoreCase))
{
suppressLibrary = !enable.Value;
}
else if (string.Equals(pkt, "7cec85d7bea7798e", StringComparison.OrdinalIgnoreCase))
{
suppressPlatform = !enable.Value;
}
}
} while (xml.ReadToNextSibling("supportPortability", ns));
return new AssemblyPortabilityPolicy(suppressPlatform, suppressLibrary);
}
}
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Workspaces/MSBuildTest/Resources/NetCoreMultiTFM_ProjectReferenceToFSharp/csharplib/Class1.cs | using System;
namespace csharplib
{
public class Class1
{
}
}
| using System;
namespace csharplib
{
public class Class1
{
}
}
| -1 |
dotnet/roslyn | 55,407 | Emit EnC info for methods with no sequence points | Fixes https://github.com/dotnet/roslyn/issues/55381 | tmat | 2021-08-04T19:07:07Z | 2021-08-12T16:02:12Z | af25bd0383bf43f8f2bbada6c236ca4c43dfa9c1 | d87afc9cab53de52d5be7f7a96454b069ac49992 | Emit EnC info for methods with no sequence points. Fixes https://github.com/dotnet/roslyn/issues/55381 | ./src/Compilers/Test/Resources/Core/SymbolsTests/NoPia/Pia1.dll | MZ @ !L!This program cannot be run in DOS mode.
$ PE L aL ! $ @ @ @ `$ K @ ` H .text `.rsrc @ @ @.reloc ` @ B $ H P BSJB v4.0.30319 l t #~ 8 #Strings #US #GUID 0 #Blob W %3 , 1 * ] > t > > >
> ; ; F#
F#
( ( ! ! ) P 1
9 P A ! . 3 . . # ~ . + C C & |