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,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Compilers/VisualBasic/Test/Symbol/Microsoft.CodeAnalysis.VisualBasic.Symbol.UnitTests.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>net5.0;net472</TargetFrameworks>
<RootNamespace></RootNamespace>
<!-- A zillion test failures + crash. See https://github.com/mono/mono/issues/10756. -->
<SkipTests Condition="'$(TestRuntime)' == 'Mono'">true</SkipTests>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" />
<ProjectReference Include="..\..\..\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" />
<ProjectReference Include="..\..\..\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\..\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" />
<ProjectReference Include="..\..\..\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" />
<ProjectReference Include="..\..\..\Test\Utilities\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Test.Utilities.vbproj" />
<ProjectReference Include="..\..\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="My Project\" />
</ItemGroup>
<ItemGroup>
<Import Include="IdentifierComparison = Microsoft.CodeAnalysis.CaseInsensitiveComparison" />
<Import Include="Roslyn.Utilities" />
<Import Include="Xunit" />
</ItemGroup>
<ItemGroup>
<None Include="SymbolsTests\Metadata\MscorlibNamespacesAndTypes.bsl" />
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
<Import Project="$(RepositoryEngineeringDir)targets\ILAsm.targets" />
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>net5.0;net472</TargetFrameworks>
<RootNamespace></RootNamespace>
<!-- A zillion test failures + crash. See https://github.com/mono/mono/issues/10756. -->
<SkipTests Condition="'$(TestRuntime)' == 'Mono'">true</SkipTests>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" />
<ProjectReference Include="..\..\..\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" />
<ProjectReference Include="..\..\..\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\..\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" />
<ProjectReference Include="..\..\..\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" />
<ProjectReference Include="..\..\..\Test\Utilities\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Test.Utilities.vbproj" />
<ProjectReference Include="..\..\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="My Project\" />
</ItemGroup>
<ItemGroup>
<Import Include="IdentifierComparison = Microsoft.CodeAnalysis.CaseInsensitiveComparison" />
<Import Include="Roslyn.Utilities" />
<Import Include="Xunit" />
</ItemGroup>
<ItemGroup>
<None Include="SymbolsTests\Metadata\MscorlibNamespacesAndTypes.bsl" />
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
<Import Project="$(RepositoryEngineeringDir)targets\ILAsm.targets" />
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Compilers/VisualBasic/Test/CommandLine/Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>net472</TargetFramework>
<RootNamespace></RootNamespace>
<GenerateMicrosoftCodeAnalysisCommitHashAttribute>true</GenerateMicrosoftCodeAnalysisCommitHashAttribute>
<!--
Skipped because we appear to be missing things necessary to compile vb.net.
See https://github.com/mono/mono/issues/10679
-->
<SkipTests Condition="'$(TestRuntime)' == 'Mono'">true</SkipTests>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" />
<ProjectReference Include="..\..\..\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" />
<ProjectReference Include="..\..\..\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" />
<ProjectReference Include="..\..\..\Server\VBCSCompiler\VBCSCompiler.csproj" />
<ProjectReference Include="..\..\..\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\..\Test\Utilities\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Test.Utilities.vbproj" />
<ProjectReference Include="..\..\vbc\vbc.csproj" ReferenceOutputAssembly="false" OutputItemType="RoslynReferenceToDependencyDirectory" />
<ProjectReference Include="..\..\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\..\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" />
</ItemGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<Import Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="../../vbc/vbc.rsp" Link="Resources\vbc.rsp" />
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>net472</TargetFramework>
<RootNamespace></RootNamespace>
<GenerateMicrosoftCodeAnalysisCommitHashAttribute>true</GenerateMicrosoftCodeAnalysisCommitHashAttribute>
<!--
Skipped because we appear to be missing things necessary to compile vb.net.
See https://github.com/mono/mono/issues/10679
-->
<SkipTests Condition="'$(TestRuntime)' == 'Mono'">true</SkipTests>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" />
<ProjectReference Include="..\..\..\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" />
<ProjectReference Include="..\..\..\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" />
<ProjectReference Include="..\..\..\Server\VBCSCompiler\VBCSCompiler.csproj" />
<ProjectReference Include="..\..\..\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\..\Test\Utilities\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Test.Utilities.vbproj" />
<ProjectReference Include="..\..\vbc\vbc.csproj" ReferenceOutputAssembly="false" OutputItemType="RoslynReferenceToDependencyDirectory" />
<ProjectReference Include="..\..\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\..\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" />
</ItemGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<Import Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="../../vbc/vbc.rsp" Link="Resources\vbc.rsp" />
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Workspaces/MSBuildTest/Resources/ProjectFiles/VisualBasic/WithPrefer32Bit.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<PlatformTarget>AnyCPU</PlatformTarget>
<ProjectGuid>{5D92B789-04AE-4B5C-A550-4E13378FA18F}</ProjectGuid>
<OutputType>Exe</OutputType>
<StartupObject>ConsoleApplication1.Module1</StartupObject>
<RootNamespace>ConsoleApplication1</RootNamespace>
<AssemblyName>ConsoleApplication1</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Console</MyType>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\Debug\</OutputPath>
<DocumentationFile>ConsoleApplication1.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DocumentationFile>ConsoleApplication1.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>Off</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Data" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Deployment" />
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Data" />
<Import Include="System.Diagnostics" />
<Import Include="System.Linq" />
<Import Include="System.Threading.Tasks" />
<Import Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<Compile Include="VisualBasicClass.vb" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<PlatformTarget>AnyCPU</PlatformTarget>
<ProjectGuid>{5D92B789-04AE-4B5C-A550-4E13378FA18F}</ProjectGuid>
<OutputType>Exe</OutputType>
<StartupObject>ConsoleApplication1.Module1</StartupObject>
<RootNamespace>ConsoleApplication1</RootNamespace>
<AssemblyName>ConsoleApplication1</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Console</MyType>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\Debug\</OutputPath>
<DocumentationFile>ConsoleApplication1.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DocumentationFile>ConsoleApplication1.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>Off</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Data" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Deployment" />
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Data" />
<Import Include="System.Diagnostics" />
<Import Include="System.Linq" />
<Import Include="System.Threading.Tasks" />
<Import Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<Compile Include="VisualBasicClass.vb" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Tools/Source/CompilerGeneratorTools/Source/VisualBasicErrorFactsGenerator/VisualBasicErrorFactsGenerator.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Platform Condition="'$(Platform)' == ''">x64</Platform>
<PlatformTarget>x64</PlatformTarget>
<Platforms>x64</Platforms>
<OutputType>Exe</OutputType>
<StartupObject></StartupObject>
<RootNamespace>Microsoft.CodeAnalysis.VisualBasic.Internal.VBErrorFactsGenerator</RootNamespace>
<AssemblyName>VBErrorFactsGenerator</AssemblyName>
<AutoGenerateBindingRedirects>True</AutoGenerateBindingRedirects>
<TargetFramework>netcoreapp3.1</TargetFramework>
<IsShipping>false</IsShipping>
</PropertyGroup>
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Platform Condition="'$(Platform)' == ''">x64</Platform>
<PlatformTarget>x64</PlatformTarget>
<Platforms>x64</Platforms>
<OutputType>Exe</OutputType>
<StartupObject></StartupObject>
<RootNamespace>Microsoft.CodeAnalysis.VisualBasic.Internal.VBErrorFactsGenerator</RootNamespace>
<AssemblyName>VBErrorFactsGenerator</AssemblyName>
<AutoGenerateBindingRedirects>True</AutoGenerateBindingRedirects>
<TargetFramework>netcoreapp3.1</TargetFramework>
<IsShipping>false</IsShipping>
</PropertyGroup>
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Workspaces/MSBuildTest/Resources/ProjectFiles/VisualBasic/InvalidProjectReference.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<PlatformTarget>AnyCPU</PlatformTarget>
<ProductVersion></ProductVersion>
<SchemaVersion></SchemaVersion>
<ProjectGuid>{AC25ECDA-DE94-4FCF-A688-EB3A2BE3670C}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>VisualBasicProject</RootNamespace>
<AssemblyName>VisualBasicProject</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Windows</MyType>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\Debug\</OutputPath>
<DocumentationFile>VisualBasicProject.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
<RemoveIntegerChecks>true</RemoveIntegerChecks>
<AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile>
<DefineConstants>FURBY</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DocumentationFile>VisualBasicProject.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>Off</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Diagnostics" />
<Import Include="System.Linq" />
</ItemGroup>
<ItemGroup>
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<Compile Include="VisualBasicClass.vb" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="http://localhost/Invalid/InvalidProject.csproj">
<Project>{686DD036-86AA-443E-8A10-DDB43266A8C4}</Project>
<Name>CSharpProject</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<PlatformTarget>AnyCPU</PlatformTarget>
<ProductVersion></ProductVersion>
<SchemaVersion></SchemaVersion>
<ProjectGuid>{AC25ECDA-DE94-4FCF-A688-EB3A2BE3670C}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>VisualBasicProject</RootNamespace>
<AssemblyName>VisualBasicProject</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Windows</MyType>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\Debug\</OutputPath>
<DocumentationFile>VisualBasicProject.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
<RemoveIntegerChecks>true</RemoveIntegerChecks>
<AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile>
<DefineConstants>FURBY</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DocumentationFile>VisualBasicProject.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>Off</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Diagnostics" />
<Import Include="System.Linq" />
</ItemGroup>
<ItemGroup>
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<Compile Include="VisualBasicClass.vb" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="http://localhost/Invalid/InvalidProject.csproj">
<Project>{686DD036-86AA-443E-8A10-DDB43266A8C4}</Project>
<Name>CSharpProject</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/EditorFeatures/VisualBasic/Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>netcoreapp3.1;netstandard2.0</TargetFrameworks>
<RootNamespace></RootNamespace>
<ApplyNgenOptimization Condition="'$(TargetFramework)' == 'netstandard2.0'">partial</ApplyNgenOptimization>
<!-- NuGet -->
<IsPackable>true</IsPackable>
<PackageDescription>
.NET Compiler Platform ("Roslyn") support for VisualBasic editor features inside the Visual Studio editor.
</PackageDescription>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\Features\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Features.vbproj" />
<ProjectReference Include="..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" />
<ProjectReference Include="..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" />
<ProjectReference Include="..\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" />
<ProjectReference Include="..\..\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" />
<ProjectReference Include="..\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.Text.UI" Version="$(MicrosoftVisualStudioTextUIVersion)" />
<PackageReference Include="Microsoft.VisualStudio.Threading" Version="$(MicrosoftVisualStudioThreadingVersion)" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.CodeAnalysis.Editor.Shared.Extensions" />
<Import Include="Microsoft.CodeAnalysis.Editor.Shared.Options" />
<Import Include="Microsoft.CodeAnalysis.Shared.Extensions" />
<Import Include="Microsoft.CodeAnalysis.VisualBasic" />
<Import Include="Microsoft.CodeAnalysis.VisualBasic.Extensions" />
<Import Include="Roslyn.Utilities" />
<Import Include="Roslyn.Utilities.Contract" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.VisualBasic" />
<InternalsVisibleTo Include="Roslyn.Hosting.Diagnostics" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests" />
<InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.Test.Utilities" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities2" />
<InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.LiveShare" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="VBEditorResources.resx" GenerateSource="true" Namespace="Microsoft.CodeAnalysis.Editor.VisualBasic" />
</ItemGroup>
<ItemGroup>
<Folder Include="My Project\" />
</ItemGroup>
<ItemGroup>
<PublicAPI Include="PublicAPI.Shipped.txt" />
<PublicAPI Include="PublicAPI.Unshipped.txt" />
</ItemGroup>
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>netcoreapp3.1;netstandard2.0</TargetFrameworks>
<RootNamespace></RootNamespace>
<ApplyNgenOptimization Condition="'$(TargetFramework)' == 'netstandard2.0'">partial</ApplyNgenOptimization>
<!-- NuGet -->
<IsPackable>true</IsPackable>
<PackageDescription>
.NET Compiler Platform ("Roslyn") support for VisualBasic editor features inside the Visual Studio editor.
</PackageDescription>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\Features\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Features.vbproj" />
<ProjectReference Include="..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" />
<ProjectReference Include="..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" />
<ProjectReference Include="..\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" />
<ProjectReference Include="..\..\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" />
<ProjectReference Include="..\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.Text.UI" Version="$(MicrosoftVisualStudioTextUIVersion)" />
<PackageReference Include="Microsoft.VisualStudio.Threading" Version="$(MicrosoftVisualStudioThreadingVersion)" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.CodeAnalysis.Editor.Shared.Extensions" />
<Import Include="Microsoft.CodeAnalysis.Editor.Shared.Options" />
<Import Include="Microsoft.CodeAnalysis.Shared.Extensions" />
<Import Include="Microsoft.CodeAnalysis.VisualBasic" />
<Import Include="Microsoft.CodeAnalysis.VisualBasic.Extensions" />
<Import Include="Roslyn.Utilities" />
<Import Include="Roslyn.Utilities.Contract" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.VisualBasic" />
<InternalsVisibleTo Include="Roslyn.Hosting.Diagnostics" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests" />
<InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.Test.Utilities" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities2" />
<InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.LiveShare" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="VBEditorResources.resx" GenerateSource="true" Namespace="Microsoft.CodeAnalysis.Editor.VisualBasic" />
</ItemGroup>
<ItemGroup>
<Folder Include="My Project\" />
</ItemGroup>
<ItemGroup>
<PublicAPI Include="PublicAPI.Shipped.txt" />
<PublicAPI Include="PublicAPI.Unshipped.txt" />
</ItemGroup>
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/Microsoft.CodeAnalysis.VisualBasic.ExpressionCompiler.UnitTests.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<AssemblyName>Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ExpressionCompiler.UnitTests</AssemblyName>
<TargetFramework>net472</TargetFramework>
<RootNamespace></RootNamespace>
</PropertyGroup>
<ItemGroup Label="File References">
<Reference Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" />
<ProjectReference Include="..\..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" />
<ProjectReference Include="..\..\..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" />
<ProjectReference Include="..\..\..\Core\Source\ExpressionCompiler\Microsoft.CodeAnalysis.ExpressionCompiler.csproj" />
<ProjectReference Include="..\..\..\Core\Test\ExpressionCompiler\Microsoft.CodeAnalysis.ExpressionCompiler.Utilities.csproj" />
<ProjectReference Include="..\..\Source\ExpressionCompiler\Microsoft.CodeAnalysis.VisualBasic.ExpressionCompiler.vbproj" />
<ProjectReference Include="..\..\..\..\Compilers\Test\Utilities\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Test.Utilities.vbproj" />
<ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" />
</ItemGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Xml" />
<PackageReference Include="Microsoft.VisualStudio.Debugger.Engine-implementation" Version="$(MicrosoftVisualStudioDebuggerEngineimplementationVersion)" />
<PackageReference Include="Microsoft.DiaSymReader" Version="$(MicrosoftDiaSymReaderVersion)" />
</ItemGroup>
<ItemGroup>
<Folder Include="My Project\" />
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
<Import Project="$(RepositoryEngineeringDir)targets\ILAsm.targets" />
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<AssemblyName>Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ExpressionCompiler.UnitTests</AssemblyName>
<TargetFramework>net472</TargetFramework>
<RootNamespace></RootNamespace>
</PropertyGroup>
<ItemGroup Label="File References">
<Reference Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" />
<ProjectReference Include="..\..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" />
<ProjectReference Include="..\..\..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" />
<ProjectReference Include="..\..\..\Core\Source\ExpressionCompiler\Microsoft.CodeAnalysis.ExpressionCompiler.csproj" />
<ProjectReference Include="..\..\..\Core\Test\ExpressionCompiler\Microsoft.CodeAnalysis.ExpressionCompiler.Utilities.csproj" />
<ProjectReference Include="..\..\Source\ExpressionCompiler\Microsoft.CodeAnalysis.VisualBasic.ExpressionCompiler.vbproj" />
<ProjectReference Include="..\..\..\..\Compilers\Test\Utilities\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Test.Utilities.vbproj" />
<ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" />
</ItemGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Xml" />
<PackageReference Include="Microsoft.VisualStudio.Debugger.Engine-implementation" Version="$(MicrosoftVisualStudioDebuggerEngineimplementationVersion)" />
<PackageReference Include="Microsoft.DiaSymReader" Version="$(MicrosoftDiaSymReaderVersion)" />
</ItemGroup>
<ItemGroup>
<Folder Include="My Project\" />
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
<Import Project="$(RepositoryEngineeringDir)targets\ILAsm.targets" />
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Workspaces/MSBuildTest/Resources/Issue29122/Proj2/ClassLibrary2.vbproj | <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{65D39B82-9F22-4350-9BFF-3988C367809B}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>ClassLibrary2</RootNamespace>
<AssemblyName>ClassLibrary2</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Windows</MyType>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<TargetFrameworkProfile />
<RestorePackages>true</RestorePackages>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>On</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<DebugSymbols>true</DebugSymbols>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>..\Dev\Modules\</OutputPath>
<NoWarn>
</NoWarn>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>..\Dev\Modules\</OutputPath>
<NoWarn>
</NoWarn>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<Compile Include="Class1.vb" />
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Proj1\ClassLibrary1.vbproj">
<Project>{f8ae35ab-1ac5-4381-bb3e-0645519695f5}</Project>
<Name>ClassLibrary1</Name>
<Private>False</Private>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
</Project> | <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{65D39B82-9F22-4350-9BFF-3988C367809B}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>ClassLibrary2</RootNamespace>
<AssemblyName>ClassLibrary2</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Windows</MyType>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<TargetFrameworkProfile />
<RestorePackages>true</RestorePackages>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>On</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<DebugSymbols>true</DebugSymbols>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>..\Dev\Modules\</OutputPath>
<NoWarn>
</NoWarn>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>..\Dev\Modules\</OutputPath>
<NoWarn>
</NoWarn>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<Compile Include="Class1.vb" />
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Proj1\ClassLibrary1.vbproj">
<Project>{f8ae35ab-1ac5-4381-bb3e-0645519695f5}</Project>
<Name>ClassLibrary1</Name>
<Private>False</Private>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/Microsoft.CodeAnalysis.VisualBasic.ResultProvider.UnitTests.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<AssemblyName>Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ResultProvider.UnitTests</AssemblyName>
<TargetFramework>net472</TargetFramework>
<VBRuntime>Default</VBRuntime>
<RootNamespace></RootNamespace>
</PropertyGroup>
<ItemGroup Label="File References">
<Reference Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\..\..\Compilers\Test\Utilities\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Test.Utilities.vbproj" />
<ProjectReference Include="..\..\..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" />
<ProjectReference Include="..\..\..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" />
<ProjectReference Include="..\..\..\Core\Test\ResultProvider\Microsoft.CodeAnalysis.ResultProvider.Utilities.csproj" />
<!-- This reference is only needed to ensure correct build ordering (we link in all the necessary files as source). -->
<ProjectReference Include="..\..\..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" />
<ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" />
</ItemGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\..\..\Compilers\VisualBasic\Portable\SymbolDisplay\ObjectDisplay.vb">
<Link>Compiler\SymbolDisplay\ObjectDisplay.vb</Link>
</Compile>
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
<Import Project="..\..\Source\ResultProvider\BasicResultProvider.projitems" Label="Shared" />
<Import Project="$(RepositoryEngineeringDir)targets\ILAsm.targets" />
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<AssemblyName>Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ResultProvider.UnitTests</AssemblyName>
<TargetFramework>net472</TargetFramework>
<VBRuntime>Default</VBRuntime>
<RootNamespace></RootNamespace>
</PropertyGroup>
<ItemGroup Label="File References">
<Reference Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\..\..\Compilers\Test\Utilities\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Test.Utilities.vbproj" />
<ProjectReference Include="..\..\..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" />
<ProjectReference Include="..\..\..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" />
<ProjectReference Include="..\..\..\Core\Test\ResultProvider\Microsoft.CodeAnalysis.ResultProvider.Utilities.csproj" />
<!-- This reference is only needed to ensure correct build ordering (we link in all the necessary files as source). -->
<ProjectReference Include="..\..\..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" />
<ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" />
</ItemGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\..\..\Compilers\VisualBasic\Portable\SymbolDisplay\ObjectDisplay.vb">
<Link>Compiler\SymbolDisplay\ObjectDisplay.vb</Link>
</Compile>
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
<Import Project="..\..\Source\ResultProvider\BasicResultProvider.projitems" Label="Shared" />
<Import Project="$(RepositoryEngineeringDir)targets\ILAsm.targets" />
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Scripting/VisualBasic/Microsoft.CodeAnalysis.VisualBasic.Scripting.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>netcoreapp3.1;netstandard2.0</TargetFrameworks>
<VBRuntime>None</VBRuntime>
<RootNamespace></RootNamespace>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\Core\Microsoft.CodeAnalysis.Scripting.csproj" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="VBScriptingResources.resx" GenerateSource="true" Namespace="Microsoft.CodeAnalysis.VisualBasic.Scripting"/>
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="vbi" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Emit.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.Scripting.TestUtilities" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.Scripting.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Scripting.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Scripting.Desktop.UnitTests" />
</ItemGroup>
<ItemGroup>
<PublicAPI Include="PublicAPI.Shipped.txt" />
</ItemGroup>
<ItemGroup>
<PublicAPI Include="PublicAPI.Unshipped.txt" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.VisualBasic" Version="$(MicrosoftVisualBasicVersion)" />
</ItemGroup>
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>netcoreapp3.1;netstandard2.0</TargetFrameworks>
<VBRuntime>None</VBRuntime>
<RootNamespace></RootNamespace>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\Core\Microsoft.CodeAnalysis.Scripting.csproj" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="VBScriptingResources.resx" GenerateSource="true" Namespace="Microsoft.CodeAnalysis.VisualBasic.Scripting"/>
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="vbi" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Emit.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.Scripting.TestUtilities" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.Scripting.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Scripting.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Scripting.Desktop.UnitTests" />
</ItemGroup>
<ItemGroup>
<PublicAPI Include="PublicAPI.Shipped.txt" />
</ItemGroup>
<ItemGroup>
<PublicAPI Include="PublicAPI.Unshipped.txt" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.VisualBasic" Version="$(MicrosoftVisualBasicVersion)" />
</ItemGroup>
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Workspaces/MSBuildTest/Resources/ProjectFiles/VisualBasic/WithoutPrefer32Bit.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<PlatformTarget>AnyCPU</PlatformTarget>
<Prefer32Bit>false</Prefer32Bit>
<ProjectGuid>{5D92B789-04AE-4B5C-A550-4E13378FA18F}</ProjectGuid>
<OutputType>Exe</OutputType>
<StartupObject>ConsoleApplication1.Module1</StartupObject>
<RootNamespace>ConsoleApplication1</RootNamespace>
<AssemblyName>ConsoleApplication1</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Console</MyType>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\Debug\</OutputPath>
<DocumentationFile>ConsoleApplication1.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DocumentationFile>ConsoleApplication1.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>Off</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Data" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Deployment" />
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Data" />
<Import Include="System.Diagnostics" />
<Import Include="System.Linq" />
<Import Include="System.Threading.Tasks" />
<Import Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<Compile Include="VisualBasicClass.vb" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<PlatformTarget>AnyCPU</PlatformTarget>
<Prefer32Bit>false</Prefer32Bit>
<ProjectGuid>{5D92B789-04AE-4B5C-A550-4E13378FA18F}</ProjectGuid>
<OutputType>Exe</OutputType>
<StartupObject>ConsoleApplication1.Module1</StartupObject>
<RootNamespace>ConsoleApplication1</RootNamespace>
<AssemblyName>ConsoleApplication1</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Console</MyType>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\Debug\</OutputPath>
<DocumentationFile>ConsoleApplication1.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DocumentationFile>ConsoleApplication1.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>Off</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Data" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Deployment" />
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Data" />
<Import Include="System.Diagnostics" />
<Import Include="System.Linq" />
<Import Include="System.Threading.Tasks" />
<Import Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<Compile Include="VisualBasicClass.vb" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Workspaces/MSBuildTest/Resources/ProjectFiles/VisualBasic/Embed.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<PlatformTarget>AnyCPU</PlatformTarget>
<ProductVersion></ProductVersion>
<SchemaVersion></SchemaVersion>
<ProjectGuid>{AC25ECDA-DE94-4FCF-A688-EB3A2BE3670C}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>VisualBasicProject</RootNamespace>
<AssemblyName>VisualBasicProject</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Windows</MyType>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<VBRuntime>Embed</VBRuntime>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\Debug\</OutputPath>
<DocumentationFile>VisualBasicProject.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
<RemoveIntegerChecks>true</RemoveIntegerChecks>
<AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile>
<DefineConstants>FURBY</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DocumentationFile>VisualBasicProject.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>Off</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Diagnostics" />
<Import Include="System.Linq" />
</ItemGroup>
<ItemGroup>
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<Compile Include="VisualBasicClass.vb" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CSharpProject\CSharpProject.csproj">
<Project>{686DD036-86AA-443E-8A10-DDB43266A8C4}</Project>
<Name>CSharpProject</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<PlatformTarget>AnyCPU</PlatformTarget>
<ProductVersion></ProductVersion>
<SchemaVersion></SchemaVersion>
<ProjectGuid>{AC25ECDA-DE94-4FCF-A688-EB3A2BE3670C}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>VisualBasicProject</RootNamespace>
<AssemblyName>VisualBasicProject</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Windows</MyType>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<VBRuntime>Embed</VBRuntime>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\Debug\</OutputPath>
<DocumentationFile>VisualBasicProject.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
<RemoveIntegerChecks>true</RemoveIntegerChecks>
<AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile>
<DefineConstants>FURBY</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DocumentationFile>VisualBasicProject.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>Off</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Diagnostics" />
<Import Include="System.Linq" />
</ItemGroup>
<ItemGroup>
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<Compile Include="VisualBasicClass.vb" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CSharpProject\CSharpProject.csproj">
<Project>{686DD036-86AA-443E-8A10-DDB43266A8C4}</Project>
<Name>CSharpProject</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Compilers/VisualBasic/Portable/Microsoft.CodeAnalysis.VisualBasic.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>netcoreapp3.1;netstandard2.0</TargetFrameworks>
<NoWarn>$(NoWarn);42014</NoWarn>
<CodeAnalysisRuleSet>..\BasicCodeAnalysisRules.ruleset</CodeAnalysisRuleSet>
<GenerateMicrosoftCodeAnalysisCommitHashAttribute>true</GenerateMicrosoftCodeAnalysisCommitHashAttribute>
<RootNamespace></RootNamespace>
<ApplyNgenOptimization Condition="'$(TargetFramework)' == 'netstandard2.0'">partial</ApplyNgenOptimization>
<!-- NuGet -->
<IsPackable>true</IsPackable>
<PackageDescription>
.NET Compiler Platform ("Roslyn") support for Visual Basic, $(AssemblyName).dll.
</PackageDescription>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\Core\Portable\Microsoft.CodeAnalysis.csproj" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="VBResources.resx" GenerateSource="true" Namespace="Microsoft.CodeAnalysis.VisualBasic" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Symbols\EmbeddedSymbols\Embedded.vb" />
<EmbeddedResource Include="Symbols\EmbeddedSymbols\InternalXmlHelper.vb" />
<EmbeddedResource Include="Symbols\EmbeddedSymbols\VbCoreSourceText.vb" />
<EmbeddedResource Include="Symbols\EmbeddedSymbols\VbMyTemplateText.vb" />
<Compile Remove="Symbols\EmbeddedSymbols\Embedded.vb" />
<Compile Remove="Symbols\EmbeddedSymbols\InternalXmlHelper.vb" />
<Compile Remove="Symbols\EmbeddedSymbols\VbCoreSourceText.vb" />
<Compile Remove="Symbols\EmbeddedSymbols\VbMyTemplateText.vb" />
</ItemGroup>
<ItemGroup>
<None Include="BoundTree\BoundNodes.xml" />
<PublicAPI Include="PublicAPI.Shipped.txt" />
<PublicAPI Include="PublicAPI.Unshipped.txt" />
<None Include="Generated\VisualBasic.Grammar.g4" />
<None Include="Symbols\SymbolsAndNoPia.docx" />
<None Include="Syntax\Syntax.xml" />
<None Include="Errors\Errors.vb" />
</ItemGroup>
<ItemGroup>
<Import Include="IdentifierComparison = Microsoft.CodeAnalysis.CaseInsensitiveComparison" />
<Import Include="Roslyn.Utilities" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ExpressionCompiler" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Scripting" />
<InternalsVisibleTo Include="vbc" />
<InternalsVisibleTo Include="vbi" />
<InternalsVisibleTo Include="VBCSCompiler" />
<InternalsVisibleTo Include="VBCSCompiler.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.Rebuild.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Emit.UnitTests" />
<InternalsVisibleTo Include="Roslyn.Compilers.VisualBasic.IOperation.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Semantic.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Symbol.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Syntax.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Test.Utilities" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ExpressionCompiler.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.Utilities" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.Test.Utilities" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.Scripting.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.Scripting.Desktop.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Scripting.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Scripting.Desktop.UnitTests" />
<InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" />
</ItemGroup>
<ItemGroup>
<Folder Include="My Project\" />
</ItemGroup>
<ItemGroup>
<None Include="..\BasicCodeAnalysisRules.ruleset">
<SubType>Designer</SubType>
</None>
</ItemGroup>
<Import Project="..\BasicAnalyzerDriver\BasicAnalyzerDriver.projitems" Label="Shared" />
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>netcoreapp3.1;netstandard2.0</TargetFrameworks>
<NoWarn>$(NoWarn);42014</NoWarn>
<CodeAnalysisRuleSet>..\BasicCodeAnalysisRules.ruleset</CodeAnalysisRuleSet>
<GenerateMicrosoftCodeAnalysisCommitHashAttribute>true</GenerateMicrosoftCodeAnalysisCommitHashAttribute>
<RootNamespace></RootNamespace>
<ApplyNgenOptimization Condition="'$(TargetFramework)' == 'netstandard2.0'">partial</ApplyNgenOptimization>
<!-- NuGet -->
<IsPackable>true</IsPackable>
<PackageDescription>
.NET Compiler Platform ("Roslyn") support for Visual Basic, $(AssemblyName).dll.
</PackageDescription>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\Core\Portable\Microsoft.CodeAnalysis.csproj" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="VBResources.resx" GenerateSource="true" Namespace="Microsoft.CodeAnalysis.VisualBasic" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Symbols\EmbeddedSymbols\Embedded.vb" />
<EmbeddedResource Include="Symbols\EmbeddedSymbols\InternalXmlHelper.vb" />
<EmbeddedResource Include="Symbols\EmbeddedSymbols\VbCoreSourceText.vb" />
<EmbeddedResource Include="Symbols\EmbeddedSymbols\VbMyTemplateText.vb" />
<Compile Remove="Symbols\EmbeddedSymbols\Embedded.vb" />
<Compile Remove="Symbols\EmbeddedSymbols\InternalXmlHelper.vb" />
<Compile Remove="Symbols\EmbeddedSymbols\VbCoreSourceText.vb" />
<Compile Remove="Symbols\EmbeddedSymbols\VbMyTemplateText.vb" />
</ItemGroup>
<ItemGroup>
<None Include="BoundTree\BoundNodes.xml" />
<PublicAPI Include="PublicAPI.Shipped.txt" />
<PublicAPI Include="PublicAPI.Unshipped.txt" />
<None Include="Generated\VisualBasic.Grammar.g4" />
<None Include="Symbols\SymbolsAndNoPia.docx" />
<None Include="Syntax\Syntax.xml" />
<None Include="Errors\Errors.vb" />
</ItemGroup>
<ItemGroup>
<Import Include="IdentifierComparison = Microsoft.CodeAnalysis.CaseInsensitiveComparison" />
<Import Include="Roslyn.Utilities" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ExpressionCompiler" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Scripting" />
<InternalsVisibleTo Include="vbc" />
<InternalsVisibleTo Include="vbi" />
<InternalsVisibleTo Include="VBCSCompiler" />
<InternalsVisibleTo Include="VBCSCompiler.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.Rebuild.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Emit.UnitTests" />
<InternalsVisibleTo Include="Roslyn.Compilers.VisualBasic.IOperation.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Semantic.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Symbol.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Syntax.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Test.Utilities" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ExpressionCompiler.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.Utilities" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.Test.Utilities" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.Scripting.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.Scripting.Desktop.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Scripting.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Scripting.Desktop.UnitTests" />
<InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" />
</ItemGroup>
<ItemGroup>
<Folder Include="My Project\" />
</ItemGroup>
<ItemGroup>
<None Include="..\BasicCodeAnalysisRules.ruleset">
<SubType>Designer</SubType>
</None>
</ItemGroup>
<Import Project="..\BasicAnalyzerDriver\BasicAnalyzerDriver.projitems" Label="Shared" />
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Workspaces/VisualBasicTest/Microsoft.CodeAnalysis.VisualBasic.Workspaces.UnitTests.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<OptionStrict>Off</OptionStrict>
<TargetFrameworks>netcoreapp3.1;net472</TargetFrameworks>
<RootNamespace></RootNamespace>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" />
<ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" />
<ProjectReference Include="..\..\EditorFeatures\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" />
<ProjectReference Include="..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" />
<ProjectReference Include="..\..\Features\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Features.csproj" />
<ProjectReference Include="..\..\Features\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Features.vbproj" />
<ProjectReference Include="..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" />
<ProjectReference Include="..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" />
<ProjectReference Include="..\CoreTestUtilities\Microsoft.CodeAnalysis.Workspaces.Test.Utilities.csproj" />
<ProjectReference Include="..\Remote\Core\Microsoft.CodeAnalysis.Remote.Workspaces.csproj" />
<ProjectReference Include="..\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" />
<ProjectReference Include="..\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" />
<ProjectReference Include="..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" />
<ProjectReference Include="..\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" />
<ProjectReference Include="..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" />
</ItemGroup>
<ItemGroup>
<Import Include="System.Xml.Linq" />
<Import Include="System.Threading.Tasks" />
</ItemGroup>
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<OptionStrict>Off</OptionStrict>
<TargetFrameworks>netcoreapp3.1;net472</TargetFrameworks>
<RootNamespace></RootNamespace>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" />
<ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" />
<ProjectReference Include="..\..\EditorFeatures\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" />
<ProjectReference Include="..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" />
<ProjectReference Include="..\..\Features\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Features.csproj" />
<ProjectReference Include="..\..\Features\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Features.vbproj" />
<ProjectReference Include="..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" />
<ProjectReference Include="..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" />
<ProjectReference Include="..\CoreTestUtilities\Microsoft.CodeAnalysis.Workspaces.Test.Utilities.csproj" />
<ProjectReference Include="..\Remote\Core\Microsoft.CodeAnalysis.Remote.Workspaces.csproj" />
<ProjectReference Include="..\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" />
<ProjectReference Include="..\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" />
<ProjectReference Include="..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" />
<ProjectReference Include="..\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" />
<ProjectReference Include="..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" />
</ItemGroup>
<ItemGroup>
<Import Include="System.Xml.Linq" />
<Import Include="System.Threading.Tasks" />
</ItemGroup>
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Interactive/vbi/vbi.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="$(RepositoryEngineeringDir)targets\GenerateCompilerExecutableBindingRedirects.targets" />
<PropertyGroup>
<OutputType>Exe</OutputType>
<StartupObject>Sub Main</StartupObject>
<TargetFrameworks>netcoreapp3.1;net472</TargetFrameworks>
<RootNamespace></RootNamespace>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" />
<ProjectReference Include="..\..\Scripting\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Scripting.vbproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.VisualBasic" Version="$(MicrosoftVisualBasicVersion)" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="vbi.coreclr.rsp" Condition="'$(TargetFramework)' == 'netcoreapp3.1'">
<Link>vbi.rsp</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="vbi.desktop.rsp" Condition="'$(TargetFramework)' != 'netcoreapp3.1'">
<Link>vbi.rsp</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Scripting.Desktop.UnitTests" />
</ItemGroup>
<ItemGroup>
<Folder Include="My Project\" />
</ItemGroup>
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="$(RepositoryEngineeringDir)targets\GenerateCompilerExecutableBindingRedirects.targets" />
<PropertyGroup>
<OutputType>Exe</OutputType>
<StartupObject>Sub Main</StartupObject>
<TargetFrameworks>netcoreapp3.1;net472</TargetFrameworks>
<RootNamespace></RootNamespace>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" />
<ProjectReference Include="..\..\Scripting\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Scripting.vbproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.VisualBasic" Version="$(MicrosoftVisualBasicVersion)" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="vbi.coreclr.rsp" Condition="'$(TargetFramework)' == 'netcoreapp3.1'">
<Link>vbi.rsp</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="vbi.desktop.rsp" Condition="'$(TargetFramework)' != 'netcoreapp3.1'">
<Link>vbi.rsp</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Scripting.Desktop.UnitTests" />
</ItemGroup>
<ItemGroup>
<Folder Include="My Project\" />
</ItemGroup>
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Scripting/VisualBasicTest.Desktop/Microsoft.CodeAnalysis.VisualBasic.Scripting.Desktop.UnitTests.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<TargetFramework>net472</TargetFramework>
<RootNamespace></RootNamespace>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" />
<ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" />
<ProjectReference Include="..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" />
<ProjectReference Include="..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" />
<ProjectReference Include="..\CoreTestUtilities\Microsoft.CodeAnalysis.Scripting.TestUtilities.csproj" />
<ProjectReference Include="..\Core\Microsoft.CodeAnalysis.Scripting.csproj" />
<ProjectReference Include="..\CSharp\Microsoft.CodeAnalysis.CSharp.Scripting.csproj" />
<ProjectReference Include="..\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Scripting.vbproj" />
</ItemGroup>
<ItemGroup>
<Reference Include="System.Data" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<Folder Include="Properties\" />
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<TargetFramework>net472</TargetFramework>
<RootNamespace></RootNamespace>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" />
<ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" />
<ProjectReference Include="..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" />
<ProjectReference Include="..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" />
<ProjectReference Include="..\CoreTestUtilities\Microsoft.CodeAnalysis.Scripting.TestUtilities.csproj" />
<ProjectReference Include="..\Core\Microsoft.CodeAnalysis.Scripting.csproj" />
<ProjectReference Include="..\CSharp\Microsoft.CodeAnalysis.CSharp.Scripting.csproj" />
<ProjectReference Include="..\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Scripting.vbproj" />
</ItemGroup>
<ItemGroup>
<Reference Include="System.Data" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<Folder Include="Properties\" />
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/CodeStyle/VisualBasic/Tests/Microsoft.CodeAnalysis.VisualBasic.CodeStyle.UnitTests.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>net472</TargetFramework>
<RootNamespace></RootNamespace>
<DefineConstants>$(DefineConstants),CODE_STYLE</DefineConstants>
<!-- https://github.com/dotnet/roslyn/issues/31412 -->
<SkipTests Condition="'$(TestRuntime)' == 'Mono'">true</SkipTests>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\..\EditorFeatures\VisualBasicTest\Diagnostics\AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest.vb" Link="AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest.vb" />
<Compile Include="..\..\..\EditorFeatures\VisualBasicTest\Utils.vb" Link="Utils.vb" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.VisualBasic.CodeFix.Testing.XUnit" Version="$(MicrosoftCodeAnalysisVisualBasicCodeFixTestingXUnitVersion)" />
</ItemGroup>
<ItemGroup Label="Project References">
<!-- Directly reference the Workspaces project so we always test against the latest Roslyn bits -->
<ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" />
<ProjectReference Include="..\..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" />
<ProjectReference Include="..\..\..\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" />
<ProjectReference Include="..\..\..\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" />
</ItemGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\Core\Analyzers\Microsoft.CodeAnalysis.CodeStyle.csproj" />
<ProjectReference Include="..\..\Core\CodeFixes\Microsoft.CodeAnalysis.CodeStyle.Fixes.csproj" />
<ProjectReference Include="..\..\Core\Tests\Microsoft.CodeAnalysis.CodeStyle.UnitTestUtilities.csproj" />
<ProjectReference Include="..\..\Core\Tests\Microsoft.CodeAnalysis.CodeStyle.LegacyTestFramework.UnitTestUtilities.csproj" />
<ProjectReference Include="..\Analyzers\Microsoft.CodeAnalysis.VisualBasic.CodeStyle.vbproj" />
<ProjectReference Include="..\CodeFixes\Microsoft.CodeAnalysis.VisualBasic.CodeStyle.Fixes.vbproj" />
</ItemGroup>
<ItemGroup Label="Project References">
<!-- TODO: Remove all the below project references once all analyzer/code fix tests are switched to Microsoft.CodeAnalysis.Testing -->
<ProjectReference Include="..\..\..\Compilers\Test\Utilities\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Test.Utilities.vbproj" />
<ProjectReference Include="..\..\..\EditorFeatures\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" />
<ProjectReference Include="..\..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" />
<ProjectReference Include="..\..\..\EditorFeatures\CSharp\Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj" />
<ProjectReference Include="..\..\..\EditorFeatures\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj" />
<ProjectReference Include="..\..\..\EditorFeatures\Core.Wpf\Microsoft.CodeAnalysis.EditorFeatures.Wpf.csproj" />
<ProjectReference Include="..\..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" />
<ProjectReference Include="..\..\..\Features\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Features.csproj" />
<ProjectReference Include="..\..\..\Features\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Features.vbproj" />
<ProjectReference Include="..\..\..\Interactive\Host\Microsoft.CodeAnalysis.InteractiveHost.csproj" />
<ProjectReference Include="..\..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" />
<ProjectReference Include="..\..\..\Scripting\CSharp\Microsoft.CodeAnalysis.CSharp.Scripting.csproj" />
<ProjectReference Include="..\..\..\Features\LanguageServer\Protocol\Microsoft.CodeAnalysis.LanguageServer.Protocol.csproj" />
<ProjectReference Include="..\..\..\Workspaces\Remote\Core\Microsoft.CodeAnalysis.Remote.Workspaces.csproj" />
<ProjectReference Include="..\..\..\Workspaces\Remote\ServiceHub\Microsoft.CodeAnalysis.Remote.ServiceHub.csproj" />
<ProjectReference Include="..\..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" />
<ProjectReference Include="..\..\..\EditorFeatures\TestUtilities\Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.csproj" />
<ProjectReference Include="..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" />
<ProjectReference Include="..\..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" />
<ProjectReference Include="..\..\..\Workspaces\CoreTestUtilities\Microsoft.CodeAnalysis.Workspaces.Test.Utilities.csproj" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.CodeAnalysis.Editor.Shared.Extensions" />
<Import Include="Microsoft.CodeAnalysis.Shared.Extensions" />
<Import Include="Microsoft.CodeAnalysis.Test.Utilities" />
<Import Include="Microsoft.CodeAnalysis.VisualBasic" />
<Import Include="Microsoft.CodeAnalysis.VisualBasic.UnitTests" />
<Import Include="Roslyn.Test.Utilities" />
<Import Include="System.Threading.Tasks" />
<Import Include="Xunit" />
</ItemGroup>
<Import Project="..\..\..\Analyzers\VisualBasic\Tests\VisualBasicAnalyzers.UnitTests.projitems" Label="Shared" />
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>net472</TargetFramework>
<RootNamespace></RootNamespace>
<DefineConstants>$(DefineConstants),CODE_STYLE</DefineConstants>
<!-- https://github.com/dotnet/roslyn/issues/31412 -->
<SkipTests Condition="'$(TestRuntime)' == 'Mono'">true</SkipTests>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\..\EditorFeatures\VisualBasicTest\Diagnostics\AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest.vb" Link="AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest.vb" />
<Compile Include="..\..\..\EditorFeatures\VisualBasicTest\Utils.vb" Link="Utils.vb" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.VisualBasic.CodeFix.Testing.XUnit" Version="$(MicrosoftCodeAnalysisVisualBasicCodeFixTestingXUnitVersion)" />
</ItemGroup>
<ItemGroup Label="Project References">
<!-- Directly reference the Workspaces project so we always test against the latest Roslyn bits -->
<ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" />
<ProjectReference Include="..\..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" />
<ProjectReference Include="..\..\..\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" />
<ProjectReference Include="..\..\..\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" />
</ItemGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\Core\Analyzers\Microsoft.CodeAnalysis.CodeStyle.csproj" />
<ProjectReference Include="..\..\Core\CodeFixes\Microsoft.CodeAnalysis.CodeStyle.Fixes.csproj" />
<ProjectReference Include="..\..\Core\Tests\Microsoft.CodeAnalysis.CodeStyle.UnitTestUtilities.csproj" />
<ProjectReference Include="..\..\Core\Tests\Microsoft.CodeAnalysis.CodeStyle.LegacyTestFramework.UnitTestUtilities.csproj" />
<ProjectReference Include="..\Analyzers\Microsoft.CodeAnalysis.VisualBasic.CodeStyle.vbproj" />
<ProjectReference Include="..\CodeFixes\Microsoft.CodeAnalysis.VisualBasic.CodeStyle.Fixes.vbproj" />
</ItemGroup>
<ItemGroup Label="Project References">
<!-- TODO: Remove all the below project references once all analyzer/code fix tests are switched to Microsoft.CodeAnalysis.Testing -->
<ProjectReference Include="..\..\..\Compilers\Test\Utilities\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Test.Utilities.vbproj" />
<ProjectReference Include="..\..\..\EditorFeatures\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" />
<ProjectReference Include="..\..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" />
<ProjectReference Include="..\..\..\EditorFeatures\CSharp\Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj" />
<ProjectReference Include="..\..\..\EditorFeatures\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj" />
<ProjectReference Include="..\..\..\EditorFeatures\Core.Wpf\Microsoft.CodeAnalysis.EditorFeatures.Wpf.csproj" />
<ProjectReference Include="..\..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" />
<ProjectReference Include="..\..\..\Features\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Features.csproj" />
<ProjectReference Include="..\..\..\Features\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Features.vbproj" />
<ProjectReference Include="..\..\..\Interactive\Host\Microsoft.CodeAnalysis.InteractiveHost.csproj" />
<ProjectReference Include="..\..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" />
<ProjectReference Include="..\..\..\Scripting\CSharp\Microsoft.CodeAnalysis.CSharp.Scripting.csproj" />
<ProjectReference Include="..\..\..\Features\LanguageServer\Protocol\Microsoft.CodeAnalysis.LanguageServer.Protocol.csproj" />
<ProjectReference Include="..\..\..\Workspaces\Remote\Core\Microsoft.CodeAnalysis.Remote.Workspaces.csproj" />
<ProjectReference Include="..\..\..\Workspaces\Remote\ServiceHub\Microsoft.CodeAnalysis.Remote.ServiceHub.csproj" />
<ProjectReference Include="..\..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" />
<ProjectReference Include="..\..\..\EditorFeatures\TestUtilities\Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.csproj" />
<ProjectReference Include="..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" />
<ProjectReference Include="..\..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" />
<ProjectReference Include="..\..\..\Workspaces\CoreTestUtilities\Microsoft.CodeAnalysis.Workspaces.Test.Utilities.csproj" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.CodeAnalysis.Editor.Shared.Extensions" />
<Import Include="Microsoft.CodeAnalysis.Shared.Extensions" />
<Import Include="Microsoft.CodeAnalysis.Test.Utilities" />
<Import Include="Microsoft.CodeAnalysis.VisualBasic" />
<Import Include="Microsoft.CodeAnalysis.VisualBasic.UnitTests" />
<Import Include="Roslyn.Test.Utilities" />
<Import Include="System.Threading.Tasks" />
<Import Include="Xunit" />
</ItemGroup>
<Import Project="..\..\..\Analyzers\VisualBasic\Tests\VisualBasicAnalyzers.UnitTests.projitems" Label="Shared" />
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Scripting/VisualBasicTest/Microsoft.CodeAnalysis.VisualBasic.Scripting.UnitTests.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>net472</TargetFramework>
<RootNamespace></RootNamespace>
<SkipTests Condition="'$(TestRuntime)' == 'Mono'">true</SkipTests>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" />
<ProjectReference Include="..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" />
<ProjectReference Include="..\CoreTestUtilities\Microsoft.CodeAnalysis.Scripting.TestUtilities.csproj" />
<ProjectReference Include="..\Core\Microsoft.CodeAnalysis.Scripting.csproj" />
<ProjectReference Include="..\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Scripting.vbproj" />
<ProjectReference Include="..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" />
<ProjectReference Include="..\CSharp\Microsoft.CodeAnalysis.CSharp.Scripting.csproj" />
<ProjectReference Include="..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Scripting.Desktop.UnitTests" />
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>net472</TargetFramework>
<RootNamespace></RootNamespace>
<SkipTests Condition="'$(TestRuntime)' == 'Mono'">true</SkipTests>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" />
<ProjectReference Include="..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" />
<ProjectReference Include="..\CoreTestUtilities\Microsoft.CodeAnalysis.Scripting.TestUtilities.csproj" />
<ProjectReference Include="..\Core\Microsoft.CodeAnalysis.Scripting.csproj" />
<ProjectReference Include="..\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Scripting.vbproj" />
<ProjectReference Include="..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" />
<ProjectReference Include="..\CSharp\Microsoft.CodeAnalysis.CSharp.Scripting.csproj" />
<ProjectReference Include="..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Scripting.Desktop.UnitTests" />
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Workspaces/MSBuildTest/Resources/ProjectFiles/VisualBasic/WithoutVBTargetsImported.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<PlatformTarget>AnyCPU</PlatformTarget>
<ProductVersion></ProductVersion>
<SchemaVersion></SchemaVersion>
<ProjectGuid>{AC25ECDA-DE94-4FCF-A688-EB3A2BE3670C}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>VisualBasicProject</RootNamespace>
<AssemblyName>VisualBasicProject</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Windows</MyType>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\Debug\</OutputPath>
<DocumentationFile>VisualBasicProject.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
<RemoveIntegerChecks>true</RemoveIntegerChecks>
<AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile>
<DefineConstants>FURBY</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DocumentationFile>VisualBasicProject.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>Off</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Diagnostics" />
<Import Include="System.Linq" />
</ItemGroup>
<ItemGroup>
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<Compile Include="VisualBasicClass.vb" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<!-- <ItemGroup>-->
<!-- <ProjectReference Include="..\CSharpProject\CSharpProject.csproj">-->
<!-- <Project>{686DD036-86AA-443E-8A10-DDB43266A8C4}</Project>-->
<!-- <Name>CSharpProject</Name>-->
<!-- </ProjectReference>-->
<!-- </ItemGroup>-->
<!-- <Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />-->
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<PlatformTarget>AnyCPU</PlatformTarget>
<ProductVersion></ProductVersion>
<SchemaVersion></SchemaVersion>
<ProjectGuid>{AC25ECDA-DE94-4FCF-A688-EB3A2BE3670C}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>VisualBasicProject</RootNamespace>
<AssemblyName>VisualBasicProject</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Windows</MyType>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\Debug\</OutputPath>
<DocumentationFile>VisualBasicProject.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
<RemoveIntegerChecks>true</RemoveIntegerChecks>
<AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile>
<DefineConstants>FURBY</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DocumentationFile>VisualBasicProject.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>Off</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Diagnostics" />
<Import Include="System.Linq" />
</ItemGroup>
<ItemGroup>
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<Compile Include="VisualBasicClass.vb" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<!-- <ItemGroup>-->
<!-- <ProjectReference Include="..\CSharpProject\CSharpProject.csproj">-->
<!-- <Project>{686DD036-86AA-443E-8A10-DDB43266A8C4}</Project>-->
<!-- <Name>CSharpProject</Name>-->
<!-- </ProjectReference>-->
<!-- </ItemGroup>-->
<!-- <Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />-->
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Compilers/VisualBasic/Test/IOperation/Roslyn.Compilers.VisualBasic.IOperation.UnitTests.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>net5.0;net472</TargetFrameworks>
<RootNamespace></RootNamespace>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" />
<ProjectReference Include="..\..\..\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" />
<ProjectReference Include="..\..\..\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\..\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" />
<ProjectReference Include="..\..\..\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" />
<ProjectReference Include="..\..\..\Test\Utilities\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Test.Utilities.vbproj" />
<ProjectReference Include="..\..\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="My Project\" />
</ItemGroup>
<ItemGroup>
<Import Include="IdentifierComparison = Microsoft.CodeAnalysis.CaseInsensitiveComparison" />
<Import Include="Roslyn.Utilities" />
<Import Include="Xunit" />
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>net5.0;net472</TargetFrameworks>
<RootNamespace></RootNamespace>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" />
<ProjectReference Include="..\..\..\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" />
<ProjectReference Include="..\..\..\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\..\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" />
<ProjectReference Include="..\..\..\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" />
<ProjectReference Include="..\..\..\Test\Utilities\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Test.Utilities.vbproj" />
<ProjectReference Include="..\..\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="My Project\" />
</ItemGroup>
<ItemGroup>
<Import Include="IdentifierComparison = Microsoft.CodeAnalysis.CaseInsensitiveComparison" />
<Import Include="Roslyn.Utilities" />
<Import Include="Xunit" />
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/CodeStyle/VisualBasic/Analyzers/Microsoft.CodeAnalysis.VisualBasic.CodeStyle.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>netstandard2.0</TargetFramework>
<RootNamespace></RootNamespace>
<DefineConstants>$(DefineConstants),CODE_STYLE</DefineConstants>
<PackageId>Microsoft.CodeAnalysis.VisualBasic.CodeStyle.NewNameSinceWeReferenceTheAnalyzersAndNuGetCannotFigureItOut</PackageId>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\DefaultOperationProvider.vb" Link="Formatting\DefaultOperationProvider.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\AggregatedFormattingResult.vb" Link="Formatting\Engine\AggregatedFormattingResult.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\FormattingResult.vb" Link="Formatting\Engine\FormattingResult.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.AbstractLineBreakTrivia.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.AbstractLineBreakTrivia.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.Analyzer.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.Analyzer.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.CodeShapeAnalyzer.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.CodeShapeAnalyzer.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.ComplexTrivia.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.ComplexTrivia.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.FormattedComplexTrivia.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.FormattedComplexTrivia.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.LineContinuationTrivia.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.LineContinuationTrivia.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.ModifiedComplexTrivia.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.ModifiedComplexTrivia.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.TriviaRewriter.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.TriviaRewriter.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\VisualBasicTriviaFormatter.vb" Link="Formatting\Engine\Trivia\VisualBasicTriviaFormatter.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\VisualBasicFormatEngine.vb" Link="Formatting\Engine\VisualBasicFormatEngine.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\VisualBasicStructuredTriviaFormatEngine.vb" Link="Formatting\Engine\VisualBasicStructuredTriviaFormatEngine.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\FormattingHelpers.vb" Link="Formatting\FormattingHelpers.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Rules\AdjustSpaceFormattingRule.vb" Link="Formatting\Rules\AdjustSpaceFormattingRule.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Rules\AlignTokensFormattingRule.vb" Link="Formatting\Rules\AlignTokensFormattingRule.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Rules\BaseFormattingRule.vb" Link="Formatting\Rules\BaseFormattingRule.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Rules\ElasticTriviaFormattingRule.vb" Link="Formatting\Rules\ElasticTriviaFormattingRule.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Rules\NodeBasedFormattingRule.vb" Link="Formatting\Rules\NodeBasedFormattingRule.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Rules\StructuredTriviaFormattingRule.vb" Link="Formatting\Rules\StructuredTriviaFormattingRule.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\VisualBasicSyntaxFormattingService.vb" Link="Formatting\VisualBasicSyntaxFormattingService.vb" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.CodeAnalysis.Shared.Extensions" />
<Import Include="Microsoft.CodeAnalysis.Shared.Utilities" />
<Import Include="Microsoft.CodeAnalysis.VisualBasic.Extensions" />
<Import Include="Roslyn.Utilities" />
</ItemGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\Core\Analyzers\Microsoft.CodeAnalysis.CodeStyle.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.CodeStyle.Fixes" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.CodeStyle.UnitTests" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="VBCodeStyleResources.resx" GenerateSource="true" Namespace="Microsoft.CodeAnalysis.VisualBasic" />
</ItemGroup>
<ItemGroup>
<PublicAPI Include="PublicAPI.Shipped.txt" />
<PublicAPI Include="PublicAPI.Unshipped.txt" />
</ItemGroup>
<Import Project="..\..\..\Workspaces\SharedUtilitiesAndExtensions\Compiler\VisualBasic\VisualBasicCompilerExtensions.projitems" Label="Shared" />
<Import Project="..\..\..\Analyzers\VisualBasic\Analyzers\VisualBasicAnalyzers.projitems" Label="Shared" />
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>netstandard2.0</TargetFramework>
<RootNamespace></RootNamespace>
<DefineConstants>$(DefineConstants),CODE_STYLE</DefineConstants>
<PackageId>Microsoft.CodeAnalysis.VisualBasic.CodeStyle.NewNameSinceWeReferenceTheAnalyzersAndNuGetCannotFigureItOut</PackageId>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\DefaultOperationProvider.vb" Link="Formatting\DefaultOperationProvider.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\AggregatedFormattingResult.vb" Link="Formatting\Engine\AggregatedFormattingResult.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\FormattingResult.vb" Link="Formatting\Engine\FormattingResult.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.AbstractLineBreakTrivia.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.AbstractLineBreakTrivia.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.Analyzer.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.Analyzer.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.CodeShapeAnalyzer.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.CodeShapeAnalyzer.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.ComplexTrivia.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.ComplexTrivia.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.FormattedComplexTrivia.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.FormattedComplexTrivia.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.LineContinuationTrivia.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.LineContinuationTrivia.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.ModifiedComplexTrivia.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.ModifiedComplexTrivia.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.TriviaRewriter.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.TriviaRewriter.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\TriviaDataFactory.vb" Link="Formatting\Engine\Trivia\TriviaDataFactory.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\Trivia\VisualBasicTriviaFormatter.vb" Link="Formatting\Engine\Trivia\VisualBasicTriviaFormatter.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\VisualBasicFormatEngine.vb" Link="Formatting\Engine\VisualBasicFormatEngine.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Engine\VisualBasicStructuredTriviaFormatEngine.vb" Link="Formatting\Engine\VisualBasicStructuredTriviaFormatEngine.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\FormattingHelpers.vb" Link="Formatting\FormattingHelpers.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Rules\AdjustSpaceFormattingRule.vb" Link="Formatting\Rules\AdjustSpaceFormattingRule.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Rules\AlignTokensFormattingRule.vb" Link="Formatting\Rules\AlignTokensFormattingRule.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Rules\BaseFormattingRule.vb" Link="Formatting\Rules\BaseFormattingRule.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Rules\ElasticTriviaFormattingRule.vb" Link="Formatting\Rules\ElasticTriviaFormattingRule.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Rules\NodeBasedFormattingRule.vb" Link="Formatting\Rules\NodeBasedFormattingRule.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\Rules\StructuredTriviaFormattingRule.vb" Link="Formatting\Rules\StructuredTriviaFormattingRule.vb" />
<Compile Include="..\..\..\Workspaces\VisualBasic\Portable\Formatting\VisualBasicSyntaxFormattingService.vb" Link="Formatting\VisualBasicSyntaxFormattingService.vb" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.CodeAnalysis.Shared.Extensions" />
<Import Include="Microsoft.CodeAnalysis.Shared.Utilities" />
<Import Include="Microsoft.CodeAnalysis.VisualBasic.Extensions" />
<Import Include="Roslyn.Utilities" />
</ItemGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\Core\Analyzers\Microsoft.CodeAnalysis.CodeStyle.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.CodeStyle.Fixes" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.CodeStyle.UnitTests" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="VBCodeStyleResources.resx" GenerateSource="true" Namespace="Microsoft.CodeAnalysis.VisualBasic" />
</ItemGroup>
<ItemGroup>
<PublicAPI Include="PublicAPI.Shipped.txt" />
<PublicAPI Include="PublicAPI.Unshipped.txt" />
</ItemGroup>
<Import Project="..\..\..\Workspaces\SharedUtilitiesAndExtensions\Compiler\VisualBasic\VisualBasicCompilerExtensions.projitems" Label="Shared" />
<Import Project="..\..\..\Analyzers\VisualBasic\Analyzers\VisualBasicAnalyzers.projitems" Label="Shared" />
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Workspaces/MSBuildTest/Resources/ProjectFiles/VisualBasic/Circular_Top.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="VisualBasicProject_Circular_Target.vbproj" />
<PropertyGroup>
<ProjectGuid>{76242A2D-2600-49DD-8C15-FEA07ECB1843}</ProjectGuid>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="VisualBasic_Circular_Target.vbproj">
<Project>{76242A2D-2600-49DD-8C15-FEA07ECB1842}</Project>
<Name>Target</Name>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
</ItemGroup>
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="VisualBasicProject_Circular_Target.vbproj" />
<PropertyGroup>
<ProjectGuid>{76242A2D-2600-49DD-8C15-FEA07ECB1843}</ProjectGuid>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="VisualBasic_Circular_Target.vbproj">
<Project>{76242A2D-2600-49DD-8C15-FEA07ECB1842}</Project>
<Name>Target</Name>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
</ItemGroup>
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Workspaces/MSBuildTest/Resources/ProjectFiles/VisualBasic/VisualBasicProject.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<PlatformTarget>AnyCPU</PlatformTarget>
<ProductVersion></ProductVersion>
<SchemaVersion></SchemaVersion>
<ProjectGuid>{AC25ECDA-DE94-4FCF-A688-EB3A2BE3670C}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>VisualBasicProject</RootNamespace>
<AssemblyName>VisualBasicProject</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Windows</MyType>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\Debug\</OutputPath>
<DocumentationFile>VisualBasicProject.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
<RemoveIntegerChecks>true</RemoveIntegerChecks>
<AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile>
<DefineConstants>FURBY</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DocumentationFile>VisualBasicProject.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
<LangVersion>15</LangVersion>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>Off</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Diagnostics" />
<Import Include="System.Linq" />
</ItemGroup>
<ItemGroup>
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<Compile Include="VisualBasicClass.vb" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CSharpProject\CSharpProject.csproj">
<Project>{686DD036-86AA-443E-8A10-DDB43266A8C4}</Project>
<Name>CSharpProject</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<PlatformTarget>AnyCPU</PlatformTarget>
<ProductVersion></ProductVersion>
<SchemaVersion></SchemaVersion>
<ProjectGuid>{AC25ECDA-DE94-4FCF-A688-EB3A2BE3670C}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>VisualBasicProject</RootNamespace>
<AssemblyName>VisualBasicProject</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Windows</MyType>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\Debug\</OutputPath>
<DocumentationFile>VisualBasicProject.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
<RemoveIntegerChecks>true</RemoveIntegerChecks>
<AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile>
<DefineConstants>FURBY</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DocumentationFile>VisualBasicProject.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
<LangVersion>15</LangVersion>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>Off</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Diagnostics" />
<Import Include="System.Linq" />
</ItemGroup>
<ItemGroup>
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<Compile Include="VisualBasicClass.vb" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CSharpProject\CSharpProject.csproj">
<Project>{686DD036-86AA-443E-8A10-DDB43266A8C4}</Project>
<Name>CSharpProject</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Workspaces/VisualBasic/Portable/Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>netcoreapp3.1;netstandard2.0</TargetFrameworks>
<RootNamespace></RootNamespace>
<ApplyNgenOptimization Condition="'$(TargetFramework)' == 'netstandard2.0'">partial</ApplyNgenOptimization>
<!-- NuGet -->
<IsPackable>true</IsPackable>
<PackageDescription>
.NET Compiler Platform ("Roslyn") support for analyzing Visual Basic projects and solutions.
</PackageDescription>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Features" />
<InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.VisualBasic" />
<InternalsVisibleTo Include="Roslyn.Hosting.Diagnostics" />
<!-- BEGIN MONODEVELOP
These MonoDevelop dependencies don't ship with Visual Studio, so can't break our
binary insertions and are exempted from the ExternalAccess adapter assembly policies.
-->
<InternalsVisibleTo Include="MonoDevelop.VBNetBinding" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" />
<InternalsVisibleTo Include="MonoDevelop.VBNetBinding.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" />
<!-- END MONODEVELOP -->
<InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Test.Utilities2" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Workspaces.UnitTests" />
<InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.LiveShare" />
<InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities2" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.DiagnosticsTests.Utilities" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="VBWorkspaceResources.resx" GenerateSource="true" NAmespace="Microsoft.CodeAnalysis.VisualBasic" />
</ItemGroup>
<ItemGroup>
<Folder Include="Workspace\LanguageServices\" />
<Folder Include="My Project\" />
</ItemGroup>
<ItemGroup>
<PublicAPI Include="PublicAPI.Shipped.txt" />
<PublicAPI Include="PublicAPI.Unshipped.txt" />
</ItemGroup>
<Import Project="..\..\..\Workspaces\SharedUtilitiesAndExtensions\Compiler\VisualBasic\VisualBasicCompilerExtensions.projitems" Label="Shared" />
<Import Project="..\..\..\Workspaces\SharedUtilitiesAndExtensions\Workspace\VisualBasic\VisualBasicWorkspaceExtensions.projitems" Label="Shared" />
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>netcoreapp3.1;netstandard2.0</TargetFrameworks>
<RootNamespace></RootNamespace>
<ApplyNgenOptimization Condition="'$(TargetFramework)' == 'netstandard2.0'">partial</ApplyNgenOptimization>
<!-- NuGet -->
<IsPackable>true</IsPackable>
<PackageDescription>
.NET Compiler Platform ("Roslyn") support for analyzing Visual Basic projects and solutions.
</PackageDescription>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Features" />
<InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.VisualBasic" />
<InternalsVisibleTo Include="Roslyn.Hosting.Diagnostics" />
<!-- BEGIN MONODEVELOP
These MonoDevelop dependencies don't ship with Visual Studio, so can't break our
binary insertions and are exempted from the ExternalAccess adapter assembly policies.
-->
<InternalsVisibleTo Include="MonoDevelop.VBNetBinding" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" />
<InternalsVisibleTo Include="MonoDevelop.VBNetBinding.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" />
<!-- END MONODEVELOP -->
<InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Test.Utilities2" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Workspaces.UnitTests" />
<InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.LiveShare" />
<InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities2" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.DiagnosticsTests.Utilities" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="VBWorkspaceResources.resx" GenerateSource="true" NAmespace="Microsoft.CodeAnalysis.VisualBasic" />
</ItemGroup>
<ItemGroup>
<Folder Include="Workspace\LanguageServices\" />
<Folder Include="My Project\" />
</ItemGroup>
<ItemGroup>
<PublicAPI Include="PublicAPI.Shipped.txt" />
<PublicAPI Include="PublicAPI.Unshipped.txt" />
</ItemGroup>
<Import Project="..\..\..\Workspaces\SharedUtilitiesAndExtensions\Compiler\VisualBasic\VisualBasicCompilerExtensions.projitems" Label="Shared" />
<Import Project="..\..\..\Workspaces\SharedUtilitiesAndExtensions\Workspace\VisualBasic\VisualBasicWorkspaceExtensions.projitems" Label="Shared" />
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Workspaces/MSBuildTest/Resources/ProjectFiles/VisualBasic/UnknownProjectExtension.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<PlatformTarget>AnyCPU</PlatformTarget>
<ProductVersion></ProductVersion>
<SchemaVersion></SchemaVersion>
<ProjectGuid>{AC25ECDA-DE94-4FCF-A688-EB3A2BE3670C}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>VisualBasicProject</RootNamespace>
<AssemblyName>VisualBasicProject</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Windows</MyType>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\Debug\</OutputPath>
<DocumentationFile>VisualBasicProject.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
<RemoveIntegerChecks>true</RemoveIntegerChecks>
<AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile>
<DefineConstants>FURBY</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DocumentationFile>VisualBasicProject.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>Off</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Diagnostics" />
<Import Include="System.Linq" />
</ItemGroup>
<ItemGroup>
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<Compile Include="VisualBasicClass.vb" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CSharpProject\CSharpProject.noproj">
<Project>{686DD036-86AA-443E-8A10-DDB43266A8C4}</Project>
<Name>CSharpProject</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<PlatformTarget>AnyCPU</PlatformTarget>
<ProductVersion></ProductVersion>
<SchemaVersion></SchemaVersion>
<ProjectGuid>{AC25ECDA-DE94-4FCF-A688-EB3A2BE3670C}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>VisualBasicProject</RootNamespace>
<AssemblyName>VisualBasicProject</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Windows</MyType>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\Debug\</OutputPath>
<DocumentationFile>VisualBasicProject.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
<RemoveIntegerChecks>true</RemoveIntegerChecks>
<AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile>
<DefineConstants>FURBY</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DocumentationFile>VisualBasicProject.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>Off</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Diagnostics" />
<Import Include="System.Linq" />
</ItemGroup>
<ItemGroup>
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<Compile Include="VisualBasicClass.vb" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CSharpProject\CSharpProject.noproj">
<Project>{686DD036-86AA-443E-8A10-DDB43266A8C4}</Project>
<Name>CSharpProject</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Workspaces/MSBuildTest/Resources/ProjectFiles/VisualBasic/VisualBasicProject_3_5.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<PlatformTarget>AnyCPU</PlatformTarget>
<ProductVersion>9.0.21022</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{AC25ECDA-DE94-4FCF-A688-EB3A2BE3670C}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>VisualBasicProject</RootNamespace>
<AssemblyName>VisualBasicProject</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Windows</MyType>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\Debug\</OutputPath>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
<RemoveIntegerChecks>true</RemoveIntegerChecks>
<AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile>
<DefineConstants>FURBY</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>Off</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Diagnostics" />
<Import Include="System.Linq" />
</ItemGroup>
<ItemGroup>
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<Compile Include="VisualBasicClass.vb" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<PlatformTarget>AnyCPU</PlatformTarget>
<ProductVersion>9.0.21022</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{AC25ECDA-DE94-4FCF-A688-EB3A2BE3670C}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>VisualBasicProject</RootNamespace>
<AssemblyName>VisualBasicProject</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Windows</MyType>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\Debug\</OutputPath>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
<RemoveIntegerChecks>true</RemoveIntegerChecks>
<AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile>
<DefineConstants>FURBY</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>Off</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Diagnostics" />
<Import Include="System.Linq" />
</ItemGroup>
<ItemGroup>
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<Compile Include="VisualBasicClass.vb" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Compilers/VisualBasic/Test/Syntax/Microsoft.CodeAnalysis.VisualBasic.Syntax.UnitTests.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>net5.0;net472</TargetFrameworks>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" />
<ProjectReference Include="..\..\..\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\..\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" />
<ProjectReference Include="..\..\..\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" />
<ProjectReference Include="..\..\..\Test\Utilities\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Test.Utilities.vbproj" />
<ProjectReference Include="..\..\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" />
</ItemGroup>
<PropertyGroup>
<RootNamespace>Microsoft.CodeAnalysis.VisualBasic.UnitTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Remove="Resources\*.*" />
<EmbeddedResource Include="Resources\*.*" LogicalName="%(FileName)%(Extension)" />
</ItemGroup>
<ItemGroup>
<Import Include="IdentifierComparison = Microsoft.CodeAnalysis.CaseInsensitiveComparison" />
<Import Include="Roslyn.Utilities" />
<Import Include="Xunit" />
</ItemGroup>
<ItemGroup>
<Folder Include="My Project\" />
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>net5.0;net472</TargetFrameworks>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" />
<ProjectReference Include="..\..\..\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\..\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" />
<ProjectReference Include="..\..\..\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" />
<ProjectReference Include="..\..\..\Test\Utilities\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Test.Utilities.vbproj" />
<ProjectReference Include="..\..\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" />
</ItemGroup>
<PropertyGroup>
<RootNamespace>Microsoft.CodeAnalysis.VisualBasic.UnitTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Remove="Resources\*.*" />
<EmbeddedResource Include="Resources\*.*" LogicalName="%(FileName)%(Extension)" />
</ItemGroup>
<ItemGroup>
<Import Include="IdentifierComparison = Microsoft.CodeAnalysis.CaseInsensitiveComparison" />
<Import Include="Roslyn.Utilities" />
<Import Include="Xunit" />
</ItemGroup>
<ItemGroup>
<Folder Include="My Project\" />
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Workspaces/MSBuildTest/Resources/ProjectFiles/VisualBasic/Circular_Target.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<PlatformTarget>AnyCPU</PlatformTarget>
<ProjectGuid>{76242A2D-2600-49DD-8C15-FEA07ECB1842}</ProjectGuid>
<OutputType>Library</OutputType>
<AssemblyName>VisualBasic.Circular.dll</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'" />
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<PlatformTarget>AnyCPU</PlatformTarget>
<ProjectGuid>{76242A2D-2600-49DD-8C15-FEA07ECB1842}</ProjectGuid>
<OutputType>Library</OutputType>
<AssemblyName>VisualBasic.Circular.dll</AssemblyName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'" />
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Tools/Source/CompilerGeneratorTools/Source/VisualBasicSyntaxGenerator/VisualBasicSyntaxGenerator.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Platform Condition="'$(Platform)' == ''">x64</Platform>
<PlatformTarget>x64</PlatformTarget>
<Platforms>x64</Platforms>
<OutputType>Exe</OutputType>
<StartupObject>Microsoft.CodeAnalysis.VisualBasic.Internal.VBSyntaxGenerator.Program</StartupObject>
<RootNamespace>Microsoft.CodeAnalysis.VisualBasic.Internal.VBSyntaxGenerator</RootNamespace>
<AssemblyName>VBSyntaxGenerator</AssemblyName>
<OptionStrict>Off</OptionStrict>
<AutoGenerateBindingRedirects>True</AutoGenerateBindingRedirects>
<TargetFramework>netcoreapp3.1</TargetFramework>
<IsShipping>false</IsShipping>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\..\..\..\Compilers\VisualBasic\Portable\Declarations\DeclarationModifiers.vb" Link="Grammar\DeclarationModifiers.vb" />
<Compile Include="..\..\..\..\..\Compilers\VisualBasic\Portable\Syntax\SyntaxKind.vb" Link="Grammar\SyntaxKind.vb" />
</ItemGroup>
<ItemGroup>
<Import Include="System.Collections.ObjectModel" />
<Import Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<Content Include="..\..\..\..\..\Compilers\VisualBasic\Portable\Syntax\Syntax.xml">
<Link>XML\Syntax.xml</Link>
</Content>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="VBSyntaxModelSchema.xsd">
<LogicalName>VBSyntaxModelSchema.xsd</LogicalName>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="..\..\..\..\..\Compilers\VisualBasic\Portable\Generated\VisualBasic.Grammar.g4" Link="Grammar\VisualBasic.Grammar.g4" />
</ItemGroup>
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Platform Condition="'$(Platform)' == ''">x64</Platform>
<PlatformTarget>x64</PlatformTarget>
<Platforms>x64</Platforms>
<OutputType>Exe</OutputType>
<StartupObject>Microsoft.CodeAnalysis.VisualBasic.Internal.VBSyntaxGenerator.Program</StartupObject>
<RootNamespace>Microsoft.CodeAnalysis.VisualBasic.Internal.VBSyntaxGenerator</RootNamespace>
<AssemblyName>VBSyntaxGenerator</AssemblyName>
<OptionStrict>Off</OptionStrict>
<AutoGenerateBindingRedirects>True</AutoGenerateBindingRedirects>
<TargetFramework>netcoreapp3.1</TargetFramework>
<IsShipping>false</IsShipping>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\..\..\..\Compilers\VisualBasic\Portable\Declarations\DeclarationModifiers.vb" Link="Grammar\DeclarationModifiers.vb" />
<Compile Include="..\..\..\..\..\Compilers\VisualBasic\Portable\Syntax\SyntaxKind.vb" Link="Grammar\SyntaxKind.vb" />
</ItemGroup>
<ItemGroup>
<Import Include="System.Collections.ObjectModel" />
<Import Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<Content Include="..\..\..\..\..\Compilers\VisualBasic\Portable\Syntax\Syntax.xml">
<Link>XML\Syntax.xml</Link>
</Content>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="VBSyntaxModelSchema.xsd">
<LogicalName>VBSyntaxModelSchema.xsd</LogicalName>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="..\..\..\..\..\Compilers\VisualBasic\Portable\Generated\VisualBasic.Grammar.g4" Link="Grammar\VisualBasic.Grammar.g4" />
</ItemGroup>
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Compilers/VisualBasic/Test/Emit/Microsoft.CodeAnalysis.VisualBasic.Emit.UnitTests.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>net5.0;net472</TargetFrameworks>
<RootNamespace></RootNamespace>
<!-- Disabling on assumption -->
<SkipTests Condition="'$(TestRuntime)' == 'Mono'">true</SkipTests>
<EmbeddedResourceUseDependentUponConvention>false</EmbeddedResourceUseDependentUponConvention>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" />
<ProjectReference Include="..\..\..\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" />
<ProjectReference Include="..\..\..\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\..\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" />
<ProjectReference Include="..\..\..\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" />
<ProjectReference Include="..\..\..\Test\Utilities\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Test.Utilities.vbproj" />
<ProjectReference Include="..\..\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.DiaSymReader" Version="$(MicrosoftDiaSymReaderVersion)" />
<PackageReference Include="Microsoft.VisualBasic" Version="$(MicrosoftVisualBasicVersion)" Condition="'$(TargetFramework)' == 'net472'" />
</ItemGroup>
<ItemGroup>
<Content Include="CodeGen\ConversionsILGenTestBaseline.txt" />
<Content Include="CodeGen\ConversionsILGenTestBaseline1.txt" />
<Content Include="ExpressionTrees\Results\CheckedAndOrXor.txt" />
<Content Include="ExpressionTrees\Results\CheckedAndUncheckedIsIsNot.txt" />
<Content Include="ExpressionTrees\Results\CheckedAndUncheckedIsIsNotNothing.txt" />
<Content Include="ExpressionTrees\Results\CheckedAndUncheckedIsTrueIsFalse.txt" />
<Content Include="ExpressionTrees\Results\CheckedAndUncheckedNarrowingUDC.txt" />
<Content Include="ExpressionTrees\Results\CheckedAndUncheckedNothingConversions.txt" />
<Content Include="ExpressionTrees\Results\CheckedAndUncheckedTypeParameters.txt" />
<Content Include="ExpressionTrees\Results\CheckedAndUncheckedUdoUnaryPlusMinusNot.txt" />
<Content Include="ExpressionTrees\Results\CheckedAndUncheckedUserTypeConversions.txt" />
<Content Include="ExpressionTrees\Results\CheckedAndUncheckedWideningUDC.txt" />
<Content Include="ExpressionTrees\Results\CheckedAndUncheckedWithDate.txt" />
<Content Include="ExpressionTrees\Results\CheckedArithmeticBinaryOperators.txt" />
<Content Include="ExpressionTrees\Results\CheckedArrayInitializers.txt" />
<Content Include="ExpressionTrees\Results\CheckedCoalesceWithNullableBoolean.txt" />
<Content Include="ExpressionTrees\Results\CheckedCoalesceWithUserDefinedConversions.txt" />
<Content Include="ExpressionTrees\Results\CheckedCollectionInitializers.txt" />
<Content Include="ExpressionTrees\Results\CheckedComparisonOperators.txt" />
<Content Include="ExpressionTrees\Results\CheckedConcatenate.txt" />
<Content Include="ExpressionTrees\Results\CheckedCTypeAndImplicitConversionsEven.txt" />
<Content Include="ExpressionTrees\Results\CheckedCTypeAndImplicitConversionsOdd.txt" />
<Content Include="ExpressionTrees\Results\CheckedDirectTrySpecificConversions.txt" />
<Content Include="ExpressionTrees\Results\CheckedLike.txt" />
<Content Include="ExpressionTrees\Results\CheckedMiscellaneousA.txt" />
<Content Include="ExpressionTrees\Results\CheckedObjectInitializers.txt" />
<Content Include="ExpressionTrees\Results\CheckedShortCircuit.txt" />
<Content Include="ExpressionTrees\Results\CheckedUnaryPlusMinusNot.txt" />
<Content Include="ExpressionTrees\Results\CheckedUserDefinedBinaryOperators.txt" />
<Content Include="ExpressionTrees\Results\ExprTree_LegacyTests02_v40_Result.txt" />
<Content Include="ExpressionTrees\Results\ExprTree_LegacyTests02_v45_Result.txt" />
<Content Include="ExpressionTrees\Results\ExprTree_LegacyTests07_Result.txt" />
<Content Include="ExpressionTrees\Results\ExprTree_LegacyTests08_Result.txt" />
<Content Include="ExpressionTrees\Results\ExprTree_LegacyTests09_Result.txt" />
<Content Include="ExpressionTrees\Results\ExprTree_LegacyTests10_Result.txt" />
<Content Include="ExpressionTrees\Results\UncheckedAndOrXor.txt" />
<Content Include="ExpressionTrees\Results\UncheckedArithmeticBinaryOperators.txt" />
<Content Include="ExpressionTrees\Results\UncheckedComparisonOperators.txt" />
<Content Include="ExpressionTrees\Results\UncheckedConcatenate.txt" />
<Content Include="ExpressionTrees\Results\UncheckedCTypeAndImplicitConversionsEven.txt" />
<Content Include="ExpressionTrees\Results\UncheckedCTypeAndImplicitConversionsOdd.txt" />
<Content Include="ExpressionTrees\Results\UncheckedDirectTrySpecificConversions.txt" />
<Content Include="ExpressionTrees\Results\UncheckedLike.txt" />
<Content Include="ExpressionTrees\Results\UncheckedShortCircuit.txt" />
<Content Include="ExpressionTrees\Results\UncheckedUnaryPlusMinusNot.txt" />
<Content Include="ExpressionTrees\Results\UncheckedUserDefinedBinaryOperators.txt" />
<Content Include="ExpressionTrees\Results\XmlLiteralsInExprLambda01_Result.txt" />
<Content Include="ExpressionTrees\Results\XmlLiteralsInExprLambda02_Result.txt" />
<Content Include="ExpressionTrees\Results\XmlLiteralsInExprLambda03_Result.txt" />
</ItemGroup>
<ItemGroup>
<Content Include="CodeGen\ConversionsILGenTestSource.vb" />
<Content Include="CodeGen\ConversionsILGenTestSource1.vb" />
<Content Include="CodeGen\ConversionsILGenTestSource2.vb" />
<Content Include="ExpressionTrees\Sources\UserDefinedBinaryOperators.vb" />
<Content Include="ExpressionTrees\Tests\TestConversion_Narrowing_UDC.vb" />
<Content Include="ExpressionTrees\Tests\TestConversion_TypeMatrix_UserTypes.vb" />
<Content Include="ExpressionTrees\Tests\TestConversion_Widening_UDC.vb" />
<Content Include="ExpressionTrees\Tests\TestUnary_UDO_IsTrueIsFalse.vb" />
<Content Include="ExpressionTrees\Tests\TestUnary_UDO_PlusMinusNot.vb" />
<Compile Remove="CodeGen\ConversionsILGenTestSource.vb" />
<Compile Remove="CodeGen\ConversionsILGenTestSource1.vb" />
<Compile Remove="CodeGen\ConversionsILGenTestSource2.vb" />
<Compile Remove="ExpressionTrees\Sources\UserDefinedBinaryOperators.vb" />
<Compile Remove="ExpressionTrees\Tests\TestConversion_Narrowing_UDC.vb" />
<Compile Remove="ExpressionTrees\Tests\TestConversion_TypeMatrix_UserTypes.vb" />
<Compile Remove="ExpressionTrees\Tests\TestConversion_Widening_UDC.vb" />
<Compile Remove="ExpressionTrees\Tests\TestUnary_UDO_IsTrueIsFalse.vb" />
<Compile Remove="ExpressionTrees\Tests\TestUnary_UDO_PlusMinusNot.vb" />
</ItemGroup>
<ItemGroup>
<Import Include="IdentifierComparison = Microsoft.CodeAnalysis.CaseInsensitiveComparison" />
<Import Include="Roslyn.Utilities" />
<Import Include="Xunit" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="CodeGen\ConversionsILGenTestBaseline.txt" />
<EmbeddedResource Include="CodeGen\ConversionsILGenTestBaseline1.txt" />
<EmbeddedResource Include="CodeGen\ConversionsILGenTestSource.vb" />
<EmbeddedResource Include="CodeGen\ConversionsILGenTestSource1.vb" />
<EmbeddedResource Include="CodeGen\ConversionsILGenTestSource2.vb" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedArithmeticBinaryOperators.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\UncheckedArithmeticBinaryOperators.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedAndOrXor.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\UncheckedAndOrXor.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedShortCircuit.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\UncheckedShortCircuit.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedComparisonOperators.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\UncheckedComparisonOperators.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedIsIsNotNothing.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedIsIsNot.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedConcatenate.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\UncheckedConcatenate.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedLike.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\UncheckedLike.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedWithDate.txt" />
<EmbeddedResource Include="ExpressionTrees\Sources\ExprLambdaUtils.vb" />
<EmbeddedResource Include="ExpressionTrees\Sources\UserDefinedBinaryOperators.vb" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedUserDefinedBinaryOperators.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\UncheckedUserDefinedBinaryOperators.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedNothingConversions.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedTypeParameters.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedDirectTrySpecificConversions.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\UncheckedDirectTrySpecificConversions.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedCTypeAndImplicitConversionsEven.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\UncheckedCTypeAndImplicitConversionsEven.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedCTypeAndImplicitConversionsOdd.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\UncheckedCTypeAndImplicitConversionsOdd.txt" />
<EmbeddedResource Include="ExpressionTrees\Tests\TestConversion_TypeMatrix_UserTypes.vb" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedUserTypeConversions.txt" />
<EmbeddedResource Include="ExpressionTrees\Tests\TestConversion_Narrowing_UDC.vb" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedNarrowingUDC.txt" />
<EmbeddedResource Include="ExpressionTrees\Tests\TestConversion_Widening_UDC.vb" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedWideningUDC.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedUnaryPlusMinusNot.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\UncheckedUnaryPlusMinusNot.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedIsTrueIsFalse.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedUdoUnaryPlusMinusNot.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedCoalesceWithNullableBoolean.txt" />
<EmbeddedResource Include="ExpressionTrees\Tests\TestUnary_UDO_PlusMinusNot.vb" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedCoalesceWithUserDefinedConversions.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedObjectInitializers.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedArrayInitializers.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedCollectionInitializers.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedMiscellaneousA.txt" />
<EmbeddedResource Include="ExpressionTrees\Tests\TestUnary_UDO_IsTrueIsFalse.vb" />
<EmbeddedResource Include="ExpressionTrees\Sources\QueryHelper.vb" />
<EmbeddedResource Include="ExpressionTrees\Results\ExprTree_LegacyTests07_Result.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\ExprTree_LegacyTests08_Result.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\ExprTree_LegacyTests09_Result.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\XmlLiteralsInExprLambda01_Result.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\XmlLiteralsInExprLambda02_Result.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\XmlLiteralsInExprLambda03_Result.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\ExprTree_LegacyTests10_Result.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\ExprTree_LegacyTests02_v40_Result.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\ExprTree_LegacyTests02_v45_Result.txt" />
</ItemGroup>
<ItemGroup>
<Folder Include="My Project\" />
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
<Import Project="$(RepositoryEngineeringDir)targets\ILAsm.targets" />
</Project>
| <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFrameworks>net5.0;net472</TargetFrameworks>
<RootNamespace></RootNamespace>
<!-- Disabling on assumption -->
<SkipTests Condition="'$(TestRuntime)' == 'Mono'">true</SkipTests>
<EmbeddedResourceUseDependentUponConvention>false</EmbeddedResourceUseDependentUponConvention>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" />
<ProjectReference Include="..\..\..\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" />
<ProjectReference Include="..\..\..\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\..\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" />
<ProjectReference Include="..\..\..\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" />
<ProjectReference Include="..\..\..\Test\Utilities\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Test.Utilities.vbproj" />
<ProjectReference Include="..\..\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.DiaSymReader" Version="$(MicrosoftDiaSymReaderVersion)" />
<PackageReference Include="Microsoft.VisualBasic" Version="$(MicrosoftVisualBasicVersion)" Condition="'$(TargetFramework)' == 'net472'" />
</ItemGroup>
<ItemGroup>
<Content Include="CodeGen\ConversionsILGenTestBaseline.txt" />
<Content Include="CodeGen\ConversionsILGenTestBaseline1.txt" />
<Content Include="ExpressionTrees\Results\CheckedAndOrXor.txt" />
<Content Include="ExpressionTrees\Results\CheckedAndUncheckedIsIsNot.txt" />
<Content Include="ExpressionTrees\Results\CheckedAndUncheckedIsIsNotNothing.txt" />
<Content Include="ExpressionTrees\Results\CheckedAndUncheckedIsTrueIsFalse.txt" />
<Content Include="ExpressionTrees\Results\CheckedAndUncheckedNarrowingUDC.txt" />
<Content Include="ExpressionTrees\Results\CheckedAndUncheckedNothingConversions.txt" />
<Content Include="ExpressionTrees\Results\CheckedAndUncheckedTypeParameters.txt" />
<Content Include="ExpressionTrees\Results\CheckedAndUncheckedUdoUnaryPlusMinusNot.txt" />
<Content Include="ExpressionTrees\Results\CheckedAndUncheckedUserTypeConversions.txt" />
<Content Include="ExpressionTrees\Results\CheckedAndUncheckedWideningUDC.txt" />
<Content Include="ExpressionTrees\Results\CheckedAndUncheckedWithDate.txt" />
<Content Include="ExpressionTrees\Results\CheckedArithmeticBinaryOperators.txt" />
<Content Include="ExpressionTrees\Results\CheckedArrayInitializers.txt" />
<Content Include="ExpressionTrees\Results\CheckedCoalesceWithNullableBoolean.txt" />
<Content Include="ExpressionTrees\Results\CheckedCoalesceWithUserDefinedConversions.txt" />
<Content Include="ExpressionTrees\Results\CheckedCollectionInitializers.txt" />
<Content Include="ExpressionTrees\Results\CheckedComparisonOperators.txt" />
<Content Include="ExpressionTrees\Results\CheckedConcatenate.txt" />
<Content Include="ExpressionTrees\Results\CheckedCTypeAndImplicitConversionsEven.txt" />
<Content Include="ExpressionTrees\Results\CheckedCTypeAndImplicitConversionsOdd.txt" />
<Content Include="ExpressionTrees\Results\CheckedDirectTrySpecificConversions.txt" />
<Content Include="ExpressionTrees\Results\CheckedLike.txt" />
<Content Include="ExpressionTrees\Results\CheckedMiscellaneousA.txt" />
<Content Include="ExpressionTrees\Results\CheckedObjectInitializers.txt" />
<Content Include="ExpressionTrees\Results\CheckedShortCircuit.txt" />
<Content Include="ExpressionTrees\Results\CheckedUnaryPlusMinusNot.txt" />
<Content Include="ExpressionTrees\Results\CheckedUserDefinedBinaryOperators.txt" />
<Content Include="ExpressionTrees\Results\ExprTree_LegacyTests02_v40_Result.txt" />
<Content Include="ExpressionTrees\Results\ExprTree_LegacyTests02_v45_Result.txt" />
<Content Include="ExpressionTrees\Results\ExprTree_LegacyTests07_Result.txt" />
<Content Include="ExpressionTrees\Results\ExprTree_LegacyTests08_Result.txt" />
<Content Include="ExpressionTrees\Results\ExprTree_LegacyTests09_Result.txt" />
<Content Include="ExpressionTrees\Results\ExprTree_LegacyTests10_Result.txt" />
<Content Include="ExpressionTrees\Results\UncheckedAndOrXor.txt" />
<Content Include="ExpressionTrees\Results\UncheckedArithmeticBinaryOperators.txt" />
<Content Include="ExpressionTrees\Results\UncheckedComparisonOperators.txt" />
<Content Include="ExpressionTrees\Results\UncheckedConcatenate.txt" />
<Content Include="ExpressionTrees\Results\UncheckedCTypeAndImplicitConversionsEven.txt" />
<Content Include="ExpressionTrees\Results\UncheckedCTypeAndImplicitConversionsOdd.txt" />
<Content Include="ExpressionTrees\Results\UncheckedDirectTrySpecificConversions.txt" />
<Content Include="ExpressionTrees\Results\UncheckedLike.txt" />
<Content Include="ExpressionTrees\Results\UncheckedShortCircuit.txt" />
<Content Include="ExpressionTrees\Results\UncheckedUnaryPlusMinusNot.txt" />
<Content Include="ExpressionTrees\Results\UncheckedUserDefinedBinaryOperators.txt" />
<Content Include="ExpressionTrees\Results\XmlLiteralsInExprLambda01_Result.txt" />
<Content Include="ExpressionTrees\Results\XmlLiteralsInExprLambda02_Result.txt" />
<Content Include="ExpressionTrees\Results\XmlLiteralsInExprLambda03_Result.txt" />
</ItemGroup>
<ItemGroup>
<Content Include="CodeGen\ConversionsILGenTestSource.vb" />
<Content Include="CodeGen\ConversionsILGenTestSource1.vb" />
<Content Include="CodeGen\ConversionsILGenTestSource2.vb" />
<Content Include="ExpressionTrees\Sources\UserDefinedBinaryOperators.vb" />
<Content Include="ExpressionTrees\Tests\TestConversion_Narrowing_UDC.vb" />
<Content Include="ExpressionTrees\Tests\TestConversion_TypeMatrix_UserTypes.vb" />
<Content Include="ExpressionTrees\Tests\TestConversion_Widening_UDC.vb" />
<Content Include="ExpressionTrees\Tests\TestUnary_UDO_IsTrueIsFalse.vb" />
<Content Include="ExpressionTrees\Tests\TestUnary_UDO_PlusMinusNot.vb" />
<Compile Remove="CodeGen\ConversionsILGenTestSource.vb" />
<Compile Remove="CodeGen\ConversionsILGenTestSource1.vb" />
<Compile Remove="CodeGen\ConversionsILGenTestSource2.vb" />
<Compile Remove="ExpressionTrees\Sources\UserDefinedBinaryOperators.vb" />
<Compile Remove="ExpressionTrees\Tests\TestConversion_Narrowing_UDC.vb" />
<Compile Remove="ExpressionTrees\Tests\TestConversion_TypeMatrix_UserTypes.vb" />
<Compile Remove="ExpressionTrees\Tests\TestConversion_Widening_UDC.vb" />
<Compile Remove="ExpressionTrees\Tests\TestUnary_UDO_IsTrueIsFalse.vb" />
<Compile Remove="ExpressionTrees\Tests\TestUnary_UDO_PlusMinusNot.vb" />
</ItemGroup>
<ItemGroup>
<Import Include="IdentifierComparison = Microsoft.CodeAnalysis.CaseInsensitiveComparison" />
<Import Include="Roslyn.Utilities" />
<Import Include="Xunit" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="CodeGen\ConversionsILGenTestBaseline.txt" />
<EmbeddedResource Include="CodeGen\ConversionsILGenTestBaseline1.txt" />
<EmbeddedResource Include="CodeGen\ConversionsILGenTestSource.vb" />
<EmbeddedResource Include="CodeGen\ConversionsILGenTestSource1.vb" />
<EmbeddedResource Include="CodeGen\ConversionsILGenTestSource2.vb" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedArithmeticBinaryOperators.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\UncheckedArithmeticBinaryOperators.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedAndOrXor.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\UncheckedAndOrXor.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedShortCircuit.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\UncheckedShortCircuit.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedComparisonOperators.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\UncheckedComparisonOperators.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedIsIsNotNothing.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedIsIsNot.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedConcatenate.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\UncheckedConcatenate.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedLike.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\UncheckedLike.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedWithDate.txt" />
<EmbeddedResource Include="ExpressionTrees\Sources\ExprLambdaUtils.vb" />
<EmbeddedResource Include="ExpressionTrees\Sources\UserDefinedBinaryOperators.vb" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedUserDefinedBinaryOperators.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\UncheckedUserDefinedBinaryOperators.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedNothingConversions.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedTypeParameters.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedDirectTrySpecificConversions.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\UncheckedDirectTrySpecificConversions.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedCTypeAndImplicitConversionsEven.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\UncheckedCTypeAndImplicitConversionsEven.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedCTypeAndImplicitConversionsOdd.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\UncheckedCTypeAndImplicitConversionsOdd.txt" />
<EmbeddedResource Include="ExpressionTrees\Tests\TestConversion_TypeMatrix_UserTypes.vb" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedUserTypeConversions.txt" />
<EmbeddedResource Include="ExpressionTrees\Tests\TestConversion_Narrowing_UDC.vb" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedNarrowingUDC.txt" />
<EmbeddedResource Include="ExpressionTrees\Tests\TestConversion_Widening_UDC.vb" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedWideningUDC.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedUnaryPlusMinusNot.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\UncheckedUnaryPlusMinusNot.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedIsTrueIsFalse.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedUdoUnaryPlusMinusNot.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedCoalesceWithNullableBoolean.txt" />
<EmbeddedResource Include="ExpressionTrees\Tests\TestUnary_UDO_PlusMinusNot.vb" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedCoalesceWithUserDefinedConversions.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedObjectInitializers.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedArrayInitializers.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedCollectionInitializers.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\CheckedMiscellaneousA.txt" />
<EmbeddedResource Include="ExpressionTrees\Tests\TestUnary_UDO_IsTrueIsFalse.vb" />
<EmbeddedResource Include="ExpressionTrees\Sources\QueryHelper.vb" />
<EmbeddedResource Include="ExpressionTrees\Results\ExprTree_LegacyTests07_Result.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\ExprTree_LegacyTests08_Result.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\ExprTree_LegacyTests09_Result.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\XmlLiteralsInExprLambda01_Result.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\XmlLiteralsInExprLambda02_Result.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\XmlLiteralsInExprLambda03_Result.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\ExprTree_LegacyTests10_Result.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\ExprTree_LegacyTests02_v40_Result.txt" />
<EmbeddedResource Include="ExpressionTrees\Results\ExprTree_LegacyTests02_v45_Result.txt" />
</ItemGroup>
<ItemGroup>
<Folder Include="My Project\" />
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
<Import Project="$(RepositoryEngineeringDir)targets\ILAsm.targets" />
</Project>
| -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Compilers/Test/Utilities/VisualBasic/Microsoft.CodeAnalysis.VisualBasic.Test.Utilities.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<RootNamespace>Microsoft.CodeAnalysis.VisualBasic.UnitTests</RootNamespace>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
<TargetFrameworks>netcoreapp3.1;net472</TargetFrameworks>
<IsShipping>false</IsShipping>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" />
<ProjectReference Include="..\..\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" />
<ProjectReference Include="..\..\..\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\..\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" />
</ItemGroup>
<ItemGroup>
<Import Include="IdentifierComparison = Microsoft.CodeAnalysis.CaseInsensitiveComparison" />
<Import Include="Microsoft.CodeAnalysis" />
<Import Include="Microsoft.CodeAnalysis.VisualBasic" />
<Import Include="Microsoft.CodeAnalysis.VisualBasic.Emit" />
<Import Include="Microsoft.CodeAnalysis.VisualBasic.Symbols" />
<Import Include="Microsoft.CodeAnalysis.VisualBasic.Syntax" />
<Import Include="Roslyn.Utilities" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Emit.UnitTests" />
<InternalsVisibleTo Include="Roslyn.Compilers.VisualBasic.IOperation.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Semantic.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Symbol.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Syntax.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExpressionEvaluator.FunctionResolver.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ExpressionCompiler.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ResultProvider.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Scripting.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests" />
</ItemGroup>
<ItemGroup>
<Folder Include="My Project\" />
</ItemGroup>
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<RootNamespace>Microsoft.CodeAnalysis.VisualBasic.UnitTests</RootNamespace>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
<TargetFrameworks>netcoreapp3.1;net472</TargetFrameworks>
<IsShipping>false</IsShipping>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" />
<ProjectReference Include="..\..\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" />
<ProjectReference Include="..\..\..\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\..\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" />
</ItemGroup>
<ItemGroup>
<Import Include="IdentifierComparison = Microsoft.CodeAnalysis.CaseInsensitiveComparison" />
<Import Include="Microsoft.CodeAnalysis" />
<Import Include="Microsoft.CodeAnalysis.VisualBasic" />
<Import Include="Microsoft.CodeAnalysis.VisualBasic.Emit" />
<Import Include="Microsoft.CodeAnalysis.VisualBasic.Symbols" />
<Import Include="Microsoft.CodeAnalysis.VisualBasic.Syntax" />
<Import Include="Roslyn.Utilities" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Emit.UnitTests" />
<InternalsVisibleTo Include="Roslyn.Compilers.VisualBasic.IOperation.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Semantic.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Symbol.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Syntax.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExpressionEvaluator.FunctionResolver.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ExpressionCompiler.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ResultProvider.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Scripting.UnitTests" />
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests" />
</ItemGroup>
<ItemGroup>
<Folder Include="My Project\" />
</ItemGroup>
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Workspaces/MSBuildTest/Resources/ProjectFiles/VisualBasic/NonExistentProjectReference.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<PlatformTarget>AnyCPU</PlatformTarget>
<ProductVersion></ProductVersion>
<SchemaVersion></SchemaVersion>
<ProjectGuid>{AC25ECDA-DE94-4FCF-A688-EB3A2BE3670C}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>VisualBasicProject</RootNamespace>
<AssemblyName>VisualBasicProject</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Windows</MyType>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\Debug\</OutputPath>
<DocumentationFile>VisualBasicProject.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
<RemoveIntegerChecks>true</RemoveIntegerChecks>
<AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile>
<DefineConstants>FURBY</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DocumentationFile>VisualBasicProject.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>Off</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Diagnostics" />
<Import Include="System.Linq" />
</ItemGroup>
<ItemGroup>
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<Compile Include="VisualBasicClass.vb" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CSharpProject\NonExistentProject.csproj">
<Project>{686DD036-86AA-443E-8A10-DDB43266A8C4}</Project>
<Name>CSharpProject</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<PlatformTarget>AnyCPU</PlatformTarget>
<ProductVersion></ProductVersion>
<SchemaVersion></SchemaVersion>
<ProjectGuid>{AC25ECDA-DE94-4FCF-A688-EB3A2BE3670C}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>VisualBasicProject</RootNamespace>
<AssemblyName>VisualBasicProject</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Windows</MyType>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\Debug\</OutputPath>
<DocumentationFile>VisualBasicProject.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
<RemoveIntegerChecks>true</RemoveIntegerChecks>
<AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile>
<DefineConstants>FURBY</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DocumentationFile>VisualBasicProject.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>Off</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Diagnostics" />
<Import Include="System.Linq" />
</ItemGroup>
<ItemGroup>
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<Compile Include="VisualBasicClass.vb" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CSharpProject\NonExistentProject.csproj">
<Project>{686DD036-86AA-443E-8A10-DDB43266A8C4}</Project>
<Name>CSharpProject</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/CodeStyle/VisualBasic/CodeFixes/Microsoft.CodeAnalysis.VisualBasic.CodeStyle.Fixes.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>netstandard2.0</TargetFramework>
<RootNamespace></RootNamespace>
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
<DefineConstants>$(DefineConstants),CODE_STYLE</DefineConstants>
<!-- NuGet -->
<IsPackable>true</IsPackable>
<IsAnalyzer>true</IsAnalyzer>
<NuspecPackageId>Microsoft.CodeAnalysis.VisualBasic.CodeStyle</NuspecPackageId>
<PackageDescription>
.NET Compiler Platform ("Roslyn") code style analyzers for Visual Basic.
</PackageDescription>
<TargetsForTfmSpecificContentInPackage>$(TargetsForTfmSpecificContentInPackage);_GetFilesToPackage</TargetsForTfmSpecificContentInPackage>
<!-- Remove once https://github.com/NuGet/Home/issues/8583 is fixed -->
<NoWarn>$(NoWarn);NU5128</NoWarn>
</PropertyGroup>
<Target Name="_GetFilesToPackage">
<PropertyGroup>
<CodeStyleAnalyzerArtifactsBinDir>$(ArtifactsBinDir)Microsoft.CodeAnalysis.CodeStyle\$(Configuration)\$(TargetFramework)</CodeStyleAnalyzerArtifactsBinDir>
<CodeStyleFixesArtifactsBinDir>$(ArtifactsBinDir)Microsoft.CodeAnalysis.CodeStyle.Fixes\$(Configuration)\$(TargetFramework)</CodeStyleFixesArtifactsBinDir>
<VisualBasicCodeStyleAnalyzerArtifactsBinDir>$(ArtifactsBinDir)Microsoft.CodeAnalysis.VisualBasic.CodeStyle\$(Configuration)\$(TargetFramework)</VisualBasicCodeStyleAnalyzerArtifactsBinDir>
<VisualBasicCodeStyleFixesArtifactsBinDir>$(ArtifactsBinDir)Microsoft.CodeAnalysis.VisualBasic.CodeStyle.Fixes\$(Configuration)\$(TargetFramework)</VisualBasicCodeStyleFixesArtifactsBinDir>
<VisualBasicCodeStyleTargetsFileName>Microsoft.CodeAnalysis.VisualBasic.CodeStyle.targets</VisualBasicCodeStyleTargetsFileName>
<DotNetExecutable Condition="'$(OS)' == 'Windows_NT'">$(DotNetRoot)dotnet.exe</DotNetExecutable>
<DotNetExecutable Condition="'$(DotNetExecutable)' == ''">$(DotNetRoot)dotnet</DotNetExecutable>
</PropertyGroup>
<Exec Command='"$(DotNetExecutable)" "$(ArtifactsBinDir)CodeStyleConfigFileGenerator\$(Configuration)\netcoreapp3.1\CodeStyleConfigFileGenerator.dll" "VisualBasic" "$(VisualBasicCodeStyleFixesArtifactsBinDir)" "$(VisualBasicCodeStyleTargetsFileName)" "$(CodeStyleAnalyzerArtifactsBinDir)\Microsoft.CodeAnalysis.CodeStyle.dll;$(VisualBasicCodeStyleAnalyzerArtifactsBinDir)\Microsoft.CodeAnalysis.VisualBasic.CodeStyle.dll"' />
<ItemGroup>
<_File Include="$(VisualBasicCodeStyleAnalyzerArtifactsBinDir)\Microsoft.CodeAnalysis.VisualBasic.CodeStyle.dll" TargetDir="analyzers/dotnet/vb" />
<_File Include="$(VisualBasicCodeStyleFixesArtifactsBinDir)\Microsoft.CodeAnalysis.VisualBasic.CodeStyle.Fixes.dll" TargetDir="analyzers/dotnet/vb" />
<_File Include="$(CodeStyleAnalyzerArtifactsBinDir)\Microsoft.CodeAnalysis.CodeStyle.dll" TargetDir="analyzers/dotnet/vb" />
<_File Include="$(CodeStyleFixesArtifactsBinDir)\Microsoft.CodeAnalysis.CodeStyle.Fixes.dll" TargetDir="analyzers/dotnet/vb" />
<_File Include="$(VisualBasicCodeStyleAnalyzerArtifactsBinDir)\**\Microsoft.CodeAnalysis.VisualBasic.CodeStyle.resources.dll" TargetDir="analyzers/dotnet/vb" />
<_File Include="$(VisualBasicCodeStyleFixesArtifactsBinDir)\**\Microsoft.CodeAnalysis.VisualBasic.CodeStyle.Fixes.resources.dll" TargetDir="analyzers/dotnet/vb" />
<_File Include="$(CodeStyleAnalyzerArtifactsBinDir)\**\Microsoft.CodeAnalysis.CodeStyle.resources.dll" TargetDir="analyzers/dotnet/vb" />
<_File Include="$(CodeStyleFixesArtifactsBinDir)\**\Microsoft.CodeAnalysis.CodeStyle.Fixes.resources.dll" TargetDir="analyzers/dotnet/vb" />
<_File Include="$(VisualBasicCodeStyleFixesArtifactsBinDir)\$(VisualBasicCodeStyleTargetsFileName)" TargetDir="build" />
<_File Include="$(VisualBasicCodeStyleFixesArtifactsBinDir)\config\**\*.*" TargetDir="build/config" />
<_File Include="$(MSBuildProjectDirectory)\build\**\*.*" TargetDir="build" />
<TfmSpecificPackageFile Include="@(_File)" PackagePath="%(_File.TargetDir)/%(_File.RecursiveDir)%(_File.FileName)%(_File.Extension)" />
</ItemGroup>
</Target>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" />
<ProjectReference Include="..\..\Core\Analyzers\Microsoft.CodeAnalysis.CodeStyle.csproj" />
<ProjectReference Include="..\..\Core\CodeFixes\Microsoft.CodeAnalysis.CodeStyle.Fixes.csproj" />
<ProjectReference Include="..\Analyzers\Microsoft.CodeAnalysis.VisualBasic.CodeStyle.vbproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.CodeStyle.UnitTests" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="VBCodeStyleFixesResources.resx" GenerateSource="true" Namespace="Microsoft.CodeAnalysis.VisualBasic" />
</ItemGroup>
<ItemGroup>
<PublicAPI Include="PublicAPI.Shipped.txt" />
<PublicAPI Include="PublicAPI.Unshipped.txt" />
</ItemGroup>
<ItemGroup>
<None Include="build\Microsoft.CodeAnalysis.VisualBasic.CodeStyle.props" />
</ItemGroup>
<Import Project="..\..\..\Workspaces\SharedUtilitiesAndExtensions\Workspace\VisualBasic\VisualBasicWorkspaceExtensions.projitems" Label="Shared" />
<Import Project="..\..\..\Analyzers\VisualBasic\CodeFixes\VisualBasicCodeFixes.projitems" Label="Shared" />
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>netstandard2.0</TargetFramework>
<RootNamespace></RootNamespace>
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
<DefineConstants>$(DefineConstants),CODE_STYLE</DefineConstants>
<!-- NuGet -->
<IsPackable>true</IsPackable>
<IsAnalyzer>true</IsAnalyzer>
<NuspecPackageId>Microsoft.CodeAnalysis.VisualBasic.CodeStyle</NuspecPackageId>
<PackageDescription>
.NET Compiler Platform ("Roslyn") code style analyzers for Visual Basic.
</PackageDescription>
<TargetsForTfmSpecificContentInPackage>$(TargetsForTfmSpecificContentInPackage);_GetFilesToPackage</TargetsForTfmSpecificContentInPackage>
<!-- Remove once https://github.com/NuGet/Home/issues/8583 is fixed -->
<NoWarn>$(NoWarn);NU5128</NoWarn>
</PropertyGroup>
<Target Name="_GetFilesToPackage">
<PropertyGroup>
<CodeStyleAnalyzerArtifactsBinDir>$(ArtifactsBinDir)Microsoft.CodeAnalysis.CodeStyle\$(Configuration)\$(TargetFramework)</CodeStyleAnalyzerArtifactsBinDir>
<CodeStyleFixesArtifactsBinDir>$(ArtifactsBinDir)Microsoft.CodeAnalysis.CodeStyle.Fixes\$(Configuration)\$(TargetFramework)</CodeStyleFixesArtifactsBinDir>
<VisualBasicCodeStyleAnalyzerArtifactsBinDir>$(ArtifactsBinDir)Microsoft.CodeAnalysis.VisualBasic.CodeStyle\$(Configuration)\$(TargetFramework)</VisualBasicCodeStyleAnalyzerArtifactsBinDir>
<VisualBasicCodeStyleFixesArtifactsBinDir>$(ArtifactsBinDir)Microsoft.CodeAnalysis.VisualBasic.CodeStyle.Fixes\$(Configuration)\$(TargetFramework)</VisualBasicCodeStyleFixesArtifactsBinDir>
<VisualBasicCodeStyleTargetsFileName>Microsoft.CodeAnalysis.VisualBasic.CodeStyle.targets</VisualBasicCodeStyleTargetsFileName>
<DotNetExecutable Condition="'$(OS)' == 'Windows_NT'">$(DotNetRoot)dotnet.exe</DotNetExecutable>
<DotNetExecutable Condition="'$(DotNetExecutable)' == ''">$(DotNetRoot)dotnet</DotNetExecutable>
</PropertyGroup>
<Exec Command='"$(DotNetExecutable)" "$(ArtifactsBinDir)CodeStyleConfigFileGenerator\$(Configuration)\netcoreapp3.1\CodeStyleConfigFileGenerator.dll" "VisualBasic" "$(VisualBasicCodeStyleFixesArtifactsBinDir)" "$(VisualBasicCodeStyleTargetsFileName)" "$(CodeStyleAnalyzerArtifactsBinDir)\Microsoft.CodeAnalysis.CodeStyle.dll;$(VisualBasicCodeStyleAnalyzerArtifactsBinDir)\Microsoft.CodeAnalysis.VisualBasic.CodeStyle.dll"' />
<ItemGroup>
<_File Include="$(VisualBasicCodeStyleAnalyzerArtifactsBinDir)\Microsoft.CodeAnalysis.VisualBasic.CodeStyle.dll" TargetDir="analyzers/dotnet/vb" />
<_File Include="$(VisualBasicCodeStyleFixesArtifactsBinDir)\Microsoft.CodeAnalysis.VisualBasic.CodeStyle.Fixes.dll" TargetDir="analyzers/dotnet/vb" />
<_File Include="$(CodeStyleAnalyzerArtifactsBinDir)\Microsoft.CodeAnalysis.CodeStyle.dll" TargetDir="analyzers/dotnet/vb" />
<_File Include="$(CodeStyleFixesArtifactsBinDir)\Microsoft.CodeAnalysis.CodeStyle.Fixes.dll" TargetDir="analyzers/dotnet/vb" />
<_File Include="$(VisualBasicCodeStyleAnalyzerArtifactsBinDir)\**\Microsoft.CodeAnalysis.VisualBasic.CodeStyle.resources.dll" TargetDir="analyzers/dotnet/vb" />
<_File Include="$(VisualBasicCodeStyleFixesArtifactsBinDir)\**\Microsoft.CodeAnalysis.VisualBasic.CodeStyle.Fixes.resources.dll" TargetDir="analyzers/dotnet/vb" />
<_File Include="$(CodeStyleAnalyzerArtifactsBinDir)\**\Microsoft.CodeAnalysis.CodeStyle.resources.dll" TargetDir="analyzers/dotnet/vb" />
<_File Include="$(CodeStyleFixesArtifactsBinDir)\**\Microsoft.CodeAnalysis.CodeStyle.Fixes.resources.dll" TargetDir="analyzers/dotnet/vb" />
<_File Include="$(VisualBasicCodeStyleFixesArtifactsBinDir)\$(VisualBasicCodeStyleTargetsFileName)" TargetDir="build" />
<_File Include="$(VisualBasicCodeStyleFixesArtifactsBinDir)\config\**\*.*" TargetDir="build/config" />
<_File Include="$(MSBuildProjectDirectory)\build\**\*.*" TargetDir="build" />
<TfmSpecificPackageFile Include="@(_File)" PackagePath="%(_File.TargetDir)/%(_File.RecursiveDir)%(_File.FileName)%(_File.Extension)" />
</ItemGroup>
</Target>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" />
<ProjectReference Include="..\..\Core\Analyzers\Microsoft.CodeAnalysis.CodeStyle.csproj" />
<ProjectReference Include="..\..\Core\CodeFixes\Microsoft.CodeAnalysis.CodeStyle.Fixes.csproj" />
<ProjectReference Include="..\Analyzers\Microsoft.CodeAnalysis.VisualBasic.CodeStyle.vbproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.CodeStyle.UnitTests" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="VBCodeStyleFixesResources.resx" GenerateSource="true" Namespace="Microsoft.CodeAnalysis.VisualBasic" />
</ItemGroup>
<ItemGroup>
<PublicAPI Include="PublicAPI.Shipped.txt" />
<PublicAPI Include="PublicAPI.Unshipped.txt" />
</ItemGroup>
<ItemGroup>
<None Include="build\Microsoft.CodeAnalysis.VisualBasic.CodeStyle.props" />
</ItemGroup>
<Import Project="..\..\..\Workspaces\SharedUtilitiesAndExtensions\Workspace\VisualBasic\VisualBasicWorkspaceExtensions.projitems" Label="Shared" />
<Import Project="..\..\..\Analyzers\VisualBasic\CodeFixes\VisualBasicCodeFixes.projitems" Label="Shared" />
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Workspaces/MSBuildTest/Resources/ProjectFiles/VisualBasic/AnalyzerReference.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<PlatformTarget>AnyCPU</PlatformTarget>
<ProductVersion></ProductVersion>
<SchemaVersion></SchemaVersion>
<ProjectGuid>{AC25ECDA-DE94-4FCF-A688-EB3A2BE3670C}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>VisualBasicProject_AnalyzerReference</RootNamespace>
<AssemblyName>VisualBasicProject_AnalyzerReference</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Windows</MyType>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<AdditionalFileItemNames>Content</AdditionalFileItemNames>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\Debug\</OutputPath>
<DocumentationFile>VisualBasicProject.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
<RemoveIntegerChecks>true</RemoveIntegerChecks>
<AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile>
<DefineConstants>FURBY</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DocumentationFile>VisualBasicProject.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>Off</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Diagnostics" />
<Import Include="System.Linq" />
</ItemGroup>
<ItemGroup>
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<Compile Include="VisualBasicClass.vb" />
<Content Include="XamlFile.xaml" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<Analyzer Include="CSharpProject.dll" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<PlatformTarget>AnyCPU</PlatformTarget>
<ProductVersion></ProductVersion>
<SchemaVersion></SchemaVersion>
<ProjectGuid>{AC25ECDA-DE94-4FCF-A688-EB3A2BE3670C}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>VisualBasicProject_AnalyzerReference</RootNamespace>
<AssemblyName>VisualBasicProject_AnalyzerReference</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Windows</MyType>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<AdditionalFileItemNames>Content</AdditionalFileItemNames>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\Debug\</OutputPath>
<DocumentationFile>VisualBasicProject.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
<RemoveIntegerChecks>true</RemoveIntegerChecks>
<AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile>
<DefineConstants>FURBY</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DocumentationFile>VisualBasicProject.xml</DocumentationFile>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>Off</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Diagnostics" />
<Import Include="System.Linq" />
</ItemGroup>
<ItemGroup>
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<Compile Include="VisualBasicClass.vb" />
<Content Include="XamlFile.xaml" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<Analyzer Include="CSharpProject.dll" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Microsoft.CodeAnalysis.VisualBasic.ExpressionCompiler.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<AssemblyName>Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ExpressionCompiler</AssemblyName>
<TargetFramework>netstandard2.0</TargetFramework>
<RootNamespace></RootNamespace>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\..\Core\Source\ExpressionCompiler\Microsoft.CodeAnalysis.ExpressionCompiler.csproj" />
</ItemGroup>
<ItemGroup>
<VsdConfigXmlFiles Include="BasicExpressionCompiler.vsdconfigxml">
<SubType>Designer</SubType>
</VsdConfigXmlFiles>
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ExpressionCompiler.UnitTests" />
<InternalsVisibleTo Include="Microsoft.VisualStudio.ProductionBreakpoints.CodeAnalysis" Key="$(VisualStudioDebuggerKey)" WorkItem="https://github.com/dotnet/roslyn/issues/35084" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Resources.resx" GenerateSource="true" Namespace="Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.Debugger.Engine-implementation" Version="$(MicrosoftVisualStudioDebuggerEngineimplementationVersion)" />
<PackageReference Include="Microsoft.VisualStudio.Debugger.Metadata-implementation">
<Version>$(MicrosoftVisualStudioDebuggerMetadataimplementationVersion)</Version>
<ExcludeAssets>compile</ExcludeAssets>
</PackageReference>
</ItemGroup>
<Import Project="$(RepositoryEngineeringDir)targets\Vsdconfig.targets" />
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<AssemblyName>Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ExpressionCompiler</AssemblyName>
<TargetFramework>netstandard2.0</TargetFramework>
<RootNamespace></RootNamespace>
</PropertyGroup>
<ItemGroup Label="Project References">
<ProjectReference Include="..\..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" />
<ProjectReference Include="..\..\..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" />
<ProjectReference Include="..\..\..\Core\Source\ExpressionCompiler\Microsoft.CodeAnalysis.ExpressionCompiler.csproj" />
</ItemGroup>
<ItemGroup>
<VsdConfigXmlFiles Include="BasicExpressionCompiler.vsdconfigxml">
<SubType>Designer</SubType>
</VsdConfigXmlFiles>
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ExpressionCompiler.UnitTests" />
<InternalsVisibleTo Include="Microsoft.VisualStudio.ProductionBreakpoints.CodeAnalysis" Key="$(VisualStudioDebuggerKey)" WorkItem="https://github.com/dotnet/roslyn/issues/35084" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Resources.resx" GenerateSource="true" Namespace="Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.Debugger.Engine-implementation" Version="$(MicrosoftVisualStudioDebuggerEngineimplementationVersion)" />
<PackageReference Include="Microsoft.VisualStudio.Debugger.Metadata-implementation">
<Version>$(MicrosoftVisualStudioDebuggerMetadataimplementationVersion)</Version>
<ExcludeAssets>compile</ExcludeAssets>
</PackageReference>
</ItemGroup>
<Import Project="$(RepositoryEngineeringDir)targets\Vsdconfig.targets" />
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Workspaces/MSBuildTest/Resources/Issue29122/Proj1/ClassLibrary1.vbproj | <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>
</ProductVersion>
<SchemaVersion>
</SchemaVersion>
<ProjectGuid>{F8AE35AB-1AC5-4381-BB3E-0645519695F5}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>ClassLibrary1</RootNamespace>
<AssemblyName>ClassLibrary1</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Windows</MyType>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<TargetFrameworkProfile />
<RestorePackages>true</RestorePackages>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>On</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
<DebugSymbols>true</DebugSymbols>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>..\Dev\</OutputPath>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
<DefineTrace>true</DefineTrace>
<OutputPath>..\Dev\</OutputPath>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<Compile Include="Class1.vb" />
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
</Project> | <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>
</ProductVersion>
<SchemaVersion>
</SchemaVersion>
<ProjectGuid>{F8AE35AB-1AC5-4381-BB3E-0645519695F5}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>ClassLibrary1</RootNamespace>
<AssemblyName>ClassLibrary1</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Windows</MyType>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<TargetFrameworkProfile />
<RestorePackages>true</RestorePackages>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>On</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
<DebugSymbols>true</DebugSymbols>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>..\Dev\</OutputPath>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
<DefineTrace>true</DefineTrace>
<OutputPath>..\Dev\</OutputPath>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<Compile Include="Class1.vb" />
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
</Project> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/VisualStudio/Core/Def/Implementation/Snippets/AbstractSnippetExpansionClient.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.SignatureHelp;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.Commanding;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.TextManager.Interop;
using MSXML;
using Roslyn.Utilities;
using CommonFormattingHelpers = Microsoft.CodeAnalysis.Editor.Shared.Utilities.CommonFormattingHelpers;
using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets
{
internal abstract class AbstractSnippetExpansionClient : ForegroundThreadAffinitizedObject, IVsExpansionClient
{
/// <summary>
/// The name of a snippet field created for caret placement in Full Method Call snippet sessions when the
/// invocation has no parameters.
/// </summary>
private const string PlaceholderSnippetField = "placeholder";
/// <summary>
/// A generated random string which is used to identify argument completion snippets from other snippets.
/// </summary>
private static readonly string s_fullMethodCallDescriptionSentinel = Guid.NewGuid().ToString("N");
private readonly SignatureHelpControllerProvider _signatureHelpControllerProvider;
private readonly IEditorCommandHandlerServiceFactory _editorCommandHandlerServiceFactory;
protected readonly IVsEditorAdaptersFactoryService EditorAdaptersFactoryService;
protected readonly Guid LanguageServiceGuid;
protected readonly ITextView TextView;
protected readonly ITextBuffer SubjectBuffer;
private readonly ImmutableArray<Lazy<ArgumentProvider, OrderableLanguageMetadata>> _allArgumentProviders;
private ImmutableArray<ArgumentProvider> _argumentProviders;
private bool _indentCaretOnCommit;
private int _indentDepth;
private bool _earlyEndExpansionHappened;
/// <summary>
/// Set to <see langword="true"/> when the snippet client registers an event listener for
/// <see cref="Controller.ModelUpdated"/>.
/// </summary>
/// <remarks>
/// This field should only be used from the main thread.
/// </remarks>
private bool _registeredForSignatureHelpEvents;
// Writes to this state only occur on the main thread.
private readonly State _state = new();
public AbstractSnippetExpansionClient(
IThreadingContext threadingContext,
Guid languageServiceGuid,
ITextView textView,
ITextBuffer subjectBuffer,
SignatureHelpControllerProvider signatureHelpControllerProvider,
IEditorCommandHandlerServiceFactory editorCommandHandlerServiceFactory,
IVsEditorAdaptersFactoryService editorAdaptersFactoryService,
ImmutableArray<Lazy<ArgumentProvider, OrderableLanguageMetadata>> argumentProviders)
: base(threadingContext)
{
this.LanguageServiceGuid = languageServiceGuid;
this.TextView = textView;
this.SubjectBuffer = subjectBuffer;
_signatureHelpControllerProvider = signatureHelpControllerProvider;
_editorCommandHandlerServiceFactory = editorCommandHandlerServiceFactory;
this.EditorAdaptersFactoryService = editorAdaptersFactoryService;
_allArgumentProviders = argumentProviders;
}
/// <inheritdoc cref="State._expansionSession"/>
public IVsExpansionSession? ExpansionSession => _state._expansionSession;
/// <inheritdoc cref="State.IsFullMethodCallSnippet"/>
public bool IsFullMethodCallSnippet => _state.IsFullMethodCallSnippet;
public ImmutableArray<ArgumentProvider> GetArgumentProviders(Workspace workspace)
{
AssertIsForeground();
// TODO: Move this to ArgumentProviderService: https://github.com/dotnet/roslyn/issues/50897
if (_argumentProviders.IsDefault)
{
_argumentProviders = workspace.Services
.SelectMatchingExtensionValues(ExtensionOrderer.Order(_allArgumentProviders), SubjectBuffer.ContentType)
.ToImmutableArray();
}
return _argumentProviders;
}
public abstract int GetExpansionFunction(IXMLDOMNode xmlFunctionNode, string bstrFieldName, out IVsExpansionFunction? pFunc);
protected abstract ITrackingSpan? InsertEmptyCommentAndGetEndPositionTrackingSpan();
internal abstract Document AddImports(Document document, int position, XElement snippetNode, bool placeSystemNamespaceFirst, bool allowInHiddenRegions, CancellationToken cancellationToken);
protected abstract string FallbackDefaultLiteral { get; }
public int FormatSpan(IVsTextLines pBuffer, VsTextSpan[] tsInSurfaceBuffer)
{
AssertIsForeground();
if (ExpansionSession == null)
{
return VSConstants.E_FAIL;
}
// If this is a manually-constructed snippet for a full method call, avoid formatting the snippet since
// doing so will disrupt signature help. Check ExpansionSession instead of '_state.IsFullMethodCallSnippet'
// because '_state._methodNameForInsertFullMethodCall' is not initialized at this point.
if (ExpansionSession.TryGetHeaderNode("Description", out var descriptionNode)
&& descriptionNode?.text == s_fullMethodCallDescriptionSentinel)
{
return VSConstants.S_OK;
}
// Formatting a snippet isn't cancellable.
var cancellationToken = CancellationToken.None;
// At this point, the $selection$ token has been replaced with the selected text and
// declarations have been replaced with their default text. We need to format the
// inserted snippet text while carefully handling $end$ position (where the caret goes
// after Return is pressed). The IVsExpansionSession keeps a tracking point for this
// position but we do the tracking ourselves to properly deal with virtual space. To
// ensure the end location is correct, we take three extra steps:
// 1. Insert an empty comment ("/**/" or "'") at the current $end$ position (prior
// to formatting), and keep a tracking span for the comment.
// 2. After formatting the new snippet text, find and delete the empty multiline
// comment (via the tracking span) and notify the IVsExpansionSession of the new
// $end$ location. If the line then contains only whitespace (due to the formatter
// putting the empty comment on its own line), then delete the white space and
// remember the indentation depth for that line.
// 3. When the snippet is finally completed (via Return), and PositionCaretForEditing()
// is called, check to see if the end location was on a line containing only white
// space in the previous step. If so, and if that line is still empty, then position
// the caret in virtual space.
// This technique ensures that a snippet like "if($condition$) { $end$ }" will end up
// as:
// if ($condition$)
// {
// $end$
// }
if (!TryGetSubjectBufferSpan(tsInSurfaceBuffer[0], out var snippetSpan))
{
return VSConstants.S_OK;
}
// Insert empty comment and track end position
var snippetTrackingSpan = snippetSpan.CreateTrackingSpan(SpanTrackingMode.EdgeInclusive);
var fullSnippetSpan = new VsTextSpan[1];
ExpansionSession.GetSnippetSpan(fullSnippetSpan);
var isFullSnippetFormat =
fullSnippetSpan[0].iStartLine == tsInSurfaceBuffer[0].iStartLine &&
fullSnippetSpan[0].iStartIndex == tsInSurfaceBuffer[0].iStartIndex &&
fullSnippetSpan[0].iEndLine == tsInSurfaceBuffer[0].iEndLine &&
fullSnippetSpan[0].iEndIndex == tsInSurfaceBuffer[0].iEndIndex;
var endPositionTrackingSpan = isFullSnippetFormat ? InsertEmptyCommentAndGetEndPositionTrackingSpan() : null;
var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(SubjectBuffer.CurrentSnapshot, snippetTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot));
SubjectBuffer.CurrentSnapshot.FormatAndApplyToBuffer(formattingSpan, CancellationToken.None);
if (isFullSnippetFormat)
{
CleanUpEndLocation(endPositionTrackingSpan);
// Unfortunately, this is the only place we can safely add references and imports
// specified in the snippet xml. In OnBeforeInsertion we have no guarantee that the
// snippet xml will be available, and changing the buffer during OnAfterInsertion can
// cause the underlying tracking spans to get out of sync.
var currentStartPosition = snippetTrackingSpan.GetStartPoint(SubjectBuffer.CurrentSnapshot).Position;
AddReferencesAndImports(
ExpansionSession, currentStartPosition, cancellationToken);
SetNewEndPosition(endPositionTrackingSpan);
}
return VSConstants.S_OK;
}
private void SetNewEndPosition(ITrackingSpan? endTrackingSpan)
{
RoslynDebug.AssertNotNull(ExpansionSession);
if (SetEndPositionIfNoneSpecified(ExpansionSession))
{
return;
}
if (endTrackingSpan != null)
{
if (!TryGetSpanOnHigherBuffer(
endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot),
TextView.TextBuffer,
out var endSpanInSurfaceBuffer))
{
return;
}
TextView.TextSnapshot.GetLineAndCharacter(endSpanInSurfaceBuffer.Start.Position, out var endLine, out var endChar);
ExpansionSession.SetEndSpan(new VsTextSpan
{
iStartLine = endLine,
iStartIndex = endChar,
iEndLine = endLine,
iEndIndex = endChar
});
}
}
private void CleanUpEndLocation(ITrackingSpan? endTrackingSpan)
{
if (endTrackingSpan != null)
{
// Find the empty comment and remove it...
var endSnapshotSpan = endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot);
SubjectBuffer.Delete(endSnapshotSpan.Span);
// Remove the whitespace before the comment if necessary. If whitespace is removed,
// then remember the indentation depth so we can appropriately position the caret
// in virtual space when the session is ended.
var line = SubjectBuffer.CurrentSnapshot.GetLineFromPosition(endSnapshotSpan.Start.Position);
var lineText = line.GetText();
if (lineText.Trim() == string.Empty)
{
_indentCaretOnCommit = true;
var document = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document != null)
{
var documentOptions = document.GetOptionsAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
_indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, documentOptions.GetOption(FormattingOptions.TabSize));
}
else
{
// If we don't have a document, then just guess the typical default TabSize value.
_indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, tabSize: 4);
}
SubjectBuffer.Delete(new Span(line.Start.Position, line.Length));
_ = SubjectBuffer.CurrentSnapshot.GetSpan(new Span(line.Start.Position, 0));
}
}
}
/// <summary>
/// If there was no $end$ token, place it at the end of the snippet code. Otherwise, it
/// defaults to the beginning of the snippet code.
/// </summary>
private static bool SetEndPositionIfNoneSpecified(IVsExpansionSession pSession)
{
if (!TryGetSnippetNode(pSession, out var snippetNode))
{
return false;
}
var ns = snippetNode.Name.NamespaceName;
var codeNode = snippetNode.Element(XName.Get("Code", ns));
if (codeNode == null)
{
return false;
}
var delimiterAttribute = codeNode.Attribute("Delimiter");
var delimiter = delimiterAttribute != null ? delimiterAttribute.Value : "$";
if (codeNode.Value.IndexOf(string.Format("{0}end{0}", delimiter), StringComparison.OrdinalIgnoreCase) != -1)
{
return false;
}
var snippetSpan = new VsTextSpan[1];
if (pSession.GetSnippetSpan(snippetSpan) != VSConstants.S_OK)
{
return false;
}
var newEndSpan = new VsTextSpan
{
iStartLine = snippetSpan[0].iEndLine,
iStartIndex = snippetSpan[0].iEndIndex,
iEndLine = snippetSpan[0].iEndLine,
iEndIndex = snippetSpan[0].iEndIndex
};
pSession.SetEndSpan(newEndSpan);
return true;
}
protected static bool TryGetSnippetNode(IVsExpansionSession pSession, [NotNullWhen(true)] out XElement? snippetNode)
{
IXMLDOMNode? xmlNode = null;
snippetNode = null;
try
{
// Cast to our own version of IVsExpansionSession so that we can get pNode as an
// IntPtr instead of a via a RCW. This allows us to guarantee that it pNode is
// released before leaving this method. Otherwise, a second invocation of the same
// snippet may cause an AccessViolationException.
var session = (IVsExpansionSessionInternal)pSession;
if (session.GetSnippetNode(null, out var pNode) != VSConstants.S_OK)
{
return false;
}
xmlNode = (IXMLDOMNode)Marshal.GetUniqueObjectForIUnknown(pNode);
snippetNode = XElement.Parse(xmlNode.xml);
return true;
}
finally
{
if (xmlNode != null && Marshal.IsComObject(xmlNode))
{
Marshal.ReleaseComObject(xmlNode);
}
}
}
public int PositionCaretForEditing(IVsTextLines pBuffer, [ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan")] VsTextSpan[] ts)
{
// If the formatted location of the $end$ position (the inserted comment) was on an
// empty line and indented, then we have already removed the white space on that line
// and the navigation location will be at column 0 on a blank line. We must now
// position the caret in virtual space.
pBuffer.GetLengthOfLine(ts[0].iStartLine, out var lineLength);
pBuffer.GetLineText(ts[0].iStartLine, 0, ts[0].iStartLine, lineLength, out var endLineText);
pBuffer.GetPositionOfLine(ts[0].iStartLine, out var endLinePosition);
PositionCaretForEditingInternal(endLineText, endLinePosition);
return VSConstants.S_OK;
}
/// <summary>
/// Internal for testing purposes. All real caret positioning logic takes place here. <see cref="PositionCaretForEditing"/>
/// only extracts the <paramref name="endLineText"/> and <paramref name="endLinePosition"/> from the provided <see cref="IVsTextLines"/>.
/// Tests can call this method directly to avoid producing an IVsTextLines.
/// </summary>
/// <param name="endLineText"></param>
/// <param name="endLinePosition"></param>
internal void PositionCaretForEditingInternal(string endLineText, int endLinePosition)
{
if (_indentCaretOnCommit && endLineText == string.Empty)
{
TextView.TryMoveCaretToAndEnsureVisible(new VirtualSnapshotPoint(TextView.TextSnapshot.GetPoint(endLinePosition), _indentDepth));
}
}
public virtual bool TryHandleTab()
{
if (ExpansionSession != null)
{
// When 'Tab' is pressed in the last field of a normal snippet, the session wraps back around to the
// first field (this is preservation of historical behavior). When 'Tab' is pressed at the end of an
// argument provider snippet, the snippet session is automatically committed (this behavior matches the
// design for Insert Full Method Call intended for multiple IDEs).
var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToNextExpansionField(fCommitIfLast: _state.IsFullMethodCallSnippet ? 1 : 0);
if (!tabbedInsideSnippetField)
{
ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1);
}
return tabbedInsideSnippetField;
}
return false;
}
public virtual bool TryHandleBackTab()
{
if (ExpansionSession != null)
{
var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToPreviousExpansionField();
if (!tabbedInsideSnippetField)
{
ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1);
}
return tabbedInsideSnippetField;
}
return false;
}
public virtual bool TryHandleEscape()
{
if (ExpansionSession != null)
{
ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1);
return true;
}
return false;
}
public virtual bool TryHandleReturn()
{
return CommitSnippet(leaveCaret: false);
}
/// <summary>
/// Commit the active snippet, if any.
/// </summary>
/// <param name="leaveCaret"><see langword="true"/> to leave the caret position unchanged by the call;
/// otherwise, <see langword="false"/> to move the caret to the <c>$end$</c> position of the snippet when the
/// snippet is committed.</param>
/// <returns><see langword="true"/> if the caret may have moved from the call; otherwise,
/// <see langword="false"/> if the caret did not move, or if there was no active snippet session to
/// commit.</returns>
public bool CommitSnippet(bool leaveCaret)
{
if (ExpansionSession != null)
{
if (!leaveCaret)
{
// Only move the caret if the enter was hit within the snippet fields.
var hitWithinField = VSConstants.S_OK == ExpansionSession.GoToNextExpansionField(fCommitIfLast: 0);
leaveCaret = !hitWithinField;
}
ExpansionSession.EndCurrentExpansion(fLeaveCaret: leaveCaret ? 1 : 0);
return !leaveCaret;
}
return false;
}
public virtual bool TryInsertExpansion(int startPositionInSubjectBuffer, int endPositionInSubjectBuffer, CancellationToken cancellationToken)
{
var textViewModel = TextView.TextViewModel;
if (textViewModel == null)
{
Debug.Assert(TextView.IsClosed);
return false;
}
// The expansion itself needs to be created in the data buffer, so map everything up
var triggerSpan = SubjectBuffer.CurrentSnapshot.GetSpan(startPositionInSubjectBuffer, endPositionInSubjectBuffer - startPositionInSubjectBuffer);
if (!TryGetSpanOnHigherBuffer(triggerSpan, textViewModel.DataBuffer, out var dataBufferSpan))
{
return false;
}
var buffer = EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer);
if (buffer is not IVsExpansion expansion)
{
return false;
}
buffer.GetLineIndexOfPosition(dataBufferSpan.Start.Position, out var startLine, out var startIndex);
buffer.GetLineIndexOfPosition(dataBufferSpan.End.Position, out var endLine, out var endIndex);
var textSpan = new VsTextSpan
{
iStartLine = startLine,
iStartIndex = startIndex,
iEndLine = endLine,
iEndIndex = endIndex
};
if (TryInsertArgumentCompletionSnippet(triggerSpan, dataBufferSpan, expansion, textSpan, cancellationToken))
{
Debug.Assert(_state.IsFullMethodCallSnippet);
return true;
}
if (expansion.InsertExpansion(textSpan, textSpan, this, LanguageServiceGuid, out _state._expansionSession) == VSConstants.S_OK)
{
// This expansion is not derived from a symbol, so make sure the state isn't tracking any symbol
// information
Debug.Assert(!_state.IsFullMethodCallSnippet);
return true;
}
return false;
}
private bool TryInsertArgumentCompletionSnippet(SnapshotSpan triggerSpan, SnapshotSpan dataBufferSpan, IVsExpansion expansion, VsTextSpan textSpan, CancellationToken cancellationToken)
{
if (!(SubjectBuffer.GetFeatureOnOffOption(CompletionOptions.EnableArgumentCompletionSnippets) ?? false))
{
// Argument completion snippets are not enabled
return false;
}
var document = SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document is null)
{
// Couldn't identify the current document
return false;
}
var symbols = ThreadingContext.JoinableTaskFactory.Run(() => GetReferencedSymbolsToLeftOfCaretAsync(document, caretPosition: triggerSpan.End, cancellationToken));
var methodSymbols = symbols.OfType<IMethodSymbol>().ToImmutableArray();
if (methodSymbols.Any())
{
// This is the method name as it appears in source text
var methodName = dataBufferSpan.GetText();
var snippet = CreateMethodCallSnippet(methodName, includeMethod: true, ImmutableArray<IParameterSymbol>.Empty, ImmutableDictionary<string, string>.Empty);
var doc = (DOMDocument)new DOMDocumentClass();
if (doc.loadXML(snippet.ToString(SaveOptions.OmitDuplicateNamespaces)))
{
if (expansion.InsertSpecificExpansion(doc, textSpan, this, LanguageServiceGuid, pszRelativePath: null, out _state._expansionSession) == VSConstants.S_OK)
{
Debug.Assert(_state._expansionSession != null);
_state._methodNameForInsertFullMethodCall = methodSymbols.First().Name;
Debug.Assert(_state._method == null);
if (_signatureHelpControllerProvider.GetController(TextView, SubjectBuffer) is { } controller)
{
EnsureRegisteredForModelUpdatedEvents(this, controller);
}
// Trigger signature help after starting the snippet session
//
// TODO: Figure out why ISignatureHelpBroker.TriggerSignatureHelp doesn't work but this does.
// https://github.com/dotnet/roslyn/issues/50036
var editorCommandHandlerService = _editorCommandHandlerServiceFactory.GetService(TextView, SubjectBuffer);
editorCommandHandlerService.Execute((view, buffer) => new InvokeSignatureHelpCommandArgs(view, buffer), nextCommandHandler: null);
return true;
}
}
}
return false;
// Local function
static void EnsureRegisteredForModelUpdatedEvents(AbstractSnippetExpansionClient client, Controller controller)
{
// Access to _registeredForSignatureHelpEvents is synchronized on the main thread
client.ThreadingContext.ThrowIfNotOnUIThread();
if (!client._registeredForSignatureHelpEvents)
{
client._registeredForSignatureHelpEvents = true;
controller.ModelUpdated += client.OnModelUpdated;
client.TextView.Closed += delegate { controller.ModelUpdated -= client.OnModelUpdated; };
}
}
}
/// <summary>
/// Creates a snippet for providing arguments to a call.
/// </summary>
/// <param name="methodName">The name of the method as it should appear in code.</param>
/// <param name="includeMethod">
/// <para><see langword="true"/> to include the method name and invocation parentheses in the resulting snippet;
/// otherwise, <see langword="false"/> if the method name and parentheses are assumed to already exist and the
/// template will only specify the argument placeholders. Since the <c>$end$</c> marker is always considered to
/// lie after the closing <c>)</c> of the invocation, it is only included when this parameter is
/// <see langword="true"/>.</para>
///
/// <para>For example, consider a call to <see cref="int.ToString(IFormatProvider)"/>. If
/// <paramref name="includeMethod"/> is <see langword="true"/>, the resulting snippet text might look like
/// this:</para>
///
/// <code>
/// ToString($provider$)$end$
/// </code>
///
/// <para>If <paramref name="includeMethod"/> is <see langword="false"/>, the resulting snippet text might look
/// like this:</para>
///
/// <code>
/// $provider$
/// </code>
///
/// <para>This parameter supports cycling between overloads of a method for argument completion. Since any text
/// edit that alters the <c>(</c> or <c>)</c> characters will force the Signature Help session to close, we are
/// careful to only update text that lies between these characters.</para>
/// </param>
/// <param name="parameters">The parameters to the method. If the specific target of the invocation is not
/// known, an empty array may be passed to create a template with a placeholder where arguments will eventually
/// go.</param>
private static XDocument CreateMethodCallSnippet(string methodName, bool includeMethod, ImmutableArray<IParameterSymbol> parameters, ImmutableDictionary<string, string> parameterValues)
{
XNamespace snippetNamespace = "http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet";
var template = new StringBuilder();
if (includeMethod)
{
template.Append(methodName).Append('(');
}
var declarations = new List<XElement>();
foreach (var parameter in parameters)
{
if (declarations.Any())
{
template.Append(", ");
}
// Create a snippet field for the argument. The name of the field matches the parameter name, and the
// default value for the field is provided by a call to the internal ArgumentValue snippet function. The
// parameter to the snippet function is a serialized SymbolKey which can be mapped back to the
// IParameterSymbol.
template.Append('$').Append(parameter.Name).Append('$');
declarations.Add(new XElement(
snippetNamespace + "Literal",
new XElement(snippetNamespace + "ID", new XText(parameter.Name)),
new XElement(snippetNamespace + "Default", new XText(parameterValues.GetValueOrDefault(parameter.Name, "")))));
}
if (!declarations.Any())
{
// If the invocation does not have any parameters, include an empty placeholder in the snippet template
// to ensure the caret starts inside the parentheses and can track changes to other overloads (which may
// have parameters).
template.Append($"${PlaceholderSnippetField}$");
declarations.Add(new XElement(
snippetNamespace + "Literal",
new XElement(snippetNamespace + "ID", new XText(PlaceholderSnippetField)),
new XElement(snippetNamespace + "Default", new XText(""))));
}
if (includeMethod)
{
template.Append(')');
}
template.Append("$end$");
// A snippet is manually constructed. Replacement fields are added for each argument, and the field name
// matches the parameter name.
// https://docs.microsoft.com/en-us/visualstudio/ide/code-snippets-schema-reference?view=vs-2019
return new XDocument(
new XDeclaration("1.0", "utf-8", null),
new XElement(
snippetNamespace + "CodeSnippets",
new XElement(
snippetNamespace + "CodeSnippet",
new XAttribute(snippetNamespace + "Format", "1.0.0"),
new XElement(
snippetNamespace + "Header",
new XElement(snippetNamespace + "Title", new XText(methodName)),
new XElement(snippetNamespace + "Description", new XText(s_fullMethodCallDescriptionSentinel))),
new XElement(
snippetNamespace + "Snippet",
new XElement(snippetNamespace + "Declarations", declarations.ToArray()),
new XElement(
snippetNamespace + "Code",
new XAttribute(snippetNamespace + "Language", "csharp"),
new XCData(template.ToString()))))));
}
private void OnModelUpdated(object sender, ModelUpdatedEventsArgs e)
{
AssertIsForeground();
if (e.NewModel is null)
{
// Signature Help was dismissed, but it's possible for a user to bring it back with Ctrl+Shift+Space.
// Leave the snippet session (if any) in its current state to allow it to process either a subsequent
// Signature Help update or the Escape/Enter keys that close the snippet session.
return;
}
if (!_state.IsFullMethodCallSnippet)
{
// Signature Help is showing an updated signature, but either there is no active snippet, or the active
// snippet is not performing argument value completion, so we just ignore it.
return;
}
if (!e.NewModel.UserSelected && _state._method is not null)
{
// This was an implicit signature change which was not triggered by user pressing up/down, and we are
// already showing an initialized argument completion snippet session, so avoid switching sessions.
return;
}
var document = SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document is null)
{
// It's unclear if/how this state would occur, but if it does we would throw an exception trying to
// use it. Just return immediately.
return;
}
// TODO: The following blocks the UI thread without cancellation, but it only occurs when an argument value
// completion session is active, which is behind an experimental feature flag.
// https://github.com/dotnet/roslyn/issues/50634
var compilation = ThreadingContext.JoinableTaskFactory.Run(() => document.Project.GetRequiredCompilationAsync(CancellationToken.None));
var newSymbolKey = (e.NewModel.SelectedItem as AbstractSignatureHelpProvider.SymbolKeySignatureHelpItem)?.SymbolKey ?? default;
var newSymbol = newSymbolKey.Resolve(compilation, cancellationToken: CancellationToken.None).GetAnySymbol();
if (newSymbol is not IMethodSymbol method)
return;
MoveToSpecificMethod(method, CancellationToken.None);
}
private static async Task<ImmutableArray<ISymbol>> GetReferencedSymbolsToLeftOfCaretAsync(
Document document,
SnapshotPoint caretPosition,
CancellationToken cancellationToken)
{
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var token = await semanticModel.SyntaxTree.GetTouchingWordAsync(caretPosition.Position, document.GetRequiredLanguageService<ISyntaxFactsService>(), cancellationToken).ConfigureAwait(false);
if (token.RawKind == 0)
{
// There is no touching word, so return empty immediately
return ImmutableArray<ISymbol>.Empty;
}
var semanticInfo = semanticModel.GetSemanticInfo(token, document.Project.Solution.Workspace, cancellationToken);
return semanticInfo.ReferencedSymbols;
}
/// <summary>
/// Update the current argument value completion session to use a specific method.
/// </summary>
/// <param name="method">The currently-selected method in Signature Help.</param>
/// <param name="cancellationToken">A cancellation token the operation may observe.</param>
public void MoveToSpecificMethod(IMethodSymbol method, CancellationToken cancellationToken)
{
AssertIsForeground();
if (ExpansionSession is null)
{
return;
}
if (SymbolEquivalenceComparer.Instance.Equals(_state._method, method))
{
return;
}
if (_state._methodNameForInsertFullMethodCall != method.Name)
{
// Signature Help is showing a signature that wasn't part of the set this argument value completion
// session was created from. It's unclear how this state should be handled, so we stop processing
// Signature Help updates for the current session.
// TODO: https://github.com/dotnet/roslyn/issues/50636
ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1);
return;
}
// If the first method overload chosen is a zero-parameter method, the snippet we'll create is the same snippet
// as the one did initially. The editor appears to have a bug where inserting a zero-width snippet (when we update the parameters)
// causes the inserted session to immediately dismiss; this works around that issue.
if (_state._method is null && method.Parameters.Length == 0)
{
_state._method = method;
return;
}
var document = SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document is null)
{
// Couldn't identify the current document
ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1);
return;
}
var textViewModel = TextView.TextViewModel;
if (textViewModel == null)
{
Debug.Assert(TextView.IsClosed);
return;
}
var buffer = EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer);
if (buffer is not IVsExpansion expansion)
{
return;
}
// We need to replace the portion of the existing Full Method Call snippet which appears inside parentheses.
// This span starts at the beginning of the first snippet field, and ends at the end of the last snippet
// field. Methods with no arguments still have an empty "placeholder" snippet field representing the initial
// caret position when the snippet is created.
var textSpan = new VsTextSpan[1];
if (ExpansionSession.GetSnippetSpan(textSpan) != VSConstants.S_OK)
{
return;
}
var firstField = _state._method?.Parameters.FirstOrDefault()?.Name ?? PlaceholderSnippetField;
if (ExpansionSession.GetFieldSpan(firstField, textSpan) != VSConstants.S_OK)
{
return;
}
VsTextSpan adjustedTextSpan;
adjustedTextSpan.iStartLine = textSpan[0].iStartLine;
adjustedTextSpan.iStartIndex = textSpan[0].iStartIndex;
var lastField = _state._method?.Parameters.LastOrDefault()?.Name ?? PlaceholderSnippetField;
if (ExpansionSession.GetFieldSpan(lastField, textSpan) != VSConstants.S_OK)
{
return;
}
adjustedTextSpan.iEndLine = textSpan[0].iEndLine;
adjustedTextSpan.iEndIndex = textSpan[0].iEndIndex;
// Track current argument values so input created/updated by a user is not lost when cycling through
// Signature Help overloads:
//
// 1. For each parameter of the method currently presented as a snippet, the value of the argument as
// it appears in code.
// 2. Place the argument values in a map from parameter name to current value.
// 3. (Later) the values in the map can be read to avoid providing new values for equivalent parameters.
var newArguments = _state._arguments;
if (_state._method is null || !_state._method.Parameters.Any())
{
// If we didn't have any previous parameters, then there is only the placeholder in the snippet.
// We don't want to lose what the user has typed there, if they typed something
if (ExpansionSession.GetFieldValue(PlaceholderSnippetField, out var placeholderValue) == VSConstants.S_OK &&
placeholderValue.Length > 0)
{
if (method.Parameters.Any())
{
newArguments = newArguments.SetItem(method.Parameters[0].Name, placeholderValue);
}
else
{
// TODO: if the user is typing before signature help updated the model, and we have no parameters here,
// should we still create a new snippet that has the existing placeholder text?
}
}
}
else if (_state._method is not null)
{
foreach (var previousParameter in _state._method.Parameters)
{
if (ExpansionSession.GetFieldValue(previousParameter.Name, out var previousValue) == VSConstants.S_OK)
{
newArguments = newArguments.SetItem(previousParameter.Name, previousValue);
}
}
}
// Now compute the new arguments for the new call
var semanticModel = document.GetRequiredSemanticModelAsync(cancellationToken).AsTask().WaitAndGetResult(cancellationToken);
var position = SubjectBuffer.CurrentSnapshot.GetPosition(adjustedTextSpan.iStartLine, adjustedTextSpan.iStartIndex);
foreach (var parameter in method.Parameters)
{
newArguments.TryGetValue(parameter.Name, out var value);
foreach (var provider in GetArgumentProviders(document.Project.Solution.Workspace))
{
var context = new ArgumentContext(provider, semanticModel, position, parameter, value, cancellationToken);
ThreadingContext.JoinableTaskFactory.Run(() => provider.ProvideArgumentAsync(context));
if (context.DefaultValue is not null)
{
value = context.DefaultValue;
break;
}
}
// If we still have no value, fill in the default
if (value is null)
{
value = FallbackDefaultLiteral;
}
newArguments = newArguments.SetItem(parameter.Name, value);
}
var snippet = CreateMethodCallSnippet(method.Name, includeMethod: false, method.Parameters, newArguments);
var doc = (DOMDocument)new DOMDocumentClass();
if (doc.loadXML(snippet.ToString(SaveOptions.OmitDuplicateNamespaces)))
{
if (expansion.InsertSpecificExpansion(doc, adjustedTextSpan, this, LanguageServiceGuid, pszRelativePath: null, out _state._expansionSession) == VSConstants.S_OK)
{
Debug.Assert(_state._expansionSession != null);
_state._methodNameForInsertFullMethodCall = method.Name;
_state._method = method;
_state._arguments = newArguments;
// On this path, the closing parenthesis is not part of the updated snippet, so there is no way for
// the snippet itself to represent the $end$ marker (which falls after the ')' character). Instead,
// we use the internal APIs to manually specify the effective position of the $end$ marker as the
// location in code immediately following the ')'. To do this, we use the knowledge that the snippet
// includes all text up to (but not including) the ')', and move that span one position to the
// right.
if (ExpansionSession.GetEndSpan(textSpan) == VSConstants.S_OK)
{
textSpan[0].iStartIndex++;
textSpan[0].iEndIndex++;
ExpansionSession.SetEndSpan(textSpan[0]);
}
}
}
}
public int EndExpansion()
{
if (ExpansionSession == null)
{
_earlyEndExpansionHappened = true;
}
_state.Clear();
_indentCaretOnCommit = false;
return VSConstants.S_OK;
}
public int IsValidKind(IVsTextLines pBuffer, VsTextSpan[] ts, string bstrKind, out int pfIsValidKind)
{
pfIsValidKind = 1;
return VSConstants.S_OK;
}
public int IsValidType(IVsTextLines pBuffer, VsTextSpan[] ts, string[] rgTypes, int iCountTypes, out int pfIsValidType)
{
pfIsValidType = 1;
return VSConstants.S_OK;
}
public int OnAfterInsertion(IVsExpansionSession pSession)
{
Logger.Log(FunctionId.Snippet_OnAfterInsertion);
return VSConstants.S_OK;
}
public int OnBeforeInsertion(IVsExpansionSession pSession)
{
Logger.Log(FunctionId.Snippet_OnBeforeInsertion);
_state._expansionSession = pSession;
// Symbol information (when necessary) is set by the caller
return VSConstants.S_OK;
}
public int OnItemChosen(string pszTitle, string pszPath)
{
var textViewModel = TextView.TextViewModel;
if (textViewModel == null)
{
Debug.Assert(TextView.IsClosed);
return VSConstants.E_FAIL;
}
int hr;
try
{
VsTextSpan textSpan;
GetCaretPositionInSurfaceBuffer(out textSpan.iStartLine, out textSpan.iStartIndex);
textSpan.iEndLine = textSpan.iStartLine;
textSpan.iEndIndex = textSpan.iStartIndex;
var expansion = (IVsExpansion?)EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer);
Contract.ThrowIfNull(expansion);
_earlyEndExpansionHappened = false;
hr = expansion.InsertNamedExpansion(pszTitle, pszPath, textSpan, this, LanguageServiceGuid, fShowDisambiguationUI: 0, pSession: out _state._expansionSession);
if (_earlyEndExpansionHappened)
{
// EndExpansion was called before InsertNamedExpansion returned, so set
// expansionSession to null to indicate that there is no active expansion
// session. This can occur when the snippet inserted doesn't have any expansion
// fields.
_state._expansionSession = null;
_earlyEndExpansionHappened = false;
}
}
catch (COMException ex)
{
hr = ex.ErrorCode;
}
return hr;
}
private void GetCaretPositionInSurfaceBuffer(out int caretLine, out int caretColumn)
{
var vsTextView = EditorAdaptersFactoryService.GetViewAdapter(TextView);
Contract.ThrowIfNull(vsTextView);
vsTextView.GetCaretPos(out caretLine, out caretColumn);
vsTextView.GetBuffer(out var textLines);
// Handle virtual space (e.g, see Dev10 778675)
textLines.GetLengthOfLine(caretLine, out var lineLength);
if (caretColumn > lineLength)
{
caretColumn = lineLength;
}
}
private void AddReferencesAndImports(
IVsExpansionSession pSession,
int position,
CancellationToken cancellationToken)
{
if (!TryGetSnippetNode(pSession, out var snippetNode))
{
return;
}
var documentWithImports = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (documentWithImports == null)
{
return;
}
var documentOptions = documentWithImports.GetOptionsAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var placeSystemNamespaceFirst = documentOptions.GetOption(GenerationOptions.PlaceSystemNamespaceFirst);
var allowInHiddenRegions = documentWithImports.CanAddImportsInHiddenRegions();
documentWithImports = AddImports(documentWithImports, position, snippetNode, placeSystemNamespaceFirst, allowInHiddenRegions, cancellationToken);
AddReferences(documentWithImports.Project, snippetNode);
}
private void AddReferences(Project originalProject, XElement snippetNode)
{
var referencesNode = snippetNode.Element(XName.Get("References", snippetNode.Name.NamespaceName));
if (referencesNode == null)
{
return;
}
var existingReferenceNames = originalProject.MetadataReferences.Select(r => Path.GetFileNameWithoutExtension(r.Display));
var workspace = originalProject.Solution.Workspace;
var projectId = originalProject.Id;
var assemblyXmlName = XName.Get("Assembly", snippetNode.Name.NamespaceName);
var failedReferenceAdditions = new List<string>();
foreach (var reference in referencesNode.Elements(XName.Get("Reference", snippetNode.Name.NamespaceName)))
{
// Note: URL references are not supported
var assemblyElement = reference.Element(assemblyXmlName);
var assemblyName = assemblyElement != null ? assemblyElement.Value.Trim() : null;
if (RoslynString.IsNullOrEmpty(assemblyName))
{
continue;
}
if (!(workspace is VisualStudioWorkspaceImpl visualStudioWorkspace) ||
!visualStudioWorkspace.TryAddReferenceToProject(projectId, assemblyName))
{
failedReferenceAdditions.Add(assemblyName);
}
}
if (failedReferenceAdditions.Any())
{
var notificationService = workspace.Services.GetRequiredService<INotificationService>();
notificationService.SendNotification(
string.Format(ServicesVSResources.The_following_references_were_not_found_0_Please_locate_and_add_them_manually, Environment.NewLine)
+ Environment.NewLine + Environment.NewLine
+ string.Join(Environment.NewLine, failedReferenceAdditions),
severity: NotificationSeverity.Warning);
}
}
protected static bool TryAddImportsToContainedDocument(Document document, IEnumerable<string> memberImportsNamespaces)
{
if (!(document.Project.Solution.Workspace is VisualStudioWorkspaceImpl vsWorkspace))
{
return false;
}
var containedDocument = vsWorkspace.TryGetContainedDocument(document.Id);
if (containedDocument == null)
{
return false;
}
if (containedDocument.ContainedLanguageHost is IVsContainedLanguageHostInternal containedLanguageHost)
{
foreach (var importClause in memberImportsNamespaces)
{
if (containedLanguageHost.InsertImportsDirective(importClause) != VSConstants.S_OK)
{
return false;
}
}
}
return true;
}
protected static bool TryGetSnippetFunctionInfo(
IXMLDOMNode xmlFunctionNode,
[NotNullWhen(true)] out string? snippetFunctionName,
[NotNullWhen(true)] out string? param)
{
if (xmlFunctionNode.text.IndexOf('(') == -1 ||
xmlFunctionNode.text.IndexOf(')') == -1 ||
xmlFunctionNode.text.IndexOf(')') < xmlFunctionNode.text.IndexOf('('))
{
snippetFunctionName = null;
param = null;
return false;
}
snippetFunctionName = xmlFunctionNode.text.Substring(0, xmlFunctionNode.text.IndexOf('('));
var paramStart = xmlFunctionNode.text.IndexOf('(') + 1;
var paramLength = xmlFunctionNode.text.LastIndexOf(')') - xmlFunctionNode.text.IndexOf('(') - 1;
param = xmlFunctionNode.text.Substring(paramStart, paramLength);
return true;
}
internal bool TryGetSubjectBufferSpan(VsTextSpan surfaceBufferTextSpan, out SnapshotSpan subjectBufferSpan)
{
var snapshotSpan = TextView.TextSnapshot.GetSpan(surfaceBufferTextSpan);
var subjectBufferSpanCollection = TextView.BufferGraph.MapDownToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, SubjectBuffer);
// Bail if a snippet span does not map down to exactly one subject buffer span.
if (subjectBufferSpanCollection.Count == 1)
{
subjectBufferSpan = subjectBufferSpanCollection.Single();
return true;
}
subjectBufferSpan = default;
return false;
}
internal bool TryGetSpanOnHigherBuffer(SnapshotSpan snapshotSpan, ITextBuffer targetBuffer, out SnapshotSpan span)
{
var spanCollection = TextView.BufferGraph.MapUpToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, targetBuffer);
// Bail if a snippet span does not map up to exactly one span.
if (spanCollection.Count == 1)
{
span = spanCollection.Single();
return true;
}
span = default;
return false;
}
private sealed class State
{
/// <summary>
/// The current expansion session.
/// </summary>
public IVsExpansionSession? _expansionSession;
/// <summary>
/// The symbol name of the method that we have invoked insert full method call on; or <see langword="null"/>
/// if there is no active snippet session or the active session is a regular snippets session.
/// </summary>
public string? _methodNameForInsertFullMethodCall;
/// <summary>
/// The current symbol presented in an Argument Provider snippet session. This may be null if Signature Help
/// has not yet provided a symbol to show.
/// </summary>
public IMethodSymbol? _method;
/// <summary>
/// Maps from parameter name to current argument value. When this dictionary does not contain a mapping for
/// a parameter, it means no argument has been provided yet by an ArgumentProvider or the user for a
/// parameter with this name. This map is cleared at the final end of an argument provider snippet session.
/// </summary>
public ImmutableDictionary<string, string> _arguments = ImmutableDictionary.Create<string, string>();
/// <summary>
/// <see langword="true"/> if the current snippet session is a Full Method Call snippet session; otherwise,
/// <see langword="false"/> if there is no current snippet session or if the current snippet session is a normal snippet.
/// </summary>
public bool IsFullMethodCallSnippet => _expansionSession is not null && _methodNameForInsertFullMethodCall is not null;
public void Clear()
{
_expansionSession = null;
_methodNameForInsertFullMethodCall = null;
_method = null;
_arguments = _arguments.Clear();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.SignatureHelp;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.Commanding;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.TextManager.Interop;
using MSXML;
using Roslyn.Utilities;
using CommonFormattingHelpers = Microsoft.CodeAnalysis.Editor.Shared.Utilities.CommonFormattingHelpers;
using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets
{
internal abstract class AbstractSnippetExpansionClient : ForegroundThreadAffinitizedObject, IVsExpansionClient
{
/// <summary>
/// The name of a snippet field created for caret placement in Full Method Call snippet sessions when the
/// invocation has no parameters.
/// </summary>
private const string PlaceholderSnippetField = "placeholder";
/// <summary>
/// A generated random string which is used to identify argument completion snippets from other snippets.
/// </summary>
private static readonly string s_fullMethodCallDescriptionSentinel = Guid.NewGuid().ToString("N");
private readonly SignatureHelpControllerProvider _signatureHelpControllerProvider;
private readonly IEditorCommandHandlerServiceFactory _editorCommandHandlerServiceFactory;
protected readonly IVsEditorAdaptersFactoryService EditorAdaptersFactoryService;
protected readonly Guid LanguageServiceGuid;
protected readonly ITextView TextView;
protected readonly ITextBuffer SubjectBuffer;
private readonly ImmutableArray<Lazy<ArgumentProvider, OrderableLanguageMetadata>> _allArgumentProviders;
private ImmutableArray<ArgumentProvider> _argumentProviders;
private bool _indentCaretOnCommit;
private int _indentDepth;
private bool _earlyEndExpansionHappened;
/// <summary>
/// Set to <see langword="true"/> when the snippet client registers an event listener for
/// <see cref="Controller.ModelUpdated"/>.
/// </summary>
/// <remarks>
/// This field should only be used from the main thread.
/// </remarks>
private bool _registeredForSignatureHelpEvents;
// Writes to this state only occur on the main thread.
private readonly State _state = new();
public AbstractSnippetExpansionClient(
IThreadingContext threadingContext,
Guid languageServiceGuid,
ITextView textView,
ITextBuffer subjectBuffer,
SignatureHelpControllerProvider signatureHelpControllerProvider,
IEditorCommandHandlerServiceFactory editorCommandHandlerServiceFactory,
IVsEditorAdaptersFactoryService editorAdaptersFactoryService,
ImmutableArray<Lazy<ArgumentProvider, OrderableLanguageMetadata>> argumentProviders)
: base(threadingContext)
{
this.LanguageServiceGuid = languageServiceGuid;
this.TextView = textView;
this.SubjectBuffer = subjectBuffer;
_signatureHelpControllerProvider = signatureHelpControllerProvider;
_editorCommandHandlerServiceFactory = editorCommandHandlerServiceFactory;
this.EditorAdaptersFactoryService = editorAdaptersFactoryService;
_allArgumentProviders = argumentProviders;
}
/// <inheritdoc cref="State._expansionSession"/>
public IVsExpansionSession? ExpansionSession => _state._expansionSession;
/// <inheritdoc cref="State.IsFullMethodCallSnippet"/>
public bool IsFullMethodCallSnippet => _state.IsFullMethodCallSnippet;
public ImmutableArray<ArgumentProvider> GetArgumentProviders(Workspace workspace)
{
AssertIsForeground();
// TODO: Move this to ArgumentProviderService: https://github.com/dotnet/roslyn/issues/50897
if (_argumentProviders.IsDefault)
{
_argumentProviders = workspace.Services
.SelectMatchingExtensionValues(ExtensionOrderer.Order(_allArgumentProviders), SubjectBuffer.ContentType)
.ToImmutableArray();
}
return _argumentProviders;
}
public abstract int GetExpansionFunction(IXMLDOMNode xmlFunctionNode, string bstrFieldName, out IVsExpansionFunction? pFunc);
protected abstract ITrackingSpan? InsertEmptyCommentAndGetEndPositionTrackingSpan();
internal abstract Document AddImports(Document document, int position, XElement snippetNode, bool placeSystemNamespaceFirst, bool allowInHiddenRegions, CancellationToken cancellationToken);
protected abstract string FallbackDefaultLiteral { get; }
public int FormatSpan(IVsTextLines pBuffer, VsTextSpan[] tsInSurfaceBuffer)
{
AssertIsForeground();
if (ExpansionSession == null)
{
return VSConstants.E_FAIL;
}
// If this is a manually-constructed snippet for a full method call, avoid formatting the snippet since
// doing so will disrupt signature help. Check ExpansionSession instead of '_state.IsFullMethodCallSnippet'
// because '_state._methodNameForInsertFullMethodCall' is not initialized at this point.
if (ExpansionSession.TryGetHeaderNode("Description", out var descriptionNode)
&& descriptionNode?.text == s_fullMethodCallDescriptionSentinel)
{
return VSConstants.S_OK;
}
// Formatting a snippet isn't cancellable.
var cancellationToken = CancellationToken.None;
// At this point, the $selection$ token has been replaced with the selected text and
// declarations have been replaced with their default text. We need to format the
// inserted snippet text while carefully handling $end$ position (where the caret goes
// after Return is pressed). The IVsExpansionSession keeps a tracking point for this
// position but we do the tracking ourselves to properly deal with virtual space. To
// ensure the end location is correct, we take three extra steps:
// 1. Insert an empty comment ("/**/" or "'") at the current $end$ position (prior
// to formatting), and keep a tracking span for the comment.
// 2. After formatting the new snippet text, find and delete the empty multiline
// comment (via the tracking span) and notify the IVsExpansionSession of the new
// $end$ location. If the line then contains only whitespace (due to the formatter
// putting the empty comment on its own line), then delete the white space and
// remember the indentation depth for that line.
// 3. When the snippet is finally completed (via Return), and PositionCaretForEditing()
// is called, check to see if the end location was on a line containing only white
// space in the previous step. If so, and if that line is still empty, then position
// the caret in virtual space.
// This technique ensures that a snippet like "if($condition$) { $end$ }" will end up
// as:
// if ($condition$)
// {
// $end$
// }
if (!TryGetSubjectBufferSpan(tsInSurfaceBuffer[0], out var snippetSpan))
{
return VSConstants.S_OK;
}
// Insert empty comment and track end position
var snippetTrackingSpan = snippetSpan.CreateTrackingSpan(SpanTrackingMode.EdgeInclusive);
var fullSnippetSpan = new VsTextSpan[1];
ExpansionSession.GetSnippetSpan(fullSnippetSpan);
var isFullSnippetFormat =
fullSnippetSpan[0].iStartLine == tsInSurfaceBuffer[0].iStartLine &&
fullSnippetSpan[0].iStartIndex == tsInSurfaceBuffer[0].iStartIndex &&
fullSnippetSpan[0].iEndLine == tsInSurfaceBuffer[0].iEndLine &&
fullSnippetSpan[0].iEndIndex == tsInSurfaceBuffer[0].iEndIndex;
var endPositionTrackingSpan = isFullSnippetFormat ? InsertEmptyCommentAndGetEndPositionTrackingSpan() : null;
var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(SubjectBuffer.CurrentSnapshot, snippetTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot));
SubjectBuffer.CurrentSnapshot.FormatAndApplyToBuffer(formattingSpan, CancellationToken.None);
if (isFullSnippetFormat)
{
CleanUpEndLocation(endPositionTrackingSpan);
// Unfortunately, this is the only place we can safely add references and imports
// specified in the snippet xml. In OnBeforeInsertion we have no guarantee that the
// snippet xml will be available, and changing the buffer during OnAfterInsertion can
// cause the underlying tracking spans to get out of sync.
var currentStartPosition = snippetTrackingSpan.GetStartPoint(SubjectBuffer.CurrentSnapshot).Position;
AddReferencesAndImports(
ExpansionSession, currentStartPosition, cancellationToken);
SetNewEndPosition(endPositionTrackingSpan);
}
return VSConstants.S_OK;
}
private void SetNewEndPosition(ITrackingSpan? endTrackingSpan)
{
RoslynDebug.AssertNotNull(ExpansionSession);
if (SetEndPositionIfNoneSpecified(ExpansionSession))
{
return;
}
if (endTrackingSpan != null)
{
if (!TryGetSpanOnHigherBuffer(
endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot),
TextView.TextBuffer,
out var endSpanInSurfaceBuffer))
{
return;
}
TextView.TextSnapshot.GetLineAndCharacter(endSpanInSurfaceBuffer.Start.Position, out var endLine, out var endChar);
ExpansionSession.SetEndSpan(new VsTextSpan
{
iStartLine = endLine,
iStartIndex = endChar,
iEndLine = endLine,
iEndIndex = endChar
});
}
}
private void CleanUpEndLocation(ITrackingSpan? endTrackingSpan)
{
if (endTrackingSpan != null)
{
// Find the empty comment and remove it...
var endSnapshotSpan = endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot);
SubjectBuffer.Delete(endSnapshotSpan.Span);
// Remove the whitespace before the comment if necessary. If whitespace is removed,
// then remember the indentation depth so we can appropriately position the caret
// in virtual space when the session is ended.
var line = SubjectBuffer.CurrentSnapshot.GetLineFromPosition(endSnapshotSpan.Start.Position);
var lineText = line.GetText();
if (lineText.Trim() == string.Empty)
{
_indentCaretOnCommit = true;
var document = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document != null)
{
var documentOptions = document.GetOptionsAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
_indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, documentOptions.GetOption(FormattingOptions.TabSize));
}
else
{
// If we don't have a document, then just guess the typical default TabSize value.
_indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, tabSize: 4);
}
SubjectBuffer.Delete(new Span(line.Start.Position, line.Length));
_ = SubjectBuffer.CurrentSnapshot.GetSpan(new Span(line.Start.Position, 0));
}
}
}
/// <summary>
/// If there was no $end$ token, place it at the end of the snippet code. Otherwise, it
/// defaults to the beginning of the snippet code.
/// </summary>
private static bool SetEndPositionIfNoneSpecified(IVsExpansionSession pSession)
{
if (!TryGetSnippetNode(pSession, out var snippetNode))
{
return false;
}
var ns = snippetNode.Name.NamespaceName;
var codeNode = snippetNode.Element(XName.Get("Code", ns));
if (codeNode == null)
{
return false;
}
var delimiterAttribute = codeNode.Attribute("Delimiter");
var delimiter = delimiterAttribute != null ? delimiterAttribute.Value : "$";
if (codeNode.Value.IndexOf(string.Format("{0}end{0}", delimiter), StringComparison.OrdinalIgnoreCase) != -1)
{
return false;
}
var snippetSpan = new VsTextSpan[1];
if (pSession.GetSnippetSpan(snippetSpan) != VSConstants.S_OK)
{
return false;
}
var newEndSpan = new VsTextSpan
{
iStartLine = snippetSpan[0].iEndLine,
iStartIndex = snippetSpan[0].iEndIndex,
iEndLine = snippetSpan[0].iEndLine,
iEndIndex = snippetSpan[0].iEndIndex
};
pSession.SetEndSpan(newEndSpan);
return true;
}
protected static bool TryGetSnippetNode(IVsExpansionSession pSession, [NotNullWhen(true)] out XElement? snippetNode)
{
IXMLDOMNode? xmlNode = null;
snippetNode = null;
try
{
// Cast to our own version of IVsExpansionSession so that we can get pNode as an
// IntPtr instead of a via a RCW. This allows us to guarantee that it pNode is
// released before leaving this method. Otherwise, a second invocation of the same
// snippet may cause an AccessViolationException.
var session = (IVsExpansionSessionInternal)pSession;
if (session.GetSnippetNode(null, out var pNode) != VSConstants.S_OK)
{
return false;
}
xmlNode = (IXMLDOMNode)Marshal.GetUniqueObjectForIUnknown(pNode);
snippetNode = XElement.Parse(xmlNode.xml);
return true;
}
finally
{
if (xmlNode != null && Marshal.IsComObject(xmlNode))
{
Marshal.ReleaseComObject(xmlNode);
}
}
}
public int PositionCaretForEditing(IVsTextLines pBuffer, [ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan")] VsTextSpan[] ts)
{
// If the formatted location of the $end$ position (the inserted comment) was on an
// empty line and indented, then we have already removed the white space on that line
// and the navigation location will be at column 0 on a blank line. We must now
// position the caret in virtual space.
pBuffer.GetLengthOfLine(ts[0].iStartLine, out var lineLength);
pBuffer.GetLineText(ts[0].iStartLine, 0, ts[0].iStartLine, lineLength, out var endLineText);
pBuffer.GetPositionOfLine(ts[0].iStartLine, out var endLinePosition);
PositionCaretForEditingInternal(endLineText, endLinePosition);
return VSConstants.S_OK;
}
/// <summary>
/// Internal for testing purposes. All real caret positioning logic takes place here. <see cref="PositionCaretForEditing"/>
/// only extracts the <paramref name="endLineText"/> and <paramref name="endLinePosition"/> from the provided <see cref="IVsTextLines"/>.
/// Tests can call this method directly to avoid producing an IVsTextLines.
/// </summary>
/// <param name="endLineText"></param>
/// <param name="endLinePosition"></param>
internal void PositionCaretForEditingInternal(string endLineText, int endLinePosition)
{
if (_indentCaretOnCommit && endLineText == string.Empty)
{
TextView.TryMoveCaretToAndEnsureVisible(new VirtualSnapshotPoint(TextView.TextSnapshot.GetPoint(endLinePosition), _indentDepth));
}
}
public virtual bool TryHandleTab()
{
if (ExpansionSession != null)
{
// When 'Tab' is pressed in the last field of a normal snippet, the session wraps back around to the
// first field (this is preservation of historical behavior). When 'Tab' is pressed at the end of an
// argument provider snippet, the snippet session is automatically committed (this behavior matches the
// design for Insert Full Method Call intended for multiple IDEs).
var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToNextExpansionField(fCommitIfLast: _state.IsFullMethodCallSnippet ? 1 : 0);
if (!tabbedInsideSnippetField)
{
ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1);
}
return tabbedInsideSnippetField;
}
return false;
}
public virtual bool TryHandleBackTab()
{
if (ExpansionSession != null)
{
var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToPreviousExpansionField();
if (!tabbedInsideSnippetField)
{
ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1);
}
return tabbedInsideSnippetField;
}
return false;
}
public virtual bool TryHandleEscape()
{
if (ExpansionSession != null)
{
ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1);
return true;
}
return false;
}
public virtual bool TryHandleReturn()
{
return CommitSnippet(leaveCaret: false);
}
/// <summary>
/// Commit the active snippet, if any.
/// </summary>
/// <param name="leaveCaret"><see langword="true"/> to leave the caret position unchanged by the call;
/// otherwise, <see langword="false"/> to move the caret to the <c>$end$</c> position of the snippet when the
/// snippet is committed.</param>
/// <returns><see langword="true"/> if the caret may have moved from the call; otherwise,
/// <see langword="false"/> if the caret did not move, or if there was no active snippet session to
/// commit.</returns>
public bool CommitSnippet(bool leaveCaret)
{
if (ExpansionSession != null)
{
if (!leaveCaret)
{
// Only move the caret if the enter was hit within the snippet fields.
var hitWithinField = VSConstants.S_OK == ExpansionSession.GoToNextExpansionField(fCommitIfLast: 0);
leaveCaret = !hitWithinField;
}
ExpansionSession.EndCurrentExpansion(fLeaveCaret: leaveCaret ? 1 : 0);
return !leaveCaret;
}
return false;
}
public virtual bool TryInsertExpansion(int startPositionInSubjectBuffer, int endPositionInSubjectBuffer, CancellationToken cancellationToken)
{
var textViewModel = TextView.TextViewModel;
if (textViewModel == null)
{
Debug.Assert(TextView.IsClosed);
return false;
}
// The expansion itself needs to be created in the data buffer, so map everything up
var triggerSpan = SubjectBuffer.CurrentSnapshot.GetSpan(startPositionInSubjectBuffer, endPositionInSubjectBuffer - startPositionInSubjectBuffer);
if (!TryGetSpanOnHigherBuffer(triggerSpan, textViewModel.DataBuffer, out var dataBufferSpan))
{
return false;
}
var buffer = EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer);
if (buffer is not IVsExpansion expansion)
{
return false;
}
buffer.GetLineIndexOfPosition(dataBufferSpan.Start.Position, out var startLine, out var startIndex);
buffer.GetLineIndexOfPosition(dataBufferSpan.End.Position, out var endLine, out var endIndex);
var textSpan = new VsTextSpan
{
iStartLine = startLine,
iStartIndex = startIndex,
iEndLine = endLine,
iEndIndex = endIndex
};
if (TryInsertArgumentCompletionSnippet(triggerSpan, dataBufferSpan, expansion, textSpan, cancellationToken))
{
Debug.Assert(_state.IsFullMethodCallSnippet);
return true;
}
if (expansion.InsertExpansion(textSpan, textSpan, this, LanguageServiceGuid, out _state._expansionSession) == VSConstants.S_OK)
{
// This expansion is not derived from a symbol, so make sure the state isn't tracking any symbol
// information
Debug.Assert(!_state.IsFullMethodCallSnippet);
return true;
}
return false;
}
private bool TryInsertArgumentCompletionSnippet(SnapshotSpan triggerSpan, SnapshotSpan dataBufferSpan, IVsExpansion expansion, VsTextSpan textSpan, CancellationToken cancellationToken)
{
if (!(SubjectBuffer.GetFeatureOnOffOption(CompletionOptions.EnableArgumentCompletionSnippets) ?? false))
{
// Argument completion snippets are not enabled
return false;
}
var document = SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document is null)
{
// Couldn't identify the current document
return false;
}
var symbols = ThreadingContext.JoinableTaskFactory.Run(() => GetReferencedSymbolsToLeftOfCaretAsync(document, caretPosition: triggerSpan.End, cancellationToken));
var methodSymbols = symbols.OfType<IMethodSymbol>().ToImmutableArray();
if (methodSymbols.Any())
{
// This is the method name as it appears in source text
var methodName = dataBufferSpan.GetText();
var snippet = CreateMethodCallSnippet(methodName, includeMethod: true, ImmutableArray<IParameterSymbol>.Empty, ImmutableDictionary<string, string>.Empty);
var doc = (DOMDocument)new DOMDocumentClass();
if (doc.loadXML(snippet.ToString(SaveOptions.OmitDuplicateNamespaces)))
{
if (expansion.InsertSpecificExpansion(doc, textSpan, this, LanguageServiceGuid, pszRelativePath: null, out _state._expansionSession) == VSConstants.S_OK)
{
Debug.Assert(_state._expansionSession != null);
_state._methodNameForInsertFullMethodCall = methodSymbols.First().Name;
Debug.Assert(_state._method == null);
if (_signatureHelpControllerProvider.GetController(TextView, SubjectBuffer) is { } controller)
{
EnsureRegisteredForModelUpdatedEvents(this, controller);
}
// Trigger signature help after starting the snippet session
//
// TODO: Figure out why ISignatureHelpBroker.TriggerSignatureHelp doesn't work but this does.
// https://github.com/dotnet/roslyn/issues/50036
var editorCommandHandlerService = _editorCommandHandlerServiceFactory.GetService(TextView, SubjectBuffer);
editorCommandHandlerService.Execute((view, buffer) => new InvokeSignatureHelpCommandArgs(view, buffer), nextCommandHandler: null);
return true;
}
}
}
return false;
// Local function
static void EnsureRegisteredForModelUpdatedEvents(AbstractSnippetExpansionClient client, Controller controller)
{
// Access to _registeredForSignatureHelpEvents is synchronized on the main thread
client.ThreadingContext.ThrowIfNotOnUIThread();
if (!client._registeredForSignatureHelpEvents)
{
client._registeredForSignatureHelpEvents = true;
controller.ModelUpdated += client.OnModelUpdated;
client.TextView.Closed += delegate { controller.ModelUpdated -= client.OnModelUpdated; };
}
}
}
/// <summary>
/// Creates a snippet for providing arguments to a call.
/// </summary>
/// <param name="methodName">The name of the method as it should appear in code.</param>
/// <param name="includeMethod">
/// <para><see langword="true"/> to include the method name and invocation parentheses in the resulting snippet;
/// otherwise, <see langword="false"/> if the method name and parentheses are assumed to already exist and the
/// template will only specify the argument placeholders. Since the <c>$end$</c> marker is always considered to
/// lie after the closing <c>)</c> of the invocation, it is only included when this parameter is
/// <see langword="true"/>.</para>
///
/// <para>For example, consider a call to <see cref="int.ToString(IFormatProvider)"/>. If
/// <paramref name="includeMethod"/> is <see langword="true"/>, the resulting snippet text might look like
/// this:</para>
///
/// <code>
/// ToString($provider$)$end$
/// </code>
///
/// <para>If <paramref name="includeMethod"/> is <see langword="false"/>, the resulting snippet text might look
/// like this:</para>
///
/// <code>
/// $provider$
/// </code>
///
/// <para>This parameter supports cycling between overloads of a method for argument completion. Since any text
/// edit that alters the <c>(</c> or <c>)</c> characters will force the Signature Help session to close, we are
/// careful to only update text that lies between these characters.</para>
/// </param>
/// <param name="parameters">The parameters to the method. If the specific target of the invocation is not
/// known, an empty array may be passed to create a template with a placeholder where arguments will eventually
/// go.</param>
private static XDocument CreateMethodCallSnippet(string methodName, bool includeMethod, ImmutableArray<IParameterSymbol> parameters, ImmutableDictionary<string, string> parameterValues)
{
XNamespace snippetNamespace = "http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet";
var template = new StringBuilder();
if (includeMethod)
{
template.Append(methodName).Append('(');
}
var declarations = new List<XElement>();
foreach (var parameter in parameters)
{
if (declarations.Any())
{
template.Append(", ");
}
// Create a snippet field for the argument. The name of the field matches the parameter name, and the
// default value for the field is provided by a call to the internal ArgumentValue snippet function. The
// parameter to the snippet function is a serialized SymbolKey which can be mapped back to the
// IParameterSymbol.
template.Append('$').Append(parameter.Name).Append('$');
declarations.Add(new XElement(
snippetNamespace + "Literal",
new XElement(snippetNamespace + "ID", new XText(parameter.Name)),
new XElement(snippetNamespace + "Default", new XText(parameterValues.GetValueOrDefault(parameter.Name, "")))));
}
if (!declarations.Any())
{
// If the invocation does not have any parameters, include an empty placeholder in the snippet template
// to ensure the caret starts inside the parentheses and can track changes to other overloads (which may
// have parameters).
template.Append($"${PlaceholderSnippetField}$");
declarations.Add(new XElement(
snippetNamespace + "Literal",
new XElement(snippetNamespace + "ID", new XText(PlaceholderSnippetField)),
new XElement(snippetNamespace + "Default", new XText(""))));
}
if (includeMethod)
{
template.Append(')');
}
template.Append("$end$");
// A snippet is manually constructed. Replacement fields are added for each argument, and the field name
// matches the parameter name.
// https://docs.microsoft.com/en-us/visualstudio/ide/code-snippets-schema-reference?view=vs-2019
return new XDocument(
new XDeclaration("1.0", "utf-8", null),
new XElement(
snippetNamespace + "CodeSnippets",
new XElement(
snippetNamespace + "CodeSnippet",
new XAttribute(snippetNamespace + "Format", "1.0.0"),
new XElement(
snippetNamespace + "Header",
new XElement(snippetNamespace + "Title", new XText(methodName)),
new XElement(snippetNamespace + "Description", new XText(s_fullMethodCallDescriptionSentinel))),
new XElement(
snippetNamespace + "Snippet",
new XElement(snippetNamespace + "Declarations", declarations.ToArray()),
new XElement(
snippetNamespace + "Code",
new XAttribute(snippetNamespace + "Language", "csharp"),
new XCData(template.ToString()))))));
}
private void OnModelUpdated(object sender, ModelUpdatedEventsArgs e)
{
AssertIsForeground();
if (e.NewModel is null)
{
// Signature Help was dismissed, but it's possible for a user to bring it back with Ctrl+Shift+Space.
// Leave the snippet session (if any) in its current state to allow it to process either a subsequent
// Signature Help update or the Escape/Enter keys that close the snippet session.
return;
}
if (!_state.IsFullMethodCallSnippet)
{
// Signature Help is showing an updated signature, but either there is no active snippet, or the active
// snippet is not performing argument value completion, so we just ignore it.
return;
}
if (!e.NewModel.UserSelected && _state._method is not null)
{
// This was an implicit signature change which was not triggered by user pressing up/down, and we are
// already showing an initialized argument completion snippet session, so avoid switching sessions.
return;
}
var document = SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document is null)
{
// It's unclear if/how this state would occur, but if it does we would throw an exception trying to
// use it. Just return immediately.
return;
}
// TODO: The following blocks the UI thread without cancellation, but it only occurs when an argument value
// completion session is active, which is behind an experimental feature flag.
// https://github.com/dotnet/roslyn/issues/50634
var compilation = ThreadingContext.JoinableTaskFactory.Run(() => document.Project.GetRequiredCompilationAsync(CancellationToken.None));
var newSymbolKey = (e.NewModel.SelectedItem as AbstractSignatureHelpProvider.SymbolKeySignatureHelpItem)?.SymbolKey ?? default;
var newSymbol = newSymbolKey.Resolve(compilation, cancellationToken: CancellationToken.None).GetAnySymbol();
if (newSymbol is not IMethodSymbol method)
return;
MoveToSpecificMethod(method, CancellationToken.None);
}
private static async Task<ImmutableArray<ISymbol>> GetReferencedSymbolsToLeftOfCaretAsync(
Document document,
SnapshotPoint caretPosition,
CancellationToken cancellationToken)
{
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var token = await semanticModel.SyntaxTree.GetTouchingWordAsync(caretPosition.Position, document.GetRequiredLanguageService<ISyntaxFactsService>(), cancellationToken).ConfigureAwait(false);
if (token.RawKind == 0)
{
// There is no touching word, so return empty immediately
return ImmutableArray<ISymbol>.Empty;
}
var semanticInfo = semanticModel.GetSemanticInfo(token, document.Project.Solution.Workspace, cancellationToken);
return semanticInfo.ReferencedSymbols;
}
/// <summary>
/// Update the current argument value completion session to use a specific method.
/// </summary>
/// <param name="method">The currently-selected method in Signature Help.</param>
/// <param name="cancellationToken">A cancellation token the operation may observe.</param>
public void MoveToSpecificMethod(IMethodSymbol method, CancellationToken cancellationToken)
{
AssertIsForeground();
if (ExpansionSession is null)
{
return;
}
if (SymbolEquivalenceComparer.Instance.Equals(_state._method, method))
{
return;
}
if (_state._methodNameForInsertFullMethodCall != method.Name)
{
// Signature Help is showing a signature that wasn't part of the set this argument value completion
// session was created from. It's unclear how this state should be handled, so we stop processing
// Signature Help updates for the current session.
// TODO: https://github.com/dotnet/roslyn/issues/50636
ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1);
return;
}
// If the first method overload chosen is a zero-parameter method, the snippet we'll create is the same snippet
// as the one did initially. The editor appears to have a bug where inserting a zero-width snippet (when we update the parameters)
// causes the inserted session to immediately dismiss; this works around that issue.
if (_state._method is null && method.Parameters.Length == 0)
{
_state._method = method;
return;
}
var document = SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document is null)
{
// Couldn't identify the current document
ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1);
return;
}
var textViewModel = TextView.TextViewModel;
if (textViewModel == null)
{
Debug.Assert(TextView.IsClosed);
return;
}
var buffer = EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer);
if (buffer is not IVsExpansion expansion)
{
return;
}
// We need to replace the portion of the existing Full Method Call snippet which appears inside parentheses.
// This span starts at the beginning of the first snippet field, and ends at the end of the last snippet
// field. Methods with no arguments still have an empty "placeholder" snippet field representing the initial
// caret position when the snippet is created.
var textSpan = new VsTextSpan[1];
if (ExpansionSession.GetSnippetSpan(textSpan) != VSConstants.S_OK)
{
return;
}
var firstField = _state._method?.Parameters.FirstOrDefault()?.Name ?? PlaceholderSnippetField;
if (ExpansionSession.GetFieldSpan(firstField, textSpan) != VSConstants.S_OK)
{
return;
}
VsTextSpan adjustedTextSpan;
adjustedTextSpan.iStartLine = textSpan[0].iStartLine;
adjustedTextSpan.iStartIndex = textSpan[0].iStartIndex;
var lastField = _state._method?.Parameters.LastOrDefault()?.Name ?? PlaceholderSnippetField;
if (ExpansionSession.GetFieldSpan(lastField, textSpan) != VSConstants.S_OK)
{
return;
}
adjustedTextSpan.iEndLine = textSpan[0].iEndLine;
adjustedTextSpan.iEndIndex = textSpan[0].iEndIndex;
// Track current argument values so input created/updated by a user is not lost when cycling through
// Signature Help overloads:
//
// 1. For each parameter of the method currently presented as a snippet, the value of the argument as
// it appears in code.
// 2. Place the argument values in a map from parameter name to current value.
// 3. (Later) the values in the map can be read to avoid providing new values for equivalent parameters.
var newArguments = _state._arguments;
if (_state._method is null || !_state._method.Parameters.Any())
{
// If we didn't have any previous parameters, then there is only the placeholder in the snippet.
// We don't want to lose what the user has typed there, if they typed something
if (ExpansionSession.GetFieldValue(PlaceholderSnippetField, out var placeholderValue) == VSConstants.S_OK &&
placeholderValue.Length > 0)
{
if (method.Parameters.Any())
{
newArguments = newArguments.SetItem(method.Parameters[0].Name, placeholderValue);
}
else
{
// TODO: if the user is typing before signature help updated the model, and we have no parameters here,
// should we still create a new snippet that has the existing placeholder text?
}
}
}
else if (_state._method is not null)
{
foreach (var previousParameter in _state._method.Parameters)
{
if (ExpansionSession.GetFieldValue(previousParameter.Name, out var previousValue) == VSConstants.S_OK)
{
newArguments = newArguments.SetItem(previousParameter.Name, previousValue);
}
}
}
// Now compute the new arguments for the new call
var semanticModel = document.GetRequiredSemanticModelAsync(cancellationToken).AsTask().WaitAndGetResult(cancellationToken);
var position = SubjectBuffer.CurrentSnapshot.GetPosition(adjustedTextSpan.iStartLine, adjustedTextSpan.iStartIndex);
foreach (var parameter in method.Parameters)
{
newArguments.TryGetValue(parameter.Name, out var value);
foreach (var provider in GetArgumentProviders(document.Project.Solution.Workspace))
{
var context = new ArgumentContext(provider, semanticModel, position, parameter, value, cancellationToken);
ThreadingContext.JoinableTaskFactory.Run(() => provider.ProvideArgumentAsync(context));
if (context.DefaultValue is not null)
{
value = context.DefaultValue;
break;
}
}
// If we still have no value, fill in the default
if (value is null)
{
value = FallbackDefaultLiteral;
}
newArguments = newArguments.SetItem(parameter.Name, value);
}
var snippet = CreateMethodCallSnippet(method.Name, includeMethod: false, method.Parameters, newArguments);
var doc = (DOMDocument)new DOMDocumentClass();
if (doc.loadXML(snippet.ToString(SaveOptions.OmitDuplicateNamespaces)))
{
if (expansion.InsertSpecificExpansion(doc, adjustedTextSpan, this, LanguageServiceGuid, pszRelativePath: null, out _state._expansionSession) == VSConstants.S_OK)
{
Debug.Assert(_state._expansionSession != null);
_state._methodNameForInsertFullMethodCall = method.Name;
_state._method = method;
_state._arguments = newArguments;
// On this path, the closing parenthesis is not part of the updated snippet, so there is no way for
// the snippet itself to represent the $end$ marker (which falls after the ')' character). Instead,
// we use the internal APIs to manually specify the effective position of the $end$ marker as the
// location in code immediately following the ')'. To do this, we use the knowledge that the snippet
// includes all text up to (but not including) the ')', and move that span one position to the
// right.
if (ExpansionSession.GetEndSpan(textSpan) == VSConstants.S_OK)
{
textSpan[0].iStartIndex++;
textSpan[0].iEndIndex++;
ExpansionSession.SetEndSpan(textSpan[0]);
}
}
}
}
public int EndExpansion()
{
if (ExpansionSession == null)
{
_earlyEndExpansionHappened = true;
}
_state.Clear();
_indentCaretOnCommit = false;
return VSConstants.S_OK;
}
public int IsValidKind(IVsTextLines pBuffer, VsTextSpan[] ts, string bstrKind, out int pfIsValidKind)
{
pfIsValidKind = 1;
return VSConstants.S_OK;
}
public int IsValidType(IVsTextLines pBuffer, VsTextSpan[] ts, string[] rgTypes, int iCountTypes, out int pfIsValidType)
{
pfIsValidType = 1;
return VSConstants.S_OK;
}
public int OnAfterInsertion(IVsExpansionSession pSession)
{
Logger.Log(FunctionId.Snippet_OnAfterInsertion);
return VSConstants.S_OK;
}
public int OnBeforeInsertion(IVsExpansionSession pSession)
{
Logger.Log(FunctionId.Snippet_OnBeforeInsertion);
_state._expansionSession = pSession;
// Symbol information (when necessary) is set by the caller
return VSConstants.S_OK;
}
public int OnItemChosen(string pszTitle, string pszPath)
{
var textViewModel = TextView.TextViewModel;
if (textViewModel == null)
{
Debug.Assert(TextView.IsClosed);
return VSConstants.E_FAIL;
}
int hr;
try
{
VsTextSpan textSpan;
GetCaretPositionInSurfaceBuffer(out textSpan.iStartLine, out textSpan.iStartIndex);
textSpan.iEndLine = textSpan.iStartLine;
textSpan.iEndIndex = textSpan.iStartIndex;
var expansion = (IVsExpansion?)EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer);
Contract.ThrowIfNull(expansion);
_earlyEndExpansionHappened = false;
hr = expansion.InsertNamedExpansion(pszTitle, pszPath, textSpan, this, LanguageServiceGuid, fShowDisambiguationUI: 0, pSession: out _state._expansionSession);
if (_earlyEndExpansionHappened)
{
// EndExpansion was called before InsertNamedExpansion returned, so set
// expansionSession to null to indicate that there is no active expansion
// session. This can occur when the snippet inserted doesn't have any expansion
// fields.
_state._expansionSession = null;
_earlyEndExpansionHappened = false;
}
}
catch (COMException ex)
{
hr = ex.ErrorCode;
}
return hr;
}
private void GetCaretPositionInSurfaceBuffer(out int caretLine, out int caretColumn)
{
var vsTextView = EditorAdaptersFactoryService.GetViewAdapter(TextView);
Contract.ThrowIfNull(vsTextView);
vsTextView.GetCaretPos(out caretLine, out caretColumn);
vsTextView.GetBuffer(out var textLines);
// Handle virtual space (e.g, see Dev10 778675)
textLines.GetLengthOfLine(caretLine, out var lineLength);
if (caretColumn > lineLength)
{
caretColumn = lineLength;
}
}
private void AddReferencesAndImports(
IVsExpansionSession pSession,
int position,
CancellationToken cancellationToken)
{
if (!TryGetSnippetNode(pSession, out var snippetNode))
{
return;
}
var documentWithImports = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (documentWithImports == null)
{
return;
}
var documentOptions = documentWithImports.GetOptionsAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var placeSystemNamespaceFirst = documentOptions.GetOption(GenerationOptions.PlaceSystemNamespaceFirst);
var allowInHiddenRegions = documentWithImports.CanAddImportsInHiddenRegions();
documentWithImports = AddImports(documentWithImports, position, snippetNode, placeSystemNamespaceFirst, allowInHiddenRegions, cancellationToken);
AddReferences(documentWithImports.Project, snippetNode);
}
private void AddReferences(Project originalProject, XElement snippetNode)
{
var referencesNode = snippetNode.Element(XName.Get("References", snippetNode.Name.NamespaceName));
if (referencesNode == null)
{
return;
}
var existingReferenceNames = originalProject.MetadataReferences.Select(r => Path.GetFileNameWithoutExtension(r.Display));
var workspace = originalProject.Solution.Workspace;
var projectId = originalProject.Id;
var assemblyXmlName = XName.Get("Assembly", snippetNode.Name.NamespaceName);
var failedReferenceAdditions = new List<string>();
foreach (var reference in referencesNode.Elements(XName.Get("Reference", snippetNode.Name.NamespaceName)))
{
// Note: URL references are not supported
var assemblyElement = reference.Element(assemblyXmlName);
var assemblyName = assemblyElement != null ? assemblyElement.Value.Trim() : null;
if (RoslynString.IsNullOrEmpty(assemblyName))
{
continue;
}
if (!(workspace is VisualStudioWorkspaceImpl visualStudioWorkspace) ||
!visualStudioWorkspace.TryAddReferenceToProject(projectId, assemblyName))
{
failedReferenceAdditions.Add(assemblyName);
}
}
if (failedReferenceAdditions.Any())
{
var notificationService = workspace.Services.GetRequiredService<INotificationService>();
notificationService.SendNotification(
string.Format(ServicesVSResources.The_following_references_were_not_found_0_Please_locate_and_add_them_manually, Environment.NewLine)
+ Environment.NewLine + Environment.NewLine
+ string.Join(Environment.NewLine, failedReferenceAdditions),
severity: NotificationSeverity.Warning);
}
}
protected static bool TryAddImportsToContainedDocument(Document document, IEnumerable<string> memberImportsNamespaces)
{
if (!(document.Project.Solution.Workspace is VisualStudioWorkspaceImpl vsWorkspace))
{
return false;
}
var containedDocument = vsWorkspace.TryGetContainedDocument(document.Id);
if (containedDocument == null)
{
return false;
}
if (containedDocument.ContainedLanguageHost is IVsContainedLanguageHostInternal containedLanguageHost)
{
foreach (var importClause in memberImportsNamespaces)
{
if (containedLanguageHost.InsertImportsDirective(importClause) != VSConstants.S_OK)
{
return false;
}
}
}
return true;
}
protected static bool TryGetSnippetFunctionInfo(
IXMLDOMNode xmlFunctionNode,
[NotNullWhen(true)] out string? snippetFunctionName,
[NotNullWhen(true)] out string? param)
{
if (xmlFunctionNode.text.IndexOf('(') == -1 ||
xmlFunctionNode.text.IndexOf(')') == -1 ||
xmlFunctionNode.text.IndexOf(')') < xmlFunctionNode.text.IndexOf('('))
{
snippetFunctionName = null;
param = null;
return false;
}
snippetFunctionName = xmlFunctionNode.text.Substring(0, xmlFunctionNode.text.IndexOf('('));
var paramStart = xmlFunctionNode.text.IndexOf('(') + 1;
var paramLength = xmlFunctionNode.text.LastIndexOf(')') - xmlFunctionNode.text.IndexOf('(') - 1;
param = xmlFunctionNode.text.Substring(paramStart, paramLength);
return true;
}
internal bool TryGetSubjectBufferSpan(VsTextSpan surfaceBufferTextSpan, out SnapshotSpan subjectBufferSpan)
{
var snapshotSpan = TextView.TextSnapshot.GetSpan(surfaceBufferTextSpan);
var subjectBufferSpanCollection = TextView.BufferGraph.MapDownToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, SubjectBuffer);
// Bail if a snippet span does not map down to exactly one subject buffer span.
if (subjectBufferSpanCollection.Count == 1)
{
subjectBufferSpan = subjectBufferSpanCollection.Single();
return true;
}
subjectBufferSpan = default;
return false;
}
internal bool TryGetSpanOnHigherBuffer(SnapshotSpan snapshotSpan, ITextBuffer targetBuffer, out SnapshotSpan span)
{
var spanCollection = TextView.BufferGraph.MapUpToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, targetBuffer);
// Bail if a snippet span does not map up to exactly one span.
if (spanCollection.Count == 1)
{
span = spanCollection.Single();
return true;
}
span = default;
return false;
}
private sealed class State
{
/// <summary>
/// The current expansion session.
/// </summary>
public IVsExpansionSession? _expansionSession;
/// <summary>
/// The symbol name of the method that we have invoked insert full method call on; or <see langword="null"/>
/// if there is no active snippet session or the active session is a regular snippets session.
/// </summary>
public string? _methodNameForInsertFullMethodCall;
/// <summary>
/// The current symbol presented in an Argument Provider snippet session. This may be null if Signature Help
/// has not yet provided a symbol to show.
/// </summary>
public IMethodSymbol? _method;
/// <summary>
/// Maps from parameter name to current argument value. When this dictionary does not contain a mapping for
/// a parameter, it means no argument has been provided yet by an ArgumentProvider or the user for a
/// parameter with this name. This map is cleared at the final end of an argument provider snippet session.
/// </summary>
public ImmutableDictionary<string, string> _arguments = ImmutableDictionary.Create<string, string>();
/// <summary>
/// <see langword="true"/> if the current snippet session is a Full Method Call snippet session; otherwise,
/// <see langword="false"/> if there is no current snippet session or if the current snippet session is a normal snippet.
/// </summary>
public bool IsFullMethodCallSnippet => _expansionSession is not null && _methodNameForInsertFullMethodCall is not null;
public void Clear()
{
_expansionSession = null;
_methodNameForInsertFullMethodCall = null;
_method = null;
_arguments = _arguments.Clear();
}
}
}
}
| -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.tr.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="tr" original="../CSharpCodeFixesResources.resx">
<body>
<trans-unit id="Add_this">
<source>Add 'this.'</source>
<target state="translated">this' ekleyin.</target>
<note />
</trans-unit>
<trans-unit id="Convert_typeof_to_nameof">
<source>Convert 'typeof' to 'nameof'</source>
<target state="translated">'Typeof' metodunu 'nameof' metoduna dönüştürün</target>
<note />
</trans-unit>
<trans-unit id="Pass_in_captured_variables_as_arguments">
<source>Pass in captured variables as arguments</source>
<target state="translated">Yakalanan değişkenleri bağımsız değişken olarak geçir</target>
<note />
</trans-unit>
<trans-unit id="Place_colon_on_following_line">
<source>Place colon on following line</source>
<target state="translated">Aşağıdaki satıra iki noktayı yerleştirin</target>
<note />
</trans-unit>
<trans-unit id="Place_statement_on_following_line">
<source>Place statement on following line</source>
<target state="translated">Aşağıdaki satıra ifadeyi yerleştirin</target>
<note />
</trans-unit>
<trans-unit id="Remove_Unnecessary_Usings">
<source>Remove Unnecessary Usings</source>
<target state="translated">Gereksiz Kullanımları Kaldır</target>
<note />
</trans-unit>
<trans-unit id="Remove_blank_lines_between_braces">
<source>Remove blank line between braces</source>
<target state="translated">Küme ayraçları arasındaki boş satırı kaldır</target>
<note />
</trans-unit>
<trans-unit id="Remove_unreachable_code">
<source>Remove unreachable code</source>
<target state="translated">Erişilemeyen kodları kaldır</target>
<note />
</trans-unit>
<trans-unit id="Warning_colon_Adding_parameters_to_local_function_declaration_may_produce_invalid_code">
<source>Warning: Adding parameters to local function declaration may produce invalid code.</source>
<target state="translated">Uyarı: Yerel işlev bildirimine parametre eklendiğinde geçersiz kod üretilebilir.</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="tr" original="../CSharpCodeFixesResources.resx">
<body>
<trans-unit id="Add_this">
<source>Add 'this.'</source>
<target state="translated">this' ekleyin.</target>
<note />
</trans-unit>
<trans-unit id="Convert_typeof_to_nameof">
<source>Convert 'typeof' to 'nameof'</source>
<target state="translated">'Typeof' metodunu 'nameof' metoduna dönüştürün</target>
<note />
</trans-unit>
<trans-unit id="Pass_in_captured_variables_as_arguments">
<source>Pass in captured variables as arguments</source>
<target state="translated">Yakalanan değişkenleri bağımsız değişken olarak geçir</target>
<note />
</trans-unit>
<trans-unit id="Place_colon_on_following_line">
<source>Place colon on following line</source>
<target state="translated">Aşağıdaki satıra iki noktayı yerleştirin</target>
<note />
</trans-unit>
<trans-unit id="Place_statement_on_following_line">
<source>Place statement on following line</source>
<target state="translated">Aşağıdaki satıra ifadeyi yerleştirin</target>
<note />
</trans-unit>
<trans-unit id="Remove_Unnecessary_Usings">
<source>Remove Unnecessary Usings</source>
<target state="translated">Gereksiz Kullanımları Kaldır</target>
<note />
</trans-unit>
<trans-unit id="Remove_blank_lines_between_braces">
<source>Remove blank line between braces</source>
<target state="translated">Küme ayraçları arasındaki boş satırı kaldır</target>
<note />
</trans-unit>
<trans-unit id="Remove_unreachable_code">
<source>Remove unreachable code</source>
<target state="translated">Erişilemeyen kodları kaldır</target>
<note />
</trans-unit>
<trans-unit id="Warning_colon_Adding_parameters_to_local_function_declaration_may_produce_invalid_code">
<source>Warning: Adding parameters to local function declaration may produce invalid code.</source>
<target state="translated">Uyarı: Yerel işlev bildirimine parametre eklendiğinde geçersiz kod üretilebilir.</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/EditorFeatures/Core/Shared/Extensions/TextChangeExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions
{
internal static class TextChangeExtensions
{
public static TextChangeRange ToTextChangeRange(this ITextChange textChange)
=> new(textChange.OldSpan.ToTextSpan(), textChange.NewLength);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions
{
internal static class TextChangeExtensions
{
public static TextChangeRange ToTextChangeRange(this ITextChange textChange)
=> new(textChange.OldSpan.ToTextSpan(), textChange.NewLength);
}
}
| -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/EditorFeatures/CSharpTest2/Recommendations/StructKeywordRecommenderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class StructKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClass_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalStatement_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalVariableDeclaration_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEmptyStatement()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCompilationUnit()
{
await VerifyKeywordAsync(
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterExtern()
{
await VerifyKeywordAsync(
@"extern alias Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterUsing()
{
await VerifyKeywordAsync(
@"using Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalUsing()
{
await VerifyKeywordAsync(
@"global using Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNamespace()
{
await VerifyKeywordAsync(
@"namespace N {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterFileScopedNamespace()
{
await VerifyKeywordAsync(
@"namespace N;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterTypeDeclaration()
{
await VerifyKeywordAsync(
@"class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateDeclaration()
{
await VerifyKeywordAsync(
@"delegate void Goo();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethod()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterField()
{
await VerifyKeywordAsync(
@"class C {
int i;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProperty()
{
await VerifyKeywordAsync(
@"class C {
int i { get; }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeUsing()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular,
@"$$
using Goo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeGlobalUsing()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular,
@"$$
global using Goo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterReadonly()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"readonly $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRef()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefReadonly()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"ref readonly $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPublicRefReadonly()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"public ref readonly $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterReadonlyRef()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"readonly ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterInternalReadonlyRef()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"internal readonly ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterReadonlyInMethod()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular,
@"class C { void M() { readonly $$ } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterRefInMethod()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular,
@"class C { void M() { ref $$ } }");
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeUsing_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$
using Goo;");
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeGlobalUsing_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$
global using Goo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAssemblyAttribute()
{
await VerifyKeywordAsync(
@"[assembly: goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRootAttribute()
{
await VerifyKeywordAsync(
@"[goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAttribute()
{
await VerifyKeywordAsync(
@"class C {
[goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideStruct()
{
await VerifyKeywordAsync(
@"struct S {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideInterface()
{
await VerifyKeywordAsync(@"interface I {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideClass()
{
await VerifyKeywordAsync(
@"class C {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPartial()
{
await VerifyKeywordAsync(
@"partial $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAbstract()
=> await VerifyAbsenceAsync(@"abstract $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterInternal()
{
await VerifyKeywordAsync(
@"internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPublic()
{
await VerifyKeywordAsync(
@"public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPrivate()
{
await VerifyKeywordAsync(
@"private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProtected()
{
await VerifyKeywordAsync(
@"protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRecord()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"record $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterSealed()
=> await VerifyAbsenceAsync(@"sealed $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterStatic()
=> await VerifyAbsenceAsync(@"static $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAbstractPublic()
=> await VerifyAbsenceAsync(@"abstract public $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterStruct()
=> await VerifyAbsenceAsync(@"struct $$");
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class StructKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClass_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalStatement_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalVariableDeclaration_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEmptyStatement()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCompilationUnit()
{
await VerifyKeywordAsync(
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterExtern()
{
await VerifyKeywordAsync(
@"extern alias Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterUsing()
{
await VerifyKeywordAsync(
@"using Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalUsing()
{
await VerifyKeywordAsync(
@"global using Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNamespace()
{
await VerifyKeywordAsync(
@"namespace N {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterFileScopedNamespace()
{
await VerifyKeywordAsync(
@"namespace N;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterTypeDeclaration()
{
await VerifyKeywordAsync(
@"class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateDeclaration()
{
await VerifyKeywordAsync(
@"delegate void Goo();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethod()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterField()
{
await VerifyKeywordAsync(
@"class C {
int i;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProperty()
{
await VerifyKeywordAsync(
@"class C {
int i { get; }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeUsing()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular,
@"$$
using Goo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeGlobalUsing()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular,
@"$$
global using Goo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterReadonly()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"readonly $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRef()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefReadonly()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"ref readonly $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPublicRefReadonly()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"public ref readonly $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterReadonlyRef()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"readonly ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterInternalReadonlyRef()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"internal readonly ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterReadonlyInMethod()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular,
@"class C { void M() { readonly $$ } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterRefInMethod()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular,
@"class C { void M() { ref $$ } }");
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeUsing_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$
using Goo;");
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeGlobalUsing_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$
global using Goo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAssemblyAttribute()
{
await VerifyKeywordAsync(
@"[assembly: goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRootAttribute()
{
await VerifyKeywordAsync(
@"[goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAttribute()
{
await VerifyKeywordAsync(
@"class C {
[goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideStruct()
{
await VerifyKeywordAsync(
@"struct S {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideInterface()
{
await VerifyKeywordAsync(@"interface I {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideClass()
{
await VerifyKeywordAsync(
@"class C {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPartial()
{
await VerifyKeywordAsync(
@"partial $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAbstract()
=> await VerifyAbsenceAsync(@"abstract $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterInternal()
{
await VerifyKeywordAsync(
@"internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPublic()
{
await VerifyKeywordAsync(
@"public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPrivate()
{
await VerifyKeywordAsync(
@"private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProtected()
{
await VerifyKeywordAsync(
@"protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRecord()
{
await VerifyKeywordAsync(SourceCodeKind.Regular,
@"record $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterSealed()
=> await VerifyAbsenceAsync(@"sealed $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterStatic()
=> await VerifyAbsenceAsync(@"static $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAbstractPublic()
=> await VerifyAbsenceAsync(@"abstract public $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterStruct()
=> await VerifyAbsenceAsync(@"struct $$");
}
}
| -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.NonCascadingSymbolSet.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal partial class FindReferencesSearchEngine
{
/// <summary>
/// A symbol set used when the find refs caller does not want cascading. This is a trivial impl that basically
/// just wraps the initial symbol provided and doesn't need to do anything beyond that.
/// </summary>
private sealed class NonCascadingSymbolSet : SymbolSet
{
private readonly ImmutableArray<ISymbol> _symbols;
public NonCascadingSymbolSet(FindReferencesSearchEngine engine, ISymbol searchSymbol) : base(engine)
{
_symbols = ImmutableArray.Create(searchSymbol);
}
public override ImmutableArray<ISymbol> GetAllSymbols()
=> _symbols;
public override Task InheritanceCascadeAsync(Project project, CancellationToken cancellationToken)
{
// Nothing to do here. We're in a non-cascading scenario, so even as we encounter a new project we
// don't have to figure out what new symbols may be found.
return Task.CompletedTask;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal partial class FindReferencesSearchEngine
{
/// <summary>
/// A symbol set used when the find refs caller does not want cascading. This is a trivial impl that basically
/// just wraps the initial symbol provided and doesn't need to do anything beyond that.
/// </summary>
private sealed class NonCascadingSymbolSet : SymbolSet
{
private readonly ImmutableArray<ISymbol> _symbols;
public NonCascadingSymbolSet(FindReferencesSearchEngine engine, ISymbol searchSymbol) : base(engine)
{
_symbols = ImmutableArray.Create(searchSymbol);
}
public override ImmutableArray<ISymbol> GetAllSymbols()
=> _symbols;
public override Task InheritanceCascadeAsync(Project project, CancellationToken cancellationToken)
{
// Nothing to do here. We're in a non-cascading scenario, so even as we encounter a new project we
// don't have to figure out what new symbols may be found.
return Task.CompletedTask;
}
}
}
}
| -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenOverridingAndHiding.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class CodeGenOverridingAndHiding
Inherits BasicTestBase
<WorkItem(540852, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540852")>
<Fact>
Public Sub TestSimpleMustOverride()
Dim source =
<compilation>
<file name="a.vb">
Imports System
MustInherit Class A
Public MustOverride Function F As Integer()
Protected MustOverride Sub Meth()
Protected Friend MustOverride Property Prop As Integer()
End Class
</file>
</compilation>
Dim verifier = CompileAndVerify(source, expectedSignatures:=
{
Signature("A", "F", ".method public newslot strict abstract virtual instance System.Int32[] F() cil managed"),
Signature("A", "Meth", ".method family newslot strict abstract virtual instance System.Void Meth() cil managed"),
Signature("A", "get_Prop", ".method famorassem newslot strict specialname abstract virtual instance System.Int32[] get_Prop() cil managed"),
Signature("A", "set_Prop", ".method famorassem newslot strict specialname abstract virtual instance System.Void set_Prop(System.Int32[] Value) cil managed"),
Signature("A", "Prop", ".property readwrite System.Int32[] Prop")
})
End Sub
<WorkItem(528311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528311")>
<WorkItem(540865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540865")>
<Fact>
Public Sub TestSimpleOverrides()
Dim source =
<compilation>
<file name="a.vb">
MustInherit Class A
Public MustOverride Sub F()
End Class
Class B
Inherits A
Public Overrides Sub F()
End Sub
End Class
</file>
</compilation>
Dim verifier = CompileAndVerify(source, expectedSignatures:=
{
Signature("B", "F", ".method public hidebysig strict virtual instance System.Void F() cil managed"),
Signature("A", "F", ".method public newslot strict abstract virtual instance System.Void F() cil managed")
})
verifier.VerifyDiagnostics()
End Sub
<WorkItem(540884, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540884")>
<Fact>
Public Sub TestMustOverrideOverrides()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Class A
Public Overridable Sub G()
Console.WriteLine("A.G")
End Sub
End Class
MustInherit Class B
Inherits A
Public MustOverride Overrides Sub G()
End Class
</file>
</compilation>
Dim verifier = CompileAndVerify(source, expectedSignatures:=
{
Signature("B", "G", ".method public hidebysig strict abstract virtual instance System.Void G() cil managed"),
Signature("A", "G", ".method public newslot strict virtual instance System.Void G() cil managed")
})
verifier.VerifyDiagnostics()
End Sub
<WorkItem(542576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542576")>
<Fact>
Public Sub TestDontMergePartials()
Dim source =
<compilation>
<file name="a.vb">
MustInherit Class A
MustOverride Function F() As Integer
Overridable Sub G()
End Sub
End Class
Partial Class B
Inherits A
'This would normally be an error if this partial part for class B
'had the NotInheritable modifier (i.e. NotOverridable and NotInheritable
'can't be combined). Strangely Dev10 doesn't report the same error
'when the NotInheritable modifier appears on a different partial part.
NotOverridable Overrides Function F() As Integer
Return 1
End Function
'This would normally be an error if this partial part for class B
'had the NotInheritable modifier (i.e. NotOverridable and NotInheritable
'can't be combined). Strangely Dev10 doesn't report the same error
'when the NotInheritable modifier appears on a different partial part.
NotOverridable Overrides Sub G()
End Sub
End Class</file>
<file name="b.vb">
NotInheritable Class B
Inherits A
End Class
</file>
</compilation>
CompileAndVerify(source, expectedSignatures:=
{
Signature("B", "F", ".method public hidebysig strict virtual final instance System.Int32 F() cil managed"),
Signature("A", "F", ".method public newslot strict abstract virtual instance System.Int32 F() cil managed"),
Signature("B", "G", ".method public hidebysig strict virtual final instance System.Void G() cil managed"),
Signature("A", "G", ".method public newslot strict virtual instance System.Void G() cil managed")
}).
VerifyDiagnostics()
End Sub
<WorkItem(543751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543751")>
<Fact(), WorkItem(543751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543751")>
Public Sub TestMustOverloadWithOptional()
CompileAndVerify(
<compilation>
<file name="a.vb">
Module Program
Const str As String = ""
Sub Main(args As String())
End Sub
Function fun()
test(temp:=Nothing, x:=1)
Return Nothing
End Function
Function test(ByRef x As Integer, temp As Object, Optional y As String = str, Optional z As Object = Nothing)
Return Nothing
End Function
Function test(ByRef x As Integer, Optional temp As Object = Nothing)
Return Nothing
End Function
End Module
</file>
</compilation>).
VerifyDiagnostics()
End Sub
<Fact()>
Public Sub CrossLanguageCase1()
'Note: For this case Dev10 produces errors (see below) while Roslyn works fine. We believe this
'is a bug in Dev10 that we fixed in Roslyn - the change is non-breaking.
Dim vb1Compilation = CreateVisualBasicCompilation("VB1",
<![CDATA[Public MustInherit Class C1
MustOverride Sub goo()
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim vb1Verifier = CompileAndVerify(vb1Compilation)
vb1Verifier.VerifyDiagnostics()
Dim cs1Compilation = CreateCSharpCompilation("CS1",
<![CDATA[using System;
public abstract class C2 : C1
{
new internal virtual void goo()
{
Console.WriteLine("C2");
}
}]]>,
compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation})
cs1Compilation.VerifyDiagnostics()
Dim vb2Compilation = CreateVisualBasicCompilation("VB2",
<![CDATA[Imports System
Public Class C3 : Inherits C2
Public Overrides Sub goo
Console.WriteLine("C3")
End Sub
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation, cs1Compilation})
Dim vb2Verifier = CompileAndVerify(vb2Compilation)
vb2Verifier.VerifyDiagnostics()
'Dev10 reports an error for the below compilation - Roslyn on the other hand allows this code to compile without errors.
'VB3.vb(2) : error BC30610: Class 'C4' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s):
'C1 : Public MustOverride Sub goo().
'Public Class C4 : Inherits C3
' ~~
Dim vb3Compilation = CreateVisualBasicCompilation("VB3",
<![CDATA[
Imports System
Public Class C4 : Inherits C3
End Class
Public Class C5 : Inherits C2
' Corresponding case in C# results in PEVerify errors - See test 'CrossLanguageCase1' in CodeGenOverridingAndHiding.cs
Public Overrides Sub goo()
Console.WriteLine("C5")
End Sub
End Class
Public Module Program
Sub Main()
Dim x As C1 = New C4
x.goo()
Dim y As C2 = New C5
y.Goo()
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={vb1Compilation, cs1Compilation, vb2Compilation})
Dim vb3Verifier = CompileAndVerify(vb3Compilation,
expectedOutput:=<![CDATA[C3
C5]]>)
vb3Verifier.VerifyDiagnostics()
End Sub
<Fact()>
Public Sub CrossLanguageCase2()
'Note: For this case Dev10 produces errors (see below) while Roslyn works fine. We believe this
'is a bug in Dev10 that we fixed in Roslyn - the change is non-breaking.
Dim vb1Compilation = CreateVisualBasicCompilation("VB1",
<![CDATA[Public MustInherit Class C1
MustOverride Sub goo()
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim vb1Verifier = CompileAndVerify(vb1Compilation)
vb1Verifier.VerifyDiagnostics()
Dim cs1Compilation = CreateCSharpCompilation("CS1",
<![CDATA[using System;
[assembly:System.Runtime.CompilerServices.InternalsVisibleTo("VB3")]
public abstract class C2 : C1
{
new internal virtual void goo()
{
Console.WriteLine("C2");
}
}]]>,
compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation})
cs1Compilation.VerifyDiagnostics()
Dim vb2Compilation = CreateVisualBasicCompilation("VB2",
<![CDATA[Imports System
Public Class C3 : Inherits C2
Public Overrides Sub goo
Console.WriteLine("C3")
End Sub
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation, cs1Compilation})
Dim vb2Verifier = CompileAndVerify(vb2Compilation)
vb2Verifier.VerifyDiagnostics()
'Dev10 reports an error for the below compilation - Roslyn on the other hand allows this code to compile without errors.
'VB3.vb(2) : error BC30610: Class 'C4' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s):
'C1 : Public MustOverride Sub goo().
'Public Class C4 : Inherits C3
' ~~
Dim vb3Compilation = CreateVisualBasicCompilation("VB3",
<![CDATA[Imports System
Public Class C4 : Inherits C3
Public Overrides Sub goo
Console.WriteLine("C4")
End Sub
End Class
Public Module Program
Sub Main()
Dim x As C1 = New C4
x.goo
Dim y As C2 = New C4
y.goo
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={vb1Compilation, cs1Compilation, vb2Compilation})
Dim vb3Verifier = CompileAndVerify(vb3Compilation,
expectedOutput:=<![CDATA[C4
C2]]>)
vb3Verifier.VerifyDiagnostics()
End Sub
<Fact()>
Public Sub CrossLanguageCase3()
'Note: Dev10 and Roslyn produce identical errors for this case.
Dim vb1Compilation = CreateVisualBasicCompilation("VB1",
<![CDATA[Public MustInherit Class C1
MustOverride Sub goo()
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim vb1Verifier = CompileAndVerify(vb1Compilation)
vb1Verifier.VerifyDiagnostics()
Dim cs1Compilation = CreateCSharpCompilation("CS1",
<![CDATA[[assembly:System.Runtime.CompilerServices.InternalsVisibleTo("VB3")]
public abstract class C2 : C1
{
new internal virtual void goo()
{
}
}]]>,
compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation})
cs1Compilation.VerifyDiagnostics()
Dim vb2Compilation = CreateVisualBasicCompilation("VB2",
<![CDATA[Public Class C3 : Inherits C2
Public Overrides Sub goo
End Sub
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation, cs1Compilation})
Dim vb2Verifier = CompileAndVerify(vb2Compilation)
vb2Verifier.VerifyDiagnostics()
Dim vb3Compilation = CreateVisualBasicCompilation("VB3",
<![CDATA[MustInherit Public Class C4 : Inherits C3
Public Overrides Sub goo
End Sub
End Class
Public Class C5 : Inherits C2
Public Overrides Sub goo()
End Sub
End Class
Public Class C6 : Inherits C2
Friend Overrides Sub goo()
End Sub
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation, cs1Compilation, vb2Compilation})
vb3Compilation.AssertTheseDiagnostics(<expected>
BC30610: Class 'C5' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s):
C1: Public MustOverride Sub goo().
Public Class C5 : Inherits C2
~~
BC30266: 'Public Overrides Sub goo()' cannot override 'Friend Overridable Overloads Sub goo()' because they have different access levels.
Public Overrides Sub goo()
~~~
BC30610: Class 'C6' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s):
C1: Public MustOverride Sub goo().
Public Class C6 : Inherits C2
~~
</expected>)
End Sub
<WorkItem(543794, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543794")>
<Fact()>
Public Sub CrossLanguageTest4()
Dim vb1Compilation = CreateVisualBasicCompilation("VB1",
<![CDATA[Public MustInherit Class C1
MustOverride Sub goo()
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim vb1Verifier = CompileAndVerify(vb1Compilation)
vb1Verifier.VerifyDiagnostics()
Dim cs1Compilation = CreateCSharpCompilation("CS1",
<![CDATA[[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("VB2")]
public abstract class C2 : C1
{
new internal virtual void goo()
{
}
}]]>,
compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation})
cs1Compilation.VerifyDiagnostics()
Dim vb2Compilation = CreateVisualBasicCompilation("VB2",
<![CDATA[MustInherit Public Class C3 : Inherits C2
Friend Overrides Sub goo()
End Sub
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation, cs1Compilation})
CompileAndVerify(vb2Compilation).VerifyDiagnostics()
End Sub
<Fact(), WorkItem(544536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544536")>
Public Sub VBOverrideCsharpOptional()
Dim cs1Compilation = CreateCSharpCompilation("CS1",
<![CDATA[
public abstract class Trivia
{
public abstract void Format(int i, int j = 2);
}
public class Whitespace : Trivia
{
public override void Format(int i, int j) {}
}
]]>,
compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
cs1Compilation.VerifyDiagnostics()
Dim vb2Compilation = CreateVisualBasicCompilation("VB2",
<![CDATA[
MustInherit Class AbstractLineBreakTrivia
Inherits Whitespace
Public Overrides Sub Format(i As Integer, j As Integer)
End Sub
End Class
Class AfterStatementTerminatorTokenTrivia
Inherits AbstractLineBreakTrivia
End Class
]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={cs1Compilation})
CompileAndVerify(vb2Compilation).VerifyDiagnostics()
End Sub
<Fact()>
Public Sub VBOverrideCsharpOptional2()
Dim cs1Compilation = CreateCSharpCompilation("CS1",
<![CDATA[
public abstract class Trivia
{
public abstract void Format(int i, int j = 2);
}
public class Whitespace : Trivia
{
public override void Format(int i, int j) {}
}
]]>,
compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
cs1Compilation.VerifyDiagnostics()
Dim vb2Compilation = CreateVisualBasicCompilation("VB2",
<![CDATA[
MustInherit Class AbstractLineBreakTrivia
Inherits Trivia
Public Overrides Sub Format(i As Integer, j As Integer)
End Sub
End Class
Class AfterStatementTerminatorTokenTrivia
Inherits AbstractLineBreakTrivia
End Class
]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={cs1Compilation})
CompilationUtils.AssertTheseDiagnostics(vb2Compilation, <expected>
BC30308: 'Public Overrides Sub Format(i As Integer, j As Integer)' cannot override 'Public MustOverride Overloads Sub Format(i As Integer, [j As Integer = 2])' because they differ by optional parameters.
Public Overrides Sub Format(i As Integer, j As Integer)
~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub OverloadingBasedOnOptionalParameters()
' NOTE: this matches Dev11 implementation, not Dev10
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Class C ' allowed
Shared Sub f(ByVal x As Integer)
End Sub
Shared Sub f(ByVal x As Integer, Optional ByVal y As Integer = 0)
End Sub
Shared Sub f(ByVal x As Integer, Optional ByVal s As String = "")
End Sub
End Class
Class C2 ' allowed
Shared Sub f(ByVal x As Integer, Optional ByVal y As Short = 1)
End Sub
Shared Sub f(ByVal x As Integer, Optional ByVal y As Integer = 1)
End Sub
End Class
Class C3 ' allowed
Shared Sub f()
End Sub
Shared Sub f(Optional ByVal x As Integer = 0)
End Sub
End Class
Class C4 ' allowed`
Shared Sub f(Optional ByVal x As Integer = 0)
End Sub
Shared Sub f(ByVal ParamArray xx As Integer())
End Sub
End Class
Class C5 ' disallowed
Shared Sub f(Optional ByVal x As Integer = 0)
End Sub
Shared Sub f(ByVal x As Integer)
End Sub
End Class
Class C6 ' disallowed
Shared Sub f(Optional ByVal x As Integer() = Nothing)
End Sub
Shared Sub f(ByVal ParamArray xx As Integer())
End Sub
End Class
Class C7 ' disallowed
Shared Sub f(Optional ByVal x As Integer = 0)
End Sub
Shared Sub f(ByRef x As Integer)
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC30300: 'Public Shared Sub f([x As Integer = 0])' and 'Public Shared Sub f(x As Integer)' cannot overload each other because they differ only by optional parameters.
Shared Sub f(Optional ByVal x As Integer = 0)
~
BC30300: 'Public Shared Sub f([x As Integer() = Nothing])' and 'Public Shared Sub f(ParamArray xx As Integer())' cannot overload each other because they differ only by optional parameters.
Shared Sub f(Optional ByVal x As Integer() = Nothing)
~
BC30368: 'Public Shared Sub f([x As Integer() = Nothing])' and 'Public Shared Sub f(ParamArray xx As Integer())' cannot overload each other because they differ only by parameters declared 'ParamArray'.
Shared Sub f(Optional ByVal x As Integer() = Nothing)
~
BC30300: 'Public Shared Sub f([x As Integer = 0])' and 'Public Shared Sub f(ByRef x As Integer)' cannot overload each other because they differ only by optional parameters.
Shared Sub f(Optional ByVal x As Integer = 0)
~
BC30345: 'Public Shared Sub f([x As Integer = 0])' and 'Public Shared Sub f(ByRef x As Integer)' cannot overload each other because they differ only by parameters declared 'ByRef' or 'ByVal'.
Shared Sub f(Optional ByVal x As Integer = 0)
~
</errors>)
End Sub
<Fact()>
Public Sub HidingBySignatureWithOptionalParameters()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Class A
Public Overridable Sub f(Optional x As String = "")
Console.WriteLine("A::f(Optional x As String = """")")
End Sub
End Class
Class B
Inherits A
Public Overridable Overloads Sub f()
Console.WriteLine("B::f()")
End Sub
End Class
Class C
Inherits B
Public Sub f(Optional x As String = "")
Console.WriteLine("C::f(Optional x As String = """")")
End Sub
Public Shared Sub Main()
Dim c As B = New C
c.f()
c.f(1)
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC40005: sub 'f' shadows an overridable method in the base class 'B'. To override the base method, this method must be declared 'Overrides'.
Public Sub f(Optional x As String = "")
~
</errors>)
End Sub
<Fact()>
Public Sub BC31404ForOverloadingBasedOnOptionalParameters()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
MustInherit Class A
Public MustOverride Sub f(Optional x As String = "")
End Class
MustInherit Class B1
Inherits A
Public MustOverride Overloads Sub f(Optional x As String = "")
End Class
MustInherit Class B2
Inherits A
Public MustOverride Overloads Sub f(x As String)
End Class
MustInherit Class B3
Inherits A
Public MustOverride Overloads Sub f(x As Integer, Optional y As String = "")
End Class
MustInherit Class B4
Inherits A
Public MustOverride Overloads Sub f()
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC31404: 'Public MustOverride Overloads Sub f([x As String = ""])' cannot shadow a method declared 'MustOverride'.
Public MustOverride Overloads Sub f(Optional x As String = "")
~
BC31404: 'Public MustOverride Overloads Sub f(x As String)' cannot shadow a method declared 'MustOverride'.
Public MustOverride Overloads Sub f(x As String)
~
</errors>)
End Sub
<Fact()>
Public Sub OverloadingWithNotAccessibleMethods()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Class A
Public Overridable Sub f(Optional x As String = "")
End Sub
End Class
Class B
Inherits A
Public Overridable Overloads Sub f()
End Sub
End Class
Class BB
Inherits A
Private Overloads Sub f()
End Sub
Private Overloads Sub f(Optional x As String = "")
End Sub
End Class
Class C
Inherits BB
Public Overloads Overrides Sub f(Optional x As String = "")
Console.Write("f(Optional x As String = "");")
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
</errors>)
End Sub
<Fact()>
Public Sub AddressOfWithFunctionOrSub1()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class Clazz
Public Shared Sub S(Optional x As Integer = 0)
Console.WriteLine("Sub S")
End Sub
Public Shared Function S() As Boolean
Console.WriteLine("Function S")
Return True
End Function
Public Shared Sub Main()
Dim a As action = AddressOf S
a()
End Sub
End Class
</file>
</compilation>, expectedOutput:="Function S")
End Sub
<Fact, WorkItem(546816, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546816")>
Public Sub OverrideFinalizeWithoutNewslot()
CompileAndVerify(
<compilation>
<file name="a.vb">
Class SelfDestruct
Protected Overrides Sub Finalize()
MyBase.Finalize()
End Sub
End Class
</file>
</compilation>,
{MscorlibRef_v20}).VerifyDiagnostics()
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class CodeGenOverridingAndHiding
Inherits BasicTestBase
<WorkItem(540852, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540852")>
<Fact>
Public Sub TestSimpleMustOverride()
Dim source =
<compilation>
<file name="a.vb">
Imports System
MustInherit Class A
Public MustOverride Function F As Integer()
Protected MustOverride Sub Meth()
Protected Friend MustOverride Property Prop As Integer()
End Class
</file>
</compilation>
Dim verifier = CompileAndVerify(source, expectedSignatures:=
{
Signature("A", "F", ".method public newslot strict abstract virtual instance System.Int32[] F() cil managed"),
Signature("A", "Meth", ".method family newslot strict abstract virtual instance System.Void Meth() cil managed"),
Signature("A", "get_Prop", ".method famorassem newslot strict specialname abstract virtual instance System.Int32[] get_Prop() cil managed"),
Signature("A", "set_Prop", ".method famorassem newslot strict specialname abstract virtual instance System.Void set_Prop(System.Int32[] Value) cil managed"),
Signature("A", "Prop", ".property readwrite System.Int32[] Prop")
})
End Sub
<WorkItem(528311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528311")>
<WorkItem(540865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540865")>
<Fact>
Public Sub TestSimpleOverrides()
Dim source =
<compilation>
<file name="a.vb">
MustInherit Class A
Public MustOverride Sub F()
End Class
Class B
Inherits A
Public Overrides Sub F()
End Sub
End Class
</file>
</compilation>
Dim verifier = CompileAndVerify(source, expectedSignatures:=
{
Signature("B", "F", ".method public hidebysig strict virtual instance System.Void F() cil managed"),
Signature("A", "F", ".method public newslot strict abstract virtual instance System.Void F() cil managed")
})
verifier.VerifyDiagnostics()
End Sub
<WorkItem(540884, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540884")>
<Fact>
Public Sub TestMustOverrideOverrides()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Class A
Public Overridable Sub G()
Console.WriteLine("A.G")
End Sub
End Class
MustInherit Class B
Inherits A
Public MustOverride Overrides Sub G()
End Class
</file>
</compilation>
Dim verifier = CompileAndVerify(source, expectedSignatures:=
{
Signature("B", "G", ".method public hidebysig strict abstract virtual instance System.Void G() cil managed"),
Signature("A", "G", ".method public newslot strict virtual instance System.Void G() cil managed")
})
verifier.VerifyDiagnostics()
End Sub
<WorkItem(542576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542576")>
<Fact>
Public Sub TestDontMergePartials()
Dim source =
<compilation>
<file name="a.vb">
MustInherit Class A
MustOverride Function F() As Integer
Overridable Sub G()
End Sub
End Class
Partial Class B
Inherits A
'This would normally be an error if this partial part for class B
'had the NotInheritable modifier (i.e. NotOverridable and NotInheritable
'can't be combined). Strangely Dev10 doesn't report the same error
'when the NotInheritable modifier appears on a different partial part.
NotOverridable Overrides Function F() As Integer
Return 1
End Function
'This would normally be an error if this partial part for class B
'had the NotInheritable modifier (i.e. NotOverridable and NotInheritable
'can't be combined). Strangely Dev10 doesn't report the same error
'when the NotInheritable modifier appears on a different partial part.
NotOverridable Overrides Sub G()
End Sub
End Class</file>
<file name="b.vb">
NotInheritable Class B
Inherits A
End Class
</file>
</compilation>
CompileAndVerify(source, expectedSignatures:=
{
Signature("B", "F", ".method public hidebysig strict virtual final instance System.Int32 F() cil managed"),
Signature("A", "F", ".method public newslot strict abstract virtual instance System.Int32 F() cil managed"),
Signature("B", "G", ".method public hidebysig strict virtual final instance System.Void G() cil managed"),
Signature("A", "G", ".method public newslot strict virtual instance System.Void G() cil managed")
}).
VerifyDiagnostics()
End Sub
<WorkItem(543751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543751")>
<Fact(), WorkItem(543751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543751")>
Public Sub TestMustOverloadWithOptional()
CompileAndVerify(
<compilation>
<file name="a.vb">
Module Program
Const str As String = ""
Sub Main(args As String())
End Sub
Function fun()
test(temp:=Nothing, x:=1)
Return Nothing
End Function
Function test(ByRef x As Integer, temp As Object, Optional y As String = str, Optional z As Object = Nothing)
Return Nothing
End Function
Function test(ByRef x As Integer, Optional temp As Object = Nothing)
Return Nothing
End Function
End Module
</file>
</compilation>).
VerifyDiagnostics()
End Sub
<Fact()>
Public Sub CrossLanguageCase1()
'Note: For this case Dev10 produces errors (see below) while Roslyn works fine. We believe this
'is a bug in Dev10 that we fixed in Roslyn - the change is non-breaking.
Dim vb1Compilation = CreateVisualBasicCompilation("VB1",
<![CDATA[Public MustInherit Class C1
MustOverride Sub goo()
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim vb1Verifier = CompileAndVerify(vb1Compilation)
vb1Verifier.VerifyDiagnostics()
Dim cs1Compilation = CreateCSharpCompilation("CS1",
<![CDATA[using System;
public abstract class C2 : C1
{
new internal virtual void goo()
{
Console.WriteLine("C2");
}
}]]>,
compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation})
cs1Compilation.VerifyDiagnostics()
Dim vb2Compilation = CreateVisualBasicCompilation("VB2",
<![CDATA[Imports System
Public Class C3 : Inherits C2
Public Overrides Sub goo
Console.WriteLine("C3")
End Sub
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation, cs1Compilation})
Dim vb2Verifier = CompileAndVerify(vb2Compilation)
vb2Verifier.VerifyDiagnostics()
'Dev10 reports an error for the below compilation - Roslyn on the other hand allows this code to compile without errors.
'VB3.vb(2) : error BC30610: Class 'C4' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s):
'C1 : Public MustOverride Sub goo().
'Public Class C4 : Inherits C3
' ~~
Dim vb3Compilation = CreateVisualBasicCompilation("VB3",
<![CDATA[
Imports System
Public Class C4 : Inherits C3
End Class
Public Class C5 : Inherits C2
' Corresponding case in C# results in PEVerify errors - See test 'CrossLanguageCase1' in CodeGenOverridingAndHiding.cs
Public Overrides Sub goo()
Console.WriteLine("C5")
End Sub
End Class
Public Module Program
Sub Main()
Dim x As C1 = New C4
x.goo()
Dim y As C2 = New C5
y.Goo()
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={vb1Compilation, cs1Compilation, vb2Compilation})
Dim vb3Verifier = CompileAndVerify(vb3Compilation,
expectedOutput:=<![CDATA[C3
C5]]>)
vb3Verifier.VerifyDiagnostics()
End Sub
<Fact()>
Public Sub CrossLanguageCase2()
'Note: For this case Dev10 produces errors (see below) while Roslyn works fine. We believe this
'is a bug in Dev10 that we fixed in Roslyn - the change is non-breaking.
Dim vb1Compilation = CreateVisualBasicCompilation("VB1",
<![CDATA[Public MustInherit Class C1
MustOverride Sub goo()
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim vb1Verifier = CompileAndVerify(vb1Compilation)
vb1Verifier.VerifyDiagnostics()
Dim cs1Compilation = CreateCSharpCompilation("CS1",
<![CDATA[using System;
[assembly:System.Runtime.CompilerServices.InternalsVisibleTo("VB3")]
public abstract class C2 : C1
{
new internal virtual void goo()
{
Console.WriteLine("C2");
}
}]]>,
compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation})
cs1Compilation.VerifyDiagnostics()
Dim vb2Compilation = CreateVisualBasicCompilation("VB2",
<![CDATA[Imports System
Public Class C3 : Inherits C2
Public Overrides Sub goo
Console.WriteLine("C3")
End Sub
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation, cs1Compilation})
Dim vb2Verifier = CompileAndVerify(vb2Compilation)
vb2Verifier.VerifyDiagnostics()
'Dev10 reports an error for the below compilation - Roslyn on the other hand allows this code to compile without errors.
'VB3.vb(2) : error BC30610: Class 'C4' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s):
'C1 : Public MustOverride Sub goo().
'Public Class C4 : Inherits C3
' ~~
Dim vb3Compilation = CreateVisualBasicCompilation("VB3",
<![CDATA[Imports System
Public Class C4 : Inherits C3
Public Overrides Sub goo
Console.WriteLine("C4")
End Sub
End Class
Public Module Program
Sub Main()
Dim x As C1 = New C4
x.goo
Dim y As C2 = New C4
y.goo
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={vb1Compilation, cs1Compilation, vb2Compilation})
Dim vb3Verifier = CompileAndVerify(vb3Compilation,
expectedOutput:=<![CDATA[C4
C2]]>)
vb3Verifier.VerifyDiagnostics()
End Sub
<Fact()>
Public Sub CrossLanguageCase3()
'Note: Dev10 and Roslyn produce identical errors for this case.
Dim vb1Compilation = CreateVisualBasicCompilation("VB1",
<![CDATA[Public MustInherit Class C1
MustOverride Sub goo()
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim vb1Verifier = CompileAndVerify(vb1Compilation)
vb1Verifier.VerifyDiagnostics()
Dim cs1Compilation = CreateCSharpCompilation("CS1",
<![CDATA[[assembly:System.Runtime.CompilerServices.InternalsVisibleTo("VB3")]
public abstract class C2 : C1
{
new internal virtual void goo()
{
}
}]]>,
compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation})
cs1Compilation.VerifyDiagnostics()
Dim vb2Compilation = CreateVisualBasicCompilation("VB2",
<![CDATA[Public Class C3 : Inherits C2
Public Overrides Sub goo
End Sub
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation, cs1Compilation})
Dim vb2Verifier = CompileAndVerify(vb2Compilation)
vb2Verifier.VerifyDiagnostics()
Dim vb3Compilation = CreateVisualBasicCompilation("VB3",
<![CDATA[MustInherit Public Class C4 : Inherits C3
Public Overrides Sub goo
End Sub
End Class
Public Class C5 : Inherits C2
Public Overrides Sub goo()
End Sub
End Class
Public Class C6 : Inherits C2
Friend Overrides Sub goo()
End Sub
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation, cs1Compilation, vb2Compilation})
vb3Compilation.AssertTheseDiagnostics(<expected>
BC30610: Class 'C5' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s):
C1: Public MustOverride Sub goo().
Public Class C5 : Inherits C2
~~
BC30266: 'Public Overrides Sub goo()' cannot override 'Friend Overridable Overloads Sub goo()' because they have different access levels.
Public Overrides Sub goo()
~~~
BC30610: Class 'C6' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s):
C1: Public MustOverride Sub goo().
Public Class C6 : Inherits C2
~~
</expected>)
End Sub
<WorkItem(543794, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543794")>
<Fact()>
Public Sub CrossLanguageTest4()
Dim vb1Compilation = CreateVisualBasicCompilation("VB1",
<![CDATA[Public MustInherit Class C1
MustOverride Sub goo()
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim vb1Verifier = CompileAndVerify(vb1Compilation)
vb1Verifier.VerifyDiagnostics()
Dim cs1Compilation = CreateCSharpCompilation("CS1",
<![CDATA[[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("VB2")]
public abstract class C2 : C1
{
new internal virtual void goo()
{
}
}]]>,
compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation})
cs1Compilation.VerifyDiagnostics()
Dim vb2Compilation = CreateVisualBasicCompilation("VB2",
<![CDATA[MustInherit Public Class C3 : Inherits C2
Friend Overrides Sub goo()
End Sub
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={vb1Compilation, cs1Compilation})
CompileAndVerify(vb2Compilation).VerifyDiagnostics()
End Sub
<Fact(), WorkItem(544536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544536")>
Public Sub VBOverrideCsharpOptional()
Dim cs1Compilation = CreateCSharpCompilation("CS1",
<![CDATA[
public abstract class Trivia
{
public abstract void Format(int i, int j = 2);
}
public class Whitespace : Trivia
{
public override void Format(int i, int j) {}
}
]]>,
compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
cs1Compilation.VerifyDiagnostics()
Dim vb2Compilation = CreateVisualBasicCompilation("VB2",
<![CDATA[
MustInherit Class AbstractLineBreakTrivia
Inherits Whitespace
Public Overrides Sub Format(i As Integer, j As Integer)
End Sub
End Class
Class AfterStatementTerminatorTokenTrivia
Inherits AbstractLineBreakTrivia
End Class
]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={cs1Compilation})
CompileAndVerify(vb2Compilation).VerifyDiagnostics()
End Sub
<Fact()>
Public Sub VBOverrideCsharpOptional2()
Dim cs1Compilation = CreateCSharpCompilation("CS1",
<![CDATA[
public abstract class Trivia
{
public abstract void Format(int i, int j = 2);
}
public class Whitespace : Trivia
{
public override void Format(int i, int j) {}
}
]]>,
compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
cs1Compilation.VerifyDiagnostics()
Dim vb2Compilation = CreateVisualBasicCompilation("VB2",
<![CDATA[
MustInherit Class AbstractLineBreakTrivia
Inherits Trivia
Public Overrides Sub Format(i As Integer, j As Integer)
End Sub
End Class
Class AfterStatementTerminatorTokenTrivia
Inherits AbstractLineBreakTrivia
End Class
]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
referencedCompilations:={cs1Compilation})
CompilationUtils.AssertTheseDiagnostics(vb2Compilation, <expected>
BC30308: 'Public Overrides Sub Format(i As Integer, j As Integer)' cannot override 'Public MustOverride Overloads Sub Format(i As Integer, [j As Integer = 2])' because they differ by optional parameters.
Public Overrides Sub Format(i As Integer, j As Integer)
~~~~~~
</expected>)
End Sub
<Fact()>
Public Sub OverloadingBasedOnOptionalParameters()
' NOTE: this matches Dev11 implementation, not Dev10
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Class C ' allowed
Shared Sub f(ByVal x As Integer)
End Sub
Shared Sub f(ByVal x As Integer, Optional ByVal y As Integer = 0)
End Sub
Shared Sub f(ByVal x As Integer, Optional ByVal s As String = "")
End Sub
End Class
Class C2 ' allowed
Shared Sub f(ByVal x As Integer, Optional ByVal y As Short = 1)
End Sub
Shared Sub f(ByVal x As Integer, Optional ByVal y As Integer = 1)
End Sub
End Class
Class C3 ' allowed
Shared Sub f()
End Sub
Shared Sub f(Optional ByVal x As Integer = 0)
End Sub
End Class
Class C4 ' allowed`
Shared Sub f(Optional ByVal x As Integer = 0)
End Sub
Shared Sub f(ByVal ParamArray xx As Integer())
End Sub
End Class
Class C5 ' disallowed
Shared Sub f(Optional ByVal x As Integer = 0)
End Sub
Shared Sub f(ByVal x As Integer)
End Sub
End Class
Class C6 ' disallowed
Shared Sub f(Optional ByVal x As Integer() = Nothing)
End Sub
Shared Sub f(ByVal ParamArray xx As Integer())
End Sub
End Class
Class C7 ' disallowed
Shared Sub f(Optional ByVal x As Integer = 0)
End Sub
Shared Sub f(ByRef x As Integer)
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC30300: 'Public Shared Sub f([x As Integer = 0])' and 'Public Shared Sub f(x As Integer)' cannot overload each other because they differ only by optional parameters.
Shared Sub f(Optional ByVal x As Integer = 0)
~
BC30300: 'Public Shared Sub f([x As Integer() = Nothing])' and 'Public Shared Sub f(ParamArray xx As Integer())' cannot overload each other because they differ only by optional parameters.
Shared Sub f(Optional ByVal x As Integer() = Nothing)
~
BC30368: 'Public Shared Sub f([x As Integer() = Nothing])' and 'Public Shared Sub f(ParamArray xx As Integer())' cannot overload each other because they differ only by parameters declared 'ParamArray'.
Shared Sub f(Optional ByVal x As Integer() = Nothing)
~
BC30300: 'Public Shared Sub f([x As Integer = 0])' and 'Public Shared Sub f(ByRef x As Integer)' cannot overload each other because they differ only by optional parameters.
Shared Sub f(Optional ByVal x As Integer = 0)
~
BC30345: 'Public Shared Sub f([x As Integer = 0])' and 'Public Shared Sub f(ByRef x As Integer)' cannot overload each other because they differ only by parameters declared 'ByRef' or 'ByVal'.
Shared Sub f(Optional ByVal x As Integer = 0)
~
</errors>)
End Sub
<Fact()>
Public Sub HidingBySignatureWithOptionalParameters()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Class A
Public Overridable Sub f(Optional x As String = "")
Console.WriteLine("A::f(Optional x As String = """")")
End Sub
End Class
Class B
Inherits A
Public Overridable Overloads Sub f()
Console.WriteLine("B::f()")
End Sub
End Class
Class C
Inherits B
Public Sub f(Optional x As String = "")
Console.WriteLine("C::f(Optional x As String = """")")
End Sub
Public Shared Sub Main()
Dim c As B = New C
c.f()
c.f(1)
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC40005: sub 'f' shadows an overridable method in the base class 'B'. To override the base method, this method must be declared 'Overrides'.
Public Sub f(Optional x As String = "")
~
</errors>)
End Sub
<Fact()>
Public Sub BC31404ForOverloadingBasedOnOptionalParameters()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
MustInherit Class A
Public MustOverride Sub f(Optional x As String = "")
End Class
MustInherit Class B1
Inherits A
Public MustOverride Overloads Sub f(Optional x As String = "")
End Class
MustInherit Class B2
Inherits A
Public MustOverride Overloads Sub f(x As String)
End Class
MustInherit Class B3
Inherits A
Public MustOverride Overloads Sub f(x As Integer, Optional y As String = "")
End Class
MustInherit Class B4
Inherits A
Public MustOverride Overloads Sub f()
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC31404: 'Public MustOverride Overloads Sub f([x As String = ""])' cannot shadow a method declared 'MustOverride'.
Public MustOverride Overloads Sub f(Optional x As String = "")
~
BC31404: 'Public MustOverride Overloads Sub f(x As String)' cannot shadow a method declared 'MustOverride'.
Public MustOverride Overloads Sub f(x As String)
~
</errors>)
End Sub
<Fact()>
Public Sub OverloadingWithNotAccessibleMethods()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Class A
Public Overridable Sub f(Optional x As String = "")
End Sub
End Class
Class B
Inherits A
Public Overridable Overloads Sub f()
End Sub
End Class
Class BB
Inherits A
Private Overloads Sub f()
End Sub
Private Overloads Sub f(Optional x As String = "")
End Sub
End Class
Class C
Inherits BB
Public Overloads Overrides Sub f(Optional x As String = "")
Console.Write("f(Optional x As String = "");")
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
</errors>)
End Sub
<Fact()>
Public Sub AddressOfWithFunctionOrSub1()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class Clazz
Public Shared Sub S(Optional x As Integer = 0)
Console.WriteLine("Sub S")
End Sub
Public Shared Function S() As Boolean
Console.WriteLine("Function S")
Return True
End Function
Public Shared Sub Main()
Dim a As action = AddressOf S
a()
End Sub
End Class
</file>
</compilation>, expectedOutput:="Function S")
End Sub
<Fact, WorkItem(546816, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546816")>
Public Sub OverrideFinalizeWithoutNewslot()
CompileAndVerify(
<compilation>
<file name="a.vb">
Class SelfDestruct
Protected Overrides Sub Finalize()
MyBase.Finalize()
End Sub
End Class
</file>
</compilation>,
{MscorlibRef_v20}).VerifyDiagnostics()
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Compilers/VisualBasic/Portable/Emit/NamedTypeSymbolAdapter.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Reflection.Metadata
Imports System.Runtime.InteropServices
Imports Microsoft.Cci
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Emit
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
#If DEBUG Then
Partial Friend Class NamedTypeSymbolAdapter
Inherits SymbolAdapter
#Else
Partial Friend Class NamedTypeSymbol
#End If
Implements ITypeReference
Implements ITypeDefinition
Implements INamedTypeReference
Implements INamedTypeDefinition
Implements INamespaceTypeReference
Implements INamespaceTypeDefinition
Implements INestedTypeReference
Implements INestedTypeDefinition
Implements IGenericTypeInstanceReference
Implements ISpecializedNestedTypeReference
Private ReadOnly Property ITypeReferenceIsEnum As Boolean Implements ITypeReference.IsEnum
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
Return AdaptedNamedTypeSymbol.TypeKind = TypeKind.Enum
End Get
End Property
Private ReadOnly Property ITypeReferenceIsValueType As Boolean Implements ITypeReference.IsValueType
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
Return AdaptedNamedTypeSymbol.IsValueType
End Get
End Property
Private Function ITypeReferenceGetResolvedType(context As EmitContext) As ITypeDefinition Implements ITypeReference.GetResolvedType
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder)
Return AsTypeDefinitionImpl(moduleBeingBuilt)
End Function
Private ReadOnly Property ITypeReferenceTypeCode As Cci.PrimitiveTypeCode Implements ITypeReference.TypeCode
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
Debug.Assert(Me.IsDefinitionOrDistinct())
If AdaptedNamedTypeSymbol.IsDefinition Then
Return AdaptedNamedTypeSymbol.PrimitiveTypeCode
End If
Return Cci.PrimitiveTypeCode.NotPrimitive
End Get
End Property
Private ReadOnly Property ITypeReferenceTypeDef As TypeDefinitionHandle Implements ITypeReference.TypeDef
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
Dim peNamedType As PENamedTypeSymbol = TryCast(AdaptedNamedTypeSymbol, PENamedTypeSymbol)
If peNamedType IsNot Nothing Then
Return peNamedType.Handle
End If
Return Nothing
End Get
End Property
Private ReadOnly Property ITypeReferenceAsGenericMethodParameterReference As IGenericMethodParameterReference Implements ITypeReference.AsGenericMethodParameterReference
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
Return Nothing
End Get
End Property
Private ReadOnly Property ITypeReferenceAsGenericTypeInstanceReference As IGenericTypeInstanceReference Implements ITypeReference.AsGenericTypeInstanceReference
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
Debug.Assert(Me.IsDefinitionOrDistinct())
If Not AdaptedNamedTypeSymbol.IsDefinition AndAlso AdaptedNamedTypeSymbol.Arity > 0 AndAlso AdaptedNamedTypeSymbol.ConstructedFrom IsNot AdaptedNamedTypeSymbol Then
Return Me
End If
Return Nothing
End Get
End Property
Private ReadOnly Property ITypeReferenceAsGenericTypeParameterReference As IGenericTypeParameterReference Implements ITypeReference.AsGenericTypeParameterReference
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
Return Nothing
End Get
End Property
Private ReadOnly Property ITypeReferenceAsNamespaceTypeReference As INamespaceTypeReference Implements ITypeReference.AsNamespaceTypeReference
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
Debug.Assert(Me.IsDefinitionOrDistinct())
If AdaptedNamedTypeSymbol.IsDefinition AndAlso AdaptedNamedTypeSymbol.ContainingType Is Nothing Then
Return Me
End If
Return Nothing
End Get
End Property
Private Function ITypeReferenceAsNamespaceTypeDefinition(context As EmitContext) As INamespaceTypeDefinition Implements ITypeReference.AsNamespaceTypeDefinition
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder)
Debug.Assert(Me.IsDefinitionOrDistinct())
If AdaptedNamedTypeSymbol.ContainingType Is Nothing AndAlso AdaptedNamedTypeSymbol.IsDefinition AndAlso AdaptedNamedTypeSymbol.ContainingModule.Equals(moduleBeingBuilt.SourceModule) Then
Return Me
End If
Return Nothing
End Function
Private ReadOnly Property ITypeReferenceAsNestedTypeReference As INestedTypeReference Implements ITypeReference.AsNestedTypeReference
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
If AdaptedNamedTypeSymbol.ContainingType IsNot Nothing Then
Return Me
End If
Return Nothing
End Get
End Property
Private Function ITypeReferenceAsNestedTypeDefinition(context As EmitContext) As INestedTypeDefinition Implements ITypeReference.AsNestedTypeDefinition
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder)
Return AsNestedTypeDefinitionImpl(moduleBeingBuilt)
End Function
Private Function AsNestedTypeDefinitionImpl(moduleBeingBuilt As PEModuleBuilder) As INestedTypeDefinition
Debug.Assert(Me.IsDefinitionOrDistinct())
If AdaptedNamedTypeSymbol.ContainingType IsNot Nothing AndAlso AdaptedNamedTypeSymbol.IsDefinition AndAlso AdaptedNamedTypeSymbol.ContainingModule.Equals(moduleBeingBuilt.SourceModule) Then
Return Me
End If
Return Nothing
End Function
Private ReadOnly Property ITypeReferenceAsSpecializedNestedTypeReference As ISpecializedNestedTypeReference Implements ITypeReference.AsSpecializedNestedTypeReference
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
Debug.Assert(Me.IsDefinitionOrDistinct())
If Not AdaptedNamedTypeSymbol.IsDefinition AndAlso (AdaptedNamedTypeSymbol.Arity = 0 OrElse AdaptedNamedTypeSymbol.ConstructedFrom Is AdaptedNamedTypeSymbol) Then
Debug.Assert(AdaptedNamedTypeSymbol.ContainingType IsNot Nothing AndAlso AdaptedNamedTypeSymbol.ContainingType.IsOrInGenericType())
Return Me
End If
Return Nothing
End Get
End Property
Private Function ITypeReferenceAsTypeDefinition(context As EmitContext) As ITypeDefinition Implements ITypeReference.AsTypeDefinition
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder)
Return AsTypeDefinitionImpl(moduleBeingBuilt)
End Function
Private Function AsTypeDefinitionImpl(moduleBeingBuilt As PEModuleBuilder) As ITypeDefinition
Debug.Assert(Me.IsDefinitionOrDistinct())
' Can't be generic instantiation
' must be declared in the module we are building
If AdaptedNamedTypeSymbol.IsDefinition AndAlso
AdaptedNamedTypeSymbol.ContainingModule.Equals(moduleBeingBuilt.SourceModule) Then
Return Me
End If
Return Nothing
End Function
Friend NotOverridable Overrides Sub IReferenceDispatch(visitor As MetadataVisitor) ' Implements IReference.Dispatch
Debug.Assert(Me.IsDefinitionOrDistinct())
If Not AdaptedNamedTypeSymbol.IsDefinition Then
If AdaptedNamedTypeSymbol.Arity > 0 AndAlso AdaptedNamedTypeSymbol.ConstructedFrom IsNot AdaptedNamedTypeSymbol Then
Debug.Assert((DirectCast(Me, ITypeReference)).AsGenericTypeInstanceReference IsNot Nothing)
visitor.Visit(DirectCast(Me, IGenericTypeInstanceReference))
Else
Debug.Assert((DirectCast(Me, ITypeReference)).AsSpecializedNestedTypeReference IsNot Nothing)
visitor.Visit(DirectCast(Me, ISpecializedNestedTypeReference))
End If
Else
Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(visitor.Context.Module, PEModuleBuilder)
Dim asDefinition As Boolean = (AdaptedNamedTypeSymbol.ContainingModule.Equals(moduleBeingBuilt.SourceModule))
If AdaptedNamedTypeSymbol.ContainingType Is Nothing Then
If asDefinition Then
Debug.Assert((DirectCast(Me, ITypeReference)).AsNamespaceTypeDefinition(visitor.Context) IsNot Nothing)
visitor.Visit(DirectCast(Me, INamespaceTypeDefinition))
Else
Debug.Assert((DirectCast(Me, ITypeReference)).AsNamespaceTypeReference IsNot Nothing)
visitor.Visit(DirectCast(Me, INamespaceTypeReference))
End If
Else
If asDefinition Then
Debug.Assert((DirectCast(Me, ITypeReference)).AsNestedTypeDefinition(visitor.Context) IsNot Nothing)
visitor.Visit(DirectCast(Me, INestedTypeDefinition))
Else
Debug.Assert((DirectCast(Me, ITypeReference)).AsNestedTypeReference IsNot Nothing)
visitor.Visit(DirectCast(Me, INestedTypeReference))
End If
End If
End If
End Sub
Friend NotOverridable Overrides Function IReferenceAsDefinition(context As EmitContext) As IDefinition ' Implements IReference.AsDefinition
Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder)
Return AsTypeDefinitionImpl(moduleBeingBuilt)
End Function
Private ReadOnly Property ITypeDefinitionAlignment As UShort Implements ITypeDefinition.Alignment
Get
CheckDefinitionInvariant()
Dim layout = AdaptedNamedTypeSymbol.Layout
Return CUShort(layout.Alignment)
End Get
End Property
Private Function ITypeDefinitionGetBaseClass(context As EmitContext) As ITypeReference Implements ITypeDefinition.GetBaseClass
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder)
Debug.Assert((DirectCast(Me, ITypeReference)).AsTypeDefinition(context) IsNot Nothing)
Dim baseType As NamedTypeSymbol = AdaptedNamedTypeSymbol.BaseTypeNoUseSiteDiagnostics
If AdaptedNamedTypeSymbol.TypeKind = TypeKind.Submission Then
' although submission semantically doesn't have a base we need to emit one into metadata:
Debug.Assert(baseType Is Nothing)
baseType = AdaptedNamedTypeSymbol.ContainingAssembly.GetSpecialType(Microsoft.CodeAnalysis.SpecialType.System_Object)
End If
If baseType IsNot Nothing Then
Return moduleBeingBuilt.Translate(baseType, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics)
End If
Return Nothing
End Function
Private Iterator Function ITypeDefinitionEvents(context As EmitContext) As IEnumerable(Of IEventDefinition) Implements ITypeDefinition.GetEvents
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
For Each e As EventSymbol In AdaptedNamedTypeSymbol.GetEventsToEmit()
Dim adapter As IEventDefinition = e.GetCciAdapter()
If adapter.ShouldInclude(context) OrElse Not adapter.GetAccessors(context).IsEmpty() Then
Yield adapter
End If
Next
End Function
Private Function ITypeDefinitionGetExplicitImplementationOverrides(context As EmitContext) As IEnumerable(Of Cci.MethodImplementation) Implements ITypeDefinition.GetExplicitImplementationOverrides
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
If AdaptedNamedTypeSymbol.IsInterface Then
Return SpecializedCollections.EmptyEnumerable(Of Cci.MethodImplementation)()
End If
Dim moduleBeingBuilt = DirectCast(context.Module, PEModuleBuilder)
Dim sourceNamedType = TryCast(AdaptedNamedTypeSymbol, SourceNamedTypeSymbol)
Dim explicitImplements As ArrayBuilder(Of Cci.MethodImplementation) = ArrayBuilder(Of Cci.MethodImplementation).GetInstance()
For Each member In AdaptedNamedTypeSymbol.GetMembersForCci()
If member.Kind = SymbolKind.Method Then
AddExplicitImplementations(context, DirectCast(member, MethodSymbol), explicitImplements, sourceNamedType, moduleBeingBuilt)
End If
Next
Dim syntheticMethods = moduleBeingBuilt.GetSynthesizedMethods(AdaptedNamedTypeSymbol)
If syntheticMethods IsNot Nothing Then
For Each synthetic In syntheticMethods
Dim method = TryCast(synthetic.GetInternalSymbol(), MethodSymbol)
If method IsNot Nothing Then
AddExplicitImplementations(context, method, explicitImplements, sourceNamedType, moduleBeingBuilt)
End If
Next
End If
Return explicitImplements.ToImmutableAndFree()
End Function
Private Sub AddExplicitImplementations(context As EmitContext,
implementingMethod As MethodSymbol,
explicitImplements As ArrayBuilder(Of Cci.MethodImplementation),
sourceNamedType As SourceNamedTypeSymbol,
moduleBeingBuilt As PEModuleBuilder)
Debug.Assert(implementingMethod.PartialDefinitionPart Is Nothing) ' must be definition
Debug.Assert(implementingMethod.IsDefinition)
For Each implemented In implementingMethod.ExplicitInterfaceImplementations
' If signature doesn't match, we have created a stub with matching signature that delegates to the implementingMethod.
' The stub will implement the implemented method in metadata.
If MethodSignatureComparer.CustomModifiersAndParametersAndReturnTypeSignatureComparer.Equals(implementingMethod, implemented) Then
explicitImplements.Add(New Cci.MethodImplementation(implementingMethod.GetCciAdapter(),
moduleBeingBuilt.TranslateOverriddenMethodReference(implemented, DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), context.Diagnostics)))
End If
Next
' Explicit overrides needed in some overriding situations.
If OverrideHidingHelper.RequiresExplicitOverride(implementingMethod) Then
explicitImplements.Add(New Cci.MethodImplementation(implementingMethod.GetCciAdapter(),
moduleBeingBuilt.TranslateOverriddenMethodReference(implementingMethod.OverriddenMethod, DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), context.Diagnostics)))
End If
If sourceNamedType IsNot Nothing Then
Dim comMethod As MethodSymbol = sourceNamedType.GetCorrespondingComClassInterfaceMethod(implementingMethod)
If comMethod IsNot Nothing Then
explicitImplements.Add(New Cci.MethodImplementation(implementingMethod.GetCciAdapter(),
moduleBeingBuilt.TranslateOverriddenMethodReference(comMethod, DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), context.Diagnostics)))
End If
End If
End Sub
Private Iterator Function ITypeDefinitionGetFields(context As EmitContext) As IEnumerable(Of IFieldDefinition) Implements ITypeDefinition.GetFields
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition(moduleBeingBuilt) != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
' All fields in a struct should be emitted
Dim isStruct = AdaptedNamedTypeSymbol.IsStructureType()
For Each field In AdaptedNamedTypeSymbol.GetFieldsToEmit()
Dim adapter = field.GetCciAdapter()
If isStruct OrElse adapter.ShouldInclude(context) OrElse IsWithEventsField(field) Then
Yield adapter
End If
Next
Dim syntheticFields = DirectCast(context.Module, PEModuleBuilder).GetSynthesizedFields(AdaptedNamedTypeSymbol)
If syntheticFields IsNot Nothing Then
For Each field In syntheticFields
If isStruct OrElse field.ShouldInclude(context) Then
Yield field
End If
Next
End If
End Function
Private Function IsWithEventsField(field As FieldSymbol) As Boolean
' Backing fields for WithEvents are emitted with AccessedThroughPropertyAttribute
' so need to be emitted even if private
Return TypeOf field Is SourceWithEventsBackingFieldSymbol
End Function
Private ReadOnly Property ITypeDefinitionGenericParameters As IEnumerable(Of IGenericTypeParameter) Implements ITypeDefinition.GenericParameters
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition(moduleBeingBuilt) != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
#If DEBUG Then
Return AdaptedNamedTypeSymbol.TypeParameters.Select(Function(t) t.GetCciAdapter())
#Else
Return AdaptedNamedTypeSymbol.TypeParameters
#End If
End Get
End Property
Private ReadOnly Property ITypeDefinitionGenericParameterCount As UShort Implements ITypeDefinition.GenericParameterCount
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
Return GenericParameterCountImpl
End Get
End Property
Private ReadOnly Property GenericParameterCountImpl As UShort
Get
Return CType(AdaptedNamedTypeSymbol.Arity, UShort)
End Get
End Property
Private ReadOnly Property ITypeDefinitionHasDeclarativeSecurity As Boolean Implements ITypeDefinition.HasDeclarativeSecurity
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
Return AdaptedNamedTypeSymbol.HasDeclarativeSecurity
End Get
End Property
Private Iterator Function ITypeDefinitionInterfaces(context As EmitContext) _
As IEnumerable(Of Cci.TypeReferenceWithAttributes) Implements ITypeDefinition.Interfaces
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
Debug.Assert((DirectCast(Me, ITypeReference)).AsTypeDefinition(context) IsNot Nothing)
Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder)
For Each [interface] In AdaptedNamedTypeSymbol.GetInterfacesToEmit()
Dim typeRef = moduleBeingBuilt.Translate([interface],
syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode),
diagnostics:=context.Diagnostics,
fromImplements:=True)
Yield [interface].GetTypeRefWithAttributes(AdaptedNamedTypeSymbol.DeclaringCompilation, typeRef)
Next
End Function
Private ReadOnly Property ITypeDefinitionIsAbstract As Boolean Implements ITypeDefinition.IsAbstract
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
Return AdaptedNamedTypeSymbol.IsMetadataAbstract
End Get
End Property
Private ReadOnly Property ITypeDefinitionIsBeforeFieldInit As Boolean Implements ITypeDefinition.IsBeforeFieldInit
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
' enums or interfaces or delegates are not BeforeFieldInit
Select Case AdaptedNamedTypeSymbol.TypeKind
Case TypeKind.Enum, TypeKind.Interface, TypeKind.Delegate
Return False
End Select
' apply the beforefieldinit attribute only if there is an implicitly specified static constructor (e.g. caused by
' a Decimal or DateTime field with an initialization).
Dim cctor = AdaptedNamedTypeSymbol.SharedConstructors.FirstOrDefault
If cctor IsNot Nothing Then
Debug.Assert(AdaptedNamedTypeSymbol.SharedConstructors.Length = 1)
' NOTE: Partial methods without implementation should be skipped in the
' analysis above, see native compiler: PRBuilder.cpp, 'DWORD PEBuilder::GetTypeDefFlags'
If Not cctor.IsImplicitlyDeclared Then
' If there is an explicitly implemented shared constructor, do not look further
Return False
End If
' if the found constructor contains a generated AddHandler for a method,
' beforefieldinit should not be applied.
For Each member In AdaptedNamedTypeSymbol.GetMembers()
If member.Kind = SymbolKind.Method Then
Dim methodSym = DirectCast(member, MethodSymbol)
Dim handledEvents = methodSym.HandledEvents
If Not handledEvents.IsEmpty Then
For Each handledEvent In handledEvents
If handledEvent.hookupMethod.MethodKind = MethodKind.SharedConstructor Then
Return False
End If
Next
End If
End If
Next
' cctor is implicit and there are no handles, so the sole purpose of
' the cctor is to initialize some fields.
' Therefore it can be deferred until fields are accessed via "beforefieldinit"
Return True
End If
' if there is a const field of type Decimal or DateTime, the synthesized shared constructor does not
' appear in the member list. We need to check this separately.
Dim sourceNamedType = TryCast(AdaptedNamedTypeSymbol, SourceMemberContainerTypeSymbol)
If sourceNamedType IsNot Nothing AndAlso Not sourceNamedType.StaticInitializers.IsDefaultOrEmpty Then
Return sourceNamedType.AnyInitializerToBeInjectedIntoConstructor(sourceNamedType.StaticInitializers,
includingNonMetadataConstants:=True)
End If
Return False
End Get
End Property
Private ReadOnly Property ITypeDefinitionIsComObject As Boolean Implements ITypeDefinition.IsComObject
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
Return AdaptedNamedTypeSymbol.IsComImport
End Get
End Property
Private ReadOnly Property ITypeDefinitionIsGeneric As Boolean Implements ITypeDefinition.IsGeneric
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
Return AdaptedNamedTypeSymbol.Arity <> 0
End Get
End Property
Private ReadOnly Property ITypeDefinitionIsInterface As Boolean Implements ITypeDefinition.IsInterface
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
Return AdaptedNamedTypeSymbol.IsInterface
End Get
End Property
Private ReadOnly Property ITypeDefinitionIsDelegate As Boolean Implements ITypeDefinition.IsDelegate
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
Return AdaptedNamedTypeSymbol.IsDelegateType()
End Get
End Property
Private ReadOnly Property ITypeDefinitionIsRuntimeSpecial As Boolean Implements ITypeDefinition.IsRuntimeSpecial
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
Return False
End Get
End Property
Private ReadOnly Property ITypeDefinitionIsSerializable As Boolean Implements ITypeDefinition.IsSerializable
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
Return AdaptedNamedTypeSymbol.IsSerializable
End Get
End Property
Private ReadOnly Property ITypeDefinitionIsSpecialName As Boolean Implements ITypeDefinition.IsSpecialName
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
Return AdaptedNamedTypeSymbol.HasSpecialName
End Get
End Property
Private ReadOnly Property ITypeDefinitionIsWindowsRuntimeImport As Boolean Implements ITypeDefinition.IsWindowsRuntimeImport
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
Return AdaptedNamedTypeSymbol.IsWindowsRuntimeImport
End Get
End Property
Private ReadOnly Property ITypeDefinitionIsSealed As Boolean Implements ITypeDefinition.IsSealed
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
Return AdaptedNamedTypeSymbol.IsMetadataSealed
End Get
End Property
Private ReadOnly Property ITypeDefinitionLayout As LayoutKind Implements ITypeDefinition.Layout
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
CheckDefinitionInvariant()
Return AdaptedNamedTypeSymbol.Layout.Kind
End Get
End Property
Private Iterator Function ITypeDefinitionGetMethods(context As EmitContext) As IEnumerable(Of IMethodDefinition) Implements ITypeDefinition.GetMethods
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
' Debug.Assert(((ITypeReference)this).AsTypeDefinition(moduleBeingBuilt) != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
For Each method In AdaptedNamedTypeSymbol.GetMethodsToEmit()
Dim adapter = method.GetCciAdapter()
If adapter.ShouldInclude(context) Then
Yield adapter
End If
Next
Dim syntheticMethods = DirectCast(context.Module, PEModuleBuilder).GetSynthesizedMethods(AdaptedNamedTypeSymbol)
If syntheticMethods IsNot Nothing Then
For Each method In syntheticMethods
If method.ShouldInclude(context) Then
Yield method
End If
Next
End If
End Function
Private Function ITypeDefinitionGetNestedTypes(context As EmitContext) As IEnumerable(Of INestedTypeDefinition) Implements ITypeDefinition.GetNestedTypes
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition(moduleBeingBuilt) != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
Dim containingModule = DirectCast(context.Module, PEModuleBuilder)
Dim result As IEnumerable(Of INestedTypeDefinition)
Dim nestedTypes = AdaptedNamedTypeSymbol.GetTypeMembers() ' Ordered.
If nestedTypes.Length = 0 Then
result = SpecializedCollections.EmptyEnumerable(Of INestedTypeDefinition)()
Else
Dim filtered As IEnumerable(Of NamedTypeSymbol)
If AdaptedNamedTypeSymbol.IsEmbedded Then
' filter out embedded nested types that are not referenced
filtered = nestedTypes.Where(containingModule.SourceModule.ContainingSourceAssembly.DeclaringCompilation.EmbeddedSymbolManager.IsReferencedPredicate)
Else
filtered = nestedTypes
End If
#If DEBUG Then
result = filtered.Select(Function(t) t.GetCciAdapter())
#Else
result = filtered
#End If
End If
Dim syntheticNested = containingModule.GetSynthesizedTypes(AdaptedNamedTypeSymbol)
If syntheticNested IsNot Nothing Then
result = result.Concat(syntheticNested)
End If
Return result
End Function
Private Iterator Function ITypeDefinitionGetProperties(context As EmitContext) As IEnumerable(Of IPropertyDefinition) Implements ITypeDefinition.GetProperties
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
For Each [property] As PropertySymbol In AdaptedNamedTypeSymbol.GetPropertiesToEmit()
Debug.Assert([property] IsNot Nothing)
Dim adapter As IPropertyDefinition = [property].GetCciAdapter()
If adapter.ShouldInclude(context) OrElse Not adapter.GetAccessors(context).IsEmpty() Then
Yield adapter
End If
Next
Dim syntheticProperties = DirectCast(context.Module, PEModuleBuilder).GetSynthesizedProperties(AdaptedNamedTypeSymbol)
If syntheticProperties IsNot Nothing Then
For Each prop In syntheticProperties
If prop.ShouldInclude(context) OrElse Not prop.GetAccessors(context).IsEmpty() Then
Yield prop
End If
Next
End If
End Function
Private ReadOnly Property ITypeDefinitionSecurityAttributes As IEnumerable(Of SecurityAttribute) Implements ITypeDefinition.SecurityAttributes
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
Debug.Assert(AdaptedNamedTypeSymbol.HasDeclarativeSecurity)
Dim securityAttributes As IEnumerable(Of SecurityAttribute) = AdaptedNamedTypeSymbol.GetSecurityInformation()
Debug.Assert(securityAttributes IsNot Nothing)
Return securityAttributes
End Get
End Property
Private ReadOnly Property ITypeDefinitionSizeOf As UInteger Implements ITypeDefinition.SizeOf
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
CheckDefinitionInvariant()
Return CUInt(AdaptedNamedTypeSymbol.Layout.Size)
End Get
End Property
Private ReadOnly Property ITypeDefinitionStringFormat As CharSet Implements ITypeDefinition.StringFormat
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
CheckDefinitionInvariant()
Return AdaptedNamedTypeSymbol.MarshallingCharSet
End Get
End Property
Private ReadOnly Property INamedTypeReferenceGenericParameterCount As UShort Implements INamedTypeReference.GenericParameterCount
Get
Return GenericParameterCountImpl
End Get
End Property
Private ReadOnly Property INamedTypeReferenceMangleName As Boolean Implements INamedTypeReference.MangleName
Get
Return AdaptedNamedTypeSymbol.MangleName
End Get
End Property
Private ReadOnly Property INamedEntityName As String Implements INamedEntity.Name
Get
' CCI automatically adds the arity suffix, so we return Name, not MetadataName here.
Return AdaptedNamedTypeSymbol.Name
End Get
End Property
Private Function INamespaceTypeReferenceGetUnit(context As EmitContext) As IUnitReference Implements INamespaceTypeReference.GetUnit
Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder)
Debug.Assert((DirectCast(Me, ITypeReference)).AsNamespaceTypeReference IsNot Nothing)
Return moduleBeingBuilt.Translate(AdaptedNamedTypeSymbol.ContainingModule, context.Diagnostics)
End Function
Private ReadOnly Property INamespaceTypeReferenceNamespaceName As String Implements INamespaceTypeReference.NamespaceName
Get
Debug.Assert((DirectCast(Me, ITypeReference)).AsNamespaceTypeReference IsNot Nothing)
Return If(AdaptedNamedTypeSymbol.GetEmittedNamespaceName(), AdaptedNamedTypeSymbol.ContainingNamespace.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat))
End Get
End Property
Private ReadOnly Property INamespaceTypeDefinitionIsPublic As Boolean Implements INamespaceTypeDefinition.IsPublic
Get
'Debug.Assert(((ITypeReference)this).AsNamespaceTypeDefinition != null);
CheckDefinitionInvariant()
Return PEModuleBuilder.MemberVisibility(AdaptedNamedTypeSymbol) = Cci.TypeMemberVisibility.Public
End Get
End Property
Private Function ITypeMemberReferenceGetContainingType(context As EmitContext) As ITypeReference Implements ITypeMemberReference.GetContainingType
Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder)
Debug.Assert((DirectCast(Me, ITypeReference)).AsNestedTypeReference IsNot Nothing)
Debug.Assert(Me.IsDefinitionOrDistinct())
Return moduleBeingBuilt.Translate(AdaptedNamedTypeSymbol.ContainingType, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics, needDeclaration:=AdaptedNamedTypeSymbol.IsDefinition)
End Function
Private ReadOnly Property ITypeDefinitionMemberContainingTypeDefinition As ITypeDefinition Implements ITypeDefinitionMember.ContainingTypeDefinition
Get
'Debug.Assert(((ITypeReference)this).AsNestedTypeDefinition != null);
'return (ITypeDefinition)moduleBeingBuilt.Translate(this.ContainingType, true);
Debug.Assert(AdaptedNamedTypeSymbol.ContainingType IsNot Nothing)
CheckDefinitionInvariant()
Return AdaptedNamedTypeSymbol.ContainingType.GetCciAdapter()
End Get
End Property
Private ReadOnly Property ITypeDefinitionMemberVisibility As TypeMemberVisibility Implements ITypeDefinitionMember.Visibility
Get
'Debug.Assert(((ITypeReference)this).AsNestedTypeDefinition != null);
Debug.Assert(AdaptedNamedTypeSymbol.ContainingType IsNot Nothing)
CheckDefinitionInvariant()
Return PEModuleBuilder.MemberVisibility(AdaptedNamedTypeSymbol)
End Get
End Property
Private Function IGenericTypeInstanceReferenceGetGenericArguments(context As EmitContext) As ImmutableArray(Of ITypeReference) Implements IGenericTypeInstanceReference.GetGenericArguments
Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder)
Debug.Assert((DirectCast(Me, ITypeReference)).AsGenericTypeInstanceReference IsNot Nothing)
Dim hasModifiers = AdaptedNamedTypeSymbol.HasTypeArgumentsCustomModifiers
Dim builder = ArrayBuilder(Of ITypeReference).GetInstance()
Dim arguments = AdaptedNamedTypeSymbol.TypeArgumentsNoUseSiteDiagnostics
For i As Integer = 0 To arguments.Length - 1
Dim arg = moduleBeingBuilt.Translate(arguments(i), syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics)
If hasModifiers Then
Dim modifiers = AdaptedNamedTypeSymbol.GetTypeArgumentCustomModifiers(i)
If Not modifiers.IsDefaultOrEmpty Then
arg = New Cci.ModifiedTypeReference(arg, modifiers.As(Of Cci.ICustomModifier))
End If
End If
builder.Add(arg)
Next
Return builder.ToImmutableAndFree
End Function
Private Function IGenericTypeInstanceReferenceGetGenericType(context As EmitContext) As INamedTypeReference Implements IGenericTypeInstanceReference.GetGenericType
Debug.Assert((DirectCast(Me, ITypeReference)).AsGenericTypeInstanceReference IsNot Nothing)
Return GenericTypeImpl(context)
End Function
Private ReadOnly Property GenericTypeImpl(context As EmitContext) As INamedTypeReference
Get
Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder)
Return moduleBeingBuilt.Translate(AdaptedNamedTypeSymbol.OriginalDefinition, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode),
diagnostics:=context.Diagnostics, needDeclaration:=True)
End Get
End Property
Private Function ISpecializedNestedTypeReferenceGetUnspecializedVersion(context As EmitContext) As INestedTypeReference Implements ISpecializedNestedTypeReference.GetUnspecializedVersion
Debug.Assert((DirectCast(Me, ITypeReference)).AsSpecializedNestedTypeReference IsNot Nothing)
Dim result = GenericTypeImpl(context).AsNestedTypeReference
Debug.Assert(result IsNot Nothing)
Return result
End Function
End Class
Partial Friend Class NamedTypeSymbol
#If DEBUG Then
Private _lazyAdapter As NamedTypeSymbolAdapter
Protected Overrides Function GetCciAdapterImpl() As SymbolAdapter
Return GetCciAdapter()
End Function
Friend Shadows Function GetCciAdapter() As NamedTypeSymbolAdapter
If _lazyAdapter Is Nothing Then
Return InterlockedOperations.Initialize(_lazyAdapter, New NamedTypeSymbolAdapter(Me))
End If
Return _lazyAdapter
End Function
#Else
Friend ReadOnly Property AdaptedNamedTypeSymbol As NamedTypeSymbol
Get
Return Me
End Get
End Property
Friend Shadows Function GetCciAdapter() As NamedTypeSymbol
Return Me
End Function
#End If
Friend Overridable Iterator Function GetEventsToEmit() As IEnumerable(Of EventSymbol)
CheckDefinitionInvariant()
For Each member In Me.GetMembersForCci()
If member.Kind = SymbolKind.Event Then
Yield DirectCast(member, EventSymbol)
End If
Next
End Function
Friend MustOverride Function GetFieldsToEmit() As IEnumerable(Of FieldSymbol)
''' <summary>
''' Should return Nothing if there are none.
''' </summary>
Friend Overridable Function GetSynthesizedImplements() As IEnumerable(Of NamedTypeSymbol)
Return Nothing
End Function
Friend Overridable Function GetInterfacesToEmit() As IEnumerable(Of NamedTypeSymbol)
Debug.Assert(IsDefinition)
Debug.Assert(TypeOf ContainingModule Is SourceModuleSymbol)
' Synthesized implements should go first. Currently they are used only by
' ComClass feature, which depends on the order of implemented interfaces.
Dim synthesized As IEnumerable(Of NamedTypeSymbol) = GetSynthesizedImplements()
' If this type implements I, and the base class also implements interface I, and this class
' does not implement all the members of I, then do not emit I as an interface. This prevents
' the CLR from using implicit interface implementation.
Dim interfaces = Me.InterfacesNoUseSiteDiagnostics
If interfaces.IsEmpty Then
Return If(synthesized, SpecializedCollections.EmptyEnumerable(Of NamedTypeSymbol)())
End If
Dim base = Me.BaseTypeNoUseSiteDiagnostics
Dim result As IEnumerable(Of NamedTypeSymbol) =
interfaces.Where(Function(sym As NamedTypeSymbol) As Boolean
Return Not (base IsNot Nothing AndAlso
base.ImplementsInterface(sym, EqualsIgnoringComparer.InstanceCLRSignatureCompare, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) AndAlso
Not Me.ImplementsAllMembersOfInterface(sym))
End Function)
Return If(synthesized Is Nothing, result, synthesized.Concat(result))
End Function
Friend Overridable ReadOnly Property IsMetadataAbstract As Boolean
Get
CheckDefinitionInvariant()
Return Me.IsMustInherit OrElse Me.IsInterface
End Get
End Property
Friend Overridable ReadOnly Property IsMetadataSealed As Boolean
Get
CheckDefinitionInvariant()
If Me.IsNotInheritable Then
Return True
End If
Select Case Me.TypeKind
Case TypeKind.Module, TypeKind.Enum, TypeKind.Structure
Return True
Case Else
Return False
End Select
End Get
End Property
Friend Overridable Function GetMembersForCci() As ImmutableArray(Of Symbol)
Return Me.GetMembers()
End Function
Friend Overridable Iterator Function GetMethodsToEmit() As IEnumerable(Of MethodSymbol)
For Each member In Me.GetMembersForCci()
If member.Kind = SymbolKind.Method Then
Dim method As MethodSymbol = DirectCast(member, MethodSymbol)
' Don't emit:
' (a) Partial methods without an implementation part
' (b) The default value type constructor - the runtime handles that
If Not method.IsPartialWithoutImplementation() AndAlso Not method.IsDefaultValueTypeConstructor() Then
Yield method
End If
End If
Next
End Function
Friend Overridable Iterator Function GetPropertiesToEmit() As IEnumerable(Of PropertySymbol)
CheckDefinitionInvariant()
For Each member In Me.GetMembersForCci()
If member.Kind = SymbolKind.Property Then
Yield DirectCast(member, PropertySymbol)
End If
Next
End Function
End Class
#If DEBUG Then
Partial Friend NotInheritable Class NamedTypeSymbolAdapter
Friend ReadOnly Property AdaptedNamedTypeSymbol As NamedTypeSymbol
Friend Sub New(underlyingNamedTypeSymbol As NamedTypeSymbol)
AdaptedNamedTypeSymbol = underlyingNamedTypeSymbol
End Sub
Friend Overrides ReadOnly Property AdaptedSymbol As Symbol
Get
Return AdaptedNamedTypeSymbol
End Get
End Property
End Class
#End If
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Reflection.Metadata
Imports System.Runtime.InteropServices
Imports Microsoft.Cci
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Emit
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
#If DEBUG Then
Partial Friend Class NamedTypeSymbolAdapter
Inherits SymbolAdapter
#Else
Partial Friend Class NamedTypeSymbol
#End If
Implements ITypeReference
Implements ITypeDefinition
Implements INamedTypeReference
Implements INamedTypeDefinition
Implements INamespaceTypeReference
Implements INamespaceTypeDefinition
Implements INestedTypeReference
Implements INestedTypeDefinition
Implements IGenericTypeInstanceReference
Implements ISpecializedNestedTypeReference
Private ReadOnly Property ITypeReferenceIsEnum As Boolean Implements ITypeReference.IsEnum
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
Return AdaptedNamedTypeSymbol.TypeKind = TypeKind.Enum
End Get
End Property
Private ReadOnly Property ITypeReferenceIsValueType As Boolean Implements ITypeReference.IsValueType
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
Return AdaptedNamedTypeSymbol.IsValueType
End Get
End Property
Private Function ITypeReferenceGetResolvedType(context As EmitContext) As ITypeDefinition Implements ITypeReference.GetResolvedType
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder)
Return AsTypeDefinitionImpl(moduleBeingBuilt)
End Function
Private ReadOnly Property ITypeReferenceTypeCode As Cci.PrimitiveTypeCode Implements ITypeReference.TypeCode
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
Debug.Assert(Me.IsDefinitionOrDistinct())
If AdaptedNamedTypeSymbol.IsDefinition Then
Return AdaptedNamedTypeSymbol.PrimitiveTypeCode
End If
Return Cci.PrimitiveTypeCode.NotPrimitive
End Get
End Property
Private ReadOnly Property ITypeReferenceTypeDef As TypeDefinitionHandle Implements ITypeReference.TypeDef
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
Dim peNamedType As PENamedTypeSymbol = TryCast(AdaptedNamedTypeSymbol, PENamedTypeSymbol)
If peNamedType IsNot Nothing Then
Return peNamedType.Handle
End If
Return Nothing
End Get
End Property
Private ReadOnly Property ITypeReferenceAsGenericMethodParameterReference As IGenericMethodParameterReference Implements ITypeReference.AsGenericMethodParameterReference
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
Return Nothing
End Get
End Property
Private ReadOnly Property ITypeReferenceAsGenericTypeInstanceReference As IGenericTypeInstanceReference Implements ITypeReference.AsGenericTypeInstanceReference
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
Debug.Assert(Me.IsDefinitionOrDistinct())
If Not AdaptedNamedTypeSymbol.IsDefinition AndAlso AdaptedNamedTypeSymbol.Arity > 0 AndAlso AdaptedNamedTypeSymbol.ConstructedFrom IsNot AdaptedNamedTypeSymbol Then
Return Me
End If
Return Nothing
End Get
End Property
Private ReadOnly Property ITypeReferenceAsGenericTypeParameterReference As IGenericTypeParameterReference Implements ITypeReference.AsGenericTypeParameterReference
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
Return Nothing
End Get
End Property
Private ReadOnly Property ITypeReferenceAsNamespaceTypeReference As INamespaceTypeReference Implements ITypeReference.AsNamespaceTypeReference
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
Debug.Assert(Me.IsDefinitionOrDistinct())
If AdaptedNamedTypeSymbol.IsDefinition AndAlso AdaptedNamedTypeSymbol.ContainingType Is Nothing Then
Return Me
End If
Return Nothing
End Get
End Property
Private Function ITypeReferenceAsNamespaceTypeDefinition(context As EmitContext) As INamespaceTypeDefinition Implements ITypeReference.AsNamespaceTypeDefinition
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder)
Debug.Assert(Me.IsDefinitionOrDistinct())
If AdaptedNamedTypeSymbol.ContainingType Is Nothing AndAlso AdaptedNamedTypeSymbol.IsDefinition AndAlso AdaptedNamedTypeSymbol.ContainingModule.Equals(moduleBeingBuilt.SourceModule) Then
Return Me
End If
Return Nothing
End Function
Private ReadOnly Property ITypeReferenceAsNestedTypeReference As INestedTypeReference Implements ITypeReference.AsNestedTypeReference
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
If AdaptedNamedTypeSymbol.ContainingType IsNot Nothing Then
Return Me
End If
Return Nothing
End Get
End Property
Private Function ITypeReferenceAsNestedTypeDefinition(context As EmitContext) As INestedTypeDefinition Implements ITypeReference.AsNestedTypeDefinition
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder)
Return AsNestedTypeDefinitionImpl(moduleBeingBuilt)
End Function
Private Function AsNestedTypeDefinitionImpl(moduleBeingBuilt As PEModuleBuilder) As INestedTypeDefinition
Debug.Assert(Me.IsDefinitionOrDistinct())
If AdaptedNamedTypeSymbol.ContainingType IsNot Nothing AndAlso AdaptedNamedTypeSymbol.IsDefinition AndAlso AdaptedNamedTypeSymbol.ContainingModule.Equals(moduleBeingBuilt.SourceModule) Then
Return Me
End If
Return Nothing
End Function
Private ReadOnly Property ITypeReferenceAsSpecializedNestedTypeReference As ISpecializedNestedTypeReference Implements ITypeReference.AsSpecializedNestedTypeReference
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
Debug.Assert(Me.IsDefinitionOrDistinct())
If Not AdaptedNamedTypeSymbol.IsDefinition AndAlso (AdaptedNamedTypeSymbol.Arity = 0 OrElse AdaptedNamedTypeSymbol.ConstructedFrom Is AdaptedNamedTypeSymbol) Then
Debug.Assert(AdaptedNamedTypeSymbol.ContainingType IsNot Nothing AndAlso AdaptedNamedTypeSymbol.ContainingType.IsOrInGenericType())
Return Me
End If
Return Nothing
End Get
End Property
Private Function ITypeReferenceAsTypeDefinition(context As EmitContext) As ITypeDefinition Implements ITypeReference.AsTypeDefinition
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder)
Return AsTypeDefinitionImpl(moduleBeingBuilt)
End Function
Private Function AsTypeDefinitionImpl(moduleBeingBuilt As PEModuleBuilder) As ITypeDefinition
Debug.Assert(Me.IsDefinitionOrDistinct())
' Can't be generic instantiation
' must be declared in the module we are building
If AdaptedNamedTypeSymbol.IsDefinition AndAlso
AdaptedNamedTypeSymbol.ContainingModule.Equals(moduleBeingBuilt.SourceModule) Then
Return Me
End If
Return Nothing
End Function
Friend NotOverridable Overrides Sub IReferenceDispatch(visitor As MetadataVisitor) ' Implements IReference.Dispatch
Debug.Assert(Me.IsDefinitionOrDistinct())
If Not AdaptedNamedTypeSymbol.IsDefinition Then
If AdaptedNamedTypeSymbol.Arity > 0 AndAlso AdaptedNamedTypeSymbol.ConstructedFrom IsNot AdaptedNamedTypeSymbol Then
Debug.Assert((DirectCast(Me, ITypeReference)).AsGenericTypeInstanceReference IsNot Nothing)
visitor.Visit(DirectCast(Me, IGenericTypeInstanceReference))
Else
Debug.Assert((DirectCast(Me, ITypeReference)).AsSpecializedNestedTypeReference IsNot Nothing)
visitor.Visit(DirectCast(Me, ISpecializedNestedTypeReference))
End If
Else
Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(visitor.Context.Module, PEModuleBuilder)
Dim asDefinition As Boolean = (AdaptedNamedTypeSymbol.ContainingModule.Equals(moduleBeingBuilt.SourceModule))
If AdaptedNamedTypeSymbol.ContainingType Is Nothing Then
If asDefinition Then
Debug.Assert((DirectCast(Me, ITypeReference)).AsNamespaceTypeDefinition(visitor.Context) IsNot Nothing)
visitor.Visit(DirectCast(Me, INamespaceTypeDefinition))
Else
Debug.Assert((DirectCast(Me, ITypeReference)).AsNamespaceTypeReference IsNot Nothing)
visitor.Visit(DirectCast(Me, INamespaceTypeReference))
End If
Else
If asDefinition Then
Debug.Assert((DirectCast(Me, ITypeReference)).AsNestedTypeDefinition(visitor.Context) IsNot Nothing)
visitor.Visit(DirectCast(Me, INestedTypeDefinition))
Else
Debug.Assert((DirectCast(Me, ITypeReference)).AsNestedTypeReference IsNot Nothing)
visitor.Visit(DirectCast(Me, INestedTypeReference))
End If
End If
End If
End Sub
Friend NotOverridable Overrides Function IReferenceAsDefinition(context As EmitContext) As IDefinition ' Implements IReference.AsDefinition
Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder)
Return AsTypeDefinitionImpl(moduleBeingBuilt)
End Function
Private ReadOnly Property ITypeDefinitionAlignment As UShort Implements ITypeDefinition.Alignment
Get
CheckDefinitionInvariant()
Dim layout = AdaptedNamedTypeSymbol.Layout
Return CUShort(layout.Alignment)
End Get
End Property
Private Function ITypeDefinitionGetBaseClass(context As EmitContext) As ITypeReference Implements ITypeDefinition.GetBaseClass
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder)
Debug.Assert((DirectCast(Me, ITypeReference)).AsTypeDefinition(context) IsNot Nothing)
Dim baseType As NamedTypeSymbol = AdaptedNamedTypeSymbol.BaseTypeNoUseSiteDiagnostics
If AdaptedNamedTypeSymbol.TypeKind = TypeKind.Submission Then
' although submission semantically doesn't have a base we need to emit one into metadata:
Debug.Assert(baseType Is Nothing)
baseType = AdaptedNamedTypeSymbol.ContainingAssembly.GetSpecialType(Microsoft.CodeAnalysis.SpecialType.System_Object)
End If
If baseType IsNot Nothing Then
Return moduleBeingBuilt.Translate(baseType, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics)
End If
Return Nothing
End Function
Private Iterator Function ITypeDefinitionEvents(context As EmitContext) As IEnumerable(Of IEventDefinition) Implements ITypeDefinition.GetEvents
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
For Each e As EventSymbol In AdaptedNamedTypeSymbol.GetEventsToEmit()
Dim adapter As IEventDefinition = e.GetCciAdapter()
If adapter.ShouldInclude(context) OrElse Not adapter.GetAccessors(context).IsEmpty() Then
Yield adapter
End If
Next
End Function
Private Function ITypeDefinitionGetExplicitImplementationOverrides(context As EmitContext) As IEnumerable(Of Cci.MethodImplementation) Implements ITypeDefinition.GetExplicitImplementationOverrides
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
If AdaptedNamedTypeSymbol.IsInterface Then
Return SpecializedCollections.EmptyEnumerable(Of Cci.MethodImplementation)()
End If
Dim moduleBeingBuilt = DirectCast(context.Module, PEModuleBuilder)
Dim sourceNamedType = TryCast(AdaptedNamedTypeSymbol, SourceNamedTypeSymbol)
Dim explicitImplements As ArrayBuilder(Of Cci.MethodImplementation) = ArrayBuilder(Of Cci.MethodImplementation).GetInstance()
For Each member In AdaptedNamedTypeSymbol.GetMembersForCci()
If member.Kind = SymbolKind.Method Then
AddExplicitImplementations(context, DirectCast(member, MethodSymbol), explicitImplements, sourceNamedType, moduleBeingBuilt)
End If
Next
Dim syntheticMethods = moduleBeingBuilt.GetSynthesizedMethods(AdaptedNamedTypeSymbol)
If syntheticMethods IsNot Nothing Then
For Each synthetic In syntheticMethods
Dim method = TryCast(synthetic.GetInternalSymbol(), MethodSymbol)
If method IsNot Nothing Then
AddExplicitImplementations(context, method, explicitImplements, sourceNamedType, moduleBeingBuilt)
End If
Next
End If
Return explicitImplements.ToImmutableAndFree()
End Function
Private Sub AddExplicitImplementations(context As EmitContext,
implementingMethod As MethodSymbol,
explicitImplements As ArrayBuilder(Of Cci.MethodImplementation),
sourceNamedType As SourceNamedTypeSymbol,
moduleBeingBuilt As PEModuleBuilder)
Debug.Assert(implementingMethod.PartialDefinitionPart Is Nothing) ' must be definition
Debug.Assert(implementingMethod.IsDefinition)
For Each implemented In implementingMethod.ExplicitInterfaceImplementations
' If signature doesn't match, we have created a stub with matching signature that delegates to the implementingMethod.
' The stub will implement the implemented method in metadata.
If MethodSignatureComparer.CustomModifiersAndParametersAndReturnTypeSignatureComparer.Equals(implementingMethod, implemented) Then
explicitImplements.Add(New Cci.MethodImplementation(implementingMethod.GetCciAdapter(),
moduleBeingBuilt.TranslateOverriddenMethodReference(implemented, DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), context.Diagnostics)))
End If
Next
' Explicit overrides needed in some overriding situations.
If OverrideHidingHelper.RequiresExplicitOverride(implementingMethod) Then
explicitImplements.Add(New Cci.MethodImplementation(implementingMethod.GetCciAdapter(),
moduleBeingBuilt.TranslateOverriddenMethodReference(implementingMethod.OverriddenMethod, DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), context.Diagnostics)))
End If
If sourceNamedType IsNot Nothing Then
Dim comMethod As MethodSymbol = sourceNamedType.GetCorrespondingComClassInterfaceMethod(implementingMethod)
If comMethod IsNot Nothing Then
explicitImplements.Add(New Cci.MethodImplementation(implementingMethod.GetCciAdapter(),
moduleBeingBuilt.TranslateOverriddenMethodReference(comMethod, DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), context.Diagnostics)))
End If
End If
End Sub
Private Iterator Function ITypeDefinitionGetFields(context As EmitContext) As IEnumerable(Of IFieldDefinition) Implements ITypeDefinition.GetFields
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition(moduleBeingBuilt) != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
' All fields in a struct should be emitted
Dim isStruct = AdaptedNamedTypeSymbol.IsStructureType()
For Each field In AdaptedNamedTypeSymbol.GetFieldsToEmit()
Dim adapter = field.GetCciAdapter()
If isStruct OrElse adapter.ShouldInclude(context) OrElse IsWithEventsField(field) Then
Yield adapter
End If
Next
Dim syntheticFields = DirectCast(context.Module, PEModuleBuilder).GetSynthesizedFields(AdaptedNamedTypeSymbol)
If syntheticFields IsNot Nothing Then
For Each field In syntheticFields
If isStruct OrElse field.ShouldInclude(context) Then
Yield field
End If
Next
End If
End Function
Private Function IsWithEventsField(field As FieldSymbol) As Boolean
' Backing fields for WithEvents are emitted with AccessedThroughPropertyAttribute
' so need to be emitted even if private
Return TypeOf field Is SourceWithEventsBackingFieldSymbol
End Function
Private ReadOnly Property ITypeDefinitionGenericParameters As IEnumerable(Of IGenericTypeParameter) Implements ITypeDefinition.GenericParameters
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition(moduleBeingBuilt) != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
#If DEBUG Then
Return AdaptedNamedTypeSymbol.TypeParameters.Select(Function(t) t.GetCciAdapter())
#Else
Return AdaptedNamedTypeSymbol.TypeParameters
#End If
End Get
End Property
Private ReadOnly Property ITypeDefinitionGenericParameterCount As UShort Implements ITypeDefinition.GenericParameterCount
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
Return GenericParameterCountImpl
End Get
End Property
Private ReadOnly Property GenericParameterCountImpl As UShort
Get
Return CType(AdaptedNamedTypeSymbol.Arity, UShort)
End Get
End Property
Private ReadOnly Property ITypeDefinitionHasDeclarativeSecurity As Boolean Implements ITypeDefinition.HasDeclarativeSecurity
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
Return AdaptedNamedTypeSymbol.HasDeclarativeSecurity
End Get
End Property
Private Iterator Function ITypeDefinitionInterfaces(context As EmitContext) _
As IEnumerable(Of Cci.TypeReferenceWithAttributes) Implements ITypeDefinition.Interfaces
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
Debug.Assert((DirectCast(Me, ITypeReference)).AsTypeDefinition(context) IsNot Nothing)
Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder)
For Each [interface] In AdaptedNamedTypeSymbol.GetInterfacesToEmit()
Dim typeRef = moduleBeingBuilt.Translate([interface],
syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode),
diagnostics:=context.Diagnostics,
fromImplements:=True)
Yield [interface].GetTypeRefWithAttributes(AdaptedNamedTypeSymbol.DeclaringCompilation, typeRef)
Next
End Function
Private ReadOnly Property ITypeDefinitionIsAbstract As Boolean Implements ITypeDefinition.IsAbstract
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
Return AdaptedNamedTypeSymbol.IsMetadataAbstract
End Get
End Property
Private ReadOnly Property ITypeDefinitionIsBeforeFieldInit As Boolean Implements ITypeDefinition.IsBeforeFieldInit
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
' enums or interfaces or delegates are not BeforeFieldInit
Select Case AdaptedNamedTypeSymbol.TypeKind
Case TypeKind.Enum, TypeKind.Interface, TypeKind.Delegate
Return False
End Select
' apply the beforefieldinit attribute only if there is an implicitly specified static constructor (e.g. caused by
' a Decimal or DateTime field with an initialization).
Dim cctor = AdaptedNamedTypeSymbol.SharedConstructors.FirstOrDefault
If cctor IsNot Nothing Then
Debug.Assert(AdaptedNamedTypeSymbol.SharedConstructors.Length = 1)
' NOTE: Partial methods without implementation should be skipped in the
' analysis above, see native compiler: PRBuilder.cpp, 'DWORD PEBuilder::GetTypeDefFlags'
If Not cctor.IsImplicitlyDeclared Then
' If there is an explicitly implemented shared constructor, do not look further
Return False
End If
' if the found constructor contains a generated AddHandler for a method,
' beforefieldinit should not be applied.
For Each member In AdaptedNamedTypeSymbol.GetMembers()
If member.Kind = SymbolKind.Method Then
Dim methodSym = DirectCast(member, MethodSymbol)
Dim handledEvents = methodSym.HandledEvents
If Not handledEvents.IsEmpty Then
For Each handledEvent In handledEvents
If handledEvent.hookupMethod.MethodKind = MethodKind.SharedConstructor Then
Return False
End If
Next
End If
End If
Next
' cctor is implicit and there are no handles, so the sole purpose of
' the cctor is to initialize some fields.
' Therefore it can be deferred until fields are accessed via "beforefieldinit"
Return True
End If
' if there is a const field of type Decimal or DateTime, the synthesized shared constructor does not
' appear in the member list. We need to check this separately.
Dim sourceNamedType = TryCast(AdaptedNamedTypeSymbol, SourceMemberContainerTypeSymbol)
If sourceNamedType IsNot Nothing AndAlso Not sourceNamedType.StaticInitializers.IsDefaultOrEmpty Then
Return sourceNamedType.AnyInitializerToBeInjectedIntoConstructor(sourceNamedType.StaticInitializers,
includingNonMetadataConstants:=True)
End If
Return False
End Get
End Property
Private ReadOnly Property ITypeDefinitionIsComObject As Boolean Implements ITypeDefinition.IsComObject
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
Return AdaptedNamedTypeSymbol.IsComImport
End Get
End Property
Private ReadOnly Property ITypeDefinitionIsGeneric As Boolean Implements ITypeDefinition.IsGeneric
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
Return AdaptedNamedTypeSymbol.Arity <> 0
End Get
End Property
Private ReadOnly Property ITypeDefinitionIsInterface As Boolean Implements ITypeDefinition.IsInterface
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
Return AdaptedNamedTypeSymbol.IsInterface
End Get
End Property
Private ReadOnly Property ITypeDefinitionIsDelegate As Boolean Implements ITypeDefinition.IsDelegate
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
Return AdaptedNamedTypeSymbol.IsDelegateType()
End Get
End Property
Private ReadOnly Property ITypeDefinitionIsRuntimeSpecial As Boolean Implements ITypeDefinition.IsRuntimeSpecial
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
Return False
End Get
End Property
Private ReadOnly Property ITypeDefinitionIsSerializable As Boolean Implements ITypeDefinition.IsSerializable
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
Return AdaptedNamedTypeSymbol.IsSerializable
End Get
End Property
Private ReadOnly Property ITypeDefinitionIsSpecialName As Boolean Implements ITypeDefinition.IsSpecialName
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
Return AdaptedNamedTypeSymbol.HasSpecialName
End Get
End Property
Private ReadOnly Property ITypeDefinitionIsWindowsRuntimeImport As Boolean Implements ITypeDefinition.IsWindowsRuntimeImport
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
Return AdaptedNamedTypeSymbol.IsWindowsRuntimeImport
End Get
End Property
Private ReadOnly Property ITypeDefinitionIsSealed As Boolean Implements ITypeDefinition.IsSealed
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
Return AdaptedNamedTypeSymbol.IsMetadataSealed
End Get
End Property
Private ReadOnly Property ITypeDefinitionLayout As LayoutKind Implements ITypeDefinition.Layout
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
CheckDefinitionInvariant()
Return AdaptedNamedTypeSymbol.Layout.Kind
End Get
End Property
Private Iterator Function ITypeDefinitionGetMethods(context As EmitContext) As IEnumerable(Of IMethodDefinition) Implements ITypeDefinition.GetMethods
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
' Debug.Assert(((ITypeReference)this).AsTypeDefinition(moduleBeingBuilt) != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
For Each method In AdaptedNamedTypeSymbol.GetMethodsToEmit()
Dim adapter = method.GetCciAdapter()
If adapter.ShouldInclude(context) Then
Yield adapter
End If
Next
Dim syntheticMethods = DirectCast(context.Module, PEModuleBuilder).GetSynthesizedMethods(AdaptedNamedTypeSymbol)
If syntheticMethods IsNot Nothing Then
For Each method In syntheticMethods
If method.ShouldInclude(context) Then
Yield method
End If
Next
End If
End Function
Private Function ITypeDefinitionGetNestedTypes(context As EmitContext) As IEnumerable(Of INestedTypeDefinition) Implements ITypeDefinition.GetNestedTypes
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition(moduleBeingBuilt) != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
Dim containingModule = DirectCast(context.Module, PEModuleBuilder)
Dim result As IEnumerable(Of INestedTypeDefinition)
Dim nestedTypes = AdaptedNamedTypeSymbol.GetTypeMembers() ' Ordered.
If nestedTypes.Length = 0 Then
result = SpecializedCollections.EmptyEnumerable(Of INestedTypeDefinition)()
Else
Dim filtered As IEnumerable(Of NamedTypeSymbol)
If AdaptedNamedTypeSymbol.IsEmbedded Then
' filter out embedded nested types that are not referenced
filtered = nestedTypes.Where(containingModule.SourceModule.ContainingSourceAssembly.DeclaringCompilation.EmbeddedSymbolManager.IsReferencedPredicate)
Else
filtered = nestedTypes
End If
#If DEBUG Then
result = filtered.Select(Function(t) t.GetCciAdapter())
#Else
result = filtered
#End If
End If
Dim syntheticNested = containingModule.GetSynthesizedTypes(AdaptedNamedTypeSymbol)
If syntheticNested IsNot Nothing Then
result = result.Concat(syntheticNested)
End If
Return result
End Function
Private Iterator Function ITypeDefinitionGetProperties(context As EmitContext) As IEnumerable(Of IPropertyDefinition) Implements ITypeDefinition.GetProperties
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
For Each [property] As PropertySymbol In AdaptedNamedTypeSymbol.GetPropertiesToEmit()
Debug.Assert([property] IsNot Nothing)
Dim adapter As IPropertyDefinition = [property].GetCciAdapter()
If adapter.ShouldInclude(context) OrElse Not adapter.GetAccessors(context).IsEmpty() Then
Yield adapter
End If
Next
Dim syntheticProperties = DirectCast(context.Module, PEModuleBuilder).GetSynthesizedProperties(AdaptedNamedTypeSymbol)
If syntheticProperties IsNot Nothing Then
For Each prop In syntheticProperties
If prop.ShouldInclude(context) OrElse Not prop.GetAccessors(context).IsEmpty() Then
Yield prop
End If
Next
End If
End Function
Private ReadOnly Property ITypeDefinitionSecurityAttributes As IEnumerable(Of SecurityAttribute) Implements ITypeDefinition.SecurityAttributes
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
'Debug.Assert(((ITypeReference)this).AsTypeDefinition != null);
' can't be generic instantiation
' must be declared in the module we are building
CheckDefinitionInvariant()
Debug.Assert(AdaptedNamedTypeSymbol.HasDeclarativeSecurity)
Dim securityAttributes As IEnumerable(Of SecurityAttribute) = AdaptedNamedTypeSymbol.GetSecurityInformation()
Debug.Assert(securityAttributes IsNot Nothing)
Return securityAttributes
End Get
End Property
Private ReadOnly Property ITypeDefinitionSizeOf As UInteger Implements ITypeDefinition.SizeOf
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
CheckDefinitionInvariant()
Return CUInt(AdaptedNamedTypeSymbol.Layout.Size)
End Get
End Property
Private ReadOnly Property ITypeDefinitionStringFormat As CharSet Implements ITypeDefinition.StringFormat
Get
Debug.Assert(Not AdaptedNamedTypeSymbol.IsAnonymousType)
CheckDefinitionInvariant()
Return AdaptedNamedTypeSymbol.MarshallingCharSet
End Get
End Property
Private ReadOnly Property INamedTypeReferenceGenericParameterCount As UShort Implements INamedTypeReference.GenericParameterCount
Get
Return GenericParameterCountImpl
End Get
End Property
Private ReadOnly Property INamedTypeReferenceMangleName As Boolean Implements INamedTypeReference.MangleName
Get
Return AdaptedNamedTypeSymbol.MangleName
End Get
End Property
Private ReadOnly Property INamedEntityName As String Implements INamedEntity.Name
Get
' CCI automatically adds the arity suffix, so we return Name, not MetadataName here.
Return AdaptedNamedTypeSymbol.Name
End Get
End Property
Private Function INamespaceTypeReferenceGetUnit(context As EmitContext) As IUnitReference Implements INamespaceTypeReference.GetUnit
Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder)
Debug.Assert((DirectCast(Me, ITypeReference)).AsNamespaceTypeReference IsNot Nothing)
Return moduleBeingBuilt.Translate(AdaptedNamedTypeSymbol.ContainingModule, context.Diagnostics)
End Function
Private ReadOnly Property INamespaceTypeReferenceNamespaceName As String Implements INamespaceTypeReference.NamespaceName
Get
Debug.Assert((DirectCast(Me, ITypeReference)).AsNamespaceTypeReference IsNot Nothing)
Return If(AdaptedNamedTypeSymbol.GetEmittedNamespaceName(), AdaptedNamedTypeSymbol.ContainingNamespace.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat))
End Get
End Property
Private ReadOnly Property INamespaceTypeDefinitionIsPublic As Boolean Implements INamespaceTypeDefinition.IsPublic
Get
'Debug.Assert(((ITypeReference)this).AsNamespaceTypeDefinition != null);
CheckDefinitionInvariant()
Return PEModuleBuilder.MemberVisibility(AdaptedNamedTypeSymbol) = Cci.TypeMemberVisibility.Public
End Get
End Property
Private Function ITypeMemberReferenceGetContainingType(context As EmitContext) As ITypeReference Implements ITypeMemberReference.GetContainingType
Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder)
Debug.Assert((DirectCast(Me, ITypeReference)).AsNestedTypeReference IsNot Nothing)
Debug.Assert(Me.IsDefinitionOrDistinct())
Return moduleBeingBuilt.Translate(AdaptedNamedTypeSymbol.ContainingType, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics, needDeclaration:=AdaptedNamedTypeSymbol.IsDefinition)
End Function
Private ReadOnly Property ITypeDefinitionMemberContainingTypeDefinition As ITypeDefinition Implements ITypeDefinitionMember.ContainingTypeDefinition
Get
'Debug.Assert(((ITypeReference)this).AsNestedTypeDefinition != null);
'return (ITypeDefinition)moduleBeingBuilt.Translate(this.ContainingType, true);
Debug.Assert(AdaptedNamedTypeSymbol.ContainingType IsNot Nothing)
CheckDefinitionInvariant()
Return AdaptedNamedTypeSymbol.ContainingType.GetCciAdapter()
End Get
End Property
Private ReadOnly Property ITypeDefinitionMemberVisibility As TypeMemberVisibility Implements ITypeDefinitionMember.Visibility
Get
'Debug.Assert(((ITypeReference)this).AsNestedTypeDefinition != null);
Debug.Assert(AdaptedNamedTypeSymbol.ContainingType IsNot Nothing)
CheckDefinitionInvariant()
Return PEModuleBuilder.MemberVisibility(AdaptedNamedTypeSymbol)
End Get
End Property
Private Function IGenericTypeInstanceReferenceGetGenericArguments(context As EmitContext) As ImmutableArray(Of ITypeReference) Implements IGenericTypeInstanceReference.GetGenericArguments
Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder)
Debug.Assert((DirectCast(Me, ITypeReference)).AsGenericTypeInstanceReference IsNot Nothing)
Dim hasModifiers = AdaptedNamedTypeSymbol.HasTypeArgumentsCustomModifiers
Dim builder = ArrayBuilder(Of ITypeReference).GetInstance()
Dim arguments = AdaptedNamedTypeSymbol.TypeArgumentsNoUseSiteDiagnostics
For i As Integer = 0 To arguments.Length - 1
Dim arg = moduleBeingBuilt.Translate(arguments(i), syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode), diagnostics:=context.Diagnostics)
If hasModifiers Then
Dim modifiers = AdaptedNamedTypeSymbol.GetTypeArgumentCustomModifiers(i)
If Not modifiers.IsDefaultOrEmpty Then
arg = New Cci.ModifiedTypeReference(arg, modifiers.As(Of Cci.ICustomModifier))
End If
End If
builder.Add(arg)
Next
Return builder.ToImmutableAndFree
End Function
Private Function IGenericTypeInstanceReferenceGetGenericType(context As EmitContext) As INamedTypeReference Implements IGenericTypeInstanceReference.GetGenericType
Debug.Assert((DirectCast(Me, ITypeReference)).AsGenericTypeInstanceReference IsNot Nothing)
Return GenericTypeImpl(context)
End Function
Private ReadOnly Property GenericTypeImpl(context As EmitContext) As INamedTypeReference
Get
Dim moduleBeingBuilt As PEModuleBuilder = DirectCast(context.Module, PEModuleBuilder)
Return moduleBeingBuilt.Translate(AdaptedNamedTypeSymbol.OriginalDefinition, syntaxNodeOpt:=DirectCast(context.SyntaxNode, VisualBasicSyntaxNode),
diagnostics:=context.Diagnostics, needDeclaration:=True)
End Get
End Property
Private Function ISpecializedNestedTypeReferenceGetUnspecializedVersion(context As EmitContext) As INestedTypeReference Implements ISpecializedNestedTypeReference.GetUnspecializedVersion
Debug.Assert((DirectCast(Me, ITypeReference)).AsSpecializedNestedTypeReference IsNot Nothing)
Dim result = GenericTypeImpl(context).AsNestedTypeReference
Debug.Assert(result IsNot Nothing)
Return result
End Function
End Class
Partial Friend Class NamedTypeSymbol
#If DEBUG Then
Private _lazyAdapter As NamedTypeSymbolAdapter
Protected Overrides Function GetCciAdapterImpl() As SymbolAdapter
Return GetCciAdapter()
End Function
Friend Shadows Function GetCciAdapter() As NamedTypeSymbolAdapter
If _lazyAdapter Is Nothing Then
Return InterlockedOperations.Initialize(_lazyAdapter, New NamedTypeSymbolAdapter(Me))
End If
Return _lazyAdapter
End Function
#Else
Friend ReadOnly Property AdaptedNamedTypeSymbol As NamedTypeSymbol
Get
Return Me
End Get
End Property
Friend Shadows Function GetCciAdapter() As NamedTypeSymbol
Return Me
End Function
#End If
Friend Overridable Iterator Function GetEventsToEmit() As IEnumerable(Of EventSymbol)
CheckDefinitionInvariant()
For Each member In Me.GetMembersForCci()
If member.Kind = SymbolKind.Event Then
Yield DirectCast(member, EventSymbol)
End If
Next
End Function
Friend MustOverride Function GetFieldsToEmit() As IEnumerable(Of FieldSymbol)
''' <summary>
''' Should return Nothing if there are none.
''' </summary>
Friend Overridable Function GetSynthesizedImplements() As IEnumerable(Of NamedTypeSymbol)
Return Nothing
End Function
Friend Overridable Function GetInterfacesToEmit() As IEnumerable(Of NamedTypeSymbol)
Debug.Assert(IsDefinition)
Debug.Assert(TypeOf ContainingModule Is SourceModuleSymbol)
' Synthesized implements should go first. Currently they are used only by
' ComClass feature, which depends on the order of implemented interfaces.
Dim synthesized As IEnumerable(Of NamedTypeSymbol) = GetSynthesizedImplements()
' If this type implements I, and the base class also implements interface I, and this class
' does not implement all the members of I, then do not emit I as an interface. This prevents
' the CLR from using implicit interface implementation.
Dim interfaces = Me.InterfacesNoUseSiteDiagnostics
If interfaces.IsEmpty Then
Return If(synthesized, SpecializedCollections.EmptyEnumerable(Of NamedTypeSymbol)())
End If
Dim base = Me.BaseTypeNoUseSiteDiagnostics
Dim result As IEnumerable(Of NamedTypeSymbol) =
interfaces.Where(Function(sym As NamedTypeSymbol) As Boolean
Return Not (base IsNot Nothing AndAlso
base.ImplementsInterface(sym, EqualsIgnoringComparer.InstanceCLRSignatureCompare, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) AndAlso
Not Me.ImplementsAllMembersOfInterface(sym))
End Function)
Return If(synthesized Is Nothing, result, synthesized.Concat(result))
End Function
Friend Overridable ReadOnly Property IsMetadataAbstract As Boolean
Get
CheckDefinitionInvariant()
Return Me.IsMustInherit OrElse Me.IsInterface
End Get
End Property
Friend Overridable ReadOnly Property IsMetadataSealed As Boolean
Get
CheckDefinitionInvariant()
If Me.IsNotInheritable Then
Return True
End If
Select Case Me.TypeKind
Case TypeKind.Module, TypeKind.Enum, TypeKind.Structure
Return True
Case Else
Return False
End Select
End Get
End Property
Friend Overridable Function GetMembersForCci() As ImmutableArray(Of Symbol)
Return Me.GetMembers()
End Function
Friend Overridable Iterator Function GetMethodsToEmit() As IEnumerable(Of MethodSymbol)
For Each member In Me.GetMembersForCci()
If member.Kind = SymbolKind.Method Then
Dim method As MethodSymbol = DirectCast(member, MethodSymbol)
' Don't emit:
' (a) Partial methods without an implementation part
' (b) The default value type constructor - the runtime handles that
If Not method.IsPartialWithoutImplementation() AndAlso Not method.IsDefaultValueTypeConstructor() Then
Yield method
End If
End If
Next
End Function
Friend Overridable Iterator Function GetPropertiesToEmit() As IEnumerable(Of PropertySymbol)
CheckDefinitionInvariant()
For Each member In Me.GetMembersForCci()
If member.Kind = SymbolKind.Property Then
Yield DirectCast(member, PropertySymbol)
End If
Next
End Function
End Class
#If DEBUG Then
Partial Friend NotInheritable Class NamedTypeSymbolAdapter
Friend ReadOnly Property AdaptedNamedTypeSymbol As NamedTypeSymbol
Friend Sub New(underlyingNamedTypeSymbol As NamedTypeSymbol)
AdaptedNamedTypeSymbol = underlyingNamedTypeSymbol
End Sub
Friend Overrides ReadOnly Property AdaptedSymbol As Symbol
Get
Return AdaptedNamedTypeSymbol
End Get
End Property
End Class
#End If
End Namespace
| -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/VisualStudio/Core/Def/EditorConfigSettings/Common/RemoveSinkWhenDisposed.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.Shell.TableManager;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common
{
internal class RemoveSinkWhenDisposed : IDisposable
{
private readonly List<ITableDataSink> _tableSinks;
private readonly ITableDataSink _sink;
public RemoveSinkWhenDisposed(List<ITableDataSink> tableSinks, ITableDataSink sink)
{
_tableSinks = tableSinks;
_sink = sink;
}
public void Dispose()
{
// whoever subscribed is no longer interested in my data.
// Remove them from the list of sinks
_ = _tableSinks.Remove(_sink);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.Shell.TableManager;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common
{
internal class RemoveSinkWhenDisposed : IDisposable
{
private readonly List<ITableDataSink> _tableSinks;
private readonly ITableDataSink _sink;
public RemoveSinkWhenDisposed(List<ITableDataSink> tableSinks, ITableDataSink sink)
{
_tableSinks = tableSinks;
_sink = sink;
}
public void Dispose()
{
// whoever subscribed is no longer interested in my data.
// Remove them from the list of sinks
_ = _tableSinks.Remove(_sink);
}
}
}
| -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/ExpressionEvaluator/Core/Source/ExpressionCompiler/LanguageInstructionDecoder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using Microsoft.CodeAnalysis.Symbols;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.ComponentInterfaces;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
/// <summary>
/// This class provides function name information for the Breakpoints window.
/// </summary>
internal abstract class LanguageInstructionDecoder<TCompilation, TMethodSymbol, TModuleSymbol, TTypeSymbol, TTypeParameterSymbol, TParameterSymbol> : IDkmLanguageInstructionDecoder
where TCompilation : Compilation
where TMethodSymbol : class, IMethodSymbolInternal
where TModuleSymbol : class, IModuleSymbolInternal
where TTypeSymbol : class, ITypeSymbolInternal
where TTypeParameterSymbol : class, ITypeParameterSymbolInternal
where TParameterSymbol : class, IParameterSymbolInternal
{
private readonly InstructionDecoder<TCompilation, TMethodSymbol, TModuleSymbol, TTypeSymbol, TTypeParameterSymbol> _instructionDecoder;
internal LanguageInstructionDecoder(InstructionDecoder<TCompilation, TMethodSymbol, TModuleSymbol, TTypeSymbol, TTypeParameterSymbol> instructionDecoder)
{
_instructionDecoder = instructionDecoder;
}
string IDkmLanguageInstructionDecoder.GetMethodName(DkmLanguageInstructionAddress languageInstructionAddress, DkmVariableInfoFlags argumentFlags)
{
try
{
// DkmVariableInfoFlags.FullNames was accepted by the old GetMethodName implementation,
// but it was ignored. Furthermore, it's not clear what FullNames would mean with respect
// to argument names in C# or Visual Basic. For consistency with the old behavior, we'll
// just ignore the flag as well.
Debug.Assert((argumentFlags & (DkmVariableInfoFlags.FullNames | DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types)) == argumentFlags,
$"Unexpected argumentFlags '{argumentFlags}'");
var instructionAddress = (DkmClrInstructionAddress)languageInstructionAddress.Address;
var compilation = _instructionDecoder.GetCompilation(instructionAddress.ModuleInstance);
var method = _instructionDecoder.GetMethod(compilation, instructionAddress);
var includeParameterTypes = argumentFlags.Includes(DkmVariableInfoFlags.Types);
var includeParameterNames = argumentFlags.Includes(DkmVariableInfoFlags.Names);
return _instructionDecoder.GetName(method, includeParameterTypes, includeParameterNames);
}
catch (NotImplementedMetadataException)
{
return languageInstructionAddress.GetMethodName(argumentFlags);
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using Microsoft.CodeAnalysis.Symbols;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.ComponentInterfaces;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
/// <summary>
/// This class provides function name information for the Breakpoints window.
/// </summary>
internal abstract class LanguageInstructionDecoder<TCompilation, TMethodSymbol, TModuleSymbol, TTypeSymbol, TTypeParameterSymbol, TParameterSymbol> : IDkmLanguageInstructionDecoder
where TCompilation : Compilation
where TMethodSymbol : class, IMethodSymbolInternal
where TModuleSymbol : class, IModuleSymbolInternal
where TTypeSymbol : class, ITypeSymbolInternal
where TTypeParameterSymbol : class, ITypeParameterSymbolInternal
where TParameterSymbol : class, IParameterSymbolInternal
{
private readonly InstructionDecoder<TCompilation, TMethodSymbol, TModuleSymbol, TTypeSymbol, TTypeParameterSymbol> _instructionDecoder;
internal LanguageInstructionDecoder(InstructionDecoder<TCompilation, TMethodSymbol, TModuleSymbol, TTypeSymbol, TTypeParameterSymbol> instructionDecoder)
{
_instructionDecoder = instructionDecoder;
}
string IDkmLanguageInstructionDecoder.GetMethodName(DkmLanguageInstructionAddress languageInstructionAddress, DkmVariableInfoFlags argumentFlags)
{
try
{
// DkmVariableInfoFlags.FullNames was accepted by the old GetMethodName implementation,
// but it was ignored. Furthermore, it's not clear what FullNames would mean with respect
// to argument names in C# or Visual Basic. For consistency with the old behavior, we'll
// just ignore the flag as well.
Debug.Assert((argumentFlags & (DkmVariableInfoFlags.FullNames | DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types)) == argumentFlags,
$"Unexpected argumentFlags '{argumentFlags}'");
var instructionAddress = (DkmClrInstructionAddress)languageInstructionAddress.Address;
var compilation = _instructionDecoder.GetCompilation(instructionAddress.ModuleInstance);
var method = _instructionDecoder.GetMethod(compilation, instructionAddress);
var includeParameterTypes = argumentFlags.Includes(DkmVariableInfoFlags.Types);
var includeParameterNames = argumentFlags.Includes(DkmVariableInfoFlags.Names);
return _instructionDecoder.GetName(method, includeParameterTypes, includeParameterNames);
}
catch (NotImplementedMetadataException)
{
return languageInstructionAddress.GetMethodName(argumentFlags);
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
}
}
| -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Workspaces/VisualBasic/Portable/CodeGeneration/VisualBasicDeclarationComparer.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Friend Class VisualBasicDeclarationComparer
Implements IComparer(Of SyntaxNode)
Private Shared ReadOnly s_kindPrecedenceMap As Dictionary(Of SyntaxKind, Integer) = New Dictionary(Of SyntaxKind, Integer)(SyntaxFacts.EqualityComparer) From
{
{SyntaxKind.FieldDeclaration, 0},
{SyntaxKind.ConstructorBlock, 1},
{SyntaxKind.SubNewStatement, 1},
{SyntaxKind.PropertyBlock, 2},
{SyntaxKind.PropertyStatement, 2},
{SyntaxKind.EventBlock, 3},
{SyntaxKind.EventStatement, 3},
{SyntaxKind.SubBlock, 4},
{SyntaxKind.SubStatement, 4},
{SyntaxKind.FunctionBlock, 5},
{SyntaxKind.FunctionStatement, 5},
{SyntaxKind.OperatorBlock, 6},
{SyntaxKind.OperatorStatement, 6},
{SyntaxKind.EnumBlock, 7},
{SyntaxKind.InterfaceBlock, 8},
{SyntaxKind.StructureBlock, 9},
{SyntaxKind.ClassBlock, 10},
{SyntaxKind.ModuleBlock, 11},
{SyntaxKind.DelegateSubStatement, 12},
{SyntaxKind.DelegateFunctionStatement, 12}
}
Private Shared ReadOnly s_operatorPrecedenceMap As Dictionary(Of SyntaxKind, Integer) = New Dictionary(Of SyntaxKind, Integer)(SyntaxFacts.EqualityComparer) From
{
{SyntaxKind.PlusToken, 0},
{SyntaxKind.MinusToken, 1},
{SyntaxKind.AsteriskToken, 3},
{SyntaxKind.SlashToken, 4},
{SyntaxKind.BackslashToken, 5},
{SyntaxKind.CaretToken, 6},
{SyntaxKind.AmpersandToken, 7},
{SyntaxKind.NotKeyword, 8},
{SyntaxKind.LikeKeyword, 9},
{SyntaxKind.ModKeyword, 10},
{SyntaxKind.AndKeyword, 11},
{SyntaxKind.OrKeyword, 12},
{SyntaxKind.XorKeyword, 13},
{SyntaxKind.LessThanLessThanToken, 14},
{SyntaxKind.GreaterThanGreaterThanToken, 15},
{SyntaxKind.EqualsToken, 16},
{SyntaxKind.LessThanGreaterThanToken, 17},
{SyntaxKind.GreaterThanToken, 18},
{SyntaxKind.LessThanToken, 19},
{SyntaxKind.GreaterThanEqualsToken, 20},
{SyntaxKind.LessThanEqualsToken, 21},
{SyntaxKind.IsTrueKeyword, 22},
{SyntaxKind.IsFalseKeyword, 23},
{SyntaxKind.CTypeKeyword, 24}
}
Public Shared ReadOnly WithNamesInstance As New VisualBasicDeclarationComparer(includeName:=True)
Public Shared ReadOnly WithoutNamesInstance As New VisualBasicDeclarationComparer(includeName:=False)
Private ReadOnly _includeName As Boolean
Private Sub New(includeName As Boolean)
_includeName = includeName
End Sub
Public Function Compare(x As SyntaxNode, y As SyntaxNode) As Integer Implements IComparer(Of SyntaxNode).Compare
Dim xPrecedence As Integer
Dim yPrecedence As Integer
If Not s_kindPrecedenceMap.TryGetValue(x.Kind(), xPrecedence) OrElse
Not s_kindPrecedenceMap.TryGetValue(y.Kind(), yPrecedence) Then
' The containing definition is malformed and contains a node kind we didn't expect.
' Ignore comparisons with those unexpected nodes and sort them to the end of the declaration.
Return 1
End If
If xPrecedence <> yPrecedence Then
Return If(xPrecedence < yPrecedence, -1, 1)
End If
x = ConvertBlockToStatement(x)
y = ConvertBlockToStatement(y)
Select Case x.Kind
Case SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement
Return Compare(DirectCast(x, DelegateStatementSyntax), DirectCast(y, DelegateStatementSyntax))
Case SyntaxKind.FieldDeclaration
Return Compare(DirectCast(x, FieldDeclarationSyntax), DirectCast(y, FieldDeclarationSyntax))
Case SyntaxKind.SubNewStatement
Return Compare(DirectCast(x, SubNewStatementSyntax), DirectCast(y, SubNewStatementSyntax))
Case SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement
Return Compare(DirectCast(x, MethodStatementSyntax), DirectCast(y, MethodStatementSyntax))
Case SyntaxKind.EventStatement
Return Compare(DirectCast(x, EventStatementSyntax), DirectCast(y, EventStatementSyntax))
Case SyntaxKind.PropertyStatement
Return Compare(DirectCast(x, PropertyStatementSyntax), DirectCast(y, PropertyStatementSyntax))
Case SyntaxKind.OperatorStatement
Return Compare(DirectCast(x, OperatorStatementSyntax), DirectCast(y, OperatorStatementSyntax))
Case SyntaxKind.EnumStatement
Return Compare(DirectCast(x, EnumStatementSyntax), DirectCast(y, EnumStatementSyntax))
Case SyntaxKind.InterfaceStatement,
SyntaxKind.StructureStatement,
SyntaxKind.ClassStatement,
SyntaxKind.ModuleStatement
Return Compare(DirectCast(x, TypeStatementSyntax), DirectCast(y, TypeStatementSyntax))
End Select
throw ExceptionUtilities.UnexpectedValue(x.Kind)
End Function
Private Shared Function ConvertBlockToStatement(node As SyntaxNode) As SyntaxNode
Select Case node.Kind
Case SyntaxKind.PropertyBlock
Return DirectCast(node, PropertyBlockSyntax).PropertyStatement
Case SyntaxKind.EventBlock
Return DirectCast(node, EventBlockSyntax).EventStatement
Case SyntaxKind.ConstructorBlock,
SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.OperatorBlock
Return DirectCast(node, MethodBlockBaseSyntax).BlockStatement
Case SyntaxKind.EnumBlock
Return DirectCast(node, EnumBlockSyntax).EnumStatement
Case SyntaxKind.InterfaceBlock
Return DirectCast(node, InterfaceBlockSyntax).BlockStatement
Case SyntaxKind.StructureBlock
Return DirectCast(node, StructureBlockSyntax).BlockStatement
Case SyntaxKind.ClassBlock
Return DirectCast(node, ClassBlockSyntax).BlockStatement
Case SyntaxKind.ModuleBlock
Return DirectCast(node, ModuleBlockSyntax).BlockStatement
End Select
Return node
End Function
Private Function Compare(x As DelegateStatementSyntax, y As DelegateStatementSyntax) As Integer
Dim result = 0
If EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then
If _includeName Then
EqualIdentifierName(x.Identifier, y.Identifier, result)
End If
End If
Return result
End Function
Private Function Compare(x As FieldDeclarationSyntax, y As FieldDeclarationSyntax) As Integer
Dim result = 0
If EqualConstness(x.Modifiers, y.Modifiers, result) AndAlso
EqualSharedness(x.Modifiers, y.Modifiers, result) AndAlso
EqualReadOnlyNess(x.Modifiers, y.Modifiers, result) AndAlso
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then
If _includeName Then
EqualIdentifierName(
x.Declarators.FirstOrDefault().Names.FirstOrDefault().Identifier,
y.Declarators.FirstOrDefault().Names.FirstOrDefault().Identifier,
result)
End If
End If
Return result
End Function
Private Shared Function Compare(x As SubNewStatementSyntax, y As SubNewStatementSyntax) As Integer
Dim result = 0
If EqualSharedness(x.Modifiers, y.Modifiers, result) AndAlso
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then
EqualParameterLists(x.ParameterList, y.ParameterList, result)
End If
Return result
End Function
Private Function Compare(x As MethodStatementSyntax, y As MethodStatementSyntax) As Integer
Dim result = 0
If EqualSharedness(x.Modifiers, y.Modifiers, result) AndAlso
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then
If _includeName Then
EqualIdentifierName(x.Identifier, y.Identifier, result)
End If
End If
Return result
End Function
Private Function Compare(x As EventStatementSyntax, y As EventStatementSyntax) As Integer
Dim result = 0
If EqualSharedness(x.Modifiers, y.Modifiers, result) AndAlso
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then
If _includeName Then
EqualIdentifierName(x.Identifier, y.Identifier, result)
End If
End If
Return result
End Function
Private Function Compare(x As PropertyStatementSyntax, y As PropertyStatementSyntax) As Integer
Dim result = 0
If EqualSharedness(x.Modifiers, y.Modifiers, result) AndAlso
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then
If _includeName Then
EqualIdentifierName(x.Identifier, y.Identifier, result)
End If
End If
Return result
End Function
Private Shared Function Compare(x As OperatorStatementSyntax, y As OperatorStatementSyntax) As Integer
Dim result = 0
If EqualOperatorPrecedence(x.OperatorToken, y.OperatorToken, result) Then
EqualParameterLists(x.ParameterList, y.ParameterList, result)
End If
Return result
End Function
Private Function Compare(x As EnumStatementSyntax, y As EnumStatementSyntax) As Integer
Dim result = 0
If EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then
If _includeName Then
EqualIdentifierName(x.Identifier, y.Identifier, result)
End If
End If
Return result
End Function
Private Function Compare(x As TypeStatementSyntax, y As TypeStatementSyntax) As Integer
Dim result = 0
If EqualSharedness(x.Modifiers, y.Modifiers, result) AndAlso
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then
If _includeName Then
EqualIdentifierName(x.Identifier, y.Identifier, result)
End If
End If
Return result
End Function
Private Shared Function NeitherNull(x As Object, y As Object, ByRef comparisonResult As Integer) As Boolean
If x Is Nothing AndAlso y Is Nothing Then
comparisonResult = 0
Return False
ElseIf x Is Nothing Then
comparisonResult = -1
Return False
ElseIf y Is Nothing Then
comparisonResult = 1
Return False
Else
comparisonResult = 0
Return True
End If
End Function
Private Shared Function ContainsToken(list As IEnumerable(Of SyntaxToken), kind As SyntaxKind) As Boolean
Return list.Contains(Function(token As SyntaxToken)
Return token.Kind = kind
End Function)
End Function
Private Enum Accessibility
[Public]
[Protected]
[ProtectedFriend]
[Friend]
[Private]
End Enum
Private Shared Function GetAccessibilityPrecedence(declaration As SyntaxNode, modifiers As IEnumerable(Of SyntaxToken)) As Integer
If ContainsToken(modifiers, SyntaxKind.PublicKeyword) Then
Return Accessibility.Public
ElseIf ContainsToken(modifiers, SyntaxKind.ProtectedKeyword) Then
If ContainsToken(modifiers, SyntaxKind.FriendKeyword) Then
Return Accessibility.ProtectedFriend
End If
Return Accessibility.Protected
ElseIf ContainsToken(modifiers, SyntaxKind.FriendKeyword) Then
Return Accessibility.Friend
ElseIf ContainsToken(modifiers, SyntaxKind.PrivateKeyword) Then
Return Accessibility.Private
End If
' Determine default accessibility
Select Case declaration.Kind
Case SyntaxKind.InterfaceStatement,
SyntaxKind.ModuleStatement,
SyntaxKind.ClassStatement,
SyntaxKind.StructureStatement
' Convert type definition statements to their corresponding blocks so we can traverse up the tree
declaration = declaration.Parent
End Select
Dim node = declaration.Parent
While node IsNot Nothing
Select Case node.Kind
Case SyntaxKind.InterfaceBlock
' Interface members are all Public
Return Accessibility.Public
Case SyntaxKind.ModuleBlock,
SyntaxKind.ClassBlock
' Standard module and class members default to Public unless they are variable declarations
Return If(declaration.Kind = SyntaxKind.FieldDeclaration, Accessibility.Private, Accessibility.Public)
Case SyntaxKind.StructureBlock
' Structure member declarations always default to Public
Return Accessibility.Public
End Select
node = node.Parent
End While
' Namespace members default to Friend
Return Accessibility.Friend
End Function
Private Shared Function BothHaveModifier(x As SyntaxTokenList, y As SyntaxTokenList, modifierKind As SyntaxKind, ByRef comparisonResult As Integer) As Boolean
Dim xHasModifier = ContainsToken(x, modifierKind)
Dim yHasModifier = ContainsToken(y, modifierKind)
If xHasModifier = yHasModifier Then
comparisonResult = 0
Return True
End If
comparisonResult = If(xHasModifier, -1, 1)
Return False
End Function
Private Shared Function EqualSharedness(x As SyntaxTokenList, y As SyntaxTokenList, ByRef comparisonResult As Integer) As Boolean
Return BothHaveModifier(x, y, SyntaxKind.SharedKeyword, comparisonResult)
End Function
Private Shared Function EqualReadOnlyness(x As SyntaxTokenList, y As SyntaxTokenList, ByRef comparisonResult As Integer) As Boolean
Return BothHaveModifier(x, y, SyntaxKind.ReadOnlyKeyword, comparisonResult)
End Function
Private Shared Function EqualConstness(x As SyntaxTokenList, y As SyntaxTokenList, ByRef comparisonResult As Integer) As Boolean
Return BothHaveModifier(x, y, SyntaxKind.ConstKeyword, comparisonResult)
End Function
Private Shared Function EqualAccessibility(x As SyntaxNode, xModifiers As SyntaxTokenList, y As SyntaxNode, yModifiers As SyntaxTokenList, ByRef comparisonResult As Integer) As Boolean
Dim xAccessibility = GetAccessibilityPrecedence(x, xModifiers)
Dim yAccessibility = GetAccessibilityPrecedence(y, yModifiers)
If xAccessibility = yAccessibility Then
comparisonResult = 0
Return True
End If
comparisonResult = If(xAccessibility < yAccessibility, -1, 1)
Return False
End Function
Private Shared Function EqualIdentifierName(x As SyntaxToken, y As SyntaxToken, ByRef comparisonResult As Integer) As Boolean
If NeitherNull(x, y, comparisonResult) Then
comparisonResult = CaseInsensitiveComparison.Compare(x.ValueText, y.ValueText)
End If
Return comparisonResult = 0
End Function
Private Shared Function EqualOperatorPrecedence(x As SyntaxToken, y As SyntaxToken, ByRef comparisonResult As Integer) As Boolean
If NeitherNull(x, y, comparisonResult) Then
Dim xPrecedence = 0
Dim yPrecedence = 0
s_operatorPrecedenceMap.TryGetValue(x.Kind, xPrecedence)
s_operatorPrecedenceMap.TryGetValue(y.Kind, yPrecedence)
comparisonResult = If(xPrecedence = yPrecedence, 0, If(xPrecedence < yPrecedence, -1, 1))
End If
Return comparisonResult = 0
End Function
Private Shared Function EqualParameterLists(x As ParameterListSyntax, y As ParameterListSyntax, ByRef comparisonResult As Integer) As Boolean
Dim result = 0
If NeitherNull(x, y, result) Then
Dim xParameterCount = x.Parameters.Count
Dim yParameterCount = y.Parameters.Count
comparisonResult = If(xParameterCount = yParameterCount, 0, If(x.Parameters.Count < y.Parameters.Count, -1, 1))
End If
Return comparisonResult = 0
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.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Friend Class VisualBasicDeclarationComparer
Implements IComparer(Of SyntaxNode)
Private Shared ReadOnly s_kindPrecedenceMap As Dictionary(Of SyntaxKind, Integer) = New Dictionary(Of SyntaxKind, Integer)(SyntaxFacts.EqualityComparer) From
{
{SyntaxKind.FieldDeclaration, 0},
{SyntaxKind.ConstructorBlock, 1},
{SyntaxKind.SubNewStatement, 1},
{SyntaxKind.PropertyBlock, 2},
{SyntaxKind.PropertyStatement, 2},
{SyntaxKind.EventBlock, 3},
{SyntaxKind.EventStatement, 3},
{SyntaxKind.SubBlock, 4},
{SyntaxKind.SubStatement, 4},
{SyntaxKind.FunctionBlock, 5},
{SyntaxKind.FunctionStatement, 5},
{SyntaxKind.OperatorBlock, 6},
{SyntaxKind.OperatorStatement, 6},
{SyntaxKind.EnumBlock, 7},
{SyntaxKind.InterfaceBlock, 8},
{SyntaxKind.StructureBlock, 9},
{SyntaxKind.ClassBlock, 10},
{SyntaxKind.ModuleBlock, 11},
{SyntaxKind.DelegateSubStatement, 12},
{SyntaxKind.DelegateFunctionStatement, 12}
}
Private Shared ReadOnly s_operatorPrecedenceMap As Dictionary(Of SyntaxKind, Integer) = New Dictionary(Of SyntaxKind, Integer)(SyntaxFacts.EqualityComparer) From
{
{SyntaxKind.PlusToken, 0},
{SyntaxKind.MinusToken, 1},
{SyntaxKind.AsteriskToken, 3},
{SyntaxKind.SlashToken, 4},
{SyntaxKind.BackslashToken, 5},
{SyntaxKind.CaretToken, 6},
{SyntaxKind.AmpersandToken, 7},
{SyntaxKind.NotKeyword, 8},
{SyntaxKind.LikeKeyword, 9},
{SyntaxKind.ModKeyword, 10},
{SyntaxKind.AndKeyword, 11},
{SyntaxKind.OrKeyword, 12},
{SyntaxKind.XorKeyword, 13},
{SyntaxKind.LessThanLessThanToken, 14},
{SyntaxKind.GreaterThanGreaterThanToken, 15},
{SyntaxKind.EqualsToken, 16},
{SyntaxKind.LessThanGreaterThanToken, 17},
{SyntaxKind.GreaterThanToken, 18},
{SyntaxKind.LessThanToken, 19},
{SyntaxKind.GreaterThanEqualsToken, 20},
{SyntaxKind.LessThanEqualsToken, 21},
{SyntaxKind.IsTrueKeyword, 22},
{SyntaxKind.IsFalseKeyword, 23},
{SyntaxKind.CTypeKeyword, 24}
}
Public Shared ReadOnly WithNamesInstance As New VisualBasicDeclarationComparer(includeName:=True)
Public Shared ReadOnly WithoutNamesInstance As New VisualBasicDeclarationComparer(includeName:=False)
Private ReadOnly _includeName As Boolean
Private Sub New(includeName As Boolean)
_includeName = includeName
End Sub
Public Function Compare(x As SyntaxNode, y As SyntaxNode) As Integer Implements IComparer(Of SyntaxNode).Compare
Dim xPrecedence As Integer
Dim yPrecedence As Integer
If Not s_kindPrecedenceMap.TryGetValue(x.Kind(), xPrecedence) OrElse
Not s_kindPrecedenceMap.TryGetValue(y.Kind(), yPrecedence) Then
' The containing definition is malformed and contains a node kind we didn't expect.
' Ignore comparisons with those unexpected nodes and sort them to the end of the declaration.
Return 1
End If
If xPrecedence <> yPrecedence Then
Return If(xPrecedence < yPrecedence, -1, 1)
End If
x = ConvertBlockToStatement(x)
y = ConvertBlockToStatement(y)
Select Case x.Kind
Case SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement
Return Compare(DirectCast(x, DelegateStatementSyntax), DirectCast(y, DelegateStatementSyntax))
Case SyntaxKind.FieldDeclaration
Return Compare(DirectCast(x, FieldDeclarationSyntax), DirectCast(y, FieldDeclarationSyntax))
Case SyntaxKind.SubNewStatement
Return Compare(DirectCast(x, SubNewStatementSyntax), DirectCast(y, SubNewStatementSyntax))
Case SyntaxKind.SubStatement,
SyntaxKind.FunctionStatement
Return Compare(DirectCast(x, MethodStatementSyntax), DirectCast(y, MethodStatementSyntax))
Case SyntaxKind.EventStatement
Return Compare(DirectCast(x, EventStatementSyntax), DirectCast(y, EventStatementSyntax))
Case SyntaxKind.PropertyStatement
Return Compare(DirectCast(x, PropertyStatementSyntax), DirectCast(y, PropertyStatementSyntax))
Case SyntaxKind.OperatorStatement
Return Compare(DirectCast(x, OperatorStatementSyntax), DirectCast(y, OperatorStatementSyntax))
Case SyntaxKind.EnumStatement
Return Compare(DirectCast(x, EnumStatementSyntax), DirectCast(y, EnumStatementSyntax))
Case SyntaxKind.InterfaceStatement,
SyntaxKind.StructureStatement,
SyntaxKind.ClassStatement,
SyntaxKind.ModuleStatement
Return Compare(DirectCast(x, TypeStatementSyntax), DirectCast(y, TypeStatementSyntax))
End Select
throw ExceptionUtilities.UnexpectedValue(x.Kind)
End Function
Private Shared Function ConvertBlockToStatement(node As SyntaxNode) As SyntaxNode
Select Case node.Kind
Case SyntaxKind.PropertyBlock
Return DirectCast(node, PropertyBlockSyntax).PropertyStatement
Case SyntaxKind.EventBlock
Return DirectCast(node, EventBlockSyntax).EventStatement
Case SyntaxKind.ConstructorBlock,
SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.OperatorBlock
Return DirectCast(node, MethodBlockBaseSyntax).BlockStatement
Case SyntaxKind.EnumBlock
Return DirectCast(node, EnumBlockSyntax).EnumStatement
Case SyntaxKind.InterfaceBlock
Return DirectCast(node, InterfaceBlockSyntax).BlockStatement
Case SyntaxKind.StructureBlock
Return DirectCast(node, StructureBlockSyntax).BlockStatement
Case SyntaxKind.ClassBlock
Return DirectCast(node, ClassBlockSyntax).BlockStatement
Case SyntaxKind.ModuleBlock
Return DirectCast(node, ModuleBlockSyntax).BlockStatement
End Select
Return node
End Function
Private Function Compare(x As DelegateStatementSyntax, y As DelegateStatementSyntax) As Integer
Dim result = 0
If EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then
If _includeName Then
EqualIdentifierName(x.Identifier, y.Identifier, result)
End If
End If
Return result
End Function
Private Function Compare(x As FieldDeclarationSyntax, y As FieldDeclarationSyntax) As Integer
Dim result = 0
If EqualConstness(x.Modifiers, y.Modifiers, result) AndAlso
EqualSharedness(x.Modifiers, y.Modifiers, result) AndAlso
EqualReadOnlyNess(x.Modifiers, y.Modifiers, result) AndAlso
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then
If _includeName Then
EqualIdentifierName(
x.Declarators.FirstOrDefault().Names.FirstOrDefault().Identifier,
y.Declarators.FirstOrDefault().Names.FirstOrDefault().Identifier,
result)
End If
End If
Return result
End Function
Private Shared Function Compare(x As SubNewStatementSyntax, y As SubNewStatementSyntax) As Integer
Dim result = 0
If EqualSharedness(x.Modifiers, y.Modifiers, result) AndAlso
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then
EqualParameterLists(x.ParameterList, y.ParameterList, result)
End If
Return result
End Function
Private Function Compare(x As MethodStatementSyntax, y As MethodStatementSyntax) As Integer
Dim result = 0
If EqualSharedness(x.Modifiers, y.Modifiers, result) AndAlso
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then
If _includeName Then
EqualIdentifierName(x.Identifier, y.Identifier, result)
End If
End If
Return result
End Function
Private Function Compare(x As EventStatementSyntax, y As EventStatementSyntax) As Integer
Dim result = 0
If EqualSharedness(x.Modifiers, y.Modifiers, result) AndAlso
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then
If _includeName Then
EqualIdentifierName(x.Identifier, y.Identifier, result)
End If
End If
Return result
End Function
Private Function Compare(x As PropertyStatementSyntax, y As PropertyStatementSyntax) As Integer
Dim result = 0
If EqualSharedness(x.Modifiers, y.Modifiers, result) AndAlso
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then
If _includeName Then
EqualIdentifierName(x.Identifier, y.Identifier, result)
End If
End If
Return result
End Function
Private Shared Function Compare(x As OperatorStatementSyntax, y As OperatorStatementSyntax) As Integer
Dim result = 0
If EqualOperatorPrecedence(x.OperatorToken, y.OperatorToken, result) Then
EqualParameterLists(x.ParameterList, y.ParameterList, result)
End If
Return result
End Function
Private Function Compare(x As EnumStatementSyntax, y As EnumStatementSyntax) As Integer
Dim result = 0
If EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then
If _includeName Then
EqualIdentifierName(x.Identifier, y.Identifier, result)
End If
End If
Return result
End Function
Private Function Compare(x As TypeStatementSyntax, y As TypeStatementSyntax) As Integer
Dim result = 0
If EqualSharedness(x.Modifiers, y.Modifiers, result) AndAlso
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then
If _includeName Then
EqualIdentifierName(x.Identifier, y.Identifier, result)
End If
End If
Return result
End Function
Private Shared Function NeitherNull(x As Object, y As Object, ByRef comparisonResult As Integer) As Boolean
If x Is Nothing AndAlso y Is Nothing Then
comparisonResult = 0
Return False
ElseIf x Is Nothing Then
comparisonResult = -1
Return False
ElseIf y Is Nothing Then
comparisonResult = 1
Return False
Else
comparisonResult = 0
Return True
End If
End Function
Private Shared Function ContainsToken(list As IEnumerable(Of SyntaxToken), kind As SyntaxKind) As Boolean
Return list.Contains(Function(token As SyntaxToken)
Return token.Kind = kind
End Function)
End Function
Private Enum Accessibility
[Public]
[Protected]
[ProtectedFriend]
[Friend]
[Private]
End Enum
Private Shared Function GetAccessibilityPrecedence(declaration As SyntaxNode, modifiers As IEnumerable(Of SyntaxToken)) As Integer
If ContainsToken(modifiers, SyntaxKind.PublicKeyword) Then
Return Accessibility.Public
ElseIf ContainsToken(modifiers, SyntaxKind.ProtectedKeyword) Then
If ContainsToken(modifiers, SyntaxKind.FriendKeyword) Then
Return Accessibility.ProtectedFriend
End If
Return Accessibility.Protected
ElseIf ContainsToken(modifiers, SyntaxKind.FriendKeyword) Then
Return Accessibility.Friend
ElseIf ContainsToken(modifiers, SyntaxKind.PrivateKeyword) Then
Return Accessibility.Private
End If
' Determine default accessibility
Select Case declaration.Kind
Case SyntaxKind.InterfaceStatement,
SyntaxKind.ModuleStatement,
SyntaxKind.ClassStatement,
SyntaxKind.StructureStatement
' Convert type definition statements to their corresponding blocks so we can traverse up the tree
declaration = declaration.Parent
End Select
Dim node = declaration.Parent
While node IsNot Nothing
Select Case node.Kind
Case SyntaxKind.InterfaceBlock
' Interface members are all Public
Return Accessibility.Public
Case SyntaxKind.ModuleBlock,
SyntaxKind.ClassBlock
' Standard module and class members default to Public unless they are variable declarations
Return If(declaration.Kind = SyntaxKind.FieldDeclaration, Accessibility.Private, Accessibility.Public)
Case SyntaxKind.StructureBlock
' Structure member declarations always default to Public
Return Accessibility.Public
End Select
node = node.Parent
End While
' Namespace members default to Friend
Return Accessibility.Friend
End Function
Private Shared Function BothHaveModifier(x As SyntaxTokenList, y As SyntaxTokenList, modifierKind As SyntaxKind, ByRef comparisonResult As Integer) As Boolean
Dim xHasModifier = ContainsToken(x, modifierKind)
Dim yHasModifier = ContainsToken(y, modifierKind)
If xHasModifier = yHasModifier Then
comparisonResult = 0
Return True
End If
comparisonResult = If(xHasModifier, -1, 1)
Return False
End Function
Private Shared Function EqualSharedness(x As SyntaxTokenList, y As SyntaxTokenList, ByRef comparisonResult As Integer) As Boolean
Return BothHaveModifier(x, y, SyntaxKind.SharedKeyword, comparisonResult)
End Function
Private Shared Function EqualReadOnlyness(x As SyntaxTokenList, y As SyntaxTokenList, ByRef comparisonResult As Integer) As Boolean
Return BothHaveModifier(x, y, SyntaxKind.ReadOnlyKeyword, comparisonResult)
End Function
Private Shared Function EqualConstness(x As SyntaxTokenList, y As SyntaxTokenList, ByRef comparisonResult As Integer) As Boolean
Return BothHaveModifier(x, y, SyntaxKind.ConstKeyword, comparisonResult)
End Function
Private Shared Function EqualAccessibility(x As SyntaxNode, xModifiers As SyntaxTokenList, y As SyntaxNode, yModifiers As SyntaxTokenList, ByRef comparisonResult As Integer) As Boolean
Dim xAccessibility = GetAccessibilityPrecedence(x, xModifiers)
Dim yAccessibility = GetAccessibilityPrecedence(y, yModifiers)
If xAccessibility = yAccessibility Then
comparisonResult = 0
Return True
End If
comparisonResult = If(xAccessibility < yAccessibility, -1, 1)
Return False
End Function
Private Shared Function EqualIdentifierName(x As SyntaxToken, y As SyntaxToken, ByRef comparisonResult As Integer) As Boolean
If NeitherNull(x, y, comparisonResult) Then
comparisonResult = CaseInsensitiveComparison.Compare(x.ValueText, y.ValueText)
End If
Return comparisonResult = 0
End Function
Private Shared Function EqualOperatorPrecedence(x As SyntaxToken, y As SyntaxToken, ByRef comparisonResult As Integer) As Boolean
If NeitherNull(x, y, comparisonResult) Then
Dim xPrecedence = 0
Dim yPrecedence = 0
s_operatorPrecedenceMap.TryGetValue(x.Kind, xPrecedence)
s_operatorPrecedenceMap.TryGetValue(y.Kind, yPrecedence)
comparisonResult = If(xPrecedence = yPrecedence, 0, If(xPrecedence < yPrecedence, -1, 1))
End If
Return comparisonResult = 0
End Function
Private Shared Function EqualParameterLists(x As ParameterListSyntax, y As ParameterListSyntax, ByRef comparisonResult As Integer) As Boolean
Dim result = 0
If NeitherNull(x, y, result) Then
Dim xParameterCount = x.Parameters.Count
Dim yParameterCount = y.Parameters.Count
comparisonResult = If(xParameterCount = yParameterCount, 0, If(x.Parameters.Count < y.Parameters.Count, -1, 1))
End If
Return comparisonResult = 0
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IArgument.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Operations
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Partial Public Class IOperationTests
Inherits SemanticModelTestBase
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub PositionalArgument()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(1, 0.0)'BIND:"M2(1, 0.0)"
End Sub
Sub M2(a As Integer, b As Double)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2(a As System.Int32, b As System.Double)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1, 0.0)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: '0.0')
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0) (Syntax: '0.0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub PositionalArgumentWithDefaultValue()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(1)'BIND:"M2(1)"
End Sub
Sub M2(a As Integer, Optional b As Double = 0.0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2(a As System.Int32, [b As System.Double = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2')
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0, IsImplicit) (Syntax: 'M2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub NamedArgumentListedInParameterOrder()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(a:=1, b:=1.0)'BIND:"M2(a:=1, b:=1.0)"
End Sub
Sub M2(a As Integer, Optional b As Double = 0.0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2(a As System.Int32, [b As System.Double = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(a:=1, b:=1.0)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: 'a:=1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: 'b:=1.0')
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 1) (Syntax: '1.0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub NamedArgumentListedOutOfParameterOrder()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(b:=1.0, a:=0)'BIND:"M2(b:=1.0, a:=0)"
End Sub
Sub M2(a As Integer, Optional b As Double = 0.0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2(a As System.Int32, [b As System.Double = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(b:=1.0, a:=0)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: 'a:=0')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: 'b:=1.0')
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 1) (Syntax: '1.0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub NamedArgumentInParameterOrderWithDefaultValue()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(b:=1.0, c:=2.0)'BIND:"M2(b:=1.0, c:=2.0)"
End Sub
Sub M2(Optional a As Integer = 0, Optional b As Double = 0.0, Optional c As Double = 0.0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2([a As System.Int32 = 0], [b As System.Double = 0], [c As System.Double = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(b:=1.0, c:=2.0)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(3):
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'M2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: 'b:=1.0')
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 1) (Syntax: '1.0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: c) (OperationKind.Argument, Type: null) (Syntax: 'c:=2.0')
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 2) (Syntax: '2.0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub NamedArgumentInParameterOrderWithDefaultValueUsingOmittedSyntax()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(, b:=1.0, c:=2.0)'BIND:"M2(, b:=1.0, c:=2.0)"
End Sub
Sub M2(Optional a As Integer = 0, Optional b As Double = 0.0, Optional c As Double = 0.0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2([a As System.Int32 = 0], [b As System.Double = 0], [c As System.Double = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(, b:=1.0, c:=2.0)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(3):
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: '')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: 'b:=1.0')
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 1) (Syntax: '1.0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: c) (OperationKind.Argument, Type: null) (Syntax: 'c:=2.0')
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 2) (Syntax: '2.0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub NamedArgumentOutOfParameterOrderWithDefaultValue()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(b:=2.0)'BIND:"M2(b:=2.0)"
End Sub
Sub M2(Optional a As Integer = 0, Optional b As Double = 0.0, Optional c As Double = 0.0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2([a As System.Int32 = 0], [b As System.Double = 0], [c As System.Double = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(b:=2.0)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(3):
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'M2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: 'b:=2.0')
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 2) (Syntax: '2.0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: c) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2')
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0, IsImplicit) (Syntax: 'M2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub NamedAndPositionalArgumentsWithDefaultValue()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(1, c:=2.0)'BIND:"M2(1, c:=2.0)"
End Sub
Sub M2(Optional a As Integer = 0, Optional b As Double = 0.0, Optional c As Double = 0.0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2([a As System.Int32 = 0], [b As System.Double = 0], [c As System.Double = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1, c:=2.0)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2')
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0, IsImplicit) (Syntax: 'M2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: c) (OperationKind.Argument, Type: null) (Syntax: 'c:=2.0')
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 2) (Syntax: '2.0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub PositionalByRefNonModifiableArgument()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(1)'BIND:"M2(1)"
End Sub
Sub M2(ByRef Optional a As Integer = 0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2([ByRef a As System.Int32 = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub PositionalByRefModifiableArgument()
Dim source = <![CDATA[
Class Program
Sub M1()
Dim x = 1
M2(x)'BIND:"M2(x)"
End Sub
Sub M2(ByRef Optional a As Integer = 0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2([ByRef a As System.Int32 = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(x)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub NamedByRefModifiableArgumentsOutOfParameterOrder()
Dim source = <![CDATA[
Class Program
Sub M1()
Dim x = 1
Dim y = 1.0
M2(b:=y, a:=x)'BIND:"M2(b:=y, a:=x)"
End Sub
Sub M2(ByRef Optional a As Integer = 0, ByRef Optional b As Double = 0.0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2([ByRef a As System.Int32 = 0], [ByRef b As System.Double = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(b:=y, a:=x)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: 'a:=x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: 'b:=y')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Double) (Syntax: 'y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub DefaultValueForByRefParameter()
Dim source = <![CDATA[
Class Program
Sub M1()
Dim x = 1.0
M2()'BIND:"M2()"
End Sub
Sub M2(ByRef Optional a As Integer = 0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2([ByRef a As System.Int32 = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(1):
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'M2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub PositionalByRefNonModifiableArgumentWithConversion()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(1.0)'BIND:"M2(1.0)"
End Sub
Sub M2(ByRef Optional a As Integer = 0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2([ByRef a As System.Int32 = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1.0)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: '1.0')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1.0')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 1) (Syntax: '1.0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub PositionalByRefModifiableArgumentWithConversion()
Dim source = <![CDATA[
Class Program
Sub M1()
Dim x = 1.0
M2(x)'BIND:"M2(x)"
End Sub
Sub M2(ByRef Optional a As Integer = 0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2([ByRef a As System.Int32 = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(x)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Double) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub PositionalArgumentForExtensionMethod()
Dim source = <![CDATA[
Imports System.Runtime.CompilerServices
Class P
Sub M1()
E1(1, 2)'BIND:"E1(1, 2)"
End Sub
End Class
Module Extensions
<Extension()>
Public Sub E1(a As P, Optional b As Integer = 0, Optional c As Integer = 0)
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub P.E1([b As System.Int32 = 0], [c As System.Int32 = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'E1(1, 2)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'E1')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: c) (OperationKind.Argument, Type: null) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub NamedArgumentOutOfParameterOrderForExtensionMethod()
Dim source = <![CDATA[
Imports System.Runtime.CompilerServices
Class P
Sub M1()
E1(c:=1, b:=2)'BIND:"E1(c:=1, b:=2)"
End Sub
End Class
Module Extensions
<Extension()>
Public Sub E1(a As P, Optional b As Integer = 0, Optional c As Integer = 0)
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub P.E1([b As System.Int32 = 0], [c As System.Int32 = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'E1(c:=1, b:=2)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'E1')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: 'b:=2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: c) (OperationKind.Argument, Type: null) (Syntax: 'c:=1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub ParamsArrayArgumentInNormalForm()
Dim source = <![CDATA[
Class P
Sub M1()
Dim a = New Integer() {1, 2, 3}
M2(1, a)'BIND:"M2(1, a)"
End Sub
Sub M2(x As Integer, ParamArray y As Integer())
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub P.M2(x As System.Int32, ParamArray y As System.Int32())) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1, a)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'a')
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub ParamsArrayArgumentInExpandedForm()
Dim source = <![CDATA[
Class P
Sub M1()
M2(1, 2, 3)'BIND:"M2(1, 2, 3)"
End Sub
Sub M2(x As Integer, ParamArray y As Integer())
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub P.M2(x As System.Int32, ParamArray y As System.Int32())) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1, 2, 3)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: y) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(1, 2, 3)')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'M2(1, 2, 3)')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'M2(1, 2, 3)')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'M2(1, 2, 3)')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub ParamsArrayArgumentInExpandedFormWithNoArgument()
Dim source = <![CDATA[
Imports System.Runtime.CompilerServices
Class P
Sub M1()
M2(1)'BIND:"M2(1)"
End Sub
Sub M2(x As Integer, ParamArray y As Integer())
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub P.M2(x As System.Int32, ParamArray y As System.Int32())) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: y) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(1)')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'M2(1)')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'M2(1)')
Initializer:
IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'M2(1)')
Element Values(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub Error_MissingRequiredArgument()
Dim source = <![CDATA[
Class P
Sub M1()
M2()'BIND:"M2()"
End Sub
Sub M2(x As Integer, Optional y As Integer = 0, Optional z As Integer = 0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'M2()')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30455: Argument not specified for parameter 'x' of 'Public Sub M2(x As Integer, [y As Integer = 0], [z As Integer = 0])'.
M2()'BIND:"M2()"
~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub Error_TooManyArguments()
Dim source = <![CDATA[
Class P
Sub M1()
M2(1, 2)'BIND:"M2(1, 2)"
End Sub
Sub M2(x As Integer)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'M2(1, 2)')
Children(3):
IOperation: (OperationKind.None, Type: null) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30057: Too many arguments to 'Public Sub M2(x As Integer)'.
M2(1, 2)'BIND:"M2(1, 2)"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub Error_ExtraOmittedArgument()
Dim source = <![CDATA[
Class P
Sub M1()
M2(0,,,)'BIND:"M2(0,,,)"
End Sub
Sub M2(x As Integer, Optional y As Integer = 0, Optional z As Integer = 0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'M2(0,,,)')
Children(5):
IOperation: (OperationKind.None, Type: null) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
IOmittedArgumentOperation (OperationKind.OmittedArgument, Type: null) (Syntax: '')
IOmittedArgumentOperation (OperationKind.OmittedArgument, Type: null) (Syntax: '')
IOmittedArgumentOperation (OperationKind.OmittedArgument, Type: null, IsInvalid) (Syntax: '')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30057: Too many arguments to 'Public Sub M2(x As Integer, [y As Integer = 0], [z As Integer = 0])'.
M2(0,,,)'BIND:"M2(0,,,)"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub TestValidDynamicInvocation_OmittedArgument()
Dim source = <![CDATA[
Option Strict Off
Class P
Sub M1(o As Object)
M2(o,,)'BIND:"M2(o,,)"
End Sub
Sub M2(x As Integer, Optional y As Integer = 0, Optional z As Integer = 0)
End Sub
Sub M2(x As Double, Optional y As Integer = 0, Optional z As Integer = 0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object) (Syntax: 'M2(o,,)')
Expression:
IDynamicMemberReferenceOperation (Member Name: "M2", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'M2')
Type Arguments(0)
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2')
Arguments(3):
IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o')
IOmittedArgumentOperation (OperationKind.OmittedArgument, Type: System.Object) (Syntax: '')
IOmittedArgumentOperation (OperationKind.OmittedArgument, Type: System.Object) (Syntax: '')
ArgumentNames(0)
ArgumentRefKinds: null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub Error_OmittingParamArrayArgument()
Dim source = <![CDATA[
Class P
Sub M1()
M2(0, )'BIND:"M2(0, )"
End Sub
Sub M2(x As Integer, ParamArray array As Integer())
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'M2(0, )')
Children(3):
IOperation: (OperationKind.None, Type: null) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
IOmittedArgumentOperation (OperationKind.OmittedArgument, Type: null, IsInvalid) (Syntax: '')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30588: Omitted argument cannot match a ParamArray parameter.
M2(0, )'BIND:"M2(0, )"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub Error_NamedArgumentMatchingParamArray()
Dim source = <![CDATA[
Class P
Sub M1()
Dim a = New Integer() {}
M2(x:=0, array:=a)'BIND:"M2(x:=0, array:=a)"
End Sub
Sub M2(x As Integer, ParamArray array As Integer())
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'M2(x:=0, array:=a)')
Children(3):
IOperation: (OperationKind.None, Type: null) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'a')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30587: Named argument cannot match a ParamArray parameter.
M2(x:=0, array:=a)'BIND:"M2(x:=0, array:=a)"
~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub Error_NamedArgumenNotExist()
Dim source = <![CDATA[
Class P
Sub M1()
M2(y:=1)'BIND:"M2(y:=1)"
End Sub
Sub M2(x As Integer)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'M2(y:=1)')
Children(2):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'M2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30455: Argument not specified for parameter 'x' of 'Public Sub M2(x As Integer)'.
M2(y:=1)'BIND:"M2(y:=1)"
~~
BC30272: 'y' is not a parameter of 'Public Sub M2(x As Integer)'.
M2(y:=1)'BIND:"M2(y:=1)"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub InOutConversion()
Dim source = <![CDATA[
Class Program
Sub M1()
Dim x = 1.0
M2(x)'BIND:"M2(x)"
End Sub
Sub M2(ByRef Optional a As Integer = 0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2([ByRef a As System.Int32 = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(x)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Double) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub InOutConversionUserDefined()
Dim source = <![CDATA[
Class C
Public Shared Widening Operator CType(ByVal c As C) As Integer
Return 0
End Operator
Public Shared Narrowing Operator CType(ByVal i As Integer) As C
Return New C()
End Operator
End Class
Class Program
Sub M1()
Dim x = New C()
M2(x)'BIND:"M2(x)"
End Sub
Sub M2(ByRef a As Integer)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2(ByRef a As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(x)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: C) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: Function C.op_Implicit(c As C) As System.Int32)
OutConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: Function C.op_Explicit(i As System.Int32) As C)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub InOutConversionUserDefinedWithIntermediateConversion()
Dim source = <![CDATA[
Class C
Public Shared Widening Operator CType(ByVal c As C) As Integer
Return 0
End Operator
Public Shared Narrowing Operator CType(ByVal i As Integer) As C
Return New C()
End Operator
End Class
Class Program
Sub M1()
Dim x = 2.0
M2(x)'BIND:"M2(x)"
End Sub
Sub M2(ByRef c As C)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2(ByRef c As C)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(x)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: c) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Double) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: Function C.op_Explicit(i As System.Int32) As C)
OutConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: Function C.op_Implicit(c As C) As System.Int32)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub InOutConversionUserDefinedMissingOperator()
Dim source = <![CDATA[
Class C
Public Shared Widening Operator CType(ByVal c As C) As Integer
Return 0
End Operator
End Class
Class Program
Sub M1()
Dim x = New C()
M2(x)'BIND:"M2(x)"
End Sub
Sub M2(ByRef a As Integer)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'M2(x)')
Children(2):
IOperation: (OperationKind.None, Type: null) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'x')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC33037: Cannot copy the value of 'ByRef' parameter 'a' back to the matching argument because type 'Integer' cannot be converted to type 'C'.
M2(x)'BIND:"M2(x)"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub GettingInOutConversionFromVBArgument()
Dim source = <![CDATA[
Class C
Public Shared Widening Operator CType(ByVal c As C) As Integer
Return 0
End Operator
Public Shared Narrowing Operator CType(ByVal i As Integer) As C
Return New C()
End Operator
End Class
Class Program
Sub M1()
Dim x = New C()
M2(x)'BIND:"M2(x)"
End Sub
Sub M2(ByRef a As Integer)
End Sub
End Class]]>.Value
Dim fileName = "a.vb"
Dim syntaxTree = Parse(source, fileName, options:=Nothing)
Dim compilation = CreateEmptyCompilation({syntaxTree}, DefaultVbReferences.Concat({ValueTupleRef, SystemRuntimeFacadeRef}))
Dim result = GetOperationAndSyntaxForTest(Of InvocationExpressionSyntax)(compilation, fileName)
Dim expectedInKind = ConversionKind.Widening Or ConversionKind.UserDefined
Dim expectedInMethod = compilation.GetSymbolsWithName(Function(name As String)
Return name = "op_Implicit"
End Function, SymbolFilter.Member).Single()
Dim expectedOutKind = ConversionKind.Narrowing Or ConversionKind.UserDefined
Dim expectedOutMethod = compilation.GetSymbolsWithName(Function(name As String)
Return name = "op_Explicit"
End Function, SymbolFilter.Member).Single()
Dim invocation = CType(result.operation, IInvocationOperation)
Dim argument = invocation.Arguments(0)
Dim inConversion = argument.GetInConversion()
Assert.Same(expectedInMethod, inConversion.MethodSymbol)
Assert.Equal(expectedInKind, inConversion.Kind)
Dim outConversion = argument.GetOutConversion()
Assert.Same(expectedOutMethod, outConversion.MethodSymbol)
Assert.Equal(expectedOutKind, outConversion.Kind)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TestCloneInOutConversion()
Dim source = <![CDATA[
Class C
Public Shared Widening Operator CType(ByVal c As C) As Integer
Return 0
End Operator
Public Shared Narrowing Operator CType(ByVal i As Integer) As C
Return New C()
End Operator
End Class
Class Program
Sub M1()
Dim x = New C()
Dim y = New C()
Dim z = New C()
M2(x, y, z)
End Sub
Sub M2(ByRef a As Integer, ByRef b As Double, ByRef c As C)
End Sub
End Class]]>.Value
Dim fileName = "a.vb"
Dim syntaxTree = Parse(source, fileName, options:=Nothing)
Dim compilation = CreateEmptyCompilation({syntaxTree}, DefaultVbReferences.Concat({ValueTupleRef, SystemRuntimeFacadeRef}))
Dim tree = (From t In compilation.SyntaxTrees Where t.FilePath = fileName).Single()
Dim model = compilation.GetSemanticModel(tree)
VerifyClone(model)
End Sub
<Fact>
Public Sub DirectlyBindArgument_InvocationExpression()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(1)'BIND:"1"
End Sub
Sub M2(a As Integer)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ArgumentSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub DirectlyBindParamsArgument1_InvocationExpression()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(1)'BIND:"M2(1)"
End Sub
Sub M2(paramarray a As Integer())
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M2(1)')
Expression:
IInvocationOperation ( Sub Program.M2(ParamArray a As System.Int32())) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(1):
IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(1)')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'M2(1)')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'M2(1)')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'M2(1)')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ExpressionStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub DirectlyBindParamsArgument2_InvocationExpression()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(0, 1)'BIND:"M2(0, 1)"
End Sub
Sub M2(paramarray a As Integer())
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M2(0, 1)')
Expression:
IInvocationOperation ( Sub Program.M2(ParamArray a As System.Int32())) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(0, 1)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(1):
IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(0, 1)')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'M2(0, 1)')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'M2(0, 1)')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'M2(0, 1)')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ExpressionStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub DirectlyBindOmittedArgument_InvocationExpression()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(1, , 2)'BIND:"M2(1, , 2)"
End Sub
Sub M2(a As Integer, Optional b As Integer = 0, Optional c As Integer = 0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M2(1, , 2)')
Expression:
IInvocationOperation ( Sub Program.M2(a As System.Int32, [b As System.Int32 = 0], [c As System.Int32 = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1, , 2)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: '')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: c) (OperationKind.Argument, Type: null) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ExpressionStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub DirectlyBindNAmedArgument1_InvocationExpression()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(b:=1, a:=1)'BIND:"b:=1"
End Sub
Sub M2(a As Integer, b as integer)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: 'b:=1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ArgumentSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub DirectlyBindNAmedArgument2_InvocationExpression()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(b:=1, a:=1)'BIND:"a:=1"
End Sub
Sub M2(a As Integer, b as integer)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: 'a:=1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ArgumentSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub DirectlyBindArgument_ObjectCreation()
Dim source = <![CDATA[
Class Program
Sub M1()
dim p = new Program(1)'BIND:"1"
End Sub
Sub new(a As Integer)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ArgumentSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub DirectlyBindParamsArgument1_ObjectCreation()
Dim source = <![CDATA[
Class Program
Sub M1()
Dim p = New Program(1)'BIND:"New Program(1)"
End Sub
Sub new(paramarray a As Integer())
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IObjectCreationOperation (Constructor: Sub Program..ctor(ParamArray a As System.Int32())) (OperationKind.ObjectCreation, Type: Program) (Syntax: 'New Program(1)')
Arguments(1):
IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Program')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'Program')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'Program')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'Program')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Initializer:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub DirectlyBindParamsArgument2_ObjectCreation()
Dim source = <![CDATA[
Class Program
Sub M1()
dim p = new Program(0, 1)'BIND:"new Program(0, 1)"
End Sub
Sub new(paramarray a As Integer())
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IObjectCreationOperation (Constructor: Sub Program..ctor(ParamArray a As System.Int32())) (OperationKind.ObjectCreation, Type: Program) (Syntax: 'new Program(0, 1)')
Arguments(1):
IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Program')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'Program')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'Program')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'Program')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Initializer:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact()>
Public Sub DirectlyBindArgument_RangeArgument()
Dim source = <![CDATA[
Module Program
Sub Main(args As String())
Dim a(0 To 20) As Integer'BIND:"Dim a(0 To 20) As Integer"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim a(0 To ... As Integer')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'a(0 To 20) As Integer')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Int32()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a(0 To 20)')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsImplicit) (Syntax: 'a(0 To 20)')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'a(0 To 20)')
Dimension Sizes(1):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, Constant: 21, IsImplicit) (Syntax: '0 To 20')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '0 To 20')
Initializer:
null
Initializer:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Operations
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Partial Public Class IOperationTests
Inherits SemanticModelTestBase
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub PositionalArgument()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(1, 0.0)'BIND:"M2(1, 0.0)"
End Sub
Sub M2(a As Integer, b As Double)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2(a As System.Int32, b As System.Double)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1, 0.0)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: '0.0')
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0) (Syntax: '0.0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub PositionalArgumentWithDefaultValue()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(1)'BIND:"M2(1)"
End Sub
Sub M2(a As Integer, Optional b As Double = 0.0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2(a As System.Int32, [b As System.Double = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2')
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0, IsImplicit) (Syntax: 'M2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub NamedArgumentListedInParameterOrder()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(a:=1, b:=1.0)'BIND:"M2(a:=1, b:=1.0)"
End Sub
Sub M2(a As Integer, Optional b As Double = 0.0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2(a As System.Int32, [b As System.Double = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(a:=1, b:=1.0)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: 'a:=1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: 'b:=1.0')
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 1) (Syntax: '1.0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub NamedArgumentListedOutOfParameterOrder()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(b:=1.0, a:=0)'BIND:"M2(b:=1.0, a:=0)"
End Sub
Sub M2(a As Integer, Optional b As Double = 0.0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2(a As System.Int32, [b As System.Double = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(b:=1.0, a:=0)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: 'a:=0')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: 'b:=1.0')
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 1) (Syntax: '1.0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub NamedArgumentInParameterOrderWithDefaultValue()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(b:=1.0, c:=2.0)'BIND:"M2(b:=1.0, c:=2.0)"
End Sub
Sub M2(Optional a As Integer = 0, Optional b As Double = 0.0, Optional c As Double = 0.0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2([a As System.Int32 = 0], [b As System.Double = 0], [c As System.Double = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(b:=1.0, c:=2.0)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(3):
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'M2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: 'b:=1.0')
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 1) (Syntax: '1.0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: c) (OperationKind.Argument, Type: null) (Syntax: 'c:=2.0')
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 2) (Syntax: '2.0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub NamedArgumentInParameterOrderWithDefaultValueUsingOmittedSyntax()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(, b:=1.0, c:=2.0)'BIND:"M2(, b:=1.0, c:=2.0)"
End Sub
Sub M2(Optional a As Integer = 0, Optional b As Double = 0.0, Optional c As Double = 0.0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2([a As System.Int32 = 0], [b As System.Double = 0], [c As System.Double = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(, b:=1.0, c:=2.0)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(3):
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: '')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: 'b:=1.0')
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 1) (Syntax: '1.0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: c) (OperationKind.Argument, Type: null) (Syntax: 'c:=2.0')
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 2) (Syntax: '2.0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub NamedArgumentOutOfParameterOrderWithDefaultValue()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(b:=2.0)'BIND:"M2(b:=2.0)"
End Sub
Sub M2(Optional a As Integer = 0, Optional b As Double = 0.0, Optional c As Double = 0.0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2([a As System.Int32 = 0], [b As System.Double = 0], [c As System.Double = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(b:=2.0)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(3):
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'M2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: 'b:=2.0')
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 2) (Syntax: '2.0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: c) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2')
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0, IsImplicit) (Syntax: 'M2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub NamedAndPositionalArgumentsWithDefaultValue()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(1, c:=2.0)'BIND:"M2(1, c:=2.0)"
End Sub
Sub M2(Optional a As Integer = 0, Optional b As Double = 0.0, Optional c As Double = 0.0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2([a As System.Int32 = 0], [b As System.Double = 0], [c As System.Double = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1, c:=2.0)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2')
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0, IsImplicit) (Syntax: 'M2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: c) (OperationKind.Argument, Type: null) (Syntax: 'c:=2.0')
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 2) (Syntax: '2.0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub PositionalByRefNonModifiableArgument()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(1)'BIND:"M2(1)"
End Sub
Sub M2(ByRef Optional a As Integer = 0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2([ByRef a As System.Int32 = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub PositionalByRefModifiableArgument()
Dim source = <![CDATA[
Class Program
Sub M1()
Dim x = 1
M2(x)'BIND:"M2(x)"
End Sub
Sub M2(ByRef Optional a As Integer = 0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2([ByRef a As System.Int32 = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(x)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub NamedByRefModifiableArgumentsOutOfParameterOrder()
Dim source = <![CDATA[
Class Program
Sub M1()
Dim x = 1
Dim y = 1.0
M2(b:=y, a:=x)'BIND:"M2(b:=y, a:=x)"
End Sub
Sub M2(ByRef Optional a As Integer = 0, ByRef Optional b As Double = 0.0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2([ByRef a As System.Int32 = 0], [ByRef b As System.Double = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(b:=y, a:=x)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: 'a:=x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: 'b:=y')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Double) (Syntax: 'y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub DefaultValueForByRefParameter()
Dim source = <![CDATA[
Class Program
Sub M1()
Dim x = 1.0
M2()'BIND:"M2()"
End Sub
Sub M2(ByRef Optional a As Integer = 0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2([ByRef a As System.Int32 = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(1):
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'M2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub PositionalByRefNonModifiableArgumentWithConversion()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(1.0)'BIND:"M2(1.0)"
End Sub
Sub M2(ByRef Optional a As Integer = 0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2([ByRef a As System.Int32 = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1.0)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: '1.0')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1.0')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 1) (Syntax: '1.0')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub PositionalByRefModifiableArgumentWithConversion()
Dim source = <![CDATA[
Class Program
Sub M1()
Dim x = 1.0
M2(x)'BIND:"M2(x)"
End Sub
Sub M2(ByRef Optional a As Integer = 0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2([ByRef a As System.Int32 = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(x)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Double) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub PositionalArgumentForExtensionMethod()
Dim source = <![CDATA[
Imports System.Runtime.CompilerServices
Class P
Sub M1()
E1(1, 2)'BIND:"E1(1, 2)"
End Sub
End Class
Module Extensions
<Extension()>
Public Sub E1(a As P, Optional b As Integer = 0, Optional c As Integer = 0)
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub P.E1([b As System.Int32 = 0], [c As System.Int32 = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'E1(1, 2)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'E1')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: c) (OperationKind.Argument, Type: null) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub NamedArgumentOutOfParameterOrderForExtensionMethod()
Dim source = <![CDATA[
Imports System.Runtime.CompilerServices
Class P
Sub M1()
E1(c:=1, b:=2)'BIND:"E1(c:=1, b:=2)"
End Sub
End Class
Module Extensions
<Extension()>
Public Sub E1(a As P, Optional b As Integer = 0, Optional c As Integer = 0)
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub P.E1([b As System.Int32 = 0], [c As System.Int32 = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'E1(c:=1, b:=2)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'E1')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: 'b:=2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: c) (OperationKind.Argument, Type: null) (Syntax: 'c:=1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub ParamsArrayArgumentInNormalForm()
Dim source = <![CDATA[
Class P
Sub M1()
Dim a = New Integer() {1, 2, 3}
M2(1, a)'BIND:"M2(1, a)"
End Sub
Sub M2(x As Integer, ParamArray y As Integer())
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub P.M2(x As System.Int32, ParamArray y As System.Int32())) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1, a)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'a')
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub ParamsArrayArgumentInExpandedForm()
Dim source = <![CDATA[
Class P
Sub M1()
M2(1, 2, 3)'BIND:"M2(1, 2, 3)"
End Sub
Sub M2(x As Integer, ParamArray y As Integer())
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub P.M2(x As System.Int32, ParamArray y As System.Int32())) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1, 2, 3)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: y) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(1, 2, 3)')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'M2(1, 2, 3)')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'M2(1, 2, 3)')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'M2(1, 2, 3)')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub ParamsArrayArgumentInExpandedFormWithNoArgument()
Dim source = <![CDATA[
Imports System.Runtime.CompilerServices
Class P
Sub M1()
M2(1)'BIND:"M2(1)"
End Sub
Sub M2(x As Integer, ParamArray y As Integer())
End Sub
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub P.M2(x As System.Int32, ParamArray y As System.Int32())) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: y) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(1)')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'M2(1)')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: 'M2(1)')
Initializer:
IArrayInitializerOperation (0 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'M2(1)')
Element Values(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub Error_MissingRequiredArgument()
Dim source = <![CDATA[
Class P
Sub M1()
M2()'BIND:"M2()"
End Sub
Sub M2(x As Integer, Optional y As Integer = 0, Optional z As Integer = 0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'M2()')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'M2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30455: Argument not specified for parameter 'x' of 'Public Sub M2(x As Integer, [y As Integer = 0], [z As Integer = 0])'.
M2()'BIND:"M2()"
~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub Error_TooManyArguments()
Dim source = <![CDATA[
Class P
Sub M1()
M2(1, 2)'BIND:"M2(1, 2)"
End Sub
Sub M2(x As Integer)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'M2(1, 2)')
Children(3):
IOperation: (OperationKind.None, Type: null) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30057: Too many arguments to 'Public Sub M2(x As Integer)'.
M2(1, 2)'BIND:"M2(1, 2)"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub Error_ExtraOmittedArgument()
Dim source = <![CDATA[
Class P
Sub M1()
M2(0,,,)'BIND:"M2(0,,,)"
End Sub
Sub M2(x As Integer, Optional y As Integer = 0, Optional z As Integer = 0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'M2(0,,,)')
Children(5):
IOperation: (OperationKind.None, Type: null) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
IOmittedArgumentOperation (OperationKind.OmittedArgument, Type: null) (Syntax: '')
IOmittedArgumentOperation (OperationKind.OmittedArgument, Type: null) (Syntax: '')
IOmittedArgumentOperation (OperationKind.OmittedArgument, Type: null, IsInvalid) (Syntax: '')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30057: Too many arguments to 'Public Sub M2(x As Integer, [y As Integer = 0], [z As Integer = 0])'.
M2(0,,,)'BIND:"M2(0,,,)"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub TestValidDynamicInvocation_OmittedArgument()
Dim source = <![CDATA[
Option Strict Off
Class P
Sub M1(o As Object)
M2(o,,)'BIND:"M2(o,,)"
End Sub
Sub M2(x As Integer, Optional y As Integer = 0, Optional z As Integer = 0)
End Sub
Sub M2(x As Double, Optional y As Integer = 0, Optional z As Integer = 0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: System.Object) (Syntax: 'M2(o,,)')
Expression:
IDynamicMemberReferenceOperation (Member Name: "M2", Containing Type: null) (OperationKind.DynamicMemberReference, Type: System.Object) (Syntax: 'M2')
Type Arguments(0)
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2')
Arguments(3):
IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'o')
IOmittedArgumentOperation (OperationKind.OmittedArgument, Type: System.Object) (Syntax: '')
IOmittedArgumentOperation (OperationKind.OmittedArgument, Type: System.Object) (Syntax: '')
ArgumentNames(0)
ArgumentRefKinds: null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub Error_OmittingParamArrayArgument()
Dim source = <![CDATA[
Class P
Sub M1()
M2(0, )'BIND:"M2(0, )"
End Sub
Sub M2(x As Integer, ParamArray array As Integer())
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'M2(0, )')
Children(3):
IOperation: (OperationKind.None, Type: null) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
IOmittedArgumentOperation (OperationKind.OmittedArgument, Type: null, IsInvalid) (Syntax: '')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30588: Omitted argument cannot match a ParamArray parameter.
M2(0, )'BIND:"M2(0, )"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub Error_NamedArgumentMatchingParamArray()
Dim source = <![CDATA[
Class P
Sub M1()
Dim a = New Integer() {}
M2(x:=0, array:=a)'BIND:"M2(x:=0, array:=a)"
End Sub
Sub M2(x As Integer, ParamArray array As Integer())
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'M2(x:=0, array:=a)')
Children(3):
IOperation: (OperationKind.None, Type: null) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsImplicit) (Syntax: 'M2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32()) (Syntax: 'a')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30587: Named argument cannot match a ParamArray parameter.
M2(x:=0, array:=a)'BIND:"M2(x:=0, array:=a)"
~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub Error_NamedArgumenNotExist()
Dim source = <![CDATA[
Class P
Sub M1()
M2(y:=1)'BIND:"M2(y:=1)"
End Sub
Sub M2(x As Integer)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'M2(y:=1)')
Children(2):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: P, IsInvalid, IsImplicit) (Syntax: 'M2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30455: Argument not specified for parameter 'x' of 'Public Sub M2(x As Integer)'.
M2(y:=1)'BIND:"M2(y:=1)"
~~
BC30272: 'y' is not a parameter of 'Public Sub M2(x As Integer)'.
M2(y:=1)'BIND:"M2(y:=1)"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub InOutConversion()
Dim source = <![CDATA[
Class Program
Sub M1()
Dim x = 1.0
M2(x)'BIND:"M2(x)"
End Sub
Sub M2(ByRef Optional a As Integer = 0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2([ByRef a As System.Int32 = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(x)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Double) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub InOutConversionUserDefined()
Dim source = <![CDATA[
Class C
Public Shared Widening Operator CType(ByVal c As C) As Integer
Return 0
End Operator
Public Shared Narrowing Operator CType(ByVal i As Integer) As C
Return New C()
End Operator
End Class
Class Program
Sub M1()
Dim x = New C()
M2(x)'BIND:"M2(x)"
End Sub
Sub M2(ByRef a As Integer)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2(ByRef a As System.Int32)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(x)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: C) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: Function C.op_Implicit(c As C) As System.Int32)
OutConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: Function C.op_Explicit(i As System.Int32) As C)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub InOutConversionUserDefinedWithIntermediateConversion()
Dim source = <![CDATA[
Class C
Public Shared Widening Operator CType(ByVal c As C) As Integer
Return 0
End Operator
Public Shared Narrowing Operator CType(ByVal i As Integer) As C
Return New C()
End Operator
End Class
Class Program
Sub M1()
Dim x = 2.0
M2(x)'BIND:"M2(x)"
End Sub
Sub M2(ByRef c As C)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvocationOperation ( Sub Program.M2(ByRef c As C)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(x)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: c) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Double) (Syntax: 'x')
InConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: Function C.op_Explicit(i As System.Int32) As C)
OutConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: Function C.op_Implicit(c As C) As System.Int32)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub InOutConversionUserDefinedMissingOperator()
Dim source = <![CDATA[
Class C
Public Shared Widening Operator CType(ByVal c As C) As Integer
Return 0
End Operator
End Class
Class Program
Sub M1()
Dim x = New C()
M2(x)'BIND:"M2(x)"
End Sub
Sub M2(ByRef a As Integer)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'M2(x)')
Children(2):
IOperation: (OperationKind.None, Type: null) (Syntax: 'M2')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'x')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC33037: Cannot copy the value of 'ByRef' parameter 'a' back to the matching argument because type 'Integer' cannot be converted to type 'C'.
M2(x)'BIND:"M2(x)"
~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub GettingInOutConversionFromVBArgument()
Dim source = <![CDATA[
Class C
Public Shared Widening Operator CType(ByVal c As C) As Integer
Return 0
End Operator
Public Shared Narrowing Operator CType(ByVal i As Integer) As C
Return New C()
End Operator
End Class
Class Program
Sub M1()
Dim x = New C()
M2(x)'BIND:"M2(x)"
End Sub
Sub M2(ByRef a As Integer)
End Sub
End Class]]>.Value
Dim fileName = "a.vb"
Dim syntaxTree = Parse(source, fileName, options:=Nothing)
Dim compilation = CreateEmptyCompilation({syntaxTree}, DefaultVbReferences.Concat({ValueTupleRef, SystemRuntimeFacadeRef}))
Dim result = GetOperationAndSyntaxForTest(Of InvocationExpressionSyntax)(compilation, fileName)
Dim expectedInKind = ConversionKind.Widening Or ConversionKind.UserDefined
Dim expectedInMethod = compilation.GetSymbolsWithName(Function(name As String)
Return name = "op_Implicit"
End Function, SymbolFilter.Member).Single()
Dim expectedOutKind = ConversionKind.Narrowing Or ConversionKind.UserDefined
Dim expectedOutMethod = compilation.GetSymbolsWithName(Function(name As String)
Return name = "op_Explicit"
End Function, SymbolFilter.Member).Single()
Dim invocation = CType(result.operation, IInvocationOperation)
Dim argument = invocation.Arguments(0)
Dim inConversion = argument.GetInConversion()
Assert.Same(expectedInMethod, inConversion.MethodSymbol)
Assert.Equal(expectedInKind, inConversion.Kind)
Dim outConversion = argument.GetOutConversion()
Assert.Same(expectedOutMethod, outConversion.MethodSymbol)
Assert.Equal(expectedOutKind, outConversion.Kind)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact>
Public Sub TestCloneInOutConversion()
Dim source = <![CDATA[
Class C
Public Shared Widening Operator CType(ByVal c As C) As Integer
Return 0
End Operator
Public Shared Narrowing Operator CType(ByVal i As Integer) As C
Return New C()
End Operator
End Class
Class Program
Sub M1()
Dim x = New C()
Dim y = New C()
Dim z = New C()
M2(x, y, z)
End Sub
Sub M2(ByRef a As Integer, ByRef b As Double, ByRef c As C)
End Sub
End Class]]>.Value
Dim fileName = "a.vb"
Dim syntaxTree = Parse(source, fileName, options:=Nothing)
Dim compilation = CreateEmptyCompilation({syntaxTree}, DefaultVbReferences.Concat({ValueTupleRef, SystemRuntimeFacadeRef}))
Dim tree = (From t In compilation.SyntaxTrees Where t.FilePath = fileName).Single()
Dim model = compilation.GetSemanticModel(tree)
VerifyClone(model)
End Sub
<Fact>
Public Sub DirectlyBindArgument_InvocationExpression()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(1)'BIND:"1"
End Sub
Sub M2(a As Integer)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ArgumentSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub DirectlyBindParamsArgument1_InvocationExpression()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(1)'BIND:"M2(1)"
End Sub
Sub M2(paramarray a As Integer())
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M2(1)')
Expression:
IInvocationOperation ( Sub Program.M2(ParamArray a As System.Int32())) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(1):
IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(1)')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'M2(1)')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'M2(1)')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'M2(1)')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ExpressionStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub DirectlyBindParamsArgument2_InvocationExpression()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(0, 1)'BIND:"M2(0, 1)"
End Sub
Sub M2(paramarray a As Integer())
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M2(0, 1)')
Expression:
IInvocationOperation ( Sub Program.M2(ParamArray a As System.Int32())) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(0, 1)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(1):
IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'M2(0, 1)')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'M2(0, 1)')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'M2(0, 1)')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'M2(0, 1)')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ExpressionStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub DirectlyBindOmittedArgument_InvocationExpression()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(1, , 2)'BIND:"M2(1, , 2)"
End Sub
Sub M2(a As Integer, Optional b As Integer = 0, Optional c As Integer = 0)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M2(1, , 2)')
Expression:
IInvocationOperation ( Sub Program.M2(a As System.Int32, [b As System.Int32 = 0], [c As System.Int32 = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M2(1, , 2)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsImplicit) (Syntax: 'M2')
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.DefaultValue, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: '')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsImplicit) (Syntax: '')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: c) (OperationKind.Argument, Type: null) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ExpressionStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub DirectlyBindNAmedArgument1_InvocationExpression()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(b:=1, a:=1)'BIND:"b:=1"
End Sub
Sub M2(a As Integer, b as integer)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null) (Syntax: 'b:=1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ArgumentSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub DirectlyBindNAmedArgument2_InvocationExpression()
Dim source = <![CDATA[
Class Program
Sub M1()
M2(b:=1, a:=1)'BIND:"a:=1"
End Sub
Sub M2(a As Integer, b as integer)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: 'a:=1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ArgumentSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub DirectlyBindArgument_ObjectCreation()
Dim source = <![CDATA[
Class Program
Sub M1()
dim p = new Program(1)'BIND:"1"
End Sub
Sub new(a As Integer)
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ArgumentSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub DirectlyBindParamsArgument1_ObjectCreation()
Dim source = <![CDATA[
Class Program
Sub M1()
Dim p = New Program(1)'BIND:"New Program(1)"
End Sub
Sub new(paramarray a As Integer())
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IObjectCreationOperation (Constructor: Sub Program..ctor(ParamArray a As System.Int32())) (OperationKind.ObjectCreation, Type: Program) (Syntax: 'New Program(1)')
Arguments(1):
IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Program')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'Program')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'Program')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'Program')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Initializer:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact>
Public Sub DirectlyBindParamsArgument2_ObjectCreation()
Dim source = <![CDATA[
Class Program
Sub M1()
dim p = new Program(0, 1)'BIND:"new Program(0, 1)"
End Sub
Sub new(paramarray a As Integer())
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IObjectCreationOperation (Constructor: Sub Program..ctor(ParamArray a As System.Int32())) (OperationKind.ObjectCreation, Type: Program) (Syntax: 'new Program(0, 1)')
Arguments(1):
IArgumentOperation (ArgumentKind.ParamArray, Matching Parameter: a) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Program')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'Program')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsImplicit) (Syntax: 'Program')
Initializer:
IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null, IsImplicit) (Syntax: 'Program')
Element Values(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Initializer:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of ObjectCreationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<Fact()>
Public Sub DirectlyBindArgument_RangeArgument()
Dim source = <![CDATA[
Module Program
Sub Main(args As String())
Dim a(0 To 20) As Integer'BIND:"Dim a(0 To 20) As Integer"
End Sub
End Module]]>.Value
Dim expectedOperationTree = <![CDATA[
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Dim a(0 To ... As Integer')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'a(0 To 20) As Integer')
Declarators:
IVariableDeclaratorOperation (Symbol: a As System.Int32()) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a(0 To 20)')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsImplicit) (Syntax: 'a(0 To 20)')
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32(), IsImplicit) (Syntax: 'a(0 To 20)')
Dimension Sizes(1):
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32, Constant: 21, IsImplicit) (Syntax: '0 To 20')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 20) (Syntax: '20')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '0 To 20')
Initializer:
null
Initializer:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of LocalDeclarationStatementSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Features/Core/Portable/Structure/BlockStructureServiceWithProviders.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Structure
{
internal abstract class BlockStructureServiceWithProviders : BlockStructureService
{
private readonly Workspace _workspace;
private readonly ImmutableArray<BlockStructureProvider> _providers;
protected BlockStructureServiceWithProviders(Workspace workspace)
{
_workspace = workspace;
_providers = GetBuiltInProviders().Concat(GetImportedProviders());
}
/// <summary>
/// Returns the providers always available to the service.
/// This does not included providers imported via MEF composition.
/// </summary>
protected virtual ImmutableArray<BlockStructureProvider> GetBuiltInProviders()
=> ImmutableArray<BlockStructureProvider>.Empty;
private ImmutableArray<BlockStructureProvider> GetImportedProviders()
{
var language = Language;
var mefExporter = (IMefHostExportProvider)_workspace.Services.HostServices;
var providers = mefExporter.GetExports<BlockStructureProvider, LanguageMetadata>()
.Where(lz => lz.Metadata.Language == language)
.Select(lz => lz.Value);
return providers.ToImmutableArray();
}
public override async Task<BlockStructure> GetBlockStructureAsync(
Document document,
CancellationToken cancellationToken)
{
var context = await CreateContextAsync(document, cancellationToken).ConfigureAwait(false);
return GetBlockStructure(context, _providers);
}
public BlockStructure GetBlockStructure(
SyntaxTree syntaxTree,
OptionSet options,
bool isMetadataAsSource,
CancellationToken cancellationToken)
{
var context = CreateContext(syntaxTree, options, isMetadataAsSource, cancellationToken);
return GetBlockStructure(context, _providers);
}
private static async Task<BlockStructureContext> CreateContextAsync(Document document, CancellationToken cancellationToken)
{
var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var options = document.Project.Solution.Options;
var isMetadataAsSource = document.Project.Solution.Workspace.Kind == WorkspaceKind.MetadataAsSource;
return CreateContext(syntaxTree, options, isMetadataAsSource, cancellationToken);
}
private static BlockStructureContext CreateContext(
SyntaxTree syntaxTree,
OptionSet options,
bool isMetadataAsSource,
CancellationToken cancellationToken)
{
var optionProvider = new BlockStructureOptionProvider(options, isMetadataAsSource);
return new BlockStructureContext(syntaxTree, optionProvider, cancellationToken);
}
private static BlockStructure GetBlockStructure(
BlockStructureContext context,
ImmutableArray<BlockStructureProvider> providers)
{
foreach (var provider in providers)
provider.ProvideBlockStructure(context);
return CreateBlockStructure(context);
}
private static BlockStructure CreateBlockStructure(BlockStructureContext context)
{
var language = context.SyntaxTree.Options.Language;
var showIndentGuidesForCodeLevelConstructs = context.OptionProvider.GetOption(BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, language);
var showIndentGuidesForDeclarationLevelConstructs = context.OptionProvider.GetOption(BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, language);
var showIndentGuidesForCommentsAndPreprocessorRegions = context.OptionProvider.GetOption(BlockStructureOptions.ShowBlockStructureGuidesForCommentsAndPreprocessorRegions, language);
var showOutliningForCodeLevelConstructs = context.OptionProvider.GetOption(BlockStructureOptions.ShowOutliningForCodeLevelConstructs, language);
var showOutliningForDeclarationLevelConstructs = context.OptionProvider.GetOption(BlockStructureOptions.ShowOutliningForDeclarationLevelConstructs, language);
var showOutliningForCommentsAndPreprocessorRegions = context.OptionProvider.GetOption(BlockStructureOptions.ShowOutliningForCommentsAndPreprocessorRegions, language);
using var _ = ArrayBuilder<BlockSpan>.GetInstance(out var updatedSpans);
foreach (var span in context.Spans)
{
var updatedSpan = UpdateBlockSpan(span,
showIndentGuidesForCodeLevelConstructs,
showIndentGuidesForDeclarationLevelConstructs,
showIndentGuidesForCommentsAndPreprocessorRegions,
showOutliningForCodeLevelConstructs,
showOutliningForDeclarationLevelConstructs,
showOutliningForCommentsAndPreprocessorRegions);
updatedSpans.Add(updatedSpan);
}
return new BlockStructure(updatedSpans.ToImmutable());
}
private static BlockSpan UpdateBlockSpan(BlockSpan blockSpan,
bool showIndentGuidesForCodeLevelConstructs,
bool showIndentGuidesForDeclarationLevelConstructs,
bool showIndentGuidesForCommentsAndPreprocessorRegions,
bool showOutliningForCodeLevelConstructs,
bool showOutliningForDeclarationLevelConstructs,
bool showOutliningForCommentsAndPreprocessorRegions)
{
var type = blockSpan.Type;
var isTopLevel = BlockTypes.IsDeclarationLevelConstruct(type);
var isMemberLevel = BlockTypes.IsCodeLevelConstruct(type);
var isComment = BlockTypes.IsCommentOrPreprocessorRegion(type);
if ((!showIndentGuidesForDeclarationLevelConstructs && isTopLevel) ||
(!showIndentGuidesForCodeLevelConstructs && isMemberLevel) ||
(!showIndentGuidesForCommentsAndPreprocessorRegions && isComment))
{
type = BlockTypes.Nonstructural;
}
var isCollapsible = blockSpan.IsCollapsible;
if (isCollapsible)
{
if ((!showOutliningForDeclarationLevelConstructs && isTopLevel) ||
(!showOutliningForCodeLevelConstructs && isMemberLevel) ||
(!showOutliningForCommentsAndPreprocessorRegions && isComment))
{
isCollapsible = false;
}
}
return blockSpan.With(type: type, isCollapsible: isCollapsible);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Structure
{
internal abstract class BlockStructureServiceWithProviders : BlockStructureService
{
private readonly Workspace _workspace;
private readonly ImmutableArray<BlockStructureProvider> _providers;
protected BlockStructureServiceWithProviders(Workspace workspace)
{
_workspace = workspace;
_providers = GetBuiltInProviders().Concat(GetImportedProviders());
}
/// <summary>
/// Returns the providers always available to the service.
/// This does not included providers imported via MEF composition.
/// </summary>
protected virtual ImmutableArray<BlockStructureProvider> GetBuiltInProviders()
=> ImmutableArray<BlockStructureProvider>.Empty;
private ImmutableArray<BlockStructureProvider> GetImportedProviders()
{
var language = Language;
var mefExporter = (IMefHostExportProvider)_workspace.Services.HostServices;
var providers = mefExporter.GetExports<BlockStructureProvider, LanguageMetadata>()
.Where(lz => lz.Metadata.Language == language)
.Select(lz => lz.Value);
return providers.ToImmutableArray();
}
public override async Task<BlockStructure> GetBlockStructureAsync(
Document document,
CancellationToken cancellationToken)
{
var context = await CreateContextAsync(document, cancellationToken).ConfigureAwait(false);
return GetBlockStructure(context, _providers);
}
public BlockStructure GetBlockStructure(
SyntaxTree syntaxTree,
OptionSet options,
bool isMetadataAsSource,
CancellationToken cancellationToken)
{
var context = CreateContext(syntaxTree, options, isMetadataAsSource, cancellationToken);
return GetBlockStructure(context, _providers);
}
private static async Task<BlockStructureContext> CreateContextAsync(Document document, CancellationToken cancellationToken)
{
var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var options = document.Project.Solution.Options;
var isMetadataAsSource = document.Project.Solution.Workspace.Kind == WorkspaceKind.MetadataAsSource;
return CreateContext(syntaxTree, options, isMetadataAsSource, cancellationToken);
}
private static BlockStructureContext CreateContext(
SyntaxTree syntaxTree,
OptionSet options,
bool isMetadataAsSource,
CancellationToken cancellationToken)
{
var optionProvider = new BlockStructureOptionProvider(options, isMetadataAsSource);
return new BlockStructureContext(syntaxTree, optionProvider, cancellationToken);
}
private static BlockStructure GetBlockStructure(
BlockStructureContext context,
ImmutableArray<BlockStructureProvider> providers)
{
foreach (var provider in providers)
provider.ProvideBlockStructure(context);
return CreateBlockStructure(context);
}
private static BlockStructure CreateBlockStructure(BlockStructureContext context)
{
var language = context.SyntaxTree.Options.Language;
var showIndentGuidesForCodeLevelConstructs = context.OptionProvider.GetOption(BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, language);
var showIndentGuidesForDeclarationLevelConstructs = context.OptionProvider.GetOption(BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, language);
var showIndentGuidesForCommentsAndPreprocessorRegions = context.OptionProvider.GetOption(BlockStructureOptions.ShowBlockStructureGuidesForCommentsAndPreprocessorRegions, language);
var showOutliningForCodeLevelConstructs = context.OptionProvider.GetOption(BlockStructureOptions.ShowOutliningForCodeLevelConstructs, language);
var showOutliningForDeclarationLevelConstructs = context.OptionProvider.GetOption(BlockStructureOptions.ShowOutliningForDeclarationLevelConstructs, language);
var showOutliningForCommentsAndPreprocessorRegions = context.OptionProvider.GetOption(BlockStructureOptions.ShowOutliningForCommentsAndPreprocessorRegions, language);
using var _ = ArrayBuilder<BlockSpan>.GetInstance(out var updatedSpans);
foreach (var span in context.Spans)
{
var updatedSpan = UpdateBlockSpan(span,
showIndentGuidesForCodeLevelConstructs,
showIndentGuidesForDeclarationLevelConstructs,
showIndentGuidesForCommentsAndPreprocessorRegions,
showOutliningForCodeLevelConstructs,
showOutliningForDeclarationLevelConstructs,
showOutliningForCommentsAndPreprocessorRegions);
updatedSpans.Add(updatedSpan);
}
return new BlockStructure(updatedSpans.ToImmutable());
}
private static BlockSpan UpdateBlockSpan(BlockSpan blockSpan,
bool showIndentGuidesForCodeLevelConstructs,
bool showIndentGuidesForDeclarationLevelConstructs,
bool showIndentGuidesForCommentsAndPreprocessorRegions,
bool showOutliningForCodeLevelConstructs,
bool showOutliningForDeclarationLevelConstructs,
bool showOutliningForCommentsAndPreprocessorRegions)
{
var type = blockSpan.Type;
var isTopLevel = BlockTypes.IsDeclarationLevelConstruct(type);
var isMemberLevel = BlockTypes.IsCodeLevelConstruct(type);
var isComment = BlockTypes.IsCommentOrPreprocessorRegion(type);
if ((!showIndentGuidesForDeclarationLevelConstructs && isTopLevel) ||
(!showIndentGuidesForCodeLevelConstructs && isMemberLevel) ||
(!showIndentGuidesForCommentsAndPreprocessorRegions && isComment))
{
type = BlockTypes.Nonstructural;
}
var isCollapsible = blockSpan.IsCollapsible;
if (isCollapsible)
{
if ((!showOutliningForDeclarationLevelConstructs && isTopLevel) ||
(!showOutliningForCodeLevelConstructs && isMemberLevel) ||
(!showOutliningForCommentsAndPreprocessorRegions && isComment))
{
isCollapsible = false;
}
}
return blockSpan.With(type: type, isCollapsible: isCollapsible);
}
}
}
| -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Compilers/CSharp/Test/Semantic/Semantics/UsingDeclarationTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.UnitTests;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.Semantics
{
/// <summary>
/// Tests related to binding (but not lowering) using declarations (i.e. using var x = ...).
/// </summary>
public class UsingDeclarationTests : CompilingTestBase
{
[Fact]
public void UsingVariableIsNotReportedAsUnused()
{
var source = @"
using System;
class C
{
static void Main()
{
using var x = (IDisposable)null;
}
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void DisallowGoToForwardAcrossUsingDeclarations()
{
var source = @"
using System;
class C
{
static void Main()
{
goto label1;
using var x = (IDisposable)null;
label1:
return;
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (7,9): error CS8641: A goto target within the same block can not cross a using declaration.
// goto label1;
Diagnostic(ErrorCode.ERR_GoToForwardJumpOverUsingVar, "goto label1;").WithLocation(7, 9),
// (8,9): warning CS0162: Unreachable code detected
// using var x = (IDisposable)null;
Diagnostic(ErrorCode.WRN_UnreachableCode, "using").WithLocation(8, 9)
);
}
[Fact]
public void DisallowGoToForwardAcrossUsingDeclarationsFromLowerBlock()
{
var source = @"
using System;
class C
{
static void Main()
{
{
goto label1;
}
using var x = (IDisposable)null;
label1:
return;
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (7,9): error CS8641: A goto target within the same block can not cross a using declaration.
// goto label1;
Diagnostic(ErrorCode.ERR_GoToForwardJumpOverUsingVar, "goto label1;").WithLocation(8, 13),
// (8,9): warning CS0162: Unreachable code detected
// using var x = (IDisposable)null;
Diagnostic(ErrorCode.WRN_UnreachableCode, "using").WithLocation(10, 9)
);
}
[Fact]
public void DisallowGoToForwardAcrossMultipleUsingDeclarationsGivesOnlyOneDiagnostic()
{
var source = @"
using System;
class C
{
static void Main()
{
goto label1;
using var x = (IDisposable)null;
using var y = (IDisposable)null;
label1:
return;
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (7,9): error CS8641: A goto target within the same block can not cross a using declaration.
// goto label1;
Diagnostic(ErrorCode.ERR_GoToForwardJumpOverUsingVar, "goto label1;").WithLocation(7, 9),
// (8,9): warning CS0162: Unreachable code detected
// using var x = (IDisposable)null;
Diagnostic(ErrorCode.WRN_UnreachableCode, "using").WithLocation(8, 9)
);
}
[Fact]
public void DisallowMultipleGoToForwardAcrossMultipleUsingDeclarations()
{
var source = @"
using System;
class C
{
static void Main()
{
goto label1;
using var x = (IDisposable)null;
goto label2;
using var y = (IDisposable)null;
label1:
label2:
return;
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (7,9): error CS8641: A goto target within the same block can not cross a using declaration.
// goto label1;
Diagnostic(ErrorCode.ERR_GoToForwardJumpOverUsingVar, "goto label1;").WithLocation(7, 9),
// (8,9): warning CS0162: Unreachable code detected
// using var x = (IDisposable)null;
Diagnostic(ErrorCode.WRN_UnreachableCode, "using").WithLocation(8, 9),
// (9,9): error CS8641: A goto target can not be after any using declarations.
// goto label2;
Diagnostic(ErrorCode.ERR_GoToForwardJumpOverUsingVar, "goto label2;").WithLocation(9, 9)
);
}
[Fact]
public void DisallowGoToBackwardsAcrossUsingDeclarationsWhenLabelIsInTheSameScope()
{
var source = @"
using System;
class C
{
static void Main()
{
label1:
using var x = (IDisposable)null;
goto label1;
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (10,9): error CS8641: A goto target within the same block can not cross a using declaration.
// goto label1;
Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label1;").WithLocation(10, 9)
);
}
[Fact]
public void DisallowGoToBackwardsAcrossUsingDeclarationsWithMultipleLabels()
{
var source = @"
using System;
class C
{
static void Main()
{
label1:
label2:
label3:
using var x = (IDisposable)null;
goto label3; // disallowed
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (7,9): warning CS0164: This label has not been referenced
// label1:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label1").WithLocation(7, 9),
// (8,9): warning CS0164: This label has not been referenced
// label2:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label2").WithLocation(8, 9),
// (10,9): error CS8641: A goto target within the same block can not cross a using declaration.
// goto label3; // disallowed
Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label3;").WithLocation(12, 9)
);
}
[Fact]
public void DisallowGoToAcrossUsingDeclarationsComplexTest()
{
var source = @"
using System;
#pragma warning disable 162 // disable unreachable code warnings
class C
{
static void Main()
{
label1:
{
label2:
using var a = (IDisposable)null;
goto label1; // allowed
goto label2; // disallowed 1
}
label3:
using var b = (IDisposable)null;
{
goto label3; // disallowed 2
}
{
goto label4; // allowed
goto label5; // disallowed 3
label4:
using var c = (IDisposable)null;
label5:
using var d = (IDisposable)null;
}
using var e = (IDisposable)null;
label6:
{
{
goto label6; //allowed
label7:
{
label8:
using var f = (IDisposable)null;
goto label7; // allowed
{
using var g = (IDisposable)null;
goto label7; //allowed
goto label8; // disallowed 4
}
}
}
}
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (14,13): error CS8642: A goto cannot jump to a location before a using declaration within the same block.
// goto label2; // disallowed 1
Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label2;").WithLocation(14, 13),
// (20,13): error CS8642: A goto cannot jump to a location before a using declaration within the same block.
// goto label3; // disallowed 2
Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label3;").WithLocation(20, 13),
// (25,13): error CS8641: A goto cannot jump to a location after a using declaration.
// goto label5; // disallowed 3
Diagnostic(ErrorCode.ERR_GoToForwardJumpOverUsingVar, "goto label5;").WithLocation(25, 13),
// (45,25): error CS8642: A goto cannot jump to a location before a using declaration within the same block.
// goto label8; // disallowed 4
Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label8;").WithLocation(45, 25)
);
}
[Fact]
public void AllowGoToAroundUsingDeclarations()
{
var source = @"
using System;
class C
{
static void Main()
{
goto label1;
label1:
using var x = (IDisposable)null;
goto label2;
label2:
return;
}
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void AllowGoToBackwardsAcrossUsingDeclarationsWhenLabelIsInHigherScope()
{
var source = @"
using System;
class C
{
static void Main()
{
label1:
{
using var x = (IDisposable)null;
goto label1;
}
}
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void AllowGoToForwardsAcrossUsingDeclarationsInALowerBlock()
{
var source = @"
using System;
class C
{
static void Main()
{
goto label1;
{
using var x = (IDisposable)null;
}
label1: ;
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (8,9): warning CS0162: Unreachable code detected
// using var x = (IDisposable)null;
Diagnostic(ErrorCode.WRN_UnreachableCode, "using").WithLocation(9, 13)
);
}
[Fact]
public void AllowGoToBackwardsAcrossUsingDeclarationsInALowerBlock()
{
var source = @"
using System;
class C
{
static void Main()
{
label1:
{
using var x = (IDisposable)null;
}
goto label1;
}
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void UsingVariableCanBeInitializedWithExistingDisposable()
{
var source = @"
using System;
class C2 : IDisposable
{
public void Dispose()
{
Console.Write(""Disposed; "");
}
}
class C
{
static void Main()
{
var x = new C2();
using var x2 = x;
using var x3 = x2;
x = null;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "Disposed; Disposed; ");
}
[Fact]
public void UsingVariableCanBeInitializedWithExistingDisposableInASingleStatement()
{
var source = @"
using System;
class C2 : IDisposable
{
public void Dispose()
{
Console.Write(""Disposed; "");
}
}
class C
{
static void Main()
{
using C2 x = new C2(), x2 = x;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "Disposed; Disposed; ");
}
[Fact]
public void UsingVariableCanBeInitializedWithExistingRefStructDisposable()
{
var source = @"
using System;
ref struct C2
{
public void Dispose()
{
Console.Write(""Disposed; "");
}
}
class C
{
static void Main()
{
var x = new C2();
using var x2 = x;
using var x3 = x2;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "Disposed; Disposed; ");
}
[Fact]
public void UsingVariableCannotBeReAssigned()
{
var source = @"
using System;
class C
{
static void Main()
{
using var x = (IDisposable)null;
x = null;
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (8,9): error CS1656: Cannot assign to 'x' because it is a 'using variable'
// x = null;
Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "x").WithArguments("x", "using variable").WithLocation(8, 9)
);
}
[Fact]
public void UsingVariableCannotBeUsedAsOutVariable()
{
var source = @"
using System;
class C
{
static void Consume(out IDisposable x)
{
x = null;
}
static void Main()
{
using var x = (IDisposable)null;
Consume(out x);
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (13,21): error CS1657: Cannot use 'x' as a ref or out value because it is a 'using variable'
// Consume(out x);
Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "x").WithArguments("x", "using variable").WithLocation(13, 21)
);
}
[Fact]
public void UsingVariableMustHaveInitializer()
{
var source = @"
using System;
class C
{
static void Main()
{
using IDisposable x;
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (7,27): error CS0210: You must provide an initializer in a fixed or using statement declaration
// using IDisposable x;
Diagnostic(ErrorCode.ERR_FixedMustInit, "x").WithLocation(7, 27)
);
}
[Fact]
public void UsingVariableFromExistingVariable()
{
var source = @"
using System;
class C
{
static void Main()
{
var x = (IDisposable)null;
using var x2 = x;
}
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void UsingVariableFromExpression()
{
var source = @"
using System;
class C
{
static IDisposable GetDisposable()
{
return null;
}
static void Main()
{
using IDisposable x = GetDisposable();
}
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void UsingVariableFromAwaitExpression()
{
var source = @"
using System;
using System.Threading.Tasks;
class C
{
static Task<IDisposable> GetDisposable()
{
return Task.FromResult<IDisposable>(null);
}
static async Task Main()
{
using IDisposable x = await GetDisposable();
}
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void UsingVariableInSwitchCase()
{
var source = @"
using System;
class C1 : IDisposable
{
public void Dispose() { }
}
class C2
{
public static void Main()
{
int x = 5;
switch (x)
{
case 5:
using C1 o1 = new C1();
break;
}
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (15,21): error CS8389: A using variable cannot be used directly within a switch section (consider using braces).
// using C1 o1 = new C1();
Diagnostic(ErrorCode.ERR_UsingVarInSwitchCase, "using C1 o1 = new C1();").WithLocation(15, 17)
);
}
[Fact]
public void UsingVariableDiagnosticsInDeclarationAreOnlyEmittedOnce()
{
var source = @"
using System;
class C1 : IDisposable
{
public void Dispose() { }
}
class C2
{
public static void Main()
{
using var c1 = new C1(), c2 = new C2();
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (11,15): error CS0819: Implicitly-typed variables cannot have multiple declarators
// using var c1 = new C1(), c2 = new C2();
Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, "var c1 = new C1(), c2 = new C2()").WithLocation(11, 15)
);
}
[Fact]
public void UsingDeclarationWithAwaitsInAsync()
{
var source = @"
using System;
using System.Threading.Tasks;
class C2 : IDisposable
{
public string ID { get; set; }
public void Dispose()
{
Console.Write($""Dispose {ID}; "");
}
}
class C
{
static async Task<IDisposable> GetDisposable(string id)
{
await Task.Yield();
return new C2(){ ID = id };
}
static async Task Main()
{
using IDisposable x = await GetDisposable(""c1"");
await Task.Yield();
Console.Write(""after c1; "");
using IDisposable y = await GetDisposable(""c2"");
Console.Write(""after c2; "");
}
}
";
var compilation = CreateCompilationWithTasksExtensions(source, options: TestOptions.DebugExe).VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "after c1; after c2; Dispose c2; Dispose c1; ");
}
[Fact]
public void UsingDeclarationsWithLangVer7_3()
{
var source = @"
using System;
class C
{
static void Main()
{
using IDisposable x = null;
}
}
";
var expected = new[]
{
// (7,9): error CS8652: The feature 'using declarations' is not available in C# 7.3. Please use language version 8.0 or greater.
// using IDisposable x = null;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "using").WithArguments("using declarations", "8.0").WithLocation(7, 9)
};
CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(expected);
CreateCompilation(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics();
}
[Fact]
public void AwaitUsingDeclarationsWithLangVer7_3()
{
var source = @"
using System;
using System.Threading.Tasks;
class C
{
static async Task Main()
{
await using IAsyncDisposable x = null;
}
}
";
var expected = new[]
{
// (8,15): error CS8652: The feature 'using declarations' is not available in C# 7.3. Please use language version 8.0 or greater.
// await using IAsyncDisposable x = null;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "using").WithArguments("using declarations", "8.0").WithLocation(8, 15)
};
CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(expected);
CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, parseOptions: TestOptions.Regular8).VerifyDiagnostics();
}
[Fact]
public void UsingDeclarationsWithObsoleteTypes()
{
var source = @"
using System;
[Obsolete]
class C1 : IDisposable
{
[Obsolete]
public void Dispose()
{
}
}
class C2 : IDisposable
{
[Obsolete]
public void Dispose()
{
}
}
ref struct S3
{
[Obsolete]
public void Dispose()
{
}
}
class C4
{
static void Main()
{
// c1 is obsolete
using C1 c1 = new C1();
// no warning, we don't warn on dispose being obsolete because it comes through interface
using C2 c2 = new C2();
// warning, we're calling the pattern based obsolete method for the ref struct
using S3 S3 = new S3();
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (34,15): warning CS0612: 'C1' is obsolete
// using C1 c1 = new C1();
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "C1").WithArguments("C1").WithLocation(34, 15),
// (34,27): warning CS0612: 'C1' is obsolete
// using C1 c1 = new C1();
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "C1").WithArguments("C1").WithLocation(34, 27),
// (40,15): warning CS0612: 'S3.Dispose()' is obsolete
// using S3 S3 = new S3();
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "using S3 S3 = new S3();").WithArguments("S3.Dispose()").WithLocation(40, 9)
);
}
[Fact]
[WorkItem(36413, "https://github.com/dotnet/roslyn/issues/36413")]
public void UsingDeclarationsWithInvalidModifiers()
{
var source = @"
using System;
class C
{
static void Main()
{
using public readonly var x = (IDisposable)null;
}
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics(
// (7,15): error CS0106: The modifier 'public' is not valid for this item
// using public readonly var x = (IDisposable)null;
Diagnostic(ErrorCode.ERR_BadMemberFlag, "public").WithArguments("public").WithLocation(7, 15),
// (7,22): error CS0106: The modifier 'readonly' is not valid for this item
// using public readonly var x = (IDisposable)null;
Diagnostic(ErrorCode.ERR_BadMemberFlag, "readonly").WithArguments("readonly").WithLocation(7, 22)
);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.UnitTests;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.Semantics
{
/// <summary>
/// Tests related to binding (but not lowering) using declarations (i.e. using var x = ...).
/// </summary>
public class UsingDeclarationTests : CompilingTestBase
{
[Fact]
public void UsingVariableIsNotReportedAsUnused()
{
var source = @"
using System;
class C
{
static void Main()
{
using var x = (IDisposable)null;
}
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void DisallowGoToForwardAcrossUsingDeclarations()
{
var source = @"
using System;
class C
{
static void Main()
{
goto label1;
using var x = (IDisposable)null;
label1:
return;
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (7,9): error CS8641: A goto target within the same block can not cross a using declaration.
// goto label1;
Diagnostic(ErrorCode.ERR_GoToForwardJumpOverUsingVar, "goto label1;").WithLocation(7, 9),
// (8,9): warning CS0162: Unreachable code detected
// using var x = (IDisposable)null;
Diagnostic(ErrorCode.WRN_UnreachableCode, "using").WithLocation(8, 9)
);
}
[Fact]
public void DisallowGoToForwardAcrossUsingDeclarationsFromLowerBlock()
{
var source = @"
using System;
class C
{
static void Main()
{
{
goto label1;
}
using var x = (IDisposable)null;
label1:
return;
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (7,9): error CS8641: A goto target within the same block can not cross a using declaration.
// goto label1;
Diagnostic(ErrorCode.ERR_GoToForwardJumpOverUsingVar, "goto label1;").WithLocation(8, 13),
// (8,9): warning CS0162: Unreachable code detected
// using var x = (IDisposable)null;
Diagnostic(ErrorCode.WRN_UnreachableCode, "using").WithLocation(10, 9)
);
}
[Fact]
public void DisallowGoToForwardAcrossMultipleUsingDeclarationsGivesOnlyOneDiagnostic()
{
var source = @"
using System;
class C
{
static void Main()
{
goto label1;
using var x = (IDisposable)null;
using var y = (IDisposable)null;
label1:
return;
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (7,9): error CS8641: A goto target within the same block can not cross a using declaration.
// goto label1;
Diagnostic(ErrorCode.ERR_GoToForwardJumpOverUsingVar, "goto label1;").WithLocation(7, 9),
// (8,9): warning CS0162: Unreachable code detected
// using var x = (IDisposable)null;
Diagnostic(ErrorCode.WRN_UnreachableCode, "using").WithLocation(8, 9)
);
}
[Fact]
public void DisallowMultipleGoToForwardAcrossMultipleUsingDeclarations()
{
var source = @"
using System;
class C
{
static void Main()
{
goto label1;
using var x = (IDisposable)null;
goto label2;
using var y = (IDisposable)null;
label1:
label2:
return;
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (7,9): error CS8641: A goto target within the same block can not cross a using declaration.
// goto label1;
Diagnostic(ErrorCode.ERR_GoToForwardJumpOverUsingVar, "goto label1;").WithLocation(7, 9),
// (8,9): warning CS0162: Unreachable code detected
// using var x = (IDisposable)null;
Diagnostic(ErrorCode.WRN_UnreachableCode, "using").WithLocation(8, 9),
// (9,9): error CS8641: A goto target can not be after any using declarations.
// goto label2;
Diagnostic(ErrorCode.ERR_GoToForwardJumpOverUsingVar, "goto label2;").WithLocation(9, 9)
);
}
[Fact]
public void DisallowGoToBackwardsAcrossUsingDeclarationsWhenLabelIsInTheSameScope()
{
var source = @"
using System;
class C
{
static void Main()
{
label1:
using var x = (IDisposable)null;
goto label1;
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (10,9): error CS8641: A goto target within the same block can not cross a using declaration.
// goto label1;
Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label1;").WithLocation(10, 9)
);
}
[Fact]
public void DisallowGoToBackwardsAcrossUsingDeclarationsWithMultipleLabels()
{
var source = @"
using System;
class C
{
static void Main()
{
label1:
label2:
label3:
using var x = (IDisposable)null;
goto label3; // disallowed
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (7,9): warning CS0164: This label has not been referenced
// label1:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label1").WithLocation(7, 9),
// (8,9): warning CS0164: This label has not been referenced
// label2:
Diagnostic(ErrorCode.WRN_UnreferencedLabel, "label2").WithLocation(8, 9),
// (10,9): error CS8641: A goto target within the same block can not cross a using declaration.
// goto label3; // disallowed
Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label3;").WithLocation(12, 9)
);
}
[Fact]
public void DisallowGoToAcrossUsingDeclarationsComplexTest()
{
var source = @"
using System;
#pragma warning disable 162 // disable unreachable code warnings
class C
{
static void Main()
{
label1:
{
label2:
using var a = (IDisposable)null;
goto label1; // allowed
goto label2; // disallowed 1
}
label3:
using var b = (IDisposable)null;
{
goto label3; // disallowed 2
}
{
goto label4; // allowed
goto label5; // disallowed 3
label4:
using var c = (IDisposable)null;
label5:
using var d = (IDisposable)null;
}
using var e = (IDisposable)null;
label6:
{
{
goto label6; //allowed
label7:
{
label8:
using var f = (IDisposable)null;
goto label7; // allowed
{
using var g = (IDisposable)null;
goto label7; //allowed
goto label8; // disallowed 4
}
}
}
}
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (14,13): error CS8642: A goto cannot jump to a location before a using declaration within the same block.
// goto label2; // disallowed 1
Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label2;").WithLocation(14, 13),
// (20,13): error CS8642: A goto cannot jump to a location before a using declaration within the same block.
// goto label3; // disallowed 2
Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label3;").WithLocation(20, 13),
// (25,13): error CS8641: A goto cannot jump to a location after a using declaration.
// goto label5; // disallowed 3
Diagnostic(ErrorCode.ERR_GoToForwardJumpOverUsingVar, "goto label5;").WithLocation(25, 13),
// (45,25): error CS8642: A goto cannot jump to a location before a using declaration within the same block.
// goto label8; // disallowed 4
Diagnostic(ErrorCode.ERR_GoToBackwardJumpOverUsingVar, "goto label8;").WithLocation(45, 25)
);
}
[Fact]
public void AllowGoToAroundUsingDeclarations()
{
var source = @"
using System;
class C
{
static void Main()
{
goto label1;
label1:
using var x = (IDisposable)null;
goto label2;
label2:
return;
}
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void AllowGoToBackwardsAcrossUsingDeclarationsWhenLabelIsInHigherScope()
{
var source = @"
using System;
class C
{
static void Main()
{
label1:
{
using var x = (IDisposable)null;
goto label1;
}
}
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void AllowGoToForwardsAcrossUsingDeclarationsInALowerBlock()
{
var source = @"
using System;
class C
{
static void Main()
{
goto label1;
{
using var x = (IDisposable)null;
}
label1: ;
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (8,9): warning CS0162: Unreachable code detected
// using var x = (IDisposable)null;
Diagnostic(ErrorCode.WRN_UnreachableCode, "using").WithLocation(9, 13)
);
}
[Fact]
public void AllowGoToBackwardsAcrossUsingDeclarationsInALowerBlock()
{
var source = @"
using System;
class C
{
static void Main()
{
label1:
{
using var x = (IDisposable)null;
}
goto label1;
}
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void UsingVariableCanBeInitializedWithExistingDisposable()
{
var source = @"
using System;
class C2 : IDisposable
{
public void Dispose()
{
Console.Write(""Disposed; "");
}
}
class C
{
static void Main()
{
var x = new C2();
using var x2 = x;
using var x3 = x2;
x = null;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "Disposed; Disposed; ");
}
[Fact]
public void UsingVariableCanBeInitializedWithExistingDisposableInASingleStatement()
{
var source = @"
using System;
class C2 : IDisposable
{
public void Dispose()
{
Console.Write(""Disposed; "");
}
}
class C
{
static void Main()
{
using C2 x = new C2(), x2 = x;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "Disposed; Disposed; ");
}
[Fact]
public void UsingVariableCanBeInitializedWithExistingRefStructDisposable()
{
var source = @"
using System;
ref struct C2
{
public void Dispose()
{
Console.Write(""Disposed; "");
}
}
class C
{
static void Main()
{
var x = new C2();
using var x2 = x;
using var x3 = x2;
}
}
";
var compilation = CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "Disposed; Disposed; ");
}
[Fact]
public void UsingVariableCannotBeReAssigned()
{
var source = @"
using System;
class C
{
static void Main()
{
using var x = (IDisposable)null;
x = null;
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (8,9): error CS1656: Cannot assign to 'x' because it is a 'using variable'
// x = null;
Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "x").WithArguments("x", "using variable").WithLocation(8, 9)
);
}
[Fact]
public void UsingVariableCannotBeUsedAsOutVariable()
{
var source = @"
using System;
class C
{
static void Consume(out IDisposable x)
{
x = null;
}
static void Main()
{
using var x = (IDisposable)null;
Consume(out x);
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (13,21): error CS1657: Cannot use 'x' as a ref or out value because it is a 'using variable'
// Consume(out x);
Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "x").WithArguments("x", "using variable").WithLocation(13, 21)
);
}
[Fact]
public void UsingVariableMustHaveInitializer()
{
var source = @"
using System;
class C
{
static void Main()
{
using IDisposable x;
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (7,27): error CS0210: You must provide an initializer in a fixed or using statement declaration
// using IDisposable x;
Diagnostic(ErrorCode.ERR_FixedMustInit, "x").WithLocation(7, 27)
);
}
[Fact]
public void UsingVariableFromExistingVariable()
{
var source = @"
using System;
class C
{
static void Main()
{
var x = (IDisposable)null;
using var x2 = x;
}
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void UsingVariableFromExpression()
{
var source = @"
using System;
class C
{
static IDisposable GetDisposable()
{
return null;
}
static void Main()
{
using IDisposable x = GetDisposable();
}
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void UsingVariableFromAwaitExpression()
{
var source = @"
using System;
using System.Threading.Tasks;
class C
{
static Task<IDisposable> GetDisposable()
{
return Task.FromResult<IDisposable>(null);
}
static async Task Main()
{
using IDisposable x = await GetDisposable();
}
}
";
CreateCompilation(source).VerifyDiagnostics();
}
[Fact]
public void UsingVariableInSwitchCase()
{
var source = @"
using System;
class C1 : IDisposable
{
public void Dispose() { }
}
class C2
{
public static void Main()
{
int x = 5;
switch (x)
{
case 5:
using C1 o1 = new C1();
break;
}
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (15,21): error CS8389: A using variable cannot be used directly within a switch section (consider using braces).
// using C1 o1 = new C1();
Diagnostic(ErrorCode.ERR_UsingVarInSwitchCase, "using C1 o1 = new C1();").WithLocation(15, 17)
);
}
[Fact]
public void UsingVariableDiagnosticsInDeclarationAreOnlyEmittedOnce()
{
var source = @"
using System;
class C1 : IDisposable
{
public void Dispose() { }
}
class C2
{
public static void Main()
{
using var c1 = new C1(), c2 = new C2();
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (11,15): error CS0819: Implicitly-typed variables cannot have multiple declarators
// using var c1 = new C1(), c2 = new C2();
Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, "var c1 = new C1(), c2 = new C2()").WithLocation(11, 15)
);
}
[Fact]
public void UsingDeclarationWithAwaitsInAsync()
{
var source = @"
using System;
using System.Threading.Tasks;
class C2 : IDisposable
{
public string ID { get; set; }
public void Dispose()
{
Console.Write($""Dispose {ID}; "");
}
}
class C
{
static async Task<IDisposable> GetDisposable(string id)
{
await Task.Yield();
return new C2(){ ID = id };
}
static async Task Main()
{
using IDisposable x = await GetDisposable(""c1"");
await Task.Yield();
Console.Write(""after c1; "");
using IDisposable y = await GetDisposable(""c2"");
Console.Write(""after c2; "");
}
}
";
var compilation = CreateCompilationWithTasksExtensions(source, options: TestOptions.DebugExe).VerifyDiagnostics();
CompileAndVerify(compilation, expectedOutput: "after c1; after c2; Dispose c2; Dispose c1; ");
}
[Fact]
public void UsingDeclarationsWithLangVer7_3()
{
var source = @"
using System;
class C
{
static void Main()
{
using IDisposable x = null;
}
}
";
var expected = new[]
{
// (7,9): error CS8652: The feature 'using declarations' is not available in C# 7.3. Please use language version 8.0 or greater.
// using IDisposable x = null;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "using").WithArguments("using declarations", "8.0").WithLocation(7, 9)
};
CreateCompilation(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(expected);
CreateCompilation(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics();
}
[Fact]
public void AwaitUsingDeclarationsWithLangVer7_3()
{
var source = @"
using System;
using System.Threading.Tasks;
class C
{
static async Task Main()
{
await using IAsyncDisposable x = null;
}
}
";
var expected = new[]
{
// (8,15): error CS8652: The feature 'using declarations' is not available in C# 7.3. Please use language version 8.0 or greater.
// await using IAsyncDisposable x = null;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "using").WithArguments("using declarations", "8.0").WithLocation(8, 15)
};
CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics(expected);
CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, parseOptions: TestOptions.Regular8).VerifyDiagnostics();
}
[Fact]
public void UsingDeclarationsWithObsoleteTypes()
{
var source = @"
using System;
[Obsolete]
class C1 : IDisposable
{
[Obsolete]
public void Dispose()
{
}
}
class C2 : IDisposable
{
[Obsolete]
public void Dispose()
{
}
}
ref struct S3
{
[Obsolete]
public void Dispose()
{
}
}
class C4
{
static void Main()
{
// c1 is obsolete
using C1 c1 = new C1();
// no warning, we don't warn on dispose being obsolete because it comes through interface
using C2 c2 = new C2();
// warning, we're calling the pattern based obsolete method for the ref struct
using S3 S3 = new S3();
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (34,15): warning CS0612: 'C1' is obsolete
// using C1 c1 = new C1();
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "C1").WithArguments("C1").WithLocation(34, 15),
// (34,27): warning CS0612: 'C1' is obsolete
// using C1 c1 = new C1();
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "C1").WithArguments("C1").WithLocation(34, 27),
// (40,15): warning CS0612: 'S3.Dispose()' is obsolete
// using S3 S3 = new S3();
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "using S3 S3 = new S3();").WithArguments("S3.Dispose()").WithLocation(40, 9)
);
}
[Fact]
[WorkItem(36413, "https://github.com/dotnet/roslyn/issues/36413")]
public void UsingDeclarationsWithInvalidModifiers()
{
var source = @"
using System;
class C
{
static void Main()
{
using public readonly var x = (IDisposable)null;
}
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics(
// (7,15): error CS0106: The modifier 'public' is not valid for this item
// using public readonly var x = (IDisposable)null;
Diagnostic(ErrorCode.ERR_BadMemberFlag, "public").WithArguments("public").WithLocation(7, 15),
// (7,22): error CS0106: The modifier 'readonly' is not valid for this item
// using public readonly var x = (IDisposable)null;
Diagnostic(ErrorCode.ERR_BadMemberFlag, "readonly").WithArguments("readonly").WithLocation(7, 22)
);
}
}
}
| -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Compilers/VisualBasic/Portable/Compilation/SyntaxTreeSemanticModel.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.Concurrent
Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports System.Collections.ObjectModel
Imports System.IO
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Operations
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Allows asking semantic questions about any node in a SyntaxTree within a Compilation.
''' </summary>
Friend Class SyntaxTreeSemanticModel
Inherits VBSemanticModel
Private ReadOnly _compilation As VisualBasicCompilation
Private ReadOnly _sourceModule As SourceModuleSymbol
Private ReadOnly _syntaxTree As SyntaxTree
Private ReadOnly _binderFactory As BinderFactory
Private ReadOnly _ignoresAccessibility As Boolean
' maps from a higher-level binder to an appropriate SemanticModel for the construct (such as a method, or initializer).
Private ReadOnly _semanticModelCache As New ConcurrentDictionary(Of (binder As Binder, ignoresAccessibility As Boolean), MemberSemanticModel)()
Friend Sub New(compilation As VisualBasicCompilation, sourceModule As SourceModuleSymbol, syntaxTree As SyntaxTree, Optional ignoreAccessibility As Boolean = False)
_compilation = compilation
_sourceModule = sourceModule
_syntaxTree = syntaxTree
_ignoresAccessibility = ignoreAccessibility
_binderFactory = New BinderFactory(sourceModule, syntaxTree)
End Sub
''' <summary>
''' The compilation associated with this binding.
''' </summary>
Public Overrides ReadOnly Property Compilation As VisualBasicCompilation
Get
Return _compilation
End Get
End Property
''' <summary>
''' The root node of the syntax tree that this binding is based on.
''' </summary>
Friend Overrides ReadOnly Property Root As SyntaxNode
Get
Return DirectCast(_syntaxTree.GetRoot(), VisualBasicSyntaxNode)
End Get
End Property
''' <summary>
''' The SyntaxTree that is bound
''' </summary>
Public Overrides ReadOnly Property SyntaxTree As SyntaxTree
Get
Return Me._syntaxTree
End Get
End Property
''' <summary>
''' Returns true if this Is a SemanticModel that ignores accessibility rules when answering semantic questions.
''' </summary>
Public NotOverridable Overrides ReadOnly Property IgnoresAccessibility As Boolean
Get
Return Me._ignoresAccessibility
End Get
End Property
''' <summary>
''' Get all the errors within the syntax tree associated with this object. Includes errors involving compiling
''' method bodies or initializers, in addition to the errors returned by GetDeclarationDiagnostics and parse errors.
''' </summary>
''' <param name="span">Optional span within the syntax tree for which to get diagnostics.
''' If no argument is specified, then diagnostics for the entire tree are returned.</param>
''' <param name="cancellationToken">A cancellation token that can be used to cancel the process of obtaining the
''' diagnostics.</param>
''' <remarks>
''' Because this method must semantically analyze all method bodies and initializers to check for diagnostics, it may
''' take a significant amount of time. Unlike GetDeclarationDiagnostics, diagnostics for method bodies and
''' initializers are not cached, the any semantic information used to obtain the diagnostics is discarded.
''' </remarks>
Public Overrides Function GetDiagnostics(Optional span As TextSpan? = Nothing, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic)
Return _compilation.GetDiagnosticsForSyntaxTree(CompilationStage.Compile, _syntaxTree, span, includeEarlierStages:=True, cancellationToken:=cancellationToken)
End Function
''' <summary>
''' Get all of the syntax errors within the syntax tree associated with this
''' object. Does not get errors involving declarations or compiling method bodies or initializers.
''' </summary>
''' <param name="span">Optional span within the syntax tree for which to get diagnostics.
''' If no argument is specified, then diagnostics for the entire tree are returned.</param>
''' <param name="cancellationToken">A cancellation token that can be used to cancel the
''' process of obtaining the diagnostics.</param>
Public Overrides Function GetSyntaxDiagnostics(Optional span As TextSpan? = Nothing, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic)
Return _compilation.GetDiagnosticsForSyntaxTree(CompilationStage.Parse, _syntaxTree, span, includeEarlierStages:=False, cancellationToken:=cancellationToken)
End Function
''' <summary>
''' Get all the syntax and declaration errors within the syntax tree associated with this object. Does not get
''' errors involving compiling method bodies or initializers.
''' </summary>
''' <param name="span">Optional span within the syntax tree for which to get diagnostics.
''' If no argument is specified, then diagnostics for the entire tree are returned.</param>
''' <param name="cancellationToken">A cancellation token that can be used to cancel the process of obtaining the
''' diagnostics.</param>
''' <remarks>The declaration errors for a syntax tree are cached. The first time this method is called, a ll
''' declarations are analyzed for diagnostics. Calling this a second time will return the cached diagnostics.
''' </remarks>
Public Overrides Function GetDeclarationDiagnostics(Optional span As TextSpan? = Nothing, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic)
Return _compilation.GetDiagnosticsForSyntaxTree(CompilationStage.Declare, _syntaxTree, span, includeEarlierStages:=False, cancellationToken:=cancellationToken)
End Function
''' <summary>
''' Get all the syntax and declaration errors within the syntax tree associated with this object. Does not get
''' errors involving compiling method bodies or initializers.
''' </summary>
''' <param name="span">Optional span within the syntax tree for which to get diagnostics.
''' If no argument is specified, then diagnostics for the entire tree are returned.</param>
''' <param name="cancellationToken">A cancellation token that can be used to cancel the process of obtaining the
''' diagnostics.</param>
''' <remarks>The declaration errors for a syntax tree are cached. The first time this method is called, a ll
''' declarations are analyzed for diagnostics. Calling this a second time will return the cached diagnostics.
''' </remarks>
Public Overrides Function GetMethodBodyDiagnostics(Optional span As TextSpan? = Nothing, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic)
Return _compilation.GetDiagnosticsForSyntaxTree(CompilationStage.Compile, _syntaxTree, span, includeEarlierStages:=False, cancellationToken:=cancellationToken)
End Function
' PERF: These variables avoid repeated allocation of Func(Of Binder, MemberSemanticModel) in GetMemberSemanticModel
Private ReadOnly _methodBodySemanticModelCreator As Func(Of (binder As Binder, ignoresAccessibility As Boolean), MemberSemanticModel) = Function(key As (binder As Binder, ignoresAccessibility As Boolean)) MethodBodySemanticModel.Create(Me, DirectCast(key.binder, SubOrFunctionBodyBinder), key.ignoresAccessibility)
Private ReadOnly _initializerSemanticModelCreator As Func(Of (binder As Binder, ignoresAccessibility As Boolean), MemberSemanticModel) = Function(key As (binder As Binder, ignoresAccessibility As Boolean)) InitializerSemanticModel.Create(Me, DirectCast(key.binder, DeclarationInitializerBinder), key.ignoresAccessibility)
Private ReadOnly _attributeSemanticModelCreator As Func(Of (binder As Binder, ignoresAccessibility As Boolean), MemberSemanticModel) = Function(key As (binder As Binder, ignoresAccessibility As Boolean)) AttributeSemanticModel.Create(Me, DirectCast(key.binder, AttributeBinder), key.ignoresAccessibility)
Public Function GetMemberSemanticModel(binder As Binder) As MemberSemanticModel
If TypeOf binder Is MethodBodyBinder Then
Return _semanticModelCache.GetOrAdd((binder, IgnoresAccessibility), _methodBodySemanticModelCreator)
End If
If TypeOf binder Is DeclarationInitializerBinder Then
Return _semanticModelCache.GetOrAdd((binder, IgnoresAccessibility), _initializerSemanticModelCreator)
End If
If TypeOf binder Is AttributeBinder Then
Return _semanticModelCache.GetOrAdd((binder, IgnoresAccessibility), _attributeSemanticModelCreator)
End If
If TypeOf binder Is TopLevelCodeBinder Then
Return _semanticModelCache.GetOrAdd((binder, IgnoresAccessibility), _methodBodySemanticModelCreator)
End If
Return Nothing
End Function
Friend Function GetMemberSemanticModel(position As Integer) As MemberSemanticModel
Dim binder As binder = _binderFactory.GetBinderForPosition(FindInitialNodeFromPosition(position), position)
Dim model = GetMemberSemanticModel(binder) ' Depends on the runtime type, so don't wrap in a SemanticModelBinder.
Debug.Assert(model Is Nothing OrElse model.RootBinder.IsSemanticModelBinder)
Return model
End Function
Friend Function GetMemberSemanticModel(node As SyntaxNode) As MemberSemanticModel
Return GetMemberSemanticModel(node.SpanStart)
End Function
Friend Overrides Function GetEnclosingBinder(position As Integer) As Binder
' special case if node is from interior of a member declaration (method body, etc)
Dim model As MemberSemanticModel = GetMemberSemanticModel(position)
If model IsNot Nothing Then
' If the node is from the interior of a member declaration, then we need to go further
' to find more nested binders.
Return model.GetEnclosingBinder(position)
Else
Dim binder As binder = _binderFactory.GetBinderForPosition(FindInitialNodeFromPosition(position), position)
Return SemanticModelBinder.Mark(binder, IgnoresAccessibility)
End If
End Function
Friend Overrides Function GetInvokeSummaryForRaiseEvent(node As RaiseEventStatementSyntax) As BoundNodeSummary
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
If model IsNot Nothing Then
Return model.GetInvokeSummaryForRaiseEvent(node)
Else
Return Nothing
End If
End Function
Friend Overrides Function GetCrefReferenceSymbolInfo(crefReference As CrefReferenceSyntax, options As VBSemanticModel.SymbolInfoOptions, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo
ValidateSymbolInfoOptions(options)
Debug.Assert(IsInCrefOrNameAttributeInterior(crefReference))
Return GetSymbolInfoForCrefOrNameAttributeReference(crefReference, options)
End Function
Friend Overrides Function GetExpressionSymbolInfo(node As ExpressionSyntax, options As SymbolInfoOptions, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo
ValidateSymbolInfoOptions(options)
node = SyntaxFactory.GetStandaloneExpression(DirectCast(node, ExpressionSyntax))
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
Dim result As SymbolInfo
If model IsNot Nothing Then
result = model.GetExpressionSymbolInfo(node, options, cancellationToken)
' If we didn't get anything and were in Type/Namespace only context, let's bind normally and see
' if any symbol comes out.
If result.IsEmpty AndAlso SyntaxFacts.IsInNamespaceOrTypeContext(node) Then
Dim tryAsExpression = TryBindNamespaceOrTypeAsExpression(node, options)
If Not tryAsExpression.IsEmpty Then
result = tryAsExpression
End If
End If
Else
' We don't have a bound tree to examine outside of a member semantic model. Instead, we just
' rebind the appropriate syntax as if we were binding it as part of symbol creation.
'
' if expression is not part of a member semantic model then
' a) it may be a reference to a type or namespace name
' b) it may be a reference to a interface member in an Implements clause
' c) it may be a reference to a field in an Handles clause
' d) it may be a reference to an event in an Handles clause
If SyntaxFacts.IsImplementedMember(node) Then
result = GetImplementedMemberSymbolInfo(DirectCast(node, QualifiedNameSyntax), options)
ElseIf SyntaxFacts.IsHandlesEvent(node) Then
result = GetHandlesEventSymbolInfo(DirectCast(node.Parent, HandlesClauseItemSyntax), options)
ElseIf SyntaxFacts.IsHandlesContainer(node) Then
Dim parent = node.Parent
If parent.Kind <> SyntaxKind.HandlesClauseItem Then
parent = parent.Parent
End If
result = GetHandlesContainerSymbolInfo(DirectCast(parent, HandlesClauseItemSyntax), options)
ElseIf SyntaxFacts.IsHandlesProperty(node) Then
result = GetHandlesPropertySymbolInfo(DirectCast(node.Parent.Parent, HandlesClauseItemSyntax), options)
ElseIf IsInCrefOrNameAttributeInterior(node) Then
result = GetSymbolInfoForCrefOrNameAttributeReference(node, options)
ElseIf SyntaxFacts.IsInNamespaceOrTypeContext(node) Then
' Bind the type or namespace name.
result = GetTypeOrNamespaceSymbolInfoNotInMember(DirectCast(node, TypeSyntax), options)
Else
result = SymbolInfo.None
End If
End If
Return result
End Function
Friend Overrides Function GetCollectionInitializerAddSymbolInfo(collectionInitializer As ObjectCreationExpressionSyntax, node As ExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(collectionInitializer)
If model IsNot Nothing Then
Return model.GetCollectionInitializerAddSymbolInfo(collectionInitializer, node, cancellationToken)
End If
Return SymbolInfo.None
End Function
Private Function TryBindNamespaceOrTypeAsExpression(node As ExpressionSyntax, options As SymbolInfoOptions) As SymbolInfo
' Let's bind expression normally and use what comes back as candidate symbols.
Dim binder As Binder = GetEnclosingBinder(node.SpanStart)
If binder IsNot Nothing Then
Dim bound As BoundExpression = binder.BindExpression(node, BindingDiagnosticBag.Discarded)
Dim newSymbolInfo = GetSymbolInfoForNode(options, New BoundNodeSummary(bound, bound, Nothing), binderOpt:=Nothing)
If Not newSymbolInfo.GetAllSymbols().IsDefaultOrEmpty Then
Return SymbolInfoFactory.Create(newSymbolInfo.GetAllSymbols(), LookupResultKind.NotATypeOrNamespace)
End If
End If
Return SymbolInfo.None
End Function
Friend Overrides Function GetExpressionTypeInfo(node As ExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As VisualBasicTypeInfo
node = SyntaxFactory.GetStandaloneExpression(DirectCast(node, ExpressionSyntax))
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
If model IsNot Nothing Then
Return model.GetExpressionTypeInfo(node, cancellationToken)
Else
' We don't have a bound tree to examine outside of a member semantic model. Instead, we just
' rebind the appropriate syntax as if we were binding it as part of symbol creation.
'
' if expression is not part of a member semantic model then
' a) it may be a reference to a type or namespace name
' b) it may be a reference to a interface member in an Implements clause
' c) it may be a reference to a field in an Handles clause
' d) it may be a reference to an event in an Handles clause
If SyntaxFacts.IsImplementedMember(node) Then
Return GetImplementedMemberTypeInfo(DirectCast(node, QualifiedNameSyntax))
ElseIf SyntaxFacts.IsHandlesEvent(node) Then
Return GetHandlesEventTypeInfo(DirectCast(node, IdentifierNameSyntax))
ElseIf SyntaxFacts.IsHandlesContainer(node) Then
Dim parent = node.Parent
If parent.Kind <> SyntaxKind.HandlesClauseItem Then
parent = parent.Parent
End If
Return GetHandlesContainerTypeInfo(DirectCast(parent, HandlesClauseItemSyntax))
ElseIf SyntaxFacts.IsHandlesProperty(node) Then
Return GetHandlesPropertyTypeInfo(DirectCast(node.Parent.Parent, HandlesClauseItemSyntax))
ElseIf IsInCrefOrNameAttributeInterior(node) Then
Dim typeSyntax = TryCast(node, TypeSyntax)
If typeSyntax IsNot Nothing Then
Return GetTypeInfoForCrefOrNameAttributeReference(typeSyntax)
End If
ElseIf SyntaxFacts.IsInNamespaceOrTypeContext(node) Then
' Bind the type or namespace name.
Return GetTypeOrNamespaceTypeInfoNotInMember(DirectCast(node, TypeSyntax))
End If
Return VisualBasicTypeInfo.None
End If
End Function
Friend Overrides Function GetExpressionMemberGroup(node As ExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Symbol)
node = SyntaxFactory.GetStandaloneExpression(DirectCast(node, ExpressionSyntax))
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
If model IsNot Nothing Then
Return model.GetExpressionMemberGroup(node, cancellationToken)
Else
Return ImmutableArray(Of Symbol).Empty
End If
End Function
Friend Overrides Function GetExpressionConstantValue(node As ExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As ConstantValue
node = SyntaxFactory.GetStandaloneExpression(DirectCast(node, ExpressionSyntax))
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
If model IsNot Nothing Then
Return model.GetExpressionConstantValue(node, cancellationToken)
Else
Return Nothing
End If
End Function
Friend Overrides Function GetOperationWorker(node As VisualBasicSyntaxNode, cancellationToken As CancellationToken) As IOperation
Dim model As MemberSemanticModel
Dim methodBlock = TryCast(node, MethodBlockBaseSyntax)
If methodBlock IsNot Nothing Then
' Trying to get the MemberSemanticModel for a MethodBlock will end up returning
' nothing. That's because trying to get Binder for the MethodBlock will actually
' return the binder for the containing type. To avoid this we ask for the model
' passing in a position at the end of the method's starting block-statement.
' This will cause it to try to get the interior MemberSemanticModel.
model = GetMemberSemanticModel(methodBlock.BlockStatement.EndPosition)
Else
model = Me.GetMemberSemanticModel(node)
End If
If model IsNot Nothing Then
Return model.GetOperationWorker(node, cancellationToken)
Else
Return Nothing
End If
End Function
Friend Overrides Function GetAttributeSymbolInfo(attribute As AttributeSyntax, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(attribute)
If model IsNot Nothing Then
Return model.GetAttributeSymbolInfo(attribute, cancellationToken)
Else
Return SymbolInfo.None
End If
End Function
Friend Overrides Function GetQueryClauseSymbolInfo(node As QueryClauseSyntax, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
If model IsNot Nothing Then
Return model.GetQueryClauseSymbolInfo(node, cancellationToken)
Else
Return SymbolInfo.None
End If
End Function
Friend Overrides Function GetLetClauseSymbolInfo(node As ExpressionRangeVariableSyntax, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
If model IsNot Nothing Then
Return model.GetLetClauseSymbolInfo(node, cancellationToken)
Else
Return SymbolInfo.None
End If
End Function
Friend Overrides Function GetOrderingSymbolInfo(node As OrderingSyntax, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
If model IsNot Nothing Then
Return model.GetOrderingSymbolInfo(node, cancellationToken)
Else
Return SymbolInfo.None
End If
End Function
Friend Overrides Function GetAggregateClauseSymbolInfoWorker(node As AggregateClauseSyntax, Optional cancellationToken As CancellationToken = Nothing) As AggregateClauseSymbolInfo
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
If model IsNot Nothing Then
Return model.GetAggregateClauseSymbolInfoWorker(node, cancellationToken)
Else
Return New AggregateClauseSymbolInfo(SymbolInfo.None, SymbolInfo.None)
End If
End Function
Friend Overrides Function GetCollectionRangeVariableSymbolInfoWorker(node As CollectionRangeVariableSyntax, Optional cancellationToken As CancellationToken = Nothing) As CollectionRangeVariableSymbolInfo
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
If model IsNot Nothing Then
Return model.GetCollectionRangeVariableSymbolInfoWorker(node, cancellationToken)
Else
Return CollectionRangeVariableSymbolInfo.None
End If
End Function
Friend Overrides Function GetAttributeTypeInfo(attribute As AttributeSyntax, Optional cancellationToken As CancellationToken = Nothing) As VisualBasicTypeInfo
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(attribute)
If model IsNot Nothing Then
Return model.GetAttributeTypeInfo(attribute, cancellationToken)
Else
Return VisualBasicTypeInfo.None
End If
End Function
Friend Overrides Function GetAttributeMemberGroup(attribute As AttributeSyntax, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Symbol)
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(attribute)
If model IsNot Nothing Then
Return model.GetAttributeMemberGroup(attribute, cancellationToken)
Else
Return ImmutableArray(Of Symbol).Empty
End If
End Function
Private Function GetTypeOrNamespaceSymbolNotInMember(expression As TypeSyntax) As Symbol
' Set up the binding context.
Dim binder As Binder = GetEnclosingBinder(expression.SpanStart)
' Attempt to bind the type or namespace
Dim resultSymbol As Symbol
If SyntaxFacts.IsInTypeOnlyContext(expression) Then
resultSymbol = binder.BindTypeOrAliasSyntax(expression, BindingDiagnosticBag.Discarded)
Else
resultSymbol = binder.BindNamespaceOrTypeOrAliasSyntax(expression, BindingDiagnosticBag.Discarded)
End If
' Create the result.
Return resultSymbol
End Function
' Get the symbol info of reference from 'cref' or 'name' attribute value
Private Function GetSymbolInfoForCrefOrNameAttributeReference(node As VisualBasicSyntaxNode, options As SymbolInfoOptions) As SymbolInfo
Dim typeParameters As ImmutableArray(Of Symbol) = Nothing
Dim result As ImmutableArray(Of Symbol) = GetCrefOrNameAttributeReferenceSymbols(node, (options And SymbolInfoOptions.ResolveAliases) = 0, typeParameters)
If result.IsDefaultOrEmpty Then
If typeParameters.IsDefaultOrEmpty Then
Return SymbolInfo.None
Else
Return SymbolInfoFactory.Create(typeParameters, LookupResultKind.NotReferencable)
End If
End If
If result.Length = 1 Then
Dim retValue As SymbolInfo = GetSymbolInfoForSymbol(result(0), options)
If retValue.CandidateReason = CandidateReason.None Then
Return retValue
End If
result = ImmutableArray(Of Symbol).Empty
End If
Dim symbolsBuilder = ArrayBuilder(Of Symbol).GetInstance()
symbolsBuilder.AddRange(result)
Dim symbols As ImmutableArray(Of Symbol) = RemoveErrorTypesAndDuplicates(symbolsBuilder, options)
symbolsBuilder.Free()
If symbols.Length = 0 Then
Return SymbolInfoFactory.Create(symbols, LookupResultKind.Empty)
End If
Return SymbolInfoFactory.Create(symbols, If(symbols.Length = 1, LookupResultKind.Good, LookupResultKind.Ambiguous))
End Function
' Get the type info of reference from 'cref' or 'name' attribute value
Private Function GetTypeInfoForCrefOrNameAttributeReference(name As TypeSyntax) As VisualBasicTypeInfo
Dim typeParameters As ImmutableArray(Of Symbol) = Nothing
Dim result As ImmutableArray(Of Symbol) = GetCrefOrNameAttributeReferenceSymbols(name, preserveAlias:=False, typeParameters:=typeParameters)
If result.IsDefaultOrEmpty Then
result = typeParameters
If result.IsDefaultOrEmpty Then
Return VisualBasicTypeInfo.None
End If
End If
If result.Length > 1 Then
Return VisualBasicTypeInfo.None
End If
Dim resultSymbol As Symbol = result(0)
Select Case resultSymbol.Kind
Case SymbolKind.ArrayType,
SymbolKind.TypeParameter,
SymbolKind.NamedType
Return GetTypeInfoForSymbol(resultSymbol)
End Select
Return VisualBasicTypeInfo.None
End Function
''' <summary>
''' Get symbols referenced from 'cref' or 'name' attribute value.
''' </summary>
''' <param name="node">Node to bind.</param>
''' <param name="preserveAlias">True to leave <see cref="AliasSymbol"/>s, False to unwrap them.</param>
''' <param name="typeParameters">Out: symbols that would have been in the return value but improperly refer to type parameters.</param>
''' <returns>Referenced symbols, less type parameters.</returns>
Private Function GetCrefOrNameAttributeReferenceSymbols(node As VisualBasicSyntaxNode,
preserveAlias As Boolean,
<Out> ByRef typeParameters As ImmutableArray(Of Symbol)) As ImmutableArray(Of Symbol)
typeParameters = ImmutableArray(Of Symbol).Empty
' We only allow a certain list of node kinds to be processed here
If node.Kind = SyntaxKind.XmlString Then
Return Nothing
End If
Debug.Assert(node.Kind = SyntaxKind.IdentifierName OrElse
node.Kind = SyntaxKind.GenericName OrElse
node.Kind = SyntaxKind.PredefinedType OrElse
node.Kind = SyntaxKind.QualifiedName OrElse
node.Kind = SyntaxKind.GlobalName OrElse
node.Kind = SyntaxKind.QualifiedCrefOperatorReference OrElse
node.Kind = SyntaxKind.CrefOperatorReference OrElse
node.Kind = SyntaxKind.CrefReference)
' We need to find trivia's enclosing binder first
Dim parent As VisualBasicSyntaxNode = node.Parent
Debug.Assert(parent IsNot Nothing)
Dim attributeNode As BaseXmlAttributeSyntax = Nothing
Do
Debug.Assert(parent IsNot Nothing)
Select Case parent.Kind
Case SyntaxKind.XmlCrefAttribute,
SyntaxKind.XmlNameAttribute
attributeNode = DirectCast(parent, BaseXmlAttributeSyntax)
Case SyntaxKind.DocumentationCommentTrivia
Exit Do
End Select
parent = parent.Parent
Loop
Debug.Assert(parent IsNot Nothing)
If attributeNode Is Nothing Then
Return Nothing
End If
Dim isCrefAttribute As Boolean = attributeNode.Kind = SyntaxKind.XmlCrefAttribute
Debug.Assert(isCrefAttribute OrElse attributeNode.Kind = SyntaxKind.XmlNameAttribute)
Dim trivia As SyntaxTrivia = DirectCast(parent, DocumentationCommentTriviaSyntax).ParentTrivia
If trivia.Kind = SyntaxKind.None Then
Return Nothing
End If
Dim token As SyntaxToken = CType(trivia.Token, SyntaxToken)
If token.Kind = SyntaxKind.None Then
Return Nothing
End If
Dim docCommentBinder = Me._binderFactory.GetBinderForPosition(node, node.SpanStart)
docCommentBinder = SemanticModelBinder.Mark(docCommentBinder, IgnoresAccessibility)
If isCrefAttribute Then
Dim symbols As ImmutableArray(Of Symbol)
Dim isTopLevel As Boolean
If node.Kind = SyntaxKind.CrefReference Then
isTopLevel = True
symbols = docCommentBinder.BindInsideCrefAttributeValue(DirectCast(node, CrefReferenceSyntax), preserveAlias, Nothing, CompoundUseSiteInfo(Of AssemblySymbol).Discarded)
Else
isTopLevel = node.Parent IsNot Nothing AndAlso node.Parent.Kind = SyntaxKind.CrefReference
symbols = docCommentBinder.BindInsideCrefAttributeValue(DirectCast(node, TypeSyntax), preserveAlias, Nothing, CompoundUseSiteInfo(Of AssemblySymbol).Discarded)
End If
If isTopLevel Then
Dim symbolsBuilder As ArrayBuilder(Of Symbol) = Nothing
Dim typeParametersBuilder As ArrayBuilder(Of Symbol) = Nothing
For i = 0 To symbols.Length - 1
Dim symbol = symbols(i)
If symbol.Kind = SymbolKind.TypeParameter Then
If symbolsBuilder Is Nothing Then
symbolsBuilder = ArrayBuilder(Of Symbol).GetInstance(i)
typeParametersBuilder = ArrayBuilder(Of Symbol).GetInstance()
symbolsBuilder.AddRange(symbols, i)
End If
typeParametersBuilder.Add(DirectCast(symbol, TypeParameterSymbol))
ElseIf symbolsBuilder IsNot Nothing Then
symbolsBuilder.Add(symbol)
End If
Next
If symbolsBuilder IsNot Nothing Then
symbols = symbolsBuilder.ToImmutableAndFree()
typeParameters = typeParametersBuilder.ToImmutableAndFree()
End If
End If
Return symbols
Else
Return docCommentBinder.BindXmlNameAttributeValue(DirectCast(node, IdentifierNameSyntax), useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded)
End If
End Function
' Get the symbol info of type or namespace syntax that is outside a member body
Private Function GetTypeOrNamespaceSymbolInfoNotInMember(expression As TypeSyntax, options As SymbolInfoOptions) As SymbolInfo
Dim resultSymbol As Symbol = GetTypeOrNamespaceSymbolNotInMember(expression)
' Deal with the case of a namespace group. We may need to bind more in order to see if the ambiguity can be resolved.
If resultSymbol.Kind = SymbolKind.Namespace AndAlso
expression.Parent IsNot Nothing AndAlso
expression.Parent.Kind = SyntaxKind.QualifiedName AndAlso
DirectCast(expression.Parent, QualifiedNameSyntax).Left Is expression Then
Dim ns = DirectCast(resultSymbol, NamespaceSymbol)
If ns.NamespaceKind = NamespaceKindNamespaceGroup Then
Dim parentInfo As SymbolInfo = GetTypeOrNamespaceSymbolInfoNotInMember(DirectCast(expression.Parent, QualifiedNameSyntax), Nothing)
If Not parentInfo.IsEmpty Then
Dim namespaces = New SmallDictionary(Of NamespaceSymbol, Boolean)()
If parentInfo.Symbol IsNot Nothing Then
If Not Binder.AddReceiverNamespaces(namespaces, DirectCast(parentInfo.Symbol, Symbol), Compilation) Then
namespaces = Nothing
End If
Else
For Each candidate In parentInfo.CandidateSymbols
If Not Binder.AddReceiverNamespaces(namespaces, DirectCast(candidate, Symbol), Compilation) Then
namespaces = Nothing
Exit For
End If
Next
End If
If namespaces IsNot Nothing AndAlso namespaces.Count < ns.ConstituentNamespaces.Length Then
resultSymbol = DirectCast(ns, MergedNamespaceSymbol).Shrink(namespaces.Keys)
End If
End If
End If
End If
' Create the result.
Dim result = GetSymbolInfoForSymbol(resultSymbol, options)
' If we didn't get anything and were in Type/Namespace only context, let's bind normally and see
' if any symbol comes out.
If result.IsEmpty Then
Dim tryAsExpression = TryBindNamespaceOrTypeAsExpression(expression, options)
If Not tryAsExpression.IsEmpty Then
result = tryAsExpression
End If
End If
Return result
End Function
' Get the symbol info of type or namespace syntax that is outside a member body
Private Function GetTypeOrNamespaceTypeInfoNotInMember(expression As TypeSyntax) As VisualBasicTypeInfo
Dim resultSymbol As Symbol = GetTypeOrNamespaceSymbolNotInMember(expression)
' Create the result.
Return GetTypeInfoForSymbol(resultSymbol)
End Function
Private Function GetImplementedMemberAndResultKind(symbolBuilder As ArrayBuilder(Of Symbol), memberName As QualifiedNameSyntax) As LookupResultKind
Debug.Assert(symbolBuilder.Count = 0)
Dim resultKind As LookupResultKind = LookupResultKind.Good
' Set up the binding context.
Dim binder As Binder = GetEnclosingBinder(memberName.SpanStart)
' Figure out the symbol this implements clause is on, and bind the syntax for it.
Dim implementingMemberSyntax = TryCast(memberName.Parent.Parent, MethodBaseSyntax)
If implementingMemberSyntax IsNot Nothing Then
Dim implementingMember = GetDeclaredSymbol(implementingMemberSyntax)
If implementingMember IsNot Nothing Then
Select Case implementingMember.Kind
Case SymbolKind.Method
ImplementsHelper.FindExplicitlyImplementedMember(Of MethodSymbol)(
DirectCast(implementingMember, MethodSymbol),
DirectCast(implementingMember, MethodSymbol).ContainingType,
memberName,
binder,
BindingDiagnosticBag.Discarded,
symbolBuilder,
resultKind)
Case SymbolKind.Property
ImplementsHelper.FindExplicitlyImplementedMember(Of PropertySymbol)(
DirectCast(implementingMember, PropertySymbol),
DirectCast(implementingMember, PropertySymbol).ContainingType,
memberName,
binder,
BindingDiagnosticBag.Discarded,
symbolBuilder,
resultKind)
Case SymbolKind.Event
ImplementsHelper.FindExplicitlyImplementedMember(Of EventSymbol)(
DirectCast(implementingMember, EventSymbol),
DirectCast(implementingMember, EventSymbol).ContainingType,
memberName,
binder,
BindingDiagnosticBag.Discarded,
symbolBuilder,
resultKind)
Case Else
Throw ExceptionUtilities.UnexpectedValue(implementingMember.Kind)
End Select
End If
End If
Return resultKind
End Function
Private Function GetHandledEventOrContainerSymbolsAndResultKind(eventSymbolBuilder As ArrayBuilder(Of Symbol),
containerSymbolBuilder As ArrayBuilder(Of Symbol),
propertySymbolBuilder As ArrayBuilder(Of Symbol),
handlesClause As HandlesClauseItemSyntax) As LookupResultKind
Dim resultKind As LookupResultKind = LookupResultKind.Good
' Set up the binding context.
Dim binder As Binder = GetEnclosingBinder(handlesClause.SpanStart)
' Figure out the symbol this handles clause is on, and bind the syntax for it.
Dim handlingMethodSyntax = TryCast(handlesClause.Parent.Parent, MethodStatementSyntax)
If handlingMethodSyntax IsNot Nothing Then
Dim implementingMember = GetDeclaredSymbol(handlingMethodSyntax)
If implementingMember IsNot Nothing Then
Dim methodSym = DirectCast(implementingMember, SourceMemberMethodSymbol)
methodSym.BindSingleHandlesClause(handlesClause,
binder,
BindingDiagnosticBag.Discarded,
eventSymbolBuilder,
containerSymbolBuilder,
propertySymbolBuilder,
resultKind)
End If
End If
Return resultKind
End Function
' Get the symbol info of an implemented member in an implements clause.
Private Function GetImplementedMemberSymbolInfo(memberName As QualifiedNameSyntax, options As SymbolInfoOptions) As SymbolInfo
Dim implementedMemberBuilder As ArrayBuilder(Of Symbol) = ArrayBuilder(Of Symbol).GetInstance()
Dim resultKind As LookupResultKind = GetImplementedMemberAndResultKind(implementedMemberBuilder, memberName)
Dim symbols As ImmutableArray(Of Symbol) = RemoveErrorTypesAndDuplicates(implementedMemberBuilder, options)
implementedMemberBuilder.Free()
Return SymbolInfoFactory.Create(symbols, resultKind)
End Function
' Get the symbol info of a handled event in a handles clause.
Private Function GetHandlesEventSymbolInfo(handlesClause As HandlesClauseItemSyntax, options As SymbolInfoOptions) As SymbolInfo
Dim builder As ArrayBuilder(Of Symbol) = ArrayBuilder(Of Symbol).GetInstance()
Dim resultKind As LookupResultKind = GetHandledEventOrContainerSymbolsAndResultKind(eventSymbolBuilder:=builder,
containerSymbolBuilder:=Nothing,
propertySymbolBuilder:=Nothing,
handlesClause:=handlesClause)
Dim symbols As ImmutableArray(Of Symbol) = RemoveErrorTypesAndDuplicates(builder, options)
builder.Free()
Return SymbolInfoFactory.Create(symbols, resultKind)
End Function
' Get the symbol info of an identifier event container in a handles clause.
Private Function GetHandlesContainerSymbolInfo(handlesClause As HandlesClauseItemSyntax, options As SymbolInfoOptions) As SymbolInfo
Dim builder As ArrayBuilder(Of Symbol) = ArrayBuilder(Of Symbol).GetInstance()
Dim resultKind As LookupResultKind = GetHandledEventOrContainerSymbolsAndResultKind(eventSymbolBuilder:=Nothing,
containerSymbolBuilder:=builder,
propertySymbolBuilder:=Nothing,
handlesClause:=handlesClause)
Dim symbols As ImmutableArray(Of Symbol) = RemoveErrorTypesAndDuplicates(builder, options)
builder.Free()
Return SymbolInfoFactory.Create(symbols, resultKind)
End Function
' Get the symbol info of a withevents sourcing property in a handles clause.
Private Function GetHandlesPropertySymbolInfo(handlesClause As HandlesClauseItemSyntax, options As SymbolInfoOptions) As SymbolInfo
Dim builder As ArrayBuilder(Of Symbol) = ArrayBuilder(Of Symbol).GetInstance()
Dim resultKind As LookupResultKind = GetHandledEventOrContainerSymbolsAndResultKind(eventSymbolBuilder:=Nothing,
containerSymbolBuilder:=Nothing,
propertySymbolBuilder:=builder,
handlesClause:=handlesClause)
Dim symbols As ImmutableArray(Of Symbol) = RemoveErrorTypesAndDuplicates(builder, options)
builder.Free()
Return SymbolInfoFactory.Create(symbols, resultKind)
End Function
' Get the type info of a implemented member in a implements clause.
Private Function GetImplementedMemberTypeInfo(memberName As QualifiedNameSyntax) As VisualBasicTypeInfo
' Implemented members have no type.
Return VisualBasicTypeInfo.None
End Function
' Get the type info of a implemented member in a implements clause.
Private Function GetHandlesEventTypeInfo(memberName As IdentifierNameSyntax) As VisualBasicTypeInfo
' Handled events have no type.
Return VisualBasicTypeInfo.None
End Function
' Get the type info of a implemented member in a implements clause.
Private Function GetHandlesContainerTypeInfo(memberName As HandlesClauseItemSyntax) As VisualBasicTypeInfo
' Handled events have no type.
Return VisualBasicTypeInfo.None
End Function
' Get the type info of a implemented member in a implements clause.
Private Function GetHandlesPropertyTypeInfo(memberName As HandlesClauseItemSyntax) As VisualBasicTypeInfo
' Handled events have no type.
Return VisualBasicTypeInfo.None
End Function
''' <summary>
''' Checks all symbol locations against the syntax provided and return symbol if any of the locations is
''' inside the syntax span. Returns Nothing otherwise.
''' </summary>
Private Function CheckSymbolLocationsAgainstSyntax(symbol As NamedTypeSymbol, nodeToCheck As VisualBasicSyntaxNode) As NamedTypeSymbol
For Each location In symbol.Locations
If location.SourceTree Is Me.SyntaxTree AndAlso nodeToCheck.Span.Contains(location.SourceSpan) Then
Return symbol
End If
Next
Return Nothing
End Function
''' <summary>
''' Given a delegate declaration, get the corresponding type symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares a type.</param>
''' <returns>The type symbol that was declared.</returns>
Public Overloads Function GetDeclaredSymbol(declarationSyntax As DelegateStatementSyntax, Optional cancellationToken As CancellationToken = Nothing) As NamedTypeSymbol
If declarationSyntax Is Nothing Then Throw New ArgumentNullException(NameOf(declarationSyntax))
If Not IsInTree(declarationSyntax) Then Throw New ArgumentException(VBResources.DeclarationSyntaxNotWithinTree)
' Don't need to wrap in a SemanticModelBinder, since we're not binding.
Dim binder As Binder = _binderFactory.GetNamedTypeBinder(declarationSyntax)
If binder IsNot Nothing AndAlso TypeOf binder Is NamedTypeBinder Then
Return CheckSymbolLocationsAgainstSyntax(DirectCast(binder.ContainingType, NamedTypeSymbol), declarationSyntax)
Else
Return Nothing ' Can this happen? Maybe in some edge case error cases.
End If
End Function
''' <summary>
''' Given a type declaration, get the corresponding type symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares a type.</param>
''' <returns>The type symbol that was declared.</returns>
Public Overloads Overrides Function GetDeclaredSymbol(declarationSyntax As TypeStatementSyntax, Optional cancellationToken As CancellationToken = Nothing) As INamedTypeSymbol
If declarationSyntax Is Nothing Then Throw New ArgumentNullException(NameOf(declarationSyntax))
If Not IsInTree(declarationSyntax) Then Throw New ArgumentException(VBResources.DeclarationSyntaxNotWithinTree)
' Don't need to wrap in a SemanticModelBinder, since we're not binding.
Dim binder As Binder = _binderFactory.GetNamedTypeBinder(declarationSyntax)
If binder IsNot Nothing AndAlso TypeOf binder Is NamedTypeBinder Then
Return CheckSymbolLocationsAgainstSyntax(DirectCast(binder.ContainingType, NamedTypeSymbol), declarationSyntax)
Else
Return Nothing ' Can this happen? Maybe in some edge case error cases.
End If
End Function
''' <summary>
''' Given a enum declaration, get the corresponding type symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares an enum.</param>
''' <returns>The type symbol that was declared.</returns>
Public Overloads Overrides Function GetDeclaredSymbol(declarationSyntax As EnumStatementSyntax, Optional cancellationToken As CancellationToken = Nothing) As INamedTypeSymbol
If declarationSyntax Is Nothing Then Throw New ArgumentNullException(NameOf(declarationSyntax))
If Not IsInTree(declarationSyntax) Then Throw New ArgumentException(VBResources.DeclarationSyntaxNotWithinTree)
' Don't need to wrap in a SemanticModelBinder, since we're not binding.
Dim binder As Binder = _binderFactory.GetNamedTypeBinder(declarationSyntax)
If binder IsNot Nothing AndAlso TypeOf binder Is NamedTypeBinder Then
Return CheckSymbolLocationsAgainstSyntax(DirectCast(binder.ContainingType, NamedTypeSymbol), declarationSyntax)
Else
Return Nothing ' Can this happen? Maybe in some edge case with errors
End If
End Function
''' <summary>
''' Given a namespace declaration, get the corresponding type symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares a namespace.</param>
''' <returns>The namespace symbol that was declared.</returns>
Public Overloads Overrides Function GetDeclaredSymbol(declarationSyntax As NamespaceStatementSyntax, Optional cancellationToken As CancellationToken = Nothing) As INamespaceSymbol
If declarationSyntax Is Nothing Then Throw New ArgumentNullException(NameOf(declarationSyntax))
If Not IsInTree(declarationSyntax) Then Throw New ArgumentException(VBResources.DeclarationSyntaxNotWithinTree)
Dim parentBlock = TryCast(declarationSyntax.Parent, NamespaceBlockSyntax)
If parentBlock IsNot Nothing Then
' Don't need to wrap in a SemanticModelBinder, since we're not binding.
Dim binder As Binder = _binderFactory.GetNamespaceBinder(parentBlock)
If binder IsNot Nothing AndAlso TypeOf binder Is NamespaceBinder Then
Return DirectCast(binder.ContainingNamespaceOrType, NamespaceSymbol)
End If
End If
Return Nothing ' Edge case with errors
End Function
''' <summary>
''' Given a method, property, or event declaration, get the corresponding symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares a method, property, or event.</param>
''' <returns>The method, property, or event symbol that was declared.</returns>
Friend Overloads Overrides Function GetDeclaredSymbol(declarationSyntax As MethodBaseSyntax, Optional cancellationToken As CancellationToken = Nothing) As ISymbol
If declarationSyntax Is Nothing Then Throw New ArgumentNullException(NameOf(declarationSyntax))
If Not IsInTree(declarationSyntax) Then
Throw New ArgumentException(VBResources.DeclarationSyntaxNotWithinTree)
End If
' Delegate declarations are a subclass of MethodBaseSyntax syntax-wise, but they are
' more like a type declaration, so we need to special case here.
If declarationSyntax.Kind = SyntaxKind.DelegateFunctionStatement OrElse
declarationSyntax.Kind = SyntaxKind.DelegateSubStatement Then
Return GetDeclaredSymbol(DirectCast(declarationSyntax, DelegateStatementSyntax), cancellationToken)
End If
Dim statementSyntax = TryCast(declarationSyntax.Parent, StatementSyntax)
If statementSyntax IsNot Nothing Then
' get parent type block
Dim parentTypeBlock As TypeBlockSyntax = Nothing
Select Case statementSyntax.Kind
Case SyntaxKind.ClassBlock, SyntaxKind.EnumBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ModuleBlock
parentTypeBlock = TryCast(statementSyntax, TypeBlockSyntax)
Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorBlock, SyntaxKind.PropertyBlock, SyntaxKind.EventBlock
parentTypeBlock = TryCast(statementSyntax.Parent, TypeBlockSyntax)
' EDMAURER maybe this is a top-level decl in which case the parent is a CompilationUnitSyntax
If parentTypeBlock Is Nothing AndAlso statementSyntax.Parent IsNot Nothing Then
Dim namespaceToLookInForImplicitType As INamespaceSymbol = Nothing
Select Case statementSyntax.Parent.Kind
Case SyntaxKind.CompilationUnit
namespaceToLookInForImplicitType = Me._sourceModule.RootNamespace
Case SyntaxKind.NamespaceBlock
namespaceToLookInForImplicitType = GetDeclaredSymbol(DirectCast(statementSyntax.Parent, NamespaceBlockSyntax), cancellationToken)
End Select
If namespaceToLookInForImplicitType IsNot Nothing Then
Dim implicitType = DirectCast(namespaceToLookInForImplicitType.GetMembers(TypeSymbol.ImplicitTypeName).SingleOrDefault(), NamedTypeSymbol)
If implicitType IsNot Nothing Then
Return SourceMethodSymbol.FindSymbolFromSyntax(declarationSyntax, _syntaxTree, implicitType)
End If
End If
End If
Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock
' redirect to upper property or event symbol
If statementSyntax.Parent IsNot Nothing Then
parentTypeBlock = TryCast(statementSyntax.Parent.Parent, TypeBlockSyntax)
End If
Case SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock
' redirect to upper event symbol
If statementSyntax.Parent IsNot Nothing Then
parentTypeBlock = TryCast(statementSyntax.Parent.Parent, TypeBlockSyntax)
End If
Case Else
' broken code scenarios end up here
' to end up here, a methodbasesyntax's parent must be a statement and not be one of the above.
' The parser does e.g. not generate an enclosing block for accessors statements,
' but for Operators, conversions and constructors.
' The case where an invalid accessor is contained in e.g. an interface is handled further down in "FindSymbolFromSyntax".
' TODO: consider always creating a (missing) block around the statements in the parser
' We are asserting what we know so far. If this assert fails, this is not a bug, we either need to remove this assert or relax the assert.
Debug.Assert(statementSyntax.Kind = SyntaxKind.NamespaceBlock AndAlso
(TypeOf (declarationSyntax) Is AccessorStatementSyntax OrElse
TypeOf (declarationSyntax) Is EventStatementSyntax OrElse
TypeOf (declarationSyntax) Is MethodStatementSyntax OrElse
TypeOf (declarationSyntax) Is PropertyStatementSyntax))
Return Nothing
End Select
If parentTypeBlock IsNot Nothing Then
Dim containingType = DirectCast(GetDeclaredSymbol(parentTypeBlock.BlockStatement, cancellationToken), NamedTypeSymbol)
If containingType IsNot Nothing Then
Return SourceMethodSymbol.FindSymbolFromSyntax(declarationSyntax, _syntaxTree, containingType)
End If
End If
End If
Return Nothing
End Function
''' <summary>
''' Given a parameter declaration, get the corresponding parameter symbol.
''' </summary>
''' <param name="parameter">The syntax node that declares a parameter.</param>
''' <returns>The parameter symbol that was declared.</returns>
Public Overloads Overrides Function GetDeclaredSymbol(parameter As ParameterSyntax, Optional cancellationToken As CancellationToken = Nothing) As IParameterSymbol
If parameter Is Nothing Then
Throw New ArgumentNullException(NameOf(parameter))
End If
Dim paramList As ParameterListSyntax = TryCast(parameter.Parent, ParameterListSyntax)
If paramList IsNot Nothing Then
Dim declarationSyntax As MethodBaseSyntax = TryCast(paramList.Parent, MethodBaseSyntax)
If declarationSyntax IsNot Nothing Then
Dim symbol = GetDeclaredSymbol(declarationSyntax, cancellationToken)
If symbol IsNot Nothing Then
Select Case symbol.Kind
Case SymbolKind.Method
Return GetParameterSymbol(DirectCast(symbol, MethodSymbol).Parameters, parameter)
Case SymbolKind.Event
Dim eventSymbol As EventSymbol = DirectCast(symbol, EventSymbol)
Dim type = TryCast(eventSymbol.Type, NamedTypeSymbol)
If type?.AssociatedSymbol Is eventSymbol Then
Return GetParameterSymbol(type.DelegateInvokeMethod.Parameters, parameter)
End If
Return Nothing
Case SymbolKind.Property
Return GetParameterSymbol(DirectCast(symbol, PropertySymbol).Parameters, parameter)
Case SymbolKind.NamedType
' check for being delegate
Dim typeSymbol = DirectCast(symbol, NamedTypeSymbol)
Debug.Assert(typeSymbol.TypeKind = TYPEKIND.Delegate)
If typeSymbol.DelegateInvokeMethod IsNot Nothing Then
Return GetParameterSymbol(typeSymbol.DelegateInvokeMethod.Parameters, parameter)
End If
End Select
ElseIf TypeOf declarationSyntax Is LambdaHeaderSyntax Then
' This could be a lambda parameter.
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(declarationSyntax)
If model IsNot Nothing Then
Return model.GetDeclaredSymbol(parameter, cancellationToken)
End If
End If
End If
End If
Return Nothing
End Function
''' <summary>
''' Given a type parameter declaration, get the corresponding type parameter symbol.
''' </summary>
''' <param name="typeParameter">The syntax node that declares a type parameter.</param>
''' <returns>The type parameter symbol that was declared.</returns>
Public Overloads Overrides Function GetDeclaredSymbol(typeParameter As TypeParameterSyntax, Optional cancellationToken As CancellationToken = Nothing) As ITypeParameterSymbol
If typeParameter Is Nothing Then
Throw New ArgumentNullException(NameOf(typeParameter))
End If
If Not IsInTree(typeParameter) Then
Throw New ArgumentException(VBResources.TypeParameterNotWithinTree)
End If
Dim symbol As ISymbol = Nothing
Dim typeParamList = TryCast(typeParameter.Parent, TypeParameterListSyntax)
If typeParamList IsNot Nothing AndAlso typeParamList.Parent IsNot Nothing Then
If TypeOf typeParamList.Parent Is MethodStatementSyntax Then
symbol = GetDeclaredSymbol(DirectCast(typeParamList.Parent, MethodStatementSyntax), cancellationToken)
ElseIf TypeOf typeParamList.Parent Is TypeStatementSyntax Then
symbol = GetDeclaredSymbol(DirectCast(typeParamList.Parent, TypeStatementSyntax), cancellationToken)
ElseIf TypeOf typeParamList.Parent Is DelegateStatementSyntax Then
symbol = GetDeclaredSymbol(DirectCast(typeParamList.Parent, DelegateStatementSyntax), cancellationToken)
End If
If symbol IsNot Nothing Then
Dim typeSymbol = TryCast(symbol, NamedTypeSymbol)
If typeSymbol IsNot Nothing Then
Return Me.GetTypeParameterSymbol(typeSymbol.TypeParameters, typeParameter)
End If
Dim methodSymbol = TryCast(symbol, MethodSymbol)
If methodSymbol IsNot Nothing Then
Return Me.GetTypeParameterSymbol(methodSymbol.TypeParameters, typeParameter)
End If
End If
End If
Return Nothing
End Function
' Get a type parameter symbol from a ROA of TypeParametersSymbols and the syntax for one.
Private Function GetTypeParameterSymbol(parameters As ImmutableArray(Of TypeParameterSymbol), parameter As TypeParameterSyntax) As TypeParameterSymbol
For Each symbol In parameters
For Each location In symbol.Locations
If location.IsInSource AndAlso location.SourceTree Is _syntaxTree AndAlso parameter.Span.Contains(location.SourceSpan) Then
Return symbol
End If
Next
Next
Return Nothing
End Function
Public Overrides Function GetDeclaredSymbol(declarationSyntax As EnumMemberDeclarationSyntax, Optional cancellationToken As CancellationToken = Nothing) As IFieldSymbol
If declarationSyntax Is Nothing Then
Throw New ArgumentNullException(NameOf(declarationSyntax))
End If
If Not IsInTree(declarationSyntax) Then
Throw New ArgumentException(VBResources.DeclarationSyntaxNotWithinTree)
End If
Dim enumBlock As EnumBlockSyntax = DirectCast(declarationSyntax.Parent, EnumBlockSyntax)
If enumBlock IsNot Nothing Then
Dim containingType = DirectCast(GetDeclaredSymbol(enumBlock.EnumStatement, cancellationToken), NamedTypeSymbol)
If containingType IsNot Nothing Then
Return DirectCast(SourceFieldSymbol.FindFieldOrWithEventsSymbolFromSyntax(declarationSyntax.Identifier, _syntaxTree, containingType), FieldSymbol)
End If
End If
Return Nothing
End Function
''' <summary>
''' Given a variable declaration, get the corresponding symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares a variable.</param>
''' <returns>The symbol that was declared.</returns>
Public Overrides Function GetDeclaredSymbol(declarationSyntax As ModifiedIdentifierSyntax, Optional cancellationToken As CancellationToken = Nothing) As ISymbol
If declarationSyntax Is Nothing Then
Throw New ArgumentNullException(NameOf(declarationSyntax))
End If
If Not IsInTree(declarationSyntax) Then
Throw New ArgumentException(VBResources.DeclarationSyntaxNotWithinTree)
End If
Dim declarationParent = declarationSyntax.Parent
' Possibility 1: Field syntax, could be a Field or WithEvent property
Dim fieldSyntax As FieldDeclarationSyntax = Nothing
If declarationParent IsNot Nothing Then
fieldSyntax = TryCast(declarationParent.Parent, FieldDeclarationSyntax)
End If
Dim parentTypeBlock As TypeBlockSyntax = Nothing
If fieldSyntax IsNot Nothing Then
parentTypeBlock = TryCast(fieldSyntax.Parent, TypeBlockSyntax)
Else : End If
If parentTypeBlock IsNot Nothing Then
Dim containingType = DirectCast(GetDeclaredSymbol(parentTypeBlock.BlockStatement, cancellationToken), NamedTypeSymbol)
If containingType IsNot Nothing Then
Return SourceFieldSymbol.FindFieldOrWithEventsSymbolFromSyntax(declarationSyntax.Identifier, _syntaxTree, containingType)
End If
End If
' Possibility 2: Parameter
Dim parameterSyntax As ParameterSyntax = TryCast(declarationParent, ParameterSyntax)
If parameterSyntax IsNot Nothing Then
Return GetDeclaredSymbol(parameterSyntax, cancellationToken)
End If
' Possibility 3: Local variable
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(declarationSyntax)
If model IsNot Nothing Then
Return model.GetDeclaredSymbol(declarationSyntax, cancellationToken)
End If
Return MyBase.GetDeclaredSymbol(declarationSyntax, cancellationToken)
End Function
''' <summary>
''' Given a FieldInitializerSyntax, get the corresponding symbol of anonymous type creation.
''' </summary>
''' <param name="fieldInitializerSyntax">The anonymous object creation field initializer syntax.</param>
''' <returns>The symbol that was declared, or Nothing if no such symbol exists.</returns>
Public Overrides Function GetDeclaredSymbol(fieldInitializerSyntax As FieldInitializerSyntax, Optional cancellationToken As System.Threading.CancellationToken = Nothing) As IPropertySymbol
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(fieldInitializerSyntax)
If model IsNot Nothing Then
Return model.GetDeclaredSymbol(fieldInitializerSyntax, cancellationToken)
End If
Return MyBase.GetDeclaredSymbol(fieldInitializerSyntax, cancellationToken)
End Function
''' <summary>
''' Given an AnonymousObjectCreationExpressionSyntax, get the corresponding symbol of anonymous type.
''' </summary>
''' <param name="anonymousObjectCreationExpressionSyntax">The anonymous object creation syntax.</param>
''' <returns>The symbol that was declared, or Nothing if no such symbol exists.</returns>
Public Overrides Function GetDeclaredSymbol(anonymousObjectCreationExpressionSyntax As AnonymousObjectCreationExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As INamedTypeSymbol
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(anonymousObjectCreationExpressionSyntax)
If model IsNot Nothing Then
Return model.GetDeclaredSymbol(anonymousObjectCreationExpressionSyntax, cancellationToken)
End If
Return MyBase.GetDeclaredSymbol(anonymousObjectCreationExpressionSyntax, cancellationToken)
End Function
''' <summary>
''' Given an ExpressionRangeVariableSyntax, get the corresponding symbol.
''' </summary>
''' <param name="rangeVariableSyntax">The range variable syntax that declares a variable.</param>
''' <returns>The symbol that was declared, or Nothing if no such symbol exists.</returns>
Public Overrides Function GetDeclaredSymbol(rangeVariableSyntax As ExpressionRangeVariableSyntax, Optional cancellationToken As CancellationToken = Nothing) As IRangeVariableSymbol
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(rangeVariableSyntax)
If model IsNot Nothing Then
Return model.GetDeclaredSymbol(rangeVariableSyntax, cancellationToken)
End If
Return MyBase.GetDeclaredSymbol(rangeVariableSyntax, cancellationToken)
End Function
''' <summary>
''' Given a CollectionRangeVariableSyntax, get the corresponding symbol.
''' </summary>
''' <param name="rangeVariableSyntax">The range variable syntax that declares a variable.</param>
''' <returns>The symbol that was declared, or Nothing if no such symbol exists.</returns>
Public Overrides Function GetDeclaredSymbol(rangeVariableSyntax As CollectionRangeVariableSyntax, Optional cancellationToken As CancellationToken = Nothing) As IRangeVariableSymbol
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(rangeVariableSyntax)
If model IsNot Nothing Then
Return model.GetDeclaredSymbol(rangeVariableSyntax, cancellationToken)
End If
Return MyBase.GetDeclaredSymbol(rangeVariableSyntax, cancellationToken)
End Function
''' <summary>
''' Given an AggregationRangeVariableSyntax, get the corresponding symbol.
''' </summary>
''' <param name="rangeVariableSyntax">The range variable syntax that declares a variable.</param>
''' <returns>The symbol that was declared, or Nothing if no such symbol exists.</returns>
Public Overrides Function GetDeclaredSymbol(rangeVariableSyntax As AggregationRangeVariableSyntax, Optional cancellationToken As CancellationToken = Nothing) As IRangeVariableSymbol
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(rangeVariableSyntax)
If model IsNot Nothing Then
Return model.GetDeclaredSymbol(rangeVariableSyntax, cancellationToken)
End If
Return MyBase.GetDeclaredSymbol(rangeVariableSyntax, cancellationToken)
End Function
''' <summary>
''' Given an import clause get the corresponding symbol for the import alias that was introduced.
''' </summary>
''' <param name="declarationSyntax">The import statement syntax node.</param>
''' <returns>The alias symbol that was declared or Nothing if no alias symbol was declared.</returns>
Public Overloads Overrides Function GetDeclaredSymbol(declarationSyntax As SimpleImportsClauseSyntax, Optional cancellationToken As CancellationToken = Nothing) As IAliasSymbol
If declarationSyntax Is Nothing Then
Throw New ArgumentNullException(NameOf(declarationSyntax))
End If
If Not IsInTree(declarationSyntax) Then
Throw New ArgumentException(VBResources.DeclarationSyntaxNotWithinTree)
End If
If declarationSyntax.Alias Is Nothing Then
Return Nothing
End If
Dim aliasName As String = declarationSyntax.Alias.Identifier.ValueText
If Not String.IsNullOrEmpty(aliasName) Then
Dim sourceFile = Me._sourceModule.TryGetSourceFile(Me.SyntaxTree)
Debug.Assert(sourceFile IsNot Nothing)
Dim aliasImports As IReadOnlyDictionary(Of String, AliasAndImportsClausePosition) = sourceFile.AliasImportsOpt
Dim symbol As AliasAndImportsClausePosition = Nothing
If aliasImports IsNot Nothing AndAlso aliasImports.TryGetValue(aliasName, symbol) Then
' make sure the symbol is declared inside declarationSyntax node
For Each location In symbol.Alias.Locations
If location.IsInSource AndAlso location.SourceTree Is _syntaxTree AndAlso declarationSyntax.Span.Contains(location.SourceSpan) Then
Return symbol.Alias
End If
Next
' If the alias name was in the map but the location didn't match, then the syntax declares a duplicate alias.
' We'll return a new AliasSymbol to improve the API experience.
Dim binder As Binder = GetEnclosingBinder(declarationSyntax.SpanStart)
Dim targetSymbol As NamespaceOrTypeSymbol = binder.BindNamespaceOrTypeSyntax(declarationSyntax.Name, BindingDiagnosticBag.Discarded)
If targetSymbol IsNot Nothing Then
Return New AliasSymbol(binder.Compilation, binder.ContainingNamespaceOrType, aliasName, targetSymbol, declarationSyntax.GetLocation())
End If
End If
End If
Return Nothing
End Function
''' <summary>
''' Given a field declaration syntax, get the corresponding symbols.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares one or more fields.</param>
''' <returns>The field symbols that were declared.</returns>
Friend Overrides Function GetDeclaredSymbols(declarationSyntax As FieldDeclarationSyntax, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of ISymbol)
If declarationSyntax Is Nothing Then
Throw New ArgumentNullException(NameOf(declarationSyntax))
End If
If Not IsInTree(declarationSyntax) Then
Throw New ArgumentException(VBResources.DeclarationSyntaxNotWithinTree)
End If
Dim builder = New ArrayBuilder(Of ISymbol)
For Each declarator In declarationSyntax.Declarators
For Each identifier In declarator.Names
Dim field = TryCast(Me.GetDeclaredSymbol(identifier, cancellationToken), IFieldSymbol)
If field IsNot Nothing Then
builder.Add(field)
End If
Next
Next
Return builder.ToImmutableAndFree()
End Function
''' <summary>
''' Determines what type of conversion, if any, would be used if a given expression was converted to a given
''' type.
''' </summary>
''' <param name="expression">An expression which much occur within the syntax tree associated with this
''' object.</param>
''' <param name="destination">The type to attempt conversion to.</param>
''' <returns>Returns a Conversion object that summarizes whether the conversion was possible, and if so, what
''' kind of conversion it was. If no conversion was possible, a Conversion object with a false "Exists "
''' property is returned.</returns>
''' <remarks>To determine the conversion between two types (instead of an expression and a type), use
''' Compilation.ClassifyConversion.</remarks>
Public Overrides Function ClassifyConversion(expression As ExpressionSyntax, destination As ITypeSymbol) As Conversion
CheckSyntaxNode(expression)
If destination Is Nothing Then
Throw New ArgumentNullException(NameOf(destination))
End If
Dim vbdestination = destination.EnsureVbSymbolOrNothing(Of TypeSymbol)(NameOf(destination))
' TODO(cyrusn): Check arguments. This is a public entrypoint, so we must do appropriate
' checks here. However, no other methods in this type do any checking currently. So I'm
' going to hold off on this until we do a full sweep of the API.
Dim binding = Me.GetMemberSemanticModel(expression)
If binding Is Nothing Then
Return New Conversion(Nothing) 'NoConversion
End If
Return binding.ClassifyConversion(expression, vbdestination)
End Function
Public Overrides ReadOnly Property IsSpeculativeSemanticModel As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property OriginalPositionForSpeculation As Integer
Get
Return 0
End Get
End Property
Public Overrides ReadOnly Property ParentModel As SemanticModel
Get
Return Nothing
End Get
End Property
Friend Overrides ReadOnly Property ContainingModelOrSelf As SemanticModel
Get
Return Me
End Get
End Property
Friend Overrides Function TryGetSpeculativeSemanticModelForMethodBodyCore(parentModel As SyntaxTreeSemanticModel, position As Integer, method As MethodBlockBaseSyntax, <Out> ByRef speculativeModel As SemanticModel) As Boolean
Dim memberModel = Me.GetMemberSemanticModel(position)
If memberModel IsNot Nothing Then
Return memberModel.TryGetSpeculativeSemanticModelForMethodBodyCore(parentModel, position, method, speculativeModel)
End If
speculativeModel = Nothing
Return False
End Function
Friend Overrides Function TryGetSpeculativeSemanticModelCore(parentModel As SyntaxTreeSemanticModel, position As Integer, type As TypeSyntax, bindingOption As SpeculativeBindingOption, <Out> ByRef speculativeModel As SemanticModel) As Boolean
Dim memberModel = Me.GetMemberSemanticModel(position)
If memberModel IsNot Nothing Then
Return memberModel.TryGetSpeculativeSemanticModelCore(parentModel, position, type, bindingOption, speculativeModel)
End If
Dim binder As Binder = Me.GetSpeculativeBinderForExpression(position, type, bindingOption)
If binder IsNot Nothing Then
speculativeModel = SpeculativeSyntaxTreeSemanticModel.Create(Me, type, binder, position, bindingOption)
Return True
End If
speculativeModel = Nothing
Return False
End Function
Friend Overrides Function TryGetSpeculativeSemanticModelCore(parentModel As SyntaxTreeSemanticModel, position As Integer, rangeArgument As RangeArgumentSyntax, <Out> ByRef speculativeModel As SemanticModel) As Boolean
Dim memberModel = Me.GetMemberSemanticModel(position)
If memberModel IsNot Nothing Then
Return memberModel.TryGetSpeculativeSemanticModelCore(parentModel, position, rangeArgument, speculativeModel)
End If
speculativeModel = Nothing
Return False
End Function
Friend Overrides Function TryGetSpeculativeSemanticModelCore(parentModel As SyntaxTreeSemanticModel, position As Integer, statement As ExecutableStatementSyntax, <Out> ByRef speculativeModel As SemanticModel) As Boolean
Dim memberModel = Me.GetMemberSemanticModel(position)
If memberModel IsNot Nothing Then
Return memberModel.TryGetSpeculativeSemanticModelCore(parentModel, position, statement, speculativeModel)
End If
speculativeModel = Nothing
Return False
End Function
Friend Overrides Function TryGetSpeculativeSemanticModelCore(parentModel As SyntaxTreeSemanticModel, position As Integer, initializer As EqualsValueSyntax, <Out> ByRef speculativeModel As SemanticModel) As Boolean
Dim memberModel = Me.GetMemberSemanticModel(position)
If memberModel IsNot Nothing Then
Return memberModel.TryGetSpeculativeSemanticModelCore(parentModel, position, initializer, speculativeModel)
End If
speculativeModel = Nothing
Return False
End Function
''' <summary>
''' Analyze control-flow within a part of a method body.
''' </summary>
''' <param name="firstStatement">The first statement to be included in the analysis.</param>
''' <param name="lastStatement">The last statement to be included in the analysis.</param>
''' <returns>An object that can be used to obtain the result of the control flow analysis.</returns>
''' <exception cref="ArgumentException">The two statements are not contained within the same statement list.</exception>
Public Overrides Function AnalyzeControlFlow(firstStatement As StatementSyntax, lastStatement As StatementSyntax) As ControlFlowAnalysis
Dim context As RegionAnalysisContext = If(ValidateRegionDefiningStatementsRange(firstStatement, lastStatement),
CreateRegionAnalysisContext(firstStatement, lastStatement),
CreateFailedRegionAnalysisContext())
Dim result = New VisualBasicControlFlowAnalysis(context)
' we assume the analysis should only fail if the original context is invalid
Debug.Assert(result.Succeeded OrElse context.Failed)
Return result
End Function
''' <summary>
''' The first statement to be included in the analysis.
''' </summary>
''' <param name="firstStatement">The first statement to be included in the analysis.</param>
''' <param name="lastStatement">The last statement to be included in the analysis.</param>
''' <returns>An object that can be used to obtain the result of the data flow analysis.</returns>
''' <exception cref="ArgumentException">The two statements are not contained within the same statement list.</exception>
Public Overrides Function AnalyzeDataFlow(firstStatement As StatementSyntax, lastStatement As StatementSyntax) As DataFlowAnalysis
Dim context As RegionAnalysisContext = If(ValidateRegionDefiningStatementsRange(firstStatement, lastStatement),
CreateRegionAnalysisContext(firstStatement, lastStatement),
CreateFailedRegionAnalysisContext())
Dim result = New VisualBasicDataFlowAnalysis(context)
' we assume the analysis should only fail if the original context is invalid
Debug.Assert(result.Succeeded OrElse result.InvalidRegionDetectedInternal OrElse context.Failed)
Return result
End Function
''' <summary>
''' Analyze data-flow within an expression.
''' </summary>
''' <param name="expression">The expression within the associated SyntaxTree to analyze.</param>
''' <returns>An object that can be used to obtain the result of the data flow analysis.</returns>
Public Overrides Function AnalyzeDataFlow(expression As ExpressionSyntax) As DataFlowAnalysis
Dim context As RegionAnalysisContext = If(ValidateRegionDefiningExpression(expression),
CreateRegionAnalysisContext(expression),
CreateFailedRegionAnalysisContext())
Dim result = New VisualBasicDataFlowAnalysis(context)
' Assert that we either correctly precalculated succeeded
' flag or we know for sure why we failed to precalculate it
CheckSucceededFlagInAnalyzeDataFlow(expression, result, context)
Return result
End Function
<Conditional("DEBUG")>
Private Sub CheckSucceededFlagInAnalyzeDataFlow(expression As ExpressionSyntax, result As VisualBasicDataFlowAnalysis, context As RegionAnalysisContext)
If result.Succeeded OrElse result.InvalidRegionDetectedInternal OrElse context.Failed Then
Return
End If
' Some cases of unsucceeded result that cannot be precalculated properly are handled below
' CASE 1: If the region flow analysis is performed on the left part of member access like
' on 'a' part of 'a.b.c()' expression AND 'a.b' is a type, we don't create a bound node
' to be linked with syntax node 'a'. In this case FirstInRegion/LastInRegion nodes are
' calculated by trying to bind 'a' itself, and in most cases it binds into Namespace
' or Type expression. This case is handles in RegionAnalysisContext..ctor.
'
' But in Color/Color case it binds into other symbol kinds and we suppress
' assertion for this case here
Dim expressionParent As VisualBasicSyntaxNode = expression.Parent
If expression.Kind = SyntaxKind.IdentifierName AndAlso
expressionParent IsNot Nothing AndAlso expressionParent.Kind = SyntaxKind.SimpleMemberAccessExpression AndAlso
DirectCast(expressionParent, MemberAccessExpressionSyntax).Expression Is expression Then
' Color/Color confusion may only be possible if expression is an IdentifierName
' and is nested in member access. This is too wide definition, but it's
' difficult to improve this without doing semantic analysis
Return
End If
' CASE 2: If the region flow analysis is performed on the arguments of field declaration of array
' data type having explicit initializer, like 'Public AnArray(2) = {0, 1}';
' VB semantics generates an error about specifying both bounds and initializer and ignores them
If expression.Kind = SyntaxKind.NumericLiteralExpression AndAlso
expressionParent IsNot Nothing AndAlso (expressionParent.Kind = SyntaxKind.SimpleArgument AndAlso Not DirectCast(expressionParent, SimpleArgumentSyntax).IsNamed) Then
' VariableDeclarator
' | |
' ModifiedIdentifier EqualsValue
' |
' ArgumentList
' |...|...|
' SimpleArgument
' |
' NumericalLiteral
Dim argList As VisualBasicSyntaxNode = expressionParent.Parent
If argList IsNot Nothing AndAlso argList.Kind = SyntaxKind.ArgumentList Then
Dim modIdentifier As VisualBasicSyntaxNode = argList.Parent
If modIdentifier IsNot Nothing AndAlso modIdentifier.Kind = SyntaxKind.ModifiedIdentifier Then
Dim varDeclarator As VisualBasicSyntaxNode = modIdentifier.Parent
If varDeclarator IsNot Nothing AndAlso varDeclarator.Kind = SyntaxKind.VariableDeclarator AndAlso
DirectCast(varDeclarator, VariableDeclaratorSyntax).Initializer IsNot Nothing Then
Return
End If
End If
End If
End If
Throw ExceptionUtilities.Unreachable
End Sub
''' <summary>
''' Checks if the node is inside the attribute arguments
''' </summary>
Private Shared Function IsNodeInsideAttributeArguments(node As VisualBasicSyntaxNode) As Boolean
While node IsNot Nothing
If node.Kind = SyntaxKind.Attribute Then
Return True
End If
node = node.Parent
End While
Return False
End Function
''' <summary>
''' Check Expression for being in right context, for example 'For ... Next [x]'
''' is not correct context
''' </summary>
Private Shared Function IsExpressionInValidContext(expression As ExpressionSyntax) As Boolean
Dim currentNode As VisualBasicSyntaxNode = expression
Do
Dim parent As VisualBasicSyntaxNode = currentNode.Parent
If parent Is Nothing Then Return True
Dim expressionParent = TryCast(parent, ExpressionSyntax)
If expressionParent Is Nothing Then
Select Case parent.Kind
Case SyntaxKind.NextStatement
Return False
Case SyntaxKind.EqualsValue
' One cannot perform flow analysis on an expression from Enum member declaration
parent = parent.Parent
If parent Is Nothing Then
Return True
End If
Select Case parent.Kind
Case SyntaxKind.EnumMemberDeclaration,
SyntaxKind.Parameter
Return False
Case SyntaxKind.VariableDeclarator
Dim localDeclSyntax = TryCast(parent.Parent, LocalDeclarationStatementSyntax)
If localDeclSyntax IsNot Nothing Then
For Each modifier In localDeclSyntax.Modifiers
Select Case modifier.Kind
Case SyntaxKind.ConstKeyword
Return False
End Select
Next
End If
Return True
Case Else
Return True
End Select
Case SyntaxKind.RaiseEventStatement
Return False
Case SyntaxKind.NamedFieldInitializer
If DirectCast(parent, NamedFieldInitializerSyntax).Name Is currentNode Then
Return False
End If
' else proceed to the upper-level node
Case SyntaxKind.NameColonEquals
Return False
Case SyntaxKind.RangeArgument
If DirectCast(parent, RangeArgumentSyntax).LowerBound Is currentNode Then
Return False
End If
' proceed to the upper-level node
Case SyntaxKind.ArgumentList,
SyntaxKind.SimpleArgument,
SyntaxKind.ObjectMemberInitializer
' proceed to the upper-level node
Case SyntaxKind.GoToStatement
Return False
Case SyntaxKind.XmlDeclarationOption
Return False
Case Else
Return True
End Select
Else
Select Case parent.Kind
Case SyntaxKind.XmlElementEndTag
Return False
End Select
End If
' up one level
currentNode = parent
Loop
End Function
Private Sub AssertNodeInTree(node As VisualBasicSyntaxNode, argName As String)
If node Is Nothing Then
Throw New ArgumentNullException(argName)
End If
If Not IsInTree(node) Then
Throw New ArgumentException(argName & VBResources.NotWithinTree)
End If
End Sub
Private Function ValidateRegionDefiningExpression(expression As ExpressionSyntax) As Boolean
AssertNodeInTree(expression, NameOf(expression))
If expression.Kind = SyntaxKind.PredefinedType OrElse SyntaxFacts.IsInNamespaceOrTypeContext(expression) Then
Return False
End If
If SyntaxFactory.GetStandaloneExpression(expression) IsNot expression Then
Return False
End If
' Check for pseudo-expressions
Select Case expression.Kind
Case SyntaxKind.CollectionInitializer
Dim parent As VisualBasicSyntaxNode = expression.Parent
If parent IsNot Nothing Then
Select Case parent.Kind
Case SyntaxKind.ObjectCollectionInitializer
If DirectCast(parent, ObjectCollectionInitializerSyntax).Initializer Is expression Then
Return False
End If
Case SyntaxKind.ArrayCreationExpression
If DirectCast(parent, ArrayCreationExpressionSyntax).Initializer Is expression Then
Return False
End If
Case SyntaxKind.CollectionInitializer
' Nested collection initializer is not an expression from the language point of view.
' However, third level collection initializer under ObjectCollectionInitializer should
' be treated as a stand alone expression.
Dim possibleSecondLevelInitializer As VisualBasicSyntaxNode = parent
parent = parent.Parent
If parent IsNot Nothing AndAlso parent.Kind = SyntaxKind.CollectionInitializer Then
Dim possibleFirstLevelInitializer As VisualBasicSyntaxNode = parent
parent = parent.Parent
If parent IsNot Nothing AndAlso parent.Kind = SyntaxKind.ObjectCollectionInitializer AndAlso
DirectCast(parent, ObjectCollectionInitializerSyntax).Initializer Is possibleFirstLevelInitializer Then
Exit Select
End If
End If
Return False
End Select
End If
Case SyntaxKind.NumericLabel,
SyntaxKind.IdentifierLabel,
SyntaxKind.NextLabel
Return False
End Select
If Not IsExpressionInValidContext(expression) OrElse IsNodeInsideAttributeArguments(expression) Then
Return False
End If
Return True
End Function
Private Function ValidateRegionDefiningStatementsRange(firstStatement As StatementSyntax, lastStatement As StatementSyntax) As Boolean
AssertNodeInTree(firstStatement, NameOf(firstStatement))
AssertNodeInTree(lastStatement, NameOf(lastStatement))
If firstStatement.Parent Is Nothing OrElse firstStatement.Parent IsNot lastStatement.Parent Then
Throw New ArgumentException("statements not within the same statement list")
End If
If firstStatement.SpanStart > lastStatement.SpanStart Then
Throw New ArgumentException("first statement does not precede last statement")
End If
If Not TypeOf firstStatement Is ExecutableStatementSyntax OrElse Not TypeOf lastStatement Is ExecutableStatementSyntax Then
Return False
End If
' Test for |For ... Next x, y|
If IsNotUppermostForBlock(firstStatement) Then
Return False
End If
If firstStatement IsNot lastStatement AndAlso IsNotUppermostForBlock(lastStatement) Then
Return False
End If
If IsNodeInsideAttributeArguments(firstStatement) OrElse (firstStatement IsNot lastStatement AndAlso IsNodeInsideAttributeArguments(lastStatement)) Then
Return False
End If
Return True
End Function
''' <summary>
''' Check ForBlockSyntax for being the uppermost For block. By uppermost
''' For block we mean that if Next clause contains several control variables,
''' the uppermost block is the one which includes all the For blocks ending with
''' the same Next clause
''' </summary>
Private Function IsNotUppermostForBlock(forBlockOrStatement As VisualBasicSyntaxNode) As Boolean
Debug.Assert(forBlockOrStatement.Kind <> SyntaxKind.ForStatement)
Debug.Assert(forBlockOrStatement.Kind <> SyntaxKind.ForEachStatement)
Dim forBlock = TryCast(forBlockOrStatement, ForOrForEachBlockSyntax)
If forBlock Is Nothing Then
Return False
End If
Dim endNode As NextStatementSyntax = forBlock.NextStatement
If endNode IsNot Nothing Then
' The only case where the statement is valid is this case is
' that the Next clause contains one single control variable (or none)
Return endNode.ControlVariables.Count > 1
End If
' go down the For statements chain until the last and ensure it has as many
' variables as there were nested For statements
Dim nesting As Integer = 1
Do
If forBlock.Statements.Count = 0 Then
Return True
End If
Dim lastStatement = TryCast(forBlock.Statements.Last(), ForOrForEachBlockSyntax)
If lastStatement Is Nothing Then
Return True
End If
nesting += 1
endNode = lastStatement.NextStatement
If endNode IsNot Nothing Then
Return endNode.ControlVariables.Count <> nesting
End If
' Else - next level
forBlock = lastStatement
Loop
End Function
''' <summary>
''' Gets the semantic information of a for each statement.
''' </summary>
''' <param name="node">The for each syntax node.</param>
Friend Overrides Function GetForEachStatementInfoWorker(node As ForEachBlockSyntax) As ForEachStatementInfo
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
If model IsNot Nothing Then
Return model.GetForEachStatementInfoWorker(node)
Else
Return Nothing
End If
End Function
Friend Overrides Function GetAwaitExpressionInfoWorker(awaitExpression As AwaitExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As AwaitExpressionInfo
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(awaitExpression)
If model IsNot Nothing Then
Return model.GetAwaitExpressionInfoWorker(awaitExpression, cancellationToken)
Else
Return Nothing
End If
End Function
#Region "Region Analysis Context Creation"
''' <summary> Used to create a region analysis context
''' with failed flag set to be used in 'failed' scenarios </summary>
Private Function CreateFailedRegionAnalysisContext() As RegionAnalysisContext
Return New RegionAnalysisContext(Me.Compilation)
End Function
Private Function CreateRegionAnalysisContext(expression As ExpressionSyntax) As RegionAnalysisContext
Dim region As TextSpan = expression.Span
Dim memberModel As MemberSemanticModel = GetMemberSemanticModel(expression)
If memberModel Is Nothing Then
' Recover from error cases
Dim node As BoundBadStatement = New BoundBadStatement(expression, ImmutableArray(Of BoundNode).Empty)
Return New RegionAnalysisContext(Compilation, Nothing, node, node, node, region)
End If
Dim boundNode As BoundNode = memberModel.GetBoundRoot()
Dim boundExpression As BoundNode = memberModel.GetUpperBoundNode(expression)
Return New RegionAnalysisContext(Compilation, memberModel.MemberSymbol, boundNode, boundExpression, boundExpression, region)
End Function
Private Function CreateRegionAnalysisContext(firstStatement As StatementSyntax, lastStatement As StatementSyntax) As RegionAnalysisContext
Dim region As TextSpan = TextSpan.FromBounds(firstStatement.SpanStart, lastStatement.Span.End)
Dim memberModel As MemberSemanticModel = GetMemberSemanticModel(firstStatement)
If memberModel Is Nothing Then
' Recover from error cases
Dim node As BoundBadStatement = New BoundBadStatement(firstStatement, ImmutableArray(Of BoundNode).Empty)
Return New RegionAnalysisContext(Compilation, Nothing, node, node, node, region)
End If
Dim boundNode As BoundNode = memberModel.GetBoundRoot()
Dim firstBoundNode As BoundNode = memberModel.GetUpperBoundNode(firstStatement)
Dim lastBoundNode As BoundNode = memberModel.GetUpperBoundNode(lastStatement)
Return New RegionAnalysisContext(Compilation, memberModel.MemberSymbol, boundNode, firstBoundNode, lastBoundNode, region)
End Function
#End Region
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.Concurrent
Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports System.Collections.ObjectModel
Imports System.IO
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Operations
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Allows asking semantic questions about any node in a SyntaxTree within a Compilation.
''' </summary>
Friend Class SyntaxTreeSemanticModel
Inherits VBSemanticModel
Private ReadOnly _compilation As VisualBasicCompilation
Private ReadOnly _sourceModule As SourceModuleSymbol
Private ReadOnly _syntaxTree As SyntaxTree
Private ReadOnly _binderFactory As BinderFactory
Private ReadOnly _ignoresAccessibility As Boolean
' maps from a higher-level binder to an appropriate SemanticModel for the construct (such as a method, or initializer).
Private ReadOnly _semanticModelCache As New ConcurrentDictionary(Of (binder As Binder, ignoresAccessibility As Boolean), MemberSemanticModel)()
Friend Sub New(compilation As VisualBasicCompilation, sourceModule As SourceModuleSymbol, syntaxTree As SyntaxTree, Optional ignoreAccessibility As Boolean = False)
_compilation = compilation
_sourceModule = sourceModule
_syntaxTree = syntaxTree
_ignoresAccessibility = ignoreAccessibility
_binderFactory = New BinderFactory(sourceModule, syntaxTree)
End Sub
''' <summary>
''' The compilation associated with this binding.
''' </summary>
Public Overrides ReadOnly Property Compilation As VisualBasicCompilation
Get
Return _compilation
End Get
End Property
''' <summary>
''' The root node of the syntax tree that this binding is based on.
''' </summary>
Friend Overrides ReadOnly Property Root As SyntaxNode
Get
Return DirectCast(_syntaxTree.GetRoot(), VisualBasicSyntaxNode)
End Get
End Property
''' <summary>
''' The SyntaxTree that is bound
''' </summary>
Public Overrides ReadOnly Property SyntaxTree As SyntaxTree
Get
Return Me._syntaxTree
End Get
End Property
''' <summary>
''' Returns true if this Is a SemanticModel that ignores accessibility rules when answering semantic questions.
''' </summary>
Public NotOverridable Overrides ReadOnly Property IgnoresAccessibility As Boolean
Get
Return Me._ignoresAccessibility
End Get
End Property
''' <summary>
''' Get all the errors within the syntax tree associated with this object. Includes errors involving compiling
''' method bodies or initializers, in addition to the errors returned by GetDeclarationDiagnostics and parse errors.
''' </summary>
''' <param name="span">Optional span within the syntax tree for which to get diagnostics.
''' If no argument is specified, then diagnostics for the entire tree are returned.</param>
''' <param name="cancellationToken">A cancellation token that can be used to cancel the process of obtaining the
''' diagnostics.</param>
''' <remarks>
''' Because this method must semantically analyze all method bodies and initializers to check for diagnostics, it may
''' take a significant amount of time. Unlike GetDeclarationDiagnostics, diagnostics for method bodies and
''' initializers are not cached, the any semantic information used to obtain the diagnostics is discarded.
''' </remarks>
Public Overrides Function GetDiagnostics(Optional span As TextSpan? = Nothing, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic)
Return _compilation.GetDiagnosticsForSyntaxTree(CompilationStage.Compile, _syntaxTree, span, includeEarlierStages:=True, cancellationToken:=cancellationToken)
End Function
''' <summary>
''' Get all of the syntax errors within the syntax tree associated with this
''' object. Does not get errors involving declarations or compiling method bodies or initializers.
''' </summary>
''' <param name="span">Optional span within the syntax tree for which to get diagnostics.
''' If no argument is specified, then diagnostics for the entire tree are returned.</param>
''' <param name="cancellationToken">A cancellation token that can be used to cancel the
''' process of obtaining the diagnostics.</param>
Public Overrides Function GetSyntaxDiagnostics(Optional span As TextSpan? = Nothing, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic)
Return _compilation.GetDiagnosticsForSyntaxTree(CompilationStage.Parse, _syntaxTree, span, includeEarlierStages:=False, cancellationToken:=cancellationToken)
End Function
''' <summary>
''' Get all the syntax and declaration errors within the syntax tree associated with this object. Does not get
''' errors involving compiling method bodies or initializers.
''' </summary>
''' <param name="span">Optional span within the syntax tree for which to get diagnostics.
''' If no argument is specified, then diagnostics for the entire tree are returned.</param>
''' <param name="cancellationToken">A cancellation token that can be used to cancel the process of obtaining the
''' diagnostics.</param>
''' <remarks>The declaration errors for a syntax tree are cached. The first time this method is called, a ll
''' declarations are analyzed for diagnostics. Calling this a second time will return the cached diagnostics.
''' </remarks>
Public Overrides Function GetDeclarationDiagnostics(Optional span As TextSpan? = Nothing, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic)
Return _compilation.GetDiagnosticsForSyntaxTree(CompilationStage.Declare, _syntaxTree, span, includeEarlierStages:=False, cancellationToken:=cancellationToken)
End Function
''' <summary>
''' Get all the syntax and declaration errors within the syntax tree associated with this object. Does not get
''' errors involving compiling method bodies or initializers.
''' </summary>
''' <param name="span">Optional span within the syntax tree for which to get diagnostics.
''' If no argument is specified, then diagnostics for the entire tree are returned.</param>
''' <param name="cancellationToken">A cancellation token that can be used to cancel the process of obtaining the
''' diagnostics.</param>
''' <remarks>The declaration errors for a syntax tree are cached. The first time this method is called, a ll
''' declarations are analyzed for diagnostics. Calling this a second time will return the cached diagnostics.
''' </remarks>
Public Overrides Function GetMethodBodyDiagnostics(Optional span As TextSpan? = Nothing, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic)
Return _compilation.GetDiagnosticsForSyntaxTree(CompilationStage.Compile, _syntaxTree, span, includeEarlierStages:=False, cancellationToken:=cancellationToken)
End Function
' PERF: These variables avoid repeated allocation of Func(Of Binder, MemberSemanticModel) in GetMemberSemanticModel
Private ReadOnly _methodBodySemanticModelCreator As Func(Of (binder As Binder, ignoresAccessibility As Boolean), MemberSemanticModel) = Function(key As (binder As Binder, ignoresAccessibility As Boolean)) MethodBodySemanticModel.Create(Me, DirectCast(key.binder, SubOrFunctionBodyBinder), key.ignoresAccessibility)
Private ReadOnly _initializerSemanticModelCreator As Func(Of (binder As Binder, ignoresAccessibility As Boolean), MemberSemanticModel) = Function(key As (binder As Binder, ignoresAccessibility As Boolean)) InitializerSemanticModel.Create(Me, DirectCast(key.binder, DeclarationInitializerBinder), key.ignoresAccessibility)
Private ReadOnly _attributeSemanticModelCreator As Func(Of (binder As Binder, ignoresAccessibility As Boolean), MemberSemanticModel) = Function(key As (binder As Binder, ignoresAccessibility As Boolean)) AttributeSemanticModel.Create(Me, DirectCast(key.binder, AttributeBinder), key.ignoresAccessibility)
Public Function GetMemberSemanticModel(binder As Binder) As MemberSemanticModel
If TypeOf binder Is MethodBodyBinder Then
Return _semanticModelCache.GetOrAdd((binder, IgnoresAccessibility), _methodBodySemanticModelCreator)
End If
If TypeOf binder Is DeclarationInitializerBinder Then
Return _semanticModelCache.GetOrAdd((binder, IgnoresAccessibility), _initializerSemanticModelCreator)
End If
If TypeOf binder Is AttributeBinder Then
Return _semanticModelCache.GetOrAdd((binder, IgnoresAccessibility), _attributeSemanticModelCreator)
End If
If TypeOf binder Is TopLevelCodeBinder Then
Return _semanticModelCache.GetOrAdd((binder, IgnoresAccessibility), _methodBodySemanticModelCreator)
End If
Return Nothing
End Function
Friend Function GetMemberSemanticModel(position As Integer) As MemberSemanticModel
Dim binder As binder = _binderFactory.GetBinderForPosition(FindInitialNodeFromPosition(position), position)
Dim model = GetMemberSemanticModel(binder) ' Depends on the runtime type, so don't wrap in a SemanticModelBinder.
Debug.Assert(model Is Nothing OrElse model.RootBinder.IsSemanticModelBinder)
Return model
End Function
Friend Function GetMemberSemanticModel(node As SyntaxNode) As MemberSemanticModel
Return GetMemberSemanticModel(node.SpanStart)
End Function
Friend Overrides Function GetEnclosingBinder(position As Integer) As Binder
' special case if node is from interior of a member declaration (method body, etc)
Dim model As MemberSemanticModel = GetMemberSemanticModel(position)
If model IsNot Nothing Then
' If the node is from the interior of a member declaration, then we need to go further
' to find more nested binders.
Return model.GetEnclosingBinder(position)
Else
Dim binder As binder = _binderFactory.GetBinderForPosition(FindInitialNodeFromPosition(position), position)
Return SemanticModelBinder.Mark(binder, IgnoresAccessibility)
End If
End Function
Friend Overrides Function GetInvokeSummaryForRaiseEvent(node As RaiseEventStatementSyntax) As BoundNodeSummary
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
If model IsNot Nothing Then
Return model.GetInvokeSummaryForRaiseEvent(node)
Else
Return Nothing
End If
End Function
Friend Overrides Function GetCrefReferenceSymbolInfo(crefReference As CrefReferenceSyntax, options As VBSemanticModel.SymbolInfoOptions, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo
ValidateSymbolInfoOptions(options)
Debug.Assert(IsInCrefOrNameAttributeInterior(crefReference))
Return GetSymbolInfoForCrefOrNameAttributeReference(crefReference, options)
End Function
Friend Overrides Function GetExpressionSymbolInfo(node As ExpressionSyntax, options As SymbolInfoOptions, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo
ValidateSymbolInfoOptions(options)
node = SyntaxFactory.GetStandaloneExpression(DirectCast(node, ExpressionSyntax))
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
Dim result As SymbolInfo
If model IsNot Nothing Then
result = model.GetExpressionSymbolInfo(node, options, cancellationToken)
' If we didn't get anything and were in Type/Namespace only context, let's bind normally and see
' if any symbol comes out.
If result.IsEmpty AndAlso SyntaxFacts.IsInNamespaceOrTypeContext(node) Then
Dim tryAsExpression = TryBindNamespaceOrTypeAsExpression(node, options)
If Not tryAsExpression.IsEmpty Then
result = tryAsExpression
End If
End If
Else
' We don't have a bound tree to examine outside of a member semantic model. Instead, we just
' rebind the appropriate syntax as if we were binding it as part of symbol creation.
'
' if expression is not part of a member semantic model then
' a) it may be a reference to a type or namespace name
' b) it may be a reference to a interface member in an Implements clause
' c) it may be a reference to a field in an Handles clause
' d) it may be a reference to an event in an Handles clause
If SyntaxFacts.IsImplementedMember(node) Then
result = GetImplementedMemberSymbolInfo(DirectCast(node, QualifiedNameSyntax), options)
ElseIf SyntaxFacts.IsHandlesEvent(node) Then
result = GetHandlesEventSymbolInfo(DirectCast(node.Parent, HandlesClauseItemSyntax), options)
ElseIf SyntaxFacts.IsHandlesContainer(node) Then
Dim parent = node.Parent
If parent.Kind <> SyntaxKind.HandlesClauseItem Then
parent = parent.Parent
End If
result = GetHandlesContainerSymbolInfo(DirectCast(parent, HandlesClauseItemSyntax), options)
ElseIf SyntaxFacts.IsHandlesProperty(node) Then
result = GetHandlesPropertySymbolInfo(DirectCast(node.Parent.Parent, HandlesClauseItemSyntax), options)
ElseIf IsInCrefOrNameAttributeInterior(node) Then
result = GetSymbolInfoForCrefOrNameAttributeReference(node, options)
ElseIf SyntaxFacts.IsInNamespaceOrTypeContext(node) Then
' Bind the type or namespace name.
result = GetTypeOrNamespaceSymbolInfoNotInMember(DirectCast(node, TypeSyntax), options)
Else
result = SymbolInfo.None
End If
End If
Return result
End Function
Friend Overrides Function GetCollectionInitializerAddSymbolInfo(collectionInitializer As ObjectCreationExpressionSyntax, node As ExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(collectionInitializer)
If model IsNot Nothing Then
Return model.GetCollectionInitializerAddSymbolInfo(collectionInitializer, node, cancellationToken)
End If
Return SymbolInfo.None
End Function
Private Function TryBindNamespaceOrTypeAsExpression(node As ExpressionSyntax, options As SymbolInfoOptions) As SymbolInfo
' Let's bind expression normally and use what comes back as candidate symbols.
Dim binder As Binder = GetEnclosingBinder(node.SpanStart)
If binder IsNot Nothing Then
Dim bound As BoundExpression = binder.BindExpression(node, BindingDiagnosticBag.Discarded)
Dim newSymbolInfo = GetSymbolInfoForNode(options, New BoundNodeSummary(bound, bound, Nothing), binderOpt:=Nothing)
If Not newSymbolInfo.GetAllSymbols().IsDefaultOrEmpty Then
Return SymbolInfoFactory.Create(newSymbolInfo.GetAllSymbols(), LookupResultKind.NotATypeOrNamespace)
End If
End If
Return SymbolInfo.None
End Function
Friend Overrides Function GetExpressionTypeInfo(node As ExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As VisualBasicTypeInfo
node = SyntaxFactory.GetStandaloneExpression(DirectCast(node, ExpressionSyntax))
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
If model IsNot Nothing Then
Return model.GetExpressionTypeInfo(node, cancellationToken)
Else
' We don't have a bound tree to examine outside of a member semantic model. Instead, we just
' rebind the appropriate syntax as if we were binding it as part of symbol creation.
'
' if expression is not part of a member semantic model then
' a) it may be a reference to a type or namespace name
' b) it may be a reference to a interface member in an Implements clause
' c) it may be a reference to a field in an Handles clause
' d) it may be a reference to an event in an Handles clause
If SyntaxFacts.IsImplementedMember(node) Then
Return GetImplementedMemberTypeInfo(DirectCast(node, QualifiedNameSyntax))
ElseIf SyntaxFacts.IsHandlesEvent(node) Then
Return GetHandlesEventTypeInfo(DirectCast(node, IdentifierNameSyntax))
ElseIf SyntaxFacts.IsHandlesContainer(node) Then
Dim parent = node.Parent
If parent.Kind <> SyntaxKind.HandlesClauseItem Then
parent = parent.Parent
End If
Return GetHandlesContainerTypeInfo(DirectCast(parent, HandlesClauseItemSyntax))
ElseIf SyntaxFacts.IsHandlesProperty(node) Then
Return GetHandlesPropertyTypeInfo(DirectCast(node.Parent.Parent, HandlesClauseItemSyntax))
ElseIf IsInCrefOrNameAttributeInterior(node) Then
Dim typeSyntax = TryCast(node, TypeSyntax)
If typeSyntax IsNot Nothing Then
Return GetTypeInfoForCrefOrNameAttributeReference(typeSyntax)
End If
ElseIf SyntaxFacts.IsInNamespaceOrTypeContext(node) Then
' Bind the type or namespace name.
Return GetTypeOrNamespaceTypeInfoNotInMember(DirectCast(node, TypeSyntax))
End If
Return VisualBasicTypeInfo.None
End If
End Function
Friend Overrides Function GetExpressionMemberGroup(node As ExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Symbol)
node = SyntaxFactory.GetStandaloneExpression(DirectCast(node, ExpressionSyntax))
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
If model IsNot Nothing Then
Return model.GetExpressionMemberGroup(node, cancellationToken)
Else
Return ImmutableArray(Of Symbol).Empty
End If
End Function
Friend Overrides Function GetExpressionConstantValue(node As ExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As ConstantValue
node = SyntaxFactory.GetStandaloneExpression(DirectCast(node, ExpressionSyntax))
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
If model IsNot Nothing Then
Return model.GetExpressionConstantValue(node, cancellationToken)
Else
Return Nothing
End If
End Function
Friend Overrides Function GetOperationWorker(node As VisualBasicSyntaxNode, cancellationToken As CancellationToken) As IOperation
Dim model As MemberSemanticModel
Dim methodBlock = TryCast(node, MethodBlockBaseSyntax)
If methodBlock IsNot Nothing Then
' Trying to get the MemberSemanticModel for a MethodBlock will end up returning
' nothing. That's because trying to get Binder for the MethodBlock will actually
' return the binder for the containing type. To avoid this we ask for the model
' passing in a position at the end of the method's starting block-statement.
' This will cause it to try to get the interior MemberSemanticModel.
model = GetMemberSemanticModel(methodBlock.BlockStatement.EndPosition)
Else
model = Me.GetMemberSemanticModel(node)
End If
If model IsNot Nothing Then
Return model.GetOperationWorker(node, cancellationToken)
Else
Return Nothing
End If
End Function
Friend Overrides Function GetAttributeSymbolInfo(attribute As AttributeSyntax, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(attribute)
If model IsNot Nothing Then
Return model.GetAttributeSymbolInfo(attribute, cancellationToken)
Else
Return SymbolInfo.None
End If
End Function
Friend Overrides Function GetQueryClauseSymbolInfo(node As QueryClauseSyntax, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
If model IsNot Nothing Then
Return model.GetQueryClauseSymbolInfo(node, cancellationToken)
Else
Return SymbolInfo.None
End If
End Function
Friend Overrides Function GetLetClauseSymbolInfo(node As ExpressionRangeVariableSyntax, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
If model IsNot Nothing Then
Return model.GetLetClauseSymbolInfo(node, cancellationToken)
Else
Return SymbolInfo.None
End If
End Function
Friend Overrides Function GetOrderingSymbolInfo(node As OrderingSyntax, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
If model IsNot Nothing Then
Return model.GetOrderingSymbolInfo(node, cancellationToken)
Else
Return SymbolInfo.None
End If
End Function
Friend Overrides Function GetAggregateClauseSymbolInfoWorker(node As AggregateClauseSyntax, Optional cancellationToken As CancellationToken = Nothing) As AggregateClauseSymbolInfo
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
If model IsNot Nothing Then
Return model.GetAggregateClauseSymbolInfoWorker(node, cancellationToken)
Else
Return New AggregateClauseSymbolInfo(SymbolInfo.None, SymbolInfo.None)
End If
End Function
Friend Overrides Function GetCollectionRangeVariableSymbolInfoWorker(node As CollectionRangeVariableSyntax, Optional cancellationToken As CancellationToken = Nothing) As CollectionRangeVariableSymbolInfo
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
If model IsNot Nothing Then
Return model.GetCollectionRangeVariableSymbolInfoWorker(node, cancellationToken)
Else
Return CollectionRangeVariableSymbolInfo.None
End If
End Function
Friend Overrides Function GetAttributeTypeInfo(attribute As AttributeSyntax, Optional cancellationToken As CancellationToken = Nothing) As VisualBasicTypeInfo
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(attribute)
If model IsNot Nothing Then
Return model.GetAttributeTypeInfo(attribute, cancellationToken)
Else
Return VisualBasicTypeInfo.None
End If
End Function
Friend Overrides Function GetAttributeMemberGroup(attribute As AttributeSyntax, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Symbol)
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(attribute)
If model IsNot Nothing Then
Return model.GetAttributeMemberGroup(attribute, cancellationToken)
Else
Return ImmutableArray(Of Symbol).Empty
End If
End Function
Private Function GetTypeOrNamespaceSymbolNotInMember(expression As TypeSyntax) As Symbol
' Set up the binding context.
Dim binder As Binder = GetEnclosingBinder(expression.SpanStart)
' Attempt to bind the type or namespace
Dim resultSymbol As Symbol
If SyntaxFacts.IsInTypeOnlyContext(expression) Then
resultSymbol = binder.BindTypeOrAliasSyntax(expression, BindingDiagnosticBag.Discarded)
Else
resultSymbol = binder.BindNamespaceOrTypeOrAliasSyntax(expression, BindingDiagnosticBag.Discarded)
End If
' Create the result.
Return resultSymbol
End Function
' Get the symbol info of reference from 'cref' or 'name' attribute value
Private Function GetSymbolInfoForCrefOrNameAttributeReference(node As VisualBasicSyntaxNode, options As SymbolInfoOptions) As SymbolInfo
Dim typeParameters As ImmutableArray(Of Symbol) = Nothing
Dim result As ImmutableArray(Of Symbol) = GetCrefOrNameAttributeReferenceSymbols(node, (options And SymbolInfoOptions.ResolveAliases) = 0, typeParameters)
If result.IsDefaultOrEmpty Then
If typeParameters.IsDefaultOrEmpty Then
Return SymbolInfo.None
Else
Return SymbolInfoFactory.Create(typeParameters, LookupResultKind.NotReferencable)
End If
End If
If result.Length = 1 Then
Dim retValue As SymbolInfo = GetSymbolInfoForSymbol(result(0), options)
If retValue.CandidateReason = CandidateReason.None Then
Return retValue
End If
result = ImmutableArray(Of Symbol).Empty
End If
Dim symbolsBuilder = ArrayBuilder(Of Symbol).GetInstance()
symbolsBuilder.AddRange(result)
Dim symbols As ImmutableArray(Of Symbol) = RemoveErrorTypesAndDuplicates(symbolsBuilder, options)
symbolsBuilder.Free()
If symbols.Length = 0 Then
Return SymbolInfoFactory.Create(symbols, LookupResultKind.Empty)
End If
Return SymbolInfoFactory.Create(symbols, If(symbols.Length = 1, LookupResultKind.Good, LookupResultKind.Ambiguous))
End Function
' Get the type info of reference from 'cref' or 'name' attribute value
Private Function GetTypeInfoForCrefOrNameAttributeReference(name As TypeSyntax) As VisualBasicTypeInfo
Dim typeParameters As ImmutableArray(Of Symbol) = Nothing
Dim result As ImmutableArray(Of Symbol) = GetCrefOrNameAttributeReferenceSymbols(name, preserveAlias:=False, typeParameters:=typeParameters)
If result.IsDefaultOrEmpty Then
result = typeParameters
If result.IsDefaultOrEmpty Then
Return VisualBasicTypeInfo.None
End If
End If
If result.Length > 1 Then
Return VisualBasicTypeInfo.None
End If
Dim resultSymbol As Symbol = result(0)
Select Case resultSymbol.Kind
Case SymbolKind.ArrayType,
SymbolKind.TypeParameter,
SymbolKind.NamedType
Return GetTypeInfoForSymbol(resultSymbol)
End Select
Return VisualBasicTypeInfo.None
End Function
''' <summary>
''' Get symbols referenced from 'cref' or 'name' attribute value.
''' </summary>
''' <param name="node">Node to bind.</param>
''' <param name="preserveAlias">True to leave <see cref="AliasSymbol"/>s, False to unwrap them.</param>
''' <param name="typeParameters">Out: symbols that would have been in the return value but improperly refer to type parameters.</param>
''' <returns>Referenced symbols, less type parameters.</returns>
Private Function GetCrefOrNameAttributeReferenceSymbols(node As VisualBasicSyntaxNode,
preserveAlias As Boolean,
<Out> ByRef typeParameters As ImmutableArray(Of Symbol)) As ImmutableArray(Of Symbol)
typeParameters = ImmutableArray(Of Symbol).Empty
' We only allow a certain list of node kinds to be processed here
If node.Kind = SyntaxKind.XmlString Then
Return Nothing
End If
Debug.Assert(node.Kind = SyntaxKind.IdentifierName OrElse
node.Kind = SyntaxKind.GenericName OrElse
node.Kind = SyntaxKind.PredefinedType OrElse
node.Kind = SyntaxKind.QualifiedName OrElse
node.Kind = SyntaxKind.GlobalName OrElse
node.Kind = SyntaxKind.QualifiedCrefOperatorReference OrElse
node.Kind = SyntaxKind.CrefOperatorReference OrElse
node.Kind = SyntaxKind.CrefReference)
' We need to find trivia's enclosing binder first
Dim parent As VisualBasicSyntaxNode = node.Parent
Debug.Assert(parent IsNot Nothing)
Dim attributeNode As BaseXmlAttributeSyntax = Nothing
Do
Debug.Assert(parent IsNot Nothing)
Select Case parent.Kind
Case SyntaxKind.XmlCrefAttribute,
SyntaxKind.XmlNameAttribute
attributeNode = DirectCast(parent, BaseXmlAttributeSyntax)
Case SyntaxKind.DocumentationCommentTrivia
Exit Do
End Select
parent = parent.Parent
Loop
Debug.Assert(parent IsNot Nothing)
If attributeNode Is Nothing Then
Return Nothing
End If
Dim isCrefAttribute As Boolean = attributeNode.Kind = SyntaxKind.XmlCrefAttribute
Debug.Assert(isCrefAttribute OrElse attributeNode.Kind = SyntaxKind.XmlNameAttribute)
Dim trivia As SyntaxTrivia = DirectCast(parent, DocumentationCommentTriviaSyntax).ParentTrivia
If trivia.Kind = SyntaxKind.None Then
Return Nothing
End If
Dim token As SyntaxToken = CType(trivia.Token, SyntaxToken)
If token.Kind = SyntaxKind.None Then
Return Nothing
End If
Dim docCommentBinder = Me._binderFactory.GetBinderForPosition(node, node.SpanStart)
docCommentBinder = SemanticModelBinder.Mark(docCommentBinder, IgnoresAccessibility)
If isCrefAttribute Then
Dim symbols As ImmutableArray(Of Symbol)
Dim isTopLevel As Boolean
If node.Kind = SyntaxKind.CrefReference Then
isTopLevel = True
symbols = docCommentBinder.BindInsideCrefAttributeValue(DirectCast(node, CrefReferenceSyntax), preserveAlias, Nothing, CompoundUseSiteInfo(Of AssemblySymbol).Discarded)
Else
isTopLevel = node.Parent IsNot Nothing AndAlso node.Parent.Kind = SyntaxKind.CrefReference
symbols = docCommentBinder.BindInsideCrefAttributeValue(DirectCast(node, TypeSyntax), preserveAlias, Nothing, CompoundUseSiteInfo(Of AssemblySymbol).Discarded)
End If
If isTopLevel Then
Dim symbolsBuilder As ArrayBuilder(Of Symbol) = Nothing
Dim typeParametersBuilder As ArrayBuilder(Of Symbol) = Nothing
For i = 0 To symbols.Length - 1
Dim symbol = symbols(i)
If symbol.Kind = SymbolKind.TypeParameter Then
If symbolsBuilder Is Nothing Then
symbolsBuilder = ArrayBuilder(Of Symbol).GetInstance(i)
typeParametersBuilder = ArrayBuilder(Of Symbol).GetInstance()
symbolsBuilder.AddRange(symbols, i)
End If
typeParametersBuilder.Add(DirectCast(symbol, TypeParameterSymbol))
ElseIf symbolsBuilder IsNot Nothing Then
symbolsBuilder.Add(symbol)
End If
Next
If symbolsBuilder IsNot Nothing Then
symbols = symbolsBuilder.ToImmutableAndFree()
typeParameters = typeParametersBuilder.ToImmutableAndFree()
End If
End If
Return symbols
Else
Return docCommentBinder.BindXmlNameAttributeValue(DirectCast(node, IdentifierNameSyntax), useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded)
End If
End Function
' Get the symbol info of type or namespace syntax that is outside a member body
Private Function GetTypeOrNamespaceSymbolInfoNotInMember(expression As TypeSyntax, options As SymbolInfoOptions) As SymbolInfo
Dim resultSymbol As Symbol = GetTypeOrNamespaceSymbolNotInMember(expression)
' Deal with the case of a namespace group. We may need to bind more in order to see if the ambiguity can be resolved.
If resultSymbol.Kind = SymbolKind.Namespace AndAlso
expression.Parent IsNot Nothing AndAlso
expression.Parent.Kind = SyntaxKind.QualifiedName AndAlso
DirectCast(expression.Parent, QualifiedNameSyntax).Left Is expression Then
Dim ns = DirectCast(resultSymbol, NamespaceSymbol)
If ns.NamespaceKind = NamespaceKindNamespaceGroup Then
Dim parentInfo As SymbolInfo = GetTypeOrNamespaceSymbolInfoNotInMember(DirectCast(expression.Parent, QualifiedNameSyntax), Nothing)
If Not parentInfo.IsEmpty Then
Dim namespaces = New SmallDictionary(Of NamespaceSymbol, Boolean)()
If parentInfo.Symbol IsNot Nothing Then
If Not Binder.AddReceiverNamespaces(namespaces, DirectCast(parentInfo.Symbol, Symbol), Compilation) Then
namespaces = Nothing
End If
Else
For Each candidate In parentInfo.CandidateSymbols
If Not Binder.AddReceiverNamespaces(namespaces, DirectCast(candidate, Symbol), Compilation) Then
namespaces = Nothing
Exit For
End If
Next
End If
If namespaces IsNot Nothing AndAlso namespaces.Count < ns.ConstituentNamespaces.Length Then
resultSymbol = DirectCast(ns, MergedNamespaceSymbol).Shrink(namespaces.Keys)
End If
End If
End If
End If
' Create the result.
Dim result = GetSymbolInfoForSymbol(resultSymbol, options)
' If we didn't get anything and were in Type/Namespace only context, let's bind normally and see
' if any symbol comes out.
If result.IsEmpty Then
Dim tryAsExpression = TryBindNamespaceOrTypeAsExpression(expression, options)
If Not tryAsExpression.IsEmpty Then
result = tryAsExpression
End If
End If
Return result
End Function
' Get the symbol info of type or namespace syntax that is outside a member body
Private Function GetTypeOrNamespaceTypeInfoNotInMember(expression As TypeSyntax) As VisualBasicTypeInfo
Dim resultSymbol As Symbol = GetTypeOrNamespaceSymbolNotInMember(expression)
' Create the result.
Return GetTypeInfoForSymbol(resultSymbol)
End Function
Private Function GetImplementedMemberAndResultKind(symbolBuilder As ArrayBuilder(Of Symbol), memberName As QualifiedNameSyntax) As LookupResultKind
Debug.Assert(symbolBuilder.Count = 0)
Dim resultKind As LookupResultKind = LookupResultKind.Good
' Set up the binding context.
Dim binder As Binder = GetEnclosingBinder(memberName.SpanStart)
' Figure out the symbol this implements clause is on, and bind the syntax for it.
Dim implementingMemberSyntax = TryCast(memberName.Parent.Parent, MethodBaseSyntax)
If implementingMemberSyntax IsNot Nothing Then
Dim implementingMember = GetDeclaredSymbol(implementingMemberSyntax)
If implementingMember IsNot Nothing Then
Select Case implementingMember.Kind
Case SymbolKind.Method
ImplementsHelper.FindExplicitlyImplementedMember(Of MethodSymbol)(
DirectCast(implementingMember, MethodSymbol),
DirectCast(implementingMember, MethodSymbol).ContainingType,
memberName,
binder,
BindingDiagnosticBag.Discarded,
symbolBuilder,
resultKind)
Case SymbolKind.Property
ImplementsHelper.FindExplicitlyImplementedMember(Of PropertySymbol)(
DirectCast(implementingMember, PropertySymbol),
DirectCast(implementingMember, PropertySymbol).ContainingType,
memberName,
binder,
BindingDiagnosticBag.Discarded,
symbolBuilder,
resultKind)
Case SymbolKind.Event
ImplementsHelper.FindExplicitlyImplementedMember(Of EventSymbol)(
DirectCast(implementingMember, EventSymbol),
DirectCast(implementingMember, EventSymbol).ContainingType,
memberName,
binder,
BindingDiagnosticBag.Discarded,
symbolBuilder,
resultKind)
Case Else
Throw ExceptionUtilities.UnexpectedValue(implementingMember.Kind)
End Select
End If
End If
Return resultKind
End Function
Private Function GetHandledEventOrContainerSymbolsAndResultKind(eventSymbolBuilder As ArrayBuilder(Of Symbol),
containerSymbolBuilder As ArrayBuilder(Of Symbol),
propertySymbolBuilder As ArrayBuilder(Of Symbol),
handlesClause As HandlesClauseItemSyntax) As LookupResultKind
Dim resultKind As LookupResultKind = LookupResultKind.Good
' Set up the binding context.
Dim binder As Binder = GetEnclosingBinder(handlesClause.SpanStart)
' Figure out the symbol this handles clause is on, and bind the syntax for it.
Dim handlingMethodSyntax = TryCast(handlesClause.Parent.Parent, MethodStatementSyntax)
If handlingMethodSyntax IsNot Nothing Then
Dim implementingMember = GetDeclaredSymbol(handlingMethodSyntax)
If implementingMember IsNot Nothing Then
Dim methodSym = DirectCast(implementingMember, SourceMemberMethodSymbol)
methodSym.BindSingleHandlesClause(handlesClause,
binder,
BindingDiagnosticBag.Discarded,
eventSymbolBuilder,
containerSymbolBuilder,
propertySymbolBuilder,
resultKind)
End If
End If
Return resultKind
End Function
' Get the symbol info of an implemented member in an implements clause.
Private Function GetImplementedMemberSymbolInfo(memberName As QualifiedNameSyntax, options As SymbolInfoOptions) As SymbolInfo
Dim implementedMemberBuilder As ArrayBuilder(Of Symbol) = ArrayBuilder(Of Symbol).GetInstance()
Dim resultKind As LookupResultKind = GetImplementedMemberAndResultKind(implementedMemberBuilder, memberName)
Dim symbols As ImmutableArray(Of Symbol) = RemoveErrorTypesAndDuplicates(implementedMemberBuilder, options)
implementedMemberBuilder.Free()
Return SymbolInfoFactory.Create(symbols, resultKind)
End Function
' Get the symbol info of a handled event in a handles clause.
Private Function GetHandlesEventSymbolInfo(handlesClause As HandlesClauseItemSyntax, options As SymbolInfoOptions) As SymbolInfo
Dim builder As ArrayBuilder(Of Symbol) = ArrayBuilder(Of Symbol).GetInstance()
Dim resultKind As LookupResultKind = GetHandledEventOrContainerSymbolsAndResultKind(eventSymbolBuilder:=builder,
containerSymbolBuilder:=Nothing,
propertySymbolBuilder:=Nothing,
handlesClause:=handlesClause)
Dim symbols As ImmutableArray(Of Symbol) = RemoveErrorTypesAndDuplicates(builder, options)
builder.Free()
Return SymbolInfoFactory.Create(symbols, resultKind)
End Function
' Get the symbol info of an identifier event container in a handles clause.
Private Function GetHandlesContainerSymbolInfo(handlesClause As HandlesClauseItemSyntax, options As SymbolInfoOptions) As SymbolInfo
Dim builder As ArrayBuilder(Of Symbol) = ArrayBuilder(Of Symbol).GetInstance()
Dim resultKind As LookupResultKind = GetHandledEventOrContainerSymbolsAndResultKind(eventSymbolBuilder:=Nothing,
containerSymbolBuilder:=builder,
propertySymbolBuilder:=Nothing,
handlesClause:=handlesClause)
Dim symbols As ImmutableArray(Of Symbol) = RemoveErrorTypesAndDuplicates(builder, options)
builder.Free()
Return SymbolInfoFactory.Create(symbols, resultKind)
End Function
' Get the symbol info of a withevents sourcing property in a handles clause.
Private Function GetHandlesPropertySymbolInfo(handlesClause As HandlesClauseItemSyntax, options As SymbolInfoOptions) As SymbolInfo
Dim builder As ArrayBuilder(Of Symbol) = ArrayBuilder(Of Symbol).GetInstance()
Dim resultKind As LookupResultKind = GetHandledEventOrContainerSymbolsAndResultKind(eventSymbolBuilder:=Nothing,
containerSymbolBuilder:=Nothing,
propertySymbolBuilder:=builder,
handlesClause:=handlesClause)
Dim symbols As ImmutableArray(Of Symbol) = RemoveErrorTypesAndDuplicates(builder, options)
builder.Free()
Return SymbolInfoFactory.Create(symbols, resultKind)
End Function
' Get the type info of a implemented member in a implements clause.
Private Function GetImplementedMemberTypeInfo(memberName As QualifiedNameSyntax) As VisualBasicTypeInfo
' Implemented members have no type.
Return VisualBasicTypeInfo.None
End Function
' Get the type info of a implemented member in a implements clause.
Private Function GetHandlesEventTypeInfo(memberName As IdentifierNameSyntax) As VisualBasicTypeInfo
' Handled events have no type.
Return VisualBasicTypeInfo.None
End Function
' Get the type info of a implemented member in a implements clause.
Private Function GetHandlesContainerTypeInfo(memberName As HandlesClauseItemSyntax) As VisualBasicTypeInfo
' Handled events have no type.
Return VisualBasicTypeInfo.None
End Function
' Get the type info of a implemented member in a implements clause.
Private Function GetHandlesPropertyTypeInfo(memberName As HandlesClauseItemSyntax) As VisualBasicTypeInfo
' Handled events have no type.
Return VisualBasicTypeInfo.None
End Function
''' <summary>
''' Checks all symbol locations against the syntax provided and return symbol if any of the locations is
''' inside the syntax span. Returns Nothing otherwise.
''' </summary>
Private Function CheckSymbolLocationsAgainstSyntax(symbol As NamedTypeSymbol, nodeToCheck As VisualBasicSyntaxNode) As NamedTypeSymbol
For Each location In symbol.Locations
If location.SourceTree Is Me.SyntaxTree AndAlso nodeToCheck.Span.Contains(location.SourceSpan) Then
Return symbol
End If
Next
Return Nothing
End Function
''' <summary>
''' Given a delegate declaration, get the corresponding type symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares a type.</param>
''' <returns>The type symbol that was declared.</returns>
Public Overloads Function GetDeclaredSymbol(declarationSyntax As DelegateStatementSyntax, Optional cancellationToken As CancellationToken = Nothing) As NamedTypeSymbol
If declarationSyntax Is Nothing Then Throw New ArgumentNullException(NameOf(declarationSyntax))
If Not IsInTree(declarationSyntax) Then Throw New ArgumentException(VBResources.DeclarationSyntaxNotWithinTree)
' Don't need to wrap in a SemanticModelBinder, since we're not binding.
Dim binder As Binder = _binderFactory.GetNamedTypeBinder(declarationSyntax)
If binder IsNot Nothing AndAlso TypeOf binder Is NamedTypeBinder Then
Return CheckSymbolLocationsAgainstSyntax(DirectCast(binder.ContainingType, NamedTypeSymbol), declarationSyntax)
Else
Return Nothing ' Can this happen? Maybe in some edge case error cases.
End If
End Function
''' <summary>
''' Given a type declaration, get the corresponding type symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares a type.</param>
''' <returns>The type symbol that was declared.</returns>
Public Overloads Overrides Function GetDeclaredSymbol(declarationSyntax As TypeStatementSyntax, Optional cancellationToken As CancellationToken = Nothing) As INamedTypeSymbol
If declarationSyntax Is Nothing Then Throw New ArgumentNullException(NameOf(declarationSyntax))
If Not IsInTree(declarationSyntax) Then Throw New ArgumentException(VBResources.DeclarationSyntaxNotWithinTree)
' Don't need to wrap in a SemanticModelBinder, since we're not binding.
Dim binder As Binder = _binderFactory.GetNamedTypeBinder(declarationSyntax)
If binder IsNot Nothing AndAlso TypeOf binder Is NamedTypeBinder Then
Return CheckSymbolLocationsAgainstSyntax(DirectCast(binder.ContainingType, NamedTypeSymbol), declarationSyntax)
Else
Return Nothing ' Can this happen? Maybe in some edge case error cases.
End If
End Function
''' <summary>
''' Given a enum declaration, get the corresponding type symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares an enum.</param>
''' <returns>The type symbol that was declared.</returns>
Public Overloads Overrides Function GetDeclaredSymbol(declarationSyntax As EnumStatementSyntax, Optional cancellationToken As CancellationToken = Nothing) As INamedTypeSymbol
If declarationSyntax Is Nothing Then Throw New ArgumentNullException(NameOf(declarationSyntax))
If Not IsInTree(declarationSyntax) Then Throw New ArgumentException(VBResources.DeclarationSyntaxNotWithinTree)
' Don't need to wrap in a SemanticModelBinder, since we're not binding.
Dim binder As Binder = _binderFactory.GetNamedTypeBinder(declarationSyntax)
If binder IsNot Nothing AndAlso TypeOf binder Is NamedTypeBinder Then
Return CheckSymbolLocationsAgainstSyntax(DirectCast(binder.ContainingType, NamedTypeSymbol), declarationSyntax)
Else
Return Nothing ' Can this happen? Maybe in some edge case with errors
End If
End Function
''' <summary>
''' Given a namespace declaration, get the corresponding type symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares a namespace.</param>
''' <returns>The namespace symbol that was declared.</returns>
Public Overloads Overrides Function GetDeclaredSymbol(declarationSyntax As NamespaceStatementSyntax, Optional cancellationToken As CancellationToken = Nothing) As INamespaceSymbol
If declarationSyntax Is Nothing Then Throw New ArgumentNullException(NameOf(declarationSyntax))
If Not IsInTree(declarationSyntax) Then Throw New ArgumentException(VBResources.DeclarationSyntaxNotWithinTree)
Dim parentBlock = TryCast(declarationSyntax.Parent, NamespaceBlockSyntax)
If parentBlock IsNot Nothing Then
' Don't need to wrap in a SemanticModelBinder, since we're not binding.
Dim binder As Binder = _binderFactory.GetNamespaceBinder(parentBlock)
If binder IsNot Nothing AndAlso TypeOf binder Is NamespaceBinder Then
Return DirectCast(binder.ContainingNamespaceOrType, NamespaceSymbol)
End If
End If
Return Nothing ' Edge case with errors
End Function
''' <summary>
''' Given a method, property, or event declaration, get the corresponding symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares a method, property, or event.</param>
''' <returns>The method, property, or event symbol that was declared.</returns>
Friend Overloads Overrides Function GetDeclaredSymbol(declarationSyntax As MethodBaseSyntax, Optional cancellationToken As CancellationToken = Nothing) As ISymbol
If declarationSyntax Is Nothing Then Throw New ArgumentNullException(NameOf(declarationSyntax))
If Not IsInTree(declarationSyntax) Then
Throw New ArgumentException(VBResources.DeclarationSyntaxNotWithinTree)
End If
' Delegate declarations are a subclass of MethodBaseSyntax syntax-wise, but they are
' more like a type declaration, so we need to special case here.
If declarationSyntax.Kind = SyntaxKind.DelegateFunctionStatement OrElse
declarationSyntax.Kind = SyntaxKind.DelegateSubStatement Then
Return GetDeclaredSymbol(DirectCast(declarationSyntax, DelegateStatementSyntax), cancellationToken)
End If
Dim statementSyntax = TryCast(declarationSyntax.Parent, StatementSyntax)
If statementSyntax IsNot Nothing Then
' get parent type block
Dim parentTypeBlock As TypeBlockSyntax = Nothing
Select Case statementSyntax.Kind
Case SyntaxKind.ClassBlock, SyntaxKind.EnumBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ModuleBlock
parentTypeBlock = TryCast(statementSyntax, TypeBlockSyntax)
Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorBlock, SyntaxKind.PropertyBlock, SyntaxKind.EventBlock
parentTypeBlock = TryCast(statementSyntax.Parent, TypeBlockSyntax)
' EDMAURER maybe this is a top-level decl in which case the parent is a CompilationUnitSyntax
If parentTypeBlock Is Nothing AndAlso statementSyntax.Parent IsNot Nothing Then
Dim namespaceToLookInForImplicitType As INamespaceSymbol = Nothing
Select Case statementSyntax.Parent.Kind
Case SyntaxKind.CompilationUnit
namespaceToLookInForImplicitType = Me._sourceModule.RootNamespace
Case SyntaxKind.NamespaceBlock
namespaceToLookInForImplicitType = GetDeclaredSymbol(DirectCast(statementSyntax.Parent, NamespaceBlockSyntax), cancellationToken)
End Select
If namespaceToLookInForImplicitType IsNot Nothing Then
Dim implicitType = DirectCast(namespaceToLookInForImplicitType.GetMembers(TypeSymbol.ImplicitTypeName).SingleOrDefault(), NamedTypeSymbol)
If implicitType IsNot Nothing Then
Return SourceMethodSymbol.FindSymbolFromSyntax(declarationSyntax, _syntaxTree, implicitType)
End If
End If
End If
Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock
' redirect to upper property or event symbol
If statementSyntax.Parent IsNot Nothing Then
parentTypeBlock = TryCast(statementSyntax.Parent.Parent, TypeBlockSyntax)
End If
Case SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock
' redirect to upper event symbol
If statementSyntax.Parent IsNot Nothing Then
parentTypeBlock = TryCast(statementSyntax.Parent.Parent, TypeBlockSyntax)
End If
Case Else
' broken code scenarios end up here
' to end up here, a methodbasesyntax's parent must be a statement and not be one of the above.
' The parser does e.g. not generate an enclosing block for accessors statements,
' but for Operators, conversions and constructors.
' The case where an invalid accessor is contained in e.g. an interface is handled further down in "FindSymbolFromSyntax".
' TODO: consider always creating a (missing) block around the statements in the parser
' We are asserting what we know so far. If this assert fails, this is not a bug, we either need to remove this assert or relax the assert.
Debug.Assert(statementSyntax.Kind = SyntaxKind.NamespaceBlock AndAlso
(TypeOf (declarationSyntax) Is AccessorStatementSyntax OrElse
TypeOf (declarationSyntax) Is EventStatementSyntax OrElse
TypeOf (declarationSyntax) Is MethodStatementSyntax OrElse
TypeOf (declarationSyntax) Is PropertyStatementSyntax))
Return Nothing
End Select
If parentTypeBlock IsNot Nothing Then
Dim containingType = DirectCast(GetDeclaredSymbol(parentTypeBlock.BlockStatement, cancellationToken), NamedTypeSymbol)
If containingType IsNot Nothing Then
Return SourceMethodSymbol.FindSymbolFromSyntax(declarationSyntax, _syntaxTree, containingType)
End If
End If
End If
Return Nothing
End Function
''' <summary>
''' Given a parameter declaration, get the corresponding parameter symbol.
''' </summary>
''' <param name="parameter">The syntax node that declares a parameter.</param>
''' <returns>The parameter symbol that was declared.</returns>
Public Overloads Overrides Function GetDeclaredSymbol(parameter As ParameterSyntax, Optional cancellationToken As CancellationToken = Nothing) As IParameterSymbol
If parameter Is Nothing Then
Throw New ArgumentNullException(NameOf(parameter))
End If
Dim paramList As ParameterListSyntax = TryCast(parameter.Parent, ParameterListSyntax)
If paramList IsNot Nothing Then
Dim declarationSyntax As MethodBaseSyntax = TryCast(paramList.Parent, MethodBaseSyntax)
If declarationSyntax IsNot Nothing Then
Dim symbol = GetDeclaredSymbol(declarationSyntax, cancellationToken)
If symbol IsNot Nothing Then
Select Case symbol.Kind
Case SymbolKind.Method
Return GetParameterSymbol(DirectCast(symbol, MethodSymbol).Parameters, parameter)
Case SymbolKind.Event
Dim eventSymbol As EventSymbol = DirectCast(symbol, EventSymbol)
Dim type = TryCast(eventSymbol.Type, NamedTypeSymbol)
If type?.AssociatedSymbol Is eventSymbol Then
Return GetParameterSymbol(type.DelegateInvokeMethod.Parameters, parameter)
End If
Return Nothing
Case SymbolKind.Property
Return GetParameterSymbol(DirectCast(symbol, PropertySymbol).Parameters, parameter)
Case SymbolKind.NamedType
' check for being delegate
Dim typeSymbol = DirectCast(symbol, NamedTypeSymbol)
Debug.Assert(typeSymbol.TypeKind = TYPEKIND.Delegate)
If typeSymbol.DelegateInvokeMethod IsNot Nothing Then
Return GetParameterSymbol(typeSymbol.DelegateInvokeMethod.Parameters, parameter)
End If
End Select
ElseIf TypeOf declarationSyntax Is LambdaHeaderSyntax Then
' This could be a lambda parameter.
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(declarationSyntax)
If model IsNot Nothing Then
Return model.GetDeclaredSymbol(parameter, cancellationToken)
End If
End If
End If
End If
Return Nothing
End Function
''' <summary>
''' Given a type parameter declaration, get the corresponding type parameter symbol.
''' </summary>
''' <param name="typeParameter">The syntax node that declares a type parameter.</param>
''' <returns>The type parameter symbol that was declared.</returns>
Public Overloads Overrides Function GetDeclaredSymbol(typeParameter As TypeParameterSyntax, Optional cancellationToken As CancellationToken = Nothing) As ITypeParameterSymbol
If typeParameter Is Nothing Then
Throw New ArgumentNullException(NameOf(typeParameter))
End If
If Not IsInTree(typeParameter) Then
Throw New ArgumentException(VBResources.TypeParameterNotWithinTree)
End If
Dim symbol As ISymbol = Nothing
Dim typeParamList = TryCast(typeParameter.Parent, TypeParameterListSyntax)
If typeParamList IsNot Nothing AndAlso typeParamList.Parent IsNot Nothing Then
If TypeOf typeParamList.Parent Is MethodStatementSyntax Then
symbol = GetDeclaredSymbol(DirectCast(typeParamList.Parent, MethodStatementSyntax), cancellationToken)
ElseIf TypeOf typeParamList.Parent Is TypeStatementSyntax Then
symbol = GetDeclaredSymbol(DirectCast(typeParamList.Parent, TypeStatementSyntax), cancellationToken)
ElseIf TypeOf typeParamList.Parent Is DelegateStatementSyntax Then
symbol = GetDeclaredSymbol(DirectCast(typeParamList.Parent, DelegateStatementSyntax), cancellationToken)
End If
If symbol IsNot Nothing Then
Dim typeSymbol = TryCast(symbol, NamedTypeSymbol)
If typeSymbol IsNot Nothing Then
Return Me.GetTypeParameterSymbol(typeSymbol.TypeParameters, typeParameter)
End If
Dim methodSymbol = TryCast(symbol, MethodSymbol)
If methodSymbol IsNot Nothing Then
Return Me.GetTypeParameterSymbol(methodSymbol.TypeParameters, typeParameter)
End If
End If
End If
Return Nothing
End Function
' Get a type parameter symbol from a ROA of TypeParametersSymbols and the syntax for one.
Private Function GetTypeParameterSymbol(parameters As ImmutableArray(Of TypeParameterSymbol), parameter As TypeParameterSyntax) As TypeParameterSymbol
For Each symbol In parameters
For Each location In symbol.Locations
If location.IsInSource AndAlso location.SourceTree Is _syntaxTree AndAlso parameter.Span.Contains(location.SourceSpan) Then
Return symbol
End If
Next
Next
Return Nothing
End Function
Public Overrides Function GetDeclaredSymbol(declarationSyntax As EnumMemberDeclarationSyntax, Optional cancellationToken As CancellationToken = Nothing) As IFieldSymbol
If declarationSyntax Is Nothing Then
Throw New ArgumentNullException(NameOf(declarationSyntax))
End If
If Not IsInTree(declarationSyntax) Then
Throw New ArgumentException(VBResources.DeclarationSyntaxNotWithinTree)
End If
Dim enumBlock As EnumBlockSyntax = DirectCast(declarationSyntax.Parent, EnumBlockSyntax)
If enumBlock IsNot Nothing Then
Dim containingType = DirectCast(GetDeclaredSymbol(enumBlock.EnumStatement, cancellationToken), NamedTypeSymbol)
If containingType IsNot Nothing Then
Return DirectCast(SourceFieldSymbol.FindFieldOrWithEventsSymbolFromSyntax(declarationSyntax.Identifier, _syntaxTree, containingType), FieldSymbol)
End If
End If
Return Nothing
End Function
''' <summary>
''' Given a variable declaration, get the corresponding symbol.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares a variable.</param>
''' <returns>The symbol that was declared.</returns>
Public Overrides Function GetDeclaredSymbol(declarationSyntax As ModifiedIdentifierSyntax, Optional cancellationToken As CancellationToken = Nothing) As ISymbol
If declarationSyntax Is Nothing Then
Throw New ArgumentNullException(NameOf(declarationSyntax))
End If
If Not IsInTree(declarationSyntax) Then
Throw New ArgumentException(VBResources.DeclarationSyntaxNotWithinTree)
End If
Dim declarationParent = declarationSyntax.Parent
' Possibility 1: Field syntax, could be a Field or WithEvent property
Dim fieldSyntax As FieldDeclarationSyntax = Nothing
If declarationParent IsNot Nothing Then
fieldSyntax = TryCast(declarationParent.Parent, FieldDeclarationSyntax)
End If
Dim parentTypeBlock As TypeBlockSyntax = Nothing
If fieldSyntax IsNot Nothing Then
parentTypeBlock = TryCast(fieldSyntax.Parent, TypeBlockSyntax)
Else : End If
If parentTypeBlock IsNot Nothing Then
Dim containingType = DirectCast(GetDeclaredSymbol(parentTypeBlock.BlockStatement, cancellationToken), NamedTypeSymbol)
If containingType IsNot Nothing Then
Return SourceFieldSymbol.FindFieldOrWithEventsSymbolFromSyntax(declarationSyntax.Identifier, _syntaxTree, containingType)
End If
End If
' Possibility 2: Parameter
Dim parameterSyntax As ParameterSyntax = TryCast(declarationParent, ParameterSyntax)
If parameterSyntax IsNot Nothing Then
Return GetDeclaredSymbol(parameterSyntax, cancellationToken)
End If
' Possibility 3: Local variable
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(declarationSyntax)
If model IsNot Nothing Then
Return model.GetDeclaredSymbol(declarationSyntax, cancellationToken)
End If
Return MyBase.GetDeclaredSymbol(declarationSyntax, cancellationToken)
End Function
''' <summary>
''' Given a FieldInitializerSyntax, get the corresponding symbol of anonymous type creation.
''' </summary>
''' <param name="fieldInitializerSyntax">The anonymous object creation field initializer syntax.</param>
''' <returns>The symbol that was declared, or Nothing if no such symbol exists.</returns>
Public Overrides Function GetDeclaredSymbol(fieldInitializerSyntax As FieldInitializerSyntax, Optional cancellationToken As System.Threading.CancellationToken = Nothing) As IPropertySymbol
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(fieldInitializerSyntax)
If model IsNot Nothing Then
Return model.GetDeclaredSymbol(fieldInitializerSyntax, cancellationToken)
End If
Return MyBase.GetDeclaredSymbol(fieldInitializerSyntax, cancellationToken)
End Function
''' <summary>
''' Given an AnonymousObjectCreationExpressionSyntax, get the corresponding symbol of anonymous type.
''' </summary>
''' <param name="anonymousObjectCreationExpressionSyntax">The anonymous object creation syntax.</param>
''' <returns>The symbol that was declared, or Nothing if no such symbol exists.</returns>
Public Overrides Function GetDeclaredSymbol(anonymousObjectCreationExpressionSyntax As AnonymousObjectCreationExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As INamedTypeSymbol
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(anonymousObjectCreationExpressionSyntax)
If model IsNot Nothing Then
Return model.GetDeclaredSymbol(anonymousObjectCreationExpressionSyntax, cancellationToken)
End If
Return MyBase.GetDeclaredSymbol(anonymousObjectCreationExpressionSyntax, cancellationToken)
End Function
''' <summary>
''' Given an ExpressionRangeVariableSyntax, get the corresponding symbol.
''' </summary>
''' <param name="rangeVariableSyntax">The range variable syntax that declares a variable.</param>
''' <returns>The symbol that was declared, or Nothing if no such symbol exists.</returns>
Public Overrides Function GetDeclaredSymbol(rangeVariableSyntax As ExpressionRangeVariableSyntax, Optional cancellationToken As CancellationToken = Nothing) As IRangeVariableSymbol
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(rangeVariableSyntax)
If model IsNot Nothing Then
Return model.GetDeclaredSymbol(rangeVariableSyntax, cancellationToken)
End If
Return MyBase.GetDeclaredSymbol(rangeVariableSyntax, cancellationToken)
End Function
''' <summary>
''' Given a CollectionRangeVariableSyntax, get the corresponding symbol.
''' </summary>
''' <param name="rangeVariableSyntax">The range variable syntax that declares a variable.</param>
''' <returns>The symbol that was declared, or Nothing if no such symbol exists.</returns>
Public Overrides Function GetDeclaredSymbol(rangeVariableSyntax As CollectionRangeVariableSyntax, Optional cancellationToken As CancellationToken = Nothing) As IRangeVariableSymbol
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(rangeVariableSyntax)
If model IsNot Nothing Then
Return model.GetDeclaredSymbol(rangeVariableSyntax, cancellationToken)
End If
Return MyBase.GetDeclaredSymbol(rangeVariableSyntax, cancellationToken)
End Function
''' <summary>
''' Given an AggregationRangeVariableSyntax, get the corresponding symbol.
''' </summary>
''' <param name="rangeVariableSyntax">The range variable syntax that declares a variable.</param>
''' <returns>The symbol that was declared, or Nothing if no such symbol exists.</returns>
Public Overrides Function GetDeclaredSymbol(rangeVariableSyntax As AggregationRangeVariableSyntax, Optional cancellationToken As CancellationToken = Nothing) As IRangeVariableSymbol
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(rangeVariableSyntax)
If model IsNot Nothing Then
Return model.GetDeclaredSymbol(rangeVariableSyntax, cancellationToken)
End If
Return MyBase.GetDeclaredSymbol(rangeVariableSyntax, cancellationToken)
End Function
''' <summary>
''' Given an import clause get the corresponding symbol for the import alias that was introduced.
''' </summary>
''' <param name="declarationSyntax">The import statement syntax node.</param>
''' <returns>The alias symbol that was declared or Nothing if no alias symbol was declared.</returns>
Public Overloads Overrides Function GetDeclaredSymbol(declarationSyntax As SimpleImportsClauseSyntax, Optional cancellationToken As CancellationToken = Nothing) As IAliasSymbol
If declarationSyntax Is Nothing Then
Throw New ArgumentNullException(NameOf(declarationSyntax))
End If
If Not IsInTree(declarationSyntax) Then
Throw New ArgumentException(VBResources.DeclarationSyntaxNotWithinTree)
End If
If declarationSyntax.Alias Is Nothing Then
Return Nothing
End If
Dim aliasName As String = declarationSyntax.Alias.Identifier.ValueText
If Not String.IsNullOrEmpty(aliasName) Then
Dim sourceFile = Me._sourceModule.TryGetSourceFile(Me.SyntaxTree)
Debug.Assert(sourceFile IsNot Nothing)
Dim aliasImports As IReadOnlyDictionary(Of String, AliasAndImportsClausePosition) = sourceFile.AliasImportsOpt
Dim symbol As AliasAndImportsClausePosition = Nothing
If aliasImports IsNot Nothing AndAlso aliasImports.TryGetValue(aliasName, symbol) Then
' make sure the symbol is declared inside declarationSyntax node
For Each location In symbol.Alias.Locations
If location.IsInSource AndAlso location.SourceTree Is _syntaxTree AndAlso declarationSyntax.Span.Contains(location.SourceSpan) Then
Return symbol.Alias
End If
Next
' If the alias name was in the map but the location didn't match, then the syntax declares a duplicate alias.
' We'll return a new AliasSymbol to improve the API experience.
Dim binder As Binder = GetEnclosingBinder(declarationSyntax.SpanStart)
Dim targetSymbol As NamespaceOrTypeSymbol = binder.BindNamespaceOrTypeSyntax(declarationSyntax.Name, BindingDiagnosticBag.Discarded)
If targetSymbol IsNot Nothing Then
Return New AliasSymbol(binder.Compilation, binder.ContainingNamespaceOrType, aliasName, targetSymbol, declarationSyntax.GetLocation())
End If
End If
End If
Return Nothing
End Function
''' <summary>
''' Given a field declaration syntax, get the corresponding symbols.
''' </summary>
''' <param name="declarationSyntax">The syntax node that declares one or more fields.</param>
''' <returns>The field symbols that were declared.</returns>
Friend Overrides Function GetDeclaredSymbols(declarationSyntax As FieldDeclarationSyntax, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of ISymbol)
If declarationSyntax Is Nothing Then
Throw New ArgumentNullException(NameOf(declarationSyntax))
End If
If Not IsInTree(declarationSyntax) Then
Throw New ArgumentException(VBResources.DeclarationSyntaxNotWithinTree)
End If
Dim builder = New ArrayBuilder(Of ISymbol)
For Each declarator In declarationSyntax.Declarators
For Each identifier In declarator.Names
Dim field = TryCast(Me.GetDeclaredSymbol(identifier, cancellationToken), IFieldSymbol)
If field IsNot Nothing Then
builder.Add(field)
End If
Next
Next
Return builder.ToImmutableAndFree()
End Function
''' <summary>
''' Determines what type of conversion, if any, would be used if a given expression was converted to a given
''' type.
''' </summary>
''' <param name="expression">An expression which much occur within the syntax tree associated with this
''' object.</param>
''' <param name="destination">The type to attempt conversion to.</param>
''' <returns>Returns a Conversion object that summarizes whether the conversion was possible, and if so, what
''' kind of conversion it was. If no conversion was possible, a Conversion object with a false "Exists "
''' property is returned.</returns>
''' <remarks>To determine the conversion between two types (instead of an expression and a type), use
''' Compilation.ClassifyConversion.</remarks>
Public Overrides Function ClassifyConversion(expression As ExpressionSyntax, destination As ITypeSymbol) As Conversion
CheckSyntaxNode(expression)
If destination Is Nothing Then
Throw New ArgumentNullException(NameOf(destination))
End If
Dim vbdestination = destination.EnsureVbSymbolOrNothing(Of TypeSymbol)(NameOf(destination))
' TODO(cyrusn): Check arguments. This is a public entrypoint, so we must do appropriate
' checks here. However, no other methods in this type do any checking currently. So I'm
' going to hold off on this until we do a full sweep of the API.
Dim binding = Me.GetMemberSemanticModel(expression)
If binding Is Nothing Then
Return New Conversion(Nothing) 'NoConversion
End If
Return binding.ClassifyConversion(expression, vbdestination)
End Function
Public Overrides ReadOnly Property IsSpeculativeSemanticModel As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property OriginalPositionForSpeculation As Integer
Get
Return 0
End Get
End Property
Public Overrides ReadOnly Property ParentModel As SemanticModel
Get
Return Nothing
End Get
End Property
Friend Overrides ReadOnly Property ContainingModelOrSelf As SemanticModel
Get
Return Me
End Get
End Property
Friend Overrides Function TryGetSpeculativeSemanticModelForMethodBodyCore(parentModel As SyntaxTreeSemanticModel, position As Integer, method As MethodBlockBaseSyntax, <Out> ByRef speculativeModel As SemanticModel) As Boolean
Dim memberModel = Me.GetMemberSemanticModel(position)
If memberModel IsNot Nothing Then
Return memberModel.TryGetSpeculativeSemanticModelForMethodBodyCore(parentModel, position, method, speculativeModel)
End If
speculativeModel = Nothing
Return False
End Function
Friend Overrides Function TryGetSpeculativeSemanticModelCore(parentModel As SyntaxTreeSemanticModel, position As Integer, type As TypeSyntax, bindingOption As SpeculativeBindingOption, <Out> ByRef speculativeModel As SemanticModel) As Boolean
Dim memberModel = Me.GetMemberSemanticModel(position)
If memberModel IsNot Nothing Then
Return memberModel.TryGetSpeculativeSemanticModelCore(parentModel, position, type, bindingOption, speculativeModel)
End If
Dim binder As Binder = Me.GetSpeculativeBinderForExpression(position, type, bindingOption)
If binder IsNot Nothing Then
speculativeModel = SpeculativeSyntaxTreeSemanticModel.Create(Me, type, binder, position, bindingOption)
Return True
End If
speculativeModel = Nothing
Return False
End Function
Friend Overrides Function TryGetSpeculativeSemanticModelCore(parentModel As SyntaxTreeSemanticModel, position As Integer, rangeArgument As RangeArgumentSyntax, <Out> ByRef speculativeModel As SemanticModel) As Boolean
Dim memberModel = Me.GetMemberSemanticModel(position)
If memberModel IsNot Nothing Then
Return memberModel.TryGetSpeculativeSemanticModelCore(parentModel, position, rangeArgument, speculativeModel)
End If
speculativeModel = Nothing
Return False
End Function
Friend Overrides Function TryGetSpeculativeSemanticModelCore(parentModel As SyntaxTreeSemanticModel, position As Integer, statement As ExecutableStatementSyntax, <Out> ByRef speculativeModel As SemanticModel) As Boolean
Dim memberModel = Me.GetMemberSemanticModel(position)
If memberModel IsNot Nothing Then
Return memberModel.TryGetSpeculativeSemanticModelCore(parentModel, position, statement, speculativeModel)
End If
speculativeModel = Nothing
Return False
End Function
Friend Overrides Function TryGetSpeculativeSemanticModelCore(parentModel As SyntaxTreeSemanticModel, position As Integer, initializer As EqualsValueSyntax, <Out> ByRef speculativeModel As SemanticModel) As Boolean
Dim memberModel = Me.GetMemberSemanticModel(position)
If memberModel IsNot Nothing Then
Return memberModel.TryGetSpeculativeSemanticModelCore(parentModel, position, initializer, speculativeModel)
End If
speculativeModel = Nothing
Return False
End Function
''' <summary>
''' Analyze control-flow within a part of a method body.
''' </summary>
''' <param name="firstStatement">The first statement to be included in the analysis.</param>
''' <param name="lastStatement">The last statement to be included in the analysis.</param>
''' <returns>An object that can be used to obtain the result of the control flow analysis.</returns>
''' <exception cref="ArgumentException">The two statements are not contained within the same statement list.</exception>
Public Overrides Function AnalyzeControlFlow(firstStatement As StatementSyntax, lastStatement As StatementSyntax) As ControlFlowAnalysis
Dim context As RegionAnalysisContext = If(ValidateRegionDefiningStatementsRange(firstStatement, lastStatement),
CreateRegionAnalysisContext(firstStatement, lastStatement),
CreateFailedRegionAnalysisContext())
Dim result = New VisualBasicControlFlowAnalysis(context)
' we assume the analysis should only fail if the original context is invalid
Debug.Assert(result.Succeeded OrElse context.Failed)
Return result
End Function
''' <summary>
''' The first statement to be included in the analysis.
''' </summary>
''' <param name="firstStatement">The first statement to be included in the analysis.</param>
''' <param name="lastStatement">The last statement to be included in the analysis.</param>
''' <returns>An object that can be used to obtain the result of the data flow analysis.</returns>
''' <exception cref="ArgumentException">The two statements are not contained within the same statement list.</exception>
Public Overrides Function AnalyzeDataFlow(firstStatement As StatementSyntax, lastStatement As StatementSyntax) As DataFlowAnalysis
Dim context As RegionAnalysisContext = If(ValidateRegionDefiningStatementsRange(firstStatement, lastStatement),
CreateRegionAnalysisContext(firstStatement, lastStatement),
CreateFailedRegionAnalysisContext())
Dim result = New VisualBasicDataFlowAnalysis(context)
' we assume the analysis should only fail if the original context is invalid
Debug.Assert(result.Succeeded OrElse result.InvalidRegionDetectedInternal OrElse context.Failed)
Return result
End Function
''' <summary>
''' Analyze data-flow within an expression.
''' </summary>
''' <param name="expression">The expression within the associated SyntaxTree to analyze.</param>
''' <returns>An object that can be used to obtain the result of the data flow analysis.</returns>
Public Overrides Function AnalyzeDataFlow(expression As ExpressionSyntax) As DataFlowAnalysis
Dim context As RegionAnalysisContext = If(ValidateRegionDefiningExpression(expression),
CreateRegionAnalysisContext(expression),
CreateFailedRegionAnalysisContext())
Dim result = New VisualBasicDataFlowAnalysis(context)
' Assert that we either correctly precalculated succeeded
' flag or we know for sure why we failed to precalculate it
CheckSucceededFlagInAnalyzeDataFlow(expression, result, context)
Return result
End Function
<Conditional("DEBUG")>
Private Sub CheckSucceededFlagInAnalyzeDataFlow(expression As ExpressionSyntax, result As VisualBasicDataFlowAnalysis, context As RegionAnalysisContext)
If result.Succeeded OrElse result.InvalidRegionDetectedInternal OrElse context.Failed Then
Return
End If
' Some cases of unsucceeded result that cannot be precalculated properly are handled below
' CASE 1: If the region flow analysis is performed on the left part of member access like
' on 'a' part of 'a.b.c()' expression AND 'a.b' is a type, we don't create a bound node
' to be linked with syntax node 'a'. In this case FirstInRegion/LastInRegion nodes are
' calculated by trying to bind 'a' itself, and in most cases it binds into Namespace
' or Type expression. This case is handles in RegionAnalysisContext..ctor.
'
' But in Color/Color case it binds into other symbol kinds and we suppress
' assertion for this case here
Dim expressionParent As VisualBasicSyntaxNode = expression.Parent
If expression.Kind = SyntaxKind.IdentifierName AndAlso
expressionParent IsNot Nothing AndAlso expressionParent.Kind = SyntaxKind.SimpleMemberAccessExpression AndAlso
DirectCast(expressionParent, MemberAccessExpressionSyntax).Expression Is expression Then
' Color/Color confusion may only be possible if expression is an IdentifierName
' and is nested in member access. This is too wide definition, but it's
' difficult to improve this without doing semantic analysis
Return
End If
' CASE 2: If the region flow analysis is performed on the arguments of field declaration of array
' data type having explicit initializer, like 'Public AnArray(2) = {0, 1}';
' VB semantics generates an error about specifying both bounds and initializer and ignores them
If expression.Kind = SyntaxKind.NumericLiteralExpression AndAlso
expressionParent IsNot Nothing AndAlso (expressionParent.Kind = SyntaxKind.SimpleArgument AndAlso Not DirectCast(expressionParent, SimpleArgumentSyntax).IsNamed) Then
' VariableDeclarator
' | |
' ModifiedIdentifier EqualsValue
' |
' ArgumentList
' |...|...|
' SimpleArgument
' |
' NumericalLiteral
Dim argList As VisualBasicSyntaxNode = expressionParent.Parent
If argList IsNot Nothing AndAlso argList.Kind = SyntaxKind.ArgumentList Then
Dim modIdentifier As VisualBasicSyntaxNode = argList.Parent
If modIdentifier IsNot Nothing AndAlso modIdentifier.Kind = SyntaxKind.ModifiedIdentifier Then
Dim varDeclarator As VisualBasicSyntaxNode = modIdentifier.Parent
If varDeclarator IsNot Nothing AndAlso varDeclarator.Kind = SyntaxKind.VariableDeclarator AndAlso
DirectCast(varDeclarator, VariableDeclaratorSyntax).Initializer IsNot Nothing Then
Return
End If
End If
End If
End If
Throw ExceptionUtilities.Unreachable
End Sub
''' <summary>
''' Checks if the node is inside the attribute arguments
''' </summary>
Private Shared Function IsNodeInsideAttributeArguments(node As VisualBasicSyntaxNode) As Boolean
While node IsNot Nothing
If node.Kind = SyntaxKind.Attribute Then
Return True
End If
node = node.Parent
End While
Return False
End Function
''' <summary>
''' Check Expression for being in right context, for example 'For ... Next [x]'
''' is not correct context
''' </summary>
Private Shared Function IsExpressionInValidContext(expression As ExpressionSyntax) As Boolean
Dim currentNode As VisualBasicSyntaxNode = expression
Do
Dim parent As VisualBasicSyntaxNode = currentNode.Parent
If parent Is Nothing Then Return True
Dim expressionParent = TryCast(parent, ExpressionSyntax)
If expressionParent Is Nothing Then
Select Case parent.Kind
Case SyntaxKind.NextStatement
Return False
Case SyntaxKind.EqualsValue
' One cannot perform flow analysis on an expression from Enum member declaration
parent = parent.Parent
If parent Is Nothing Then
Return True
End If
Select Case parent.Kind
Case SyntaxKind.EnumMemberDeclaration,
SyntaxKind.Parameter
Return False
Case SyntaxKind.VariableDeclarator
Dim localDeclSyntax = TryCast(parent.Parent, LocalDeclarationStatementSyntax)
If localDeclSyntax IsNot Nothing Then
For Each modifier In localDeclSyntax.Modifiers
Select Case modifier.Kind
Case SyntaxKind.ConstKeyword
Return False
End Select
Next
End If
Return True
Case Else
Return True
End Select
Case SyntaxKind.RaiseEventStatement
Return False
Case SyntaxKind.NamedFieldInitializer
If DirectCast(parent, NamedFieldInitializerSyntax).Name Is currentNode Then
Return False
End If
' else proceed to the upper-level node
Case SyntaxKind.NameColonEquals
Return False
Case SyntaxKind.RangeArgument
If DirectCast(parent, RangeArgumentSyntax).LowerBound Is currentNode Then
Return False
End If
' proceed to the upper-level node
Case SyntaxKind.ArgumentList,
SyntaxKind.SimpleArgument,
SyntaxKind.ObjectMemberInitializer
' proceed to the upper-level node
Case SyntaxKind.GoToStatement
Return False
Case SyntaxKind.XmlDeclarationOption
Return False
Case Else
Return True
End Select
Else
Select Case parent.Kind
Case SyntaxKind.XmlElementEndTag
Return False
End Select
End If
' up one level
currentNode = parent
Loop
End Function
Private Sub AssertNodeInTree(node As VisualBasicSyntaxNode, argName As String)
If node Is Nothing Then
Throw New ArgumentNullException(argName)
End If
If Not IsInTree(node) Then
Throw New ArgumentException(argName & VBResources.NotWithinTree)
End If
End Sub
Private Function ValidateRegionDefiningExpression(expression As ExpressionSyntax) As Boolean
AssertNodeInTree(expression, NameOf(expression))
If expression.Kind = SyntaxKind.PredefinedType OrElse SyntaxFacts.IsInNamespaceOrTypeContext(expression) Then
Return False
End If
If SyntaxFactory.GetStandaloneExpression(expression) IsNot expression Then
Return False
End If
' Check for pseudo-expressions
Select Case expression.Kind
Case SyntaxKind.CollectionInitializer
Dim parent As VisualBasicSyntaxNode = expression.Parent
If parent IsNot Nothing Then
Select Case parent.Kind
Case SyntaxKind.ObjectCollectionInitializer
If DirectCast(parent, ObjectCollectionInitializerSyntax).Initializer Is expression Then
Return False
End If
Case SyntaxKind.ArrayCreationExpression
If DirectCast(parent, ArrayCreationExpressionSyntax).Initializer Is expression Then
Return False
End If
Case SyntaxKind.CollectionInitializer
' Nested collection initializer is not an expression from the language point of view.
' However, third level collection initializer under ObjectCollectionInitializer should
' be treated as a stand alone expression.
Dim possibleSecondLevelInitializer As VisualBasicSyntaxNode = parent
parent = parent.Parent
If parent IsNot Nothing AndAlso parent.Kind = SyntaxKind.CollectionInitializer Then
Dim possibleFirstLevelInitializer As VisualBasicSyntaxNode = parent
parent = parent.Parent
If parent IsNot Nothing AndAlso parent.Kind = SyntaxKind.ObjectCollectionInitializer AndAlso
DirectCast(parent, ObjectCollectionInitializerSyntax).Initializer Is possibleFirstLevelInitializer Then
Exit Select
End If
End If
Return False
End Select
End If
Case SyntaxKind.NumericLabel,
SyntaxKind.IdentifierLabel,
SyntaxKind.NextLabel
Return False
End Select
If Not IsExpressionInValidContext(expression) OrElse IsNodeInsideAttributeArguments(expression) Then
Return False
End If
Return True
End Function
Private Function ValidateRegionDefiningStatementsRange(firstStatement As StatementSyntax, lastStatement As StatementSyntax) As Boolean
AssertNodeInTree(firstStatement, NameOf(firstStatement))
AssertNodeInTree(lastStatement, NameOf(lastStatement))
If firstStatement.Parent Is Nothing OrElse firstStatement.Parent IsNot lastStatement.Parent Then
Throw New ArgumentException("statements not within the same statement list")
End If
If firstStatement.SpanStart > lastStatement.SpanStart Then
Throw New ArgumentException("first statement does not precede last statement")
End If
If Not TypeOf firstStatement Is ExecutableStatementSyntax OrElse Not TypeOf lastStatement Is ExecutableStatementSyntax Then
Return False
End If
' Test for |For ... Next x, y|
If IsNotUppermostForBlock(firstStatement) Then
Return False
End If
If firstStatement IsNot lastStatement AndAlso IsNotUppermostForBlock(lastStatement) Then
Return False
End If
If IsNodeInsideAttributeArguments(firstStatement) OrElse (firstStatement IsNot lastStatement AndAlso IsNodeInsideAttributeArguments(lastStatement)) Then
Return False
End If
Return True
End Function
''' <summary>
''' Check ForBlockSyntax for being the uppermost For block. By uppermost
''' For block we mean that if Next clause contains several control variables,
''' the uppermost block is the one which includes all the For blocks ending with
''' the same Next clause
''' </summary>
Private Function IsNotUppermostForBlock(forBlockOrStatement As VisualBasicSyntaxNode) As Boolean
Debug.Assert(forBlockOrStatement.Kind <> SyntaxKind.ForStatement)
Debug.Assert(forBlockOrStatement.Kind <> SyntaxKind.ForEachStatement)
Dim forBlock = TryCast(forBlockOrStatement, ForOrForEachBlockSyntax)
If forBlock Is Nothing Then
Return False
End If
Dim endNode As NextStatementSyntax = forBlock.NextStatement
If endNode IsNot Nothing Then
' The only case where the statement is valid is this case is
' that the Next clause contains one single control variable (or none)
Return endNode.ControlVariables.Count > 1
End If
' go down the For statements chain until the last and ensure it has as many
' variables as there were nested For statements
Dim nesting As Integer = 1
Do
If forBlock.Statements.Count = 0 Then
Return True
End If
Dim lastStatement = TryCast(forBlock.Statements.Last(), ForOrForEachBlockSyntax)
If lastStatement Is Nothing Then
Return True
End If
nesting += 1
endNode = lastStatement.NextStatement
If endNode IsNot Nothing Then
Return endNode.ControlVariables.Count <> nesting
End If
' Else - next level
forBlock = lastStatement
Loop
End Function
''' <summary>
''' Gets the semantic information of a for each statement.
''' </summary>
''' <param name="node">The for each syntax node.</param>
Friend Overrides Function GetForEachStatementInfoWorker(node As ForEachBlockSyntax) As ForEachStatementInfo
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(node)
If model IsNot Nothing Then
Return model.GetForEachStatementInfoWorker(node)
Else
Return Nothing
End If
End Function
Friend Overrides Function GetAwaitExpressionInfoWorker(awaitExpression As AwaitExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As AwaitExpressionInfo
Dim model As MemberSemanticModel = Me.GetMemberSemanticModel(awaitExpression)
If model IsNot Nothing Then
Return model.GetAwaitExpressionInfoWorker(awaitExpression, cancellationToken)
Else
Return Nothing
End If
End Function
#Region "Region Analysis Context Creation"
''' <summary> Used to create a region analysis context
''' with failed flag set to be used in 'failed' scenarios </summary>
Private Function CreateFailedRegionAnalysisContext() As RegionAnalysisContext
Return New RegionAnalysisContext(Me.Compilation)
End Function
Private Function CreateRegionAnalysisContext(expression As ExpressionSyntax) As RegionAnalysisContext
Dim region As TextSpan = expression.Span
Dim memberModel As MemberSemanticModel = GetMemberSemanticModel(expression)
If memberModel Is Nothing Then
' Recover from error cases
Dim node As BoundBadStatement = New BoundBadStatement(expression, ImmutableArray(Of BoundNode).Empty)
Return New RegionAnalysisContext(Compilation, Nothing, node, node, node, region)
End If
Dim boundNode As BoundNode = memberModel.GetBoundRoot()
Dim boundExpression As BoundNode = memberModel.GetUpperBoundNode(expression)
Return New RegionAnalysisContext(Compilation, memberModel.MemberSymbol, boundNode, boundExpression, boundExpression, region)
End Function
Private Function CreateRegionAnalysisContext(firstStatement As StatementSyntax, lastStatement As StatementSyntax) As RegionAnalysisContext
Dim region As TextSpan = TextSpan.FromBounds(firstStatement.SpanStart, lastStatement.Span.End)
Dim memberModel As MemberSemanticModel = GetMemberSemanticModel(firstStatement)
If memberModel Is Nothing Then
' Recover from error cases
Dim node As BoundBadStatement = New BoundBadStatement(firstStatement, ImmutableArray(Of BoundNode).Empty)
Return New RegionAnalysisContext(Compilation, Nothing, node, node, node, region)
End If
Dim boundNode As BoundNode = memberModel.GetBoundRoot()
Dim firstBoundNode As BoundNode = memberModel.GetUpperBoundNode(firstStatement)
Dim lastBoundNode As BoundNode = memberModel.GetUpperBoundNode(lastStatement)
Return New RegionAnalysisContext(Compilation, memberModel.MemberSymbol, boundNode, firstBoundNode, lastBoundNode, region)
End Function
#End Region
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Workspaces/Core/Portable/FindSymbols/IRemoteSymbolFinderService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal interface IRemoteSymbolFinderService
{
internal interface ICallback
{
ValueTask AddReferenceItemsAsync(RemoteServiceCallbackId callbackId, int count, CancellationToken cancellationToken);
ValueTask ReferenceItemCompletedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken);
ValueTask OnStartedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken);
ValueTask OnCompletedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken);
ValueTask OnFindInDocumentStartedAsync(RemoteServiceCallbackId callbackId, DocumentId documentId, CancellationToken cancellationToken);
ValueTask OnFindInDocumentCompletedAsync(RemoteServiceCallbackId callbackId, DocumentId documentId, CancellationToken cancellationToken);
ValueTask OnDefinitionFoundAsync(RemoteServiceCallbackId callbackId, SerializableSymbolGroup group, CancellationToken cancellationToken);
ValueTask OnReferenceFoundAsync(RemoteServiceCallbackId callbackId, SerializableSymbolGroup group, SerializableSymbolAndProjectId definition, SerializableReferenceLocation reference, CancellationToken cancellationToken);
ValueTask AddLiteralItemsAsync(RemoteServiceCallbackId callbackId, int count, CancellationToken cancellationToken);
ValueTask LiteralItemCompletedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken);
ValueTask OnLiteralReferenceFoundAsync(RemoteServiceCallbackId callbackId, DocumentId documentId, TextSpan span, CancellationToken cancellationToken);
}
ValueTask FindReferencesAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, SerializableSymbolAndProjectId symbolAndProjectIdArg, ImmutableArray<DocumentId> documentArgs,
FindReferencesSearchOptions options, CancellationToken cancellationToken);
ValueTask FindLiteralReferencesAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, object value, TypeCode typeCode, CancellationToken cancellationToken);
ValueTask<ImmutableArray<SerializableSymbolAndProjectId>> FindAllDeclarationsWithNormalQueryAsync(
PinnedSolutionInfo solutionInfo, ProjectId projectId, string name, SearchKind searchKind, SymbolFilter criteria, CancellationToken cancellationToken);
ValueTask<ImmutableArray<SerializableSymbolAndProjectId>> FindSolutionSourceDeclarationsWithNormalQueryAsync(
PinnedSolutionInfo solutionInfo, string name, bool ignoreCase, SymbolFilter criteria, CancellationToken cancellationToken);
ValueTask<ImmutableArray<SerializableSymbolAndProjectId>> FindProjectSourceDeclarationsWithNormalQueryAsync(
PinnedSolutionInfo solutionInfo, ProjectId projectId, string name, bool ignoreCase, SymbolFilter criteria, CancellationToken cancellationToken);
ValueTask<ImmutableArray<SerializableSymbolAndProjectId>> FindSolutionSourceDeclarationsWithPatternAsync(
PinnedSolutionInfo solutionInfo, string pattern, SymbolFilter criteria, CancellationToken cancellationToken);
ValueTask<ImmutableArray<SerializableSymbolAndProjectId>> FindProjectSourceDeclarationsWithPatternAsync(
PinnedSolutionInfo solutionInfo, ProjectId projectId, string pattern, SymbolFilter criteria, 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;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal interface IRemoteSymbolFinderService
{
internal interface ICallback
{
ValueTask AddReferenceItemsAsync(RemoteServiceCallbackId callbackId, int count, CancellationToken cancellationToken);
ValueTask ReferenceItemCompletedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken);
ValueTask OnStartedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken);
ValueTask OnCompletedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken);
ValueTask OnFindInDocumentStartedAsync(RemoteServiceCallbackId callbackId, DocumentId documentId, CancellationToken cancellationToken);
ValueTask OnFindInDocumentCompletedAsync(RemoteServiceCallbackId callbackId, DocumentId documentId, CancellationToken cancellationToken);
ValueTask OnDefinitionFoundAsync(RemoteServiceCallbackId callbackId, SerializableSymbolGroup group, CancellationToken cancellationToken);
ValueTask OnReferenceFoundAsync(RemoteServiceCallbackId callbackId, SerializableSymbolGroup group, SerializableSymbolAndProjectId definition, SerializableReferenceLocation reference, CancellationToken cancellationToken);
ValueTask AddLiteralItemsAsync(RemoteServiceCallbackId callbackId, int count, CancellationToken cancellationToken);
ValueTask LiteralItemCompletedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken);
ValueTask OnLiteralReferenceFoundAsync(RemoteServiceCallbackId callbackId, DocumentId documentId, TextSpan span, CancellationToken cancellationToken);
}
ValueTask FindReferencesAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, SerializableSymbolAndProjectId symbolAndProjectIdArg, ImmutableArray<DocumentId> documentArgs,
FindReferencesSearchOptions options, CancellationToken cancellationToken);
ValueTask FindLiteralReferencesAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, object value, TypeCode typeCode, CancellationToken cancellationToken);
ValueTask<ImmutableArray<SerializableSymbolAndProjectId>> FindAllDeclarationsWithNormalQueryAsync(
PinnedSolutionInfo solutionInfo, ProjectId projectId, string name, SearchKind searchKind, SymbolFilter criteria, CancellationToken cancellationToken);
ValueTask<ImmutableArray<SerializableSymbolAndProjectId>> FindSolutionSourceDeclarationsWithNormalQueryAsync(
PinnedSolutionInfo solutionInfo, string name, bool ignoreCase, SymbolFilter criteria, CancellationToken cancellationToken);
ValueTask<ImmutableArray<SerializableSymbolAndProjectId>> FindProjectSourceDeclarationsWithNormalQueryAsync(
PinnedSolutionInfo solutionInfo, ProjectId projectId, string name, bool ignoreCase, SymbolFilter criteria, CancellationToken cancellationToken);
ValueTask<ImmutableArray<SerializableSymbolAndProjectId>> FindSolutionSourceDeclarationsWithPatternAsync(
PinnedSolutionInfo solutionInfo, string pattern, SymbolFilter criteria, CancellationToken cancellationToken);
ValueTask<ImmutableArray<SerializableSymbolAndProjectId>> FindProjectSourceDeclarationsWithPatternAsync(
PinnedSolutionInfo solutionInfo, ProjectId projectId, string pattern, SymbolFilter criteria, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/VisualStudio/Core/Test/SolutionExplorer/RuleSetDocumentExtensionsTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.SolutionExplorer
Public Class RuleSetDocumentExtensionsTests
<Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)>
Public Sub AdjustSingleNonExistentRule()
Dim startingRuleSet =
<RuleSet Name="MyRules" Description="A bunch of rules">
</RuleSet>
Dim document = New XDocument(startingRuleSet)
document.SetSeverity("Alpha.Analyzer", "Test001", ReportDiagnostic.Error)
Dim expectedRuleSet =
<RuleSet Name="MyRules" Description="A bunch of rules">
<Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer">
<Rule Id="Test001" Action="Error"/>
</Rules>
</RuleSet>
Assert.Equal(expectedRuleSet.Value, document.Element("RuleSet").Value)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)>
Public Sub AdjustSingleExistentRule()
Dim startingRuleSet =
<RuleSet Name="MyRules" Description="A bunch of rules">
<Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer">
<Rule Id="Test001" Action="Error"/>
</Rules>
</RuleSet>
Dim document = New XDocument(startingRuleSet)
document.SetSeverity("Alpha.Analyzer", "Test001", ReportDiagnostic.Warn)
Dim expectedRuleSet =
<RuleSet Name="MyRules" Description="A bunch of rules">
<Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer">
<Rule Id="Test001" Action="Warn"/>
</Rules>
</RuleSet>
Assert.Equal(expectedRuleSet.Value, document.Element("RuleSet").Value)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)>
Public Sub AdjustSingleRuleUnderDifferentAnalyzer()
Dim startingRuleSet =
<RuleSet Name="MyRules" Description="A bunch of rules">
<Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer">
<Rule Id="Test001" Action="Error"/>
</Rules>
</RuleSet>
Dim document = New XDocument(startingRuleSet)
document.SetSeverity("Beta.Analyzer", "Test001", ReportDiagnostic.Warn)
Dim expectedRuleSet =
<RuleSet Name="MyRules" Description="A bunch of rules">
<Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer">
<Rule Id="Test001" Action="Warn"/>
</Rules>
<Rules AnalyzerId="Beta.Analyzer" RuleNamespace="Alpha.Analyzer">
<Rule Id="Test001" Action="Warn"/>
</Rules>
</RuleSet>
Assert.Equal(expectedRuleSet.Value, document.Element("RuleSet").Value)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)>
Public Sub AdjustMultipleRules()
Dim startingRuleSet =
<RuleSet Name="MyRules" Description="A bunch of rules">
<Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer">
<Rule Id="Test001" Action="Warn"/>
</Rules>
<Rules AnalyzerId="Beta.Analyzer" RuleNamespace="Alpha.Analyzer">
<Rule Id="Test001" Action="Warn"/>
</Rules>
</RuleSet>
Dim document = New XDocument(startingRuleSet)
document.SetSeverity("Alpha.Analyzer", "Test001", ReportDiagnostic.Error)
Dim expectedRuleSet =
<RuleSet Name="MyRules" Description="A bunch of rules">
<Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer">
<Rule Id="Test001" Action="Error"/>
</Rules>
<Rules AnalyzerId="Beta.Analyzer" RuleNamespace="Alpha.Analyzer">
<Rule Id="Test001" Action="Error"/>
</Rules>
</RuleSet>
Assert.Equal(expectedRuleSet.Value, document.Element("RuleSet").Value)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)>
Public Sub RemoveSingleNonExistentRule()
Dim startingRuleSet =
<RuleSet Name="MyRules" Description="A bunch of rules">
</RuleSet>
Dim document = New XDocument(startingRuleSet)
document.SetSeverity("Alpha.Analyzer", "Test001", ReportDiagnostic.Default)
Dim expectedRuleSet =
<RuleSet Name="MyRules" Description="A bunch of rules">
<Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer">
</Rules>
</RuleSet>
Assert.Equal(expectedRuleSet.Value, document.Element("RuleSet").Value)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)>
Public Sub RemoveSingleExistentRule()
Dim startingRuleSet =
<RuleSet Name="MyRules" Description="A bunch of rules">
<Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer">
<Rule Id="Test001" Action="Error"/>
</Rules>
</RuleSet>
Dim document = New XDocument(startingRuleSet)
document.SetSeverity("Alpha.Analyzer", "Test001", ReportDiagnostic.Default)
Dim expectedRuleSet =
<RuleSet Name="MyRules" Description="A bunch of rules">
<Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer">
</Rules>
</RuleSet>
Assert.Equal(expectedRuleSet.Value, document.Element("RuleSet").Value)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)>
Public Sub RemoveMultipleRules()
Dim startingRuleSet =
<RuleSet Name="MyRules" Description="A bunch of rules">
<Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer">
<Rule Id="Test001" Action="Warn"/>
</Rules>
<Rules AnalyzerId="Beta.Analyzer" RuleNamespace="Alpha.Analyzer">
<Rule Id="Test001" Action="Warn"/>
</Rules>
</RuleSet>
Dim document = New XDocument(startingRuleSet)
document.SetSeverity("Alpha.Analyzer", "Test001", ReportDiagnostic.Default)
Dim expectedRuleSet =
<RuleSet Name="MyRules" Description="A bunch of rules">
<Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer">
</Rules>
<Rules AnalyzerId="Beta.Analyzer" RuleNamespace="Alpha.Analyzer">
</Rules>
</RuleSet>
Assert.Equal(expectedRuleSet.Value, document.Element("RuleSet").Value)
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.SolutionExplorer
Public Class RuleSetDocumentExtensionsTests
<Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)>
Public Sub AdjustSingleNonExistentRule()
Dim startingRuleSet =
<RuleSet Name="MyRules" Description="A bunch of rules">
</RuleSet>
Dim document = New XDocument(startingRuleSet)
document.SetSeverity("Alpha.Analyzer", "Test001", ReportDiagnostic.Error)
Dim expectedRuleSet =
<RuleSet Name="MyRules" Description="A bunch of rules">
<Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer">
<Rule Id="Test001" Action="Error"/>
</Rules>
</RuleSet>
Assert.Equal(expectedRuleSet.Value, document.Element("RuleSet").Value)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)>
Public Sub AdjustSingleExistentRule()
Dim startingRuleSet =
<RuleSet Name="MyRules" Description="A bunch of rules">
<Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer">
<Rule Id="Test001" Action="Error"/>
</Rules>
</RuleSet>
Dim document = New XDocument(startingRuleSet)
document.SetSeverity("Alpha.Analyzer", "Test001", ReportDiagnostic.Warn)
Dim expectedRuleSet =
<RuleSet Name="MyRules" Description="A bunch of rules">
<Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer">
<Rule Id="Test001" Action="Warn"/>
</Rules>
</RuleSet>
Assert.Equal(expectedRuleSet.Value, document.Element("RuleSet").Value)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)>
Public Sub AdjustSingleRuleUnderDifferentAnalyzer()
Dim startingRuleSet =
<RuleSet Name="MyRules" Description="A bunch of rules">
<Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer">
<Rule Id="Test001" Action="Error"/>
</Rules>
</RuleSet>
Dim document = New XDocument(startingRuleSet)
document.SetSeverity("Beta.Analyzer", "Test001", ReportDiagnostic.Warn)
Dim expectedRuleSet =
<RuleSet Name="MyRules" Description="A bunch of rules">
<Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer">
<Rule Id="Test001" Action="Warn"/>
</Rules>
<Rules AnalyzerId="Beta.Analyzer" RuleNamespace="Alpha.Analyzer">
<Rule Id="Test001" Action="Warn"/>
</Rules>
</RuleSet>
Assert.Equal(expectedRuleSet.Value, document.Element("RuleSet").Value)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)>
Public Sub AdjustMultipleRules()
Dim startingRuleSet =
<RuleSet Name="MyRules" Description="A bunch of rules">
<Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer">
<Rule Id="Test001" Action="Warn"/>
</Rules>
<Rules AnalyzerId="Beta.Analyzer" RuleNamespace="Alpha.Analyzer">
<Rule Id="Test001" Action="Warn"/>
</Rules>
</RuleSet>
Dim document = New XDocument(startingRuleSet)
document.SetSeverity("Alpha.Analyzer", "Test001", ReportDiagnostic.Error)
Dim expectedRuleSet =
<RuleSet Name="MyRules" Description="A bunch of rules">
<Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer">
<Rule Id="Test001" Action="Error"/>
</Rules>
<Rules AnalyzerId="Beta.Analyzer" RuleNamespace="Alpha.Analyzer">
<Rule Id="Test001" Action="Error"/>
</Rules>
</RuleSet>
Assert.Equal(expectedRuleSet.Value, document.Element("RuleSet").Value)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)>
Public Sub RemoveSingleNonExistentRule()
Dim startingRuleSet =
<RuleSet Name="MyRules" Description="A bunch of rules">
</RuleSet>
Dim document = New XDocument(startingRuleSet)
document.SetSeverity("Alpha.Analyzer", "Test001", ReportDiagnostic.Default)
Dim expectedRuleSet =
<RuleSet Name="MyRules" Description="A bunch of rules">
<Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer">
</Rules>
</RuleSet>
Assert.Equal(expectedRuleSet.Value, document.Element("RuleSet").Value)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)>
Public Sub RemoveSingleExistentRule()
Dim startingRuleSet =
<RuleSet Name="MyRules" Description="A bunch of rules">
<Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer">
<Rule Id="Test001" Action="Error"/>
</Rules>
</RuleSet>
Dim document = New XDocument(startingRuleSet)
document.SetSeverity("Alpha.Analyzer", "Test001", ReportDiagnostic.Default)
Dim expectedRuleSet =
<RuleSet Name="MyRules" Description="A bunch of rules">
<Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer">
</Rules>
</RuleSet>
Assert.Equal(expectedRuleSet.Value, document.Element("RuleSet").Value)
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)>
Public Sub RemoveMultipleRules()
Dim startingRuleSet =
<RuleSet Name="MyRules" Description="A bunch of rules">
<Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer">
<Rule Id="Test001" Action="Warn"/>
</Rules>
<Rules AnalyzerId="Beta.Analyzer" RuleNamespace="Alpha.Analyzer">
<Rule Id="Test001" Action="Warn"/>
</Rules>
</RuleSet>
Dim document = New XDocument(startingRuleSet)
document.SetSeverity("Alpha.Analyzer", "Test001", ReportDiagnostic.Default)
Dim expectedRuleSet =
<RuleSet Name="MyRules" Description="A bunch of rules">
<Rules AnalyzerId="Alpha.Analyzer" RuleNamespace="Alpha.Analyzer">
</Rules>
<Rules AnalyzerId="Beta.Analyzer" RuleNamespace="Alpha.Analyzer">
</Rules>
</RuleSet>
Assert.Equal(expectedRuleSet.Value, document.Element("RuleSet").Value)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Compilers/CSharp/Portable/Syntax/ParameterSyntax.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
public partial class ParameterSyntax
{
internal bool IsArgList
{
get
{
return this.Type == null && this.Identifier.ContextualKind() == SyntaxKind.ArgListKeyword;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
public partial class ParameterSyntax
{
internal bool IsArgList
{
get
{
return this.Type == null && this.Identifier.ContextualKind() == SyntaxKind.ArgListKeyword;
}
}
}
}
| -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Compilers/CSharp/Test/Semantic/Semantics/VarianceTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class VarianceTests : CompilingTestBase
{
/// <summary>
/// Test generic interface assignment with type parameter variance.
/// </summary>
[Fact]
public void TestInterfaceAssignment()
{
var text = @"
interface I<in TIn, out TOut, T> {{ }}
class A {{ }}
class B : A {{ }}
class C : B {{ }}
class Test
{{
static I<A, A, A> i01 = null;
static I<A, A, B> i02 = null;
static I<A, A, C> i03 = null;
static I<A, B, A> i04 = null;
static I<A, B, B> i05 = null;
static I<A, B, C> i06 = null;
static I<A, C, A> i07 = null;
static I<A, C, B> i08 = null;
static I<A, C, C> i09 = null;
static I<B, A, A> i10 = null;
static I<B, A, B> i11 = null;
static I<B, A, C> i12 = null;
static I<B, B, A> i13 = null;
static I<B, B, B> i14 = null;
static I<B, B, C> i15 = null;
static I<B, C, A> i16 = null;
static I<B, C, B> i17 = null;
static I<B, C, C> i18 = null;
static I<C, A, A> i19 = null;
static I<C, A, B> i20 = null;
static I<C, A, C> i21 = null;
static I<C, B, A> i22 = null;
static I<C, B, B> i23 = null;
static I<C, B, C> i24 = null;
static I<C, C, A> i25 = null;
static I<C, C, B> i26 = null;
static I<C, C, C> i27 = null;
static void Main()
{{
i{0:d2} = i{1:d2};
}}
}}";
// Table comes from manual Dev10 testing
int[][] validAssignments = new int[][]
{
/*filler for 1-indexing*/ new int[0],
/*01*/
new [] { 1, 4, 7 },
/*02*/ new [] { 2, 5, 8 },
/*03*/ new [] { 3, 6, 9 },
/*04*/ new [] { 4, 7 },
/*05*/ new [] { 5, 8 },
/*06*/ new [] { 6, 9 },
/*07*/ new [] { 7 },
/*08*/ new [] { 8 },
/*09*/ new [] { 9 },
/*10*/ new [] { 1, 4, 7, 10, 13, 16 },
/*11*/ new [] { 2, 5, 8, 11, 14, 17 },
/*12*/ new [] { 3, 6, 9, 12, 15, 18 },
/*13*/ new [] { 4, 7, 13, 16 },
/*14*/ new [] { 5, 8, 14, 17 },
/*15*/ new [] { 6, 9, 15, 18 },
/*16*/ new [] { 7, 16 },
/*17*/ new [] { 8, 17 },
/*18*/ new [] { 9, 18 },
/*19*/ new [] { 1, 4, 7, 10, 13, 16, 19, 22, 25 },
/*20*/ new [] { 2, 5, 8, 11, 14, 17, 20, 23, 26 },
/*21*/ new [] { 3, 6, 9, 12, 15, 18, 21, 24, 27 },
/*22*/ new [] { 4, 7, 13, 16, 22, 25 },
/*23*/ new [] { 5, 8, 14, 17, 23, 26 },
/*24*/ new [] { 6, 9, 15, 18, 24, 27 },
/*25*/ new [] { 7, 16, 25 },
/*26*/ new [] { 8, 17, 26 },
/*27*/ new [] { 9, 18, 27 },
};
int numFields = validAssignments.Length - 1;
for (int i = 1; i <= numFields; i++)
{
for (int j = 1; j <= numFields; j++)
{
try
{
var comp = CreateCompilation(string.Format(text, i, j));
var errors = comp.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error);
if (!validAssignments[i].Contains(j))
{
Assert.Equal(ErrorCode.ERR_NoImplicitConvCast, (ErrorCode)errors.Single().Code);
}
else
{
Assert.Empty(errors);
}
}
catch (Exception)
{
Console.WriteLine("Failed on assignment i{0:d2} = i{1:d2}", i, j);
throw;
}
}
}
}
/// <summary>
/// Test generic interface assignment with type parameter variance.
/// </summary>
[Fact]
public void TestDelegateAssignment()
{
var text = @"
delegate TOut D<in TIn, out TOut, T>(TIn tIn, T t);
class A {{ }}
class B : A {{ }}
class C : B {{ }}
class Test
{{
static D<A, A, A> d01 = null;
static D<A, A, B> d02 = null;
static D<A, A, C> d03 = null;
static D<A, B, A> d04 = null;
static D<A, B, B> d05 = null;
static D<A, B, C> d06 = null;
static D<A, C, A> d07 = null;
static D<A, C, B> d08 = null;
static D<A, C, C> d09 = null;
static D<B, A, A> d10 = null;
static D<B, A, B> d11 = null;
static D<B, A, C> d12 = null;
static D<B, B, A> d13 = null;
static D<B, B, B> d14 = null;
static D<B, B, C> d15 = null;
static D<B, C, A> d16 = null;
static D<B, C, B> d17 = null;
static D<B, C, C> d18 = null;
static D<C, A, A> d19 = null;
static D<C, A, B> d20 = null;
static D<C, A, C> d21 = null;
static D<C, B, A> d22 = null;
static D<C, B, B> d23 = null;
static D<C, B, C> d24 = null;
static D<C, C, A> d25 = null;
static D<C, C, B> d26 = null;
static D<C, C, C> d27 = null;
static void Main()
{{
d{0:d2} = d{1:d2};
}}
}}";
// Table comes from manual Dev10 testing
int[][] validAssignments = new int[][]
{
/*filler for 1-indexing*/ new int[0],
/*01*/
new [] { 1, 4, 7 },
/*02*/ new [] { 2, 5, 8 },
/*03*/ new [] { 3, 6, 9 },
/*04*/ new [] { 4, 7 },
/*05*/ new [] { 5, 8 },
/*06*/ new [] { 6, 9 },
/*07*/ new [] { 7 },
/*08*/ new [] { 8 },
/*09*/ new [] { 9 },
/*10*/ new [] { 1, 4, 7, 10, 13, 16 },
/*11*/ new [] { 2, 5, 8, 11, 14, 17 },
/*12*/ new [] { 3, 6, 9, 12, 15, 18 },
/*13*/ new [] { 4, 7, 13, 16 },
/*14*/ new [] { 5, 8, 14, 17 },
/*15*/ new [] { 6, 9, 15, 18 },
/*16*/ new [] { 7, 16 },
/*17*/ new [] { 8, 17 },
/*18*/ new [] { 9, 18 },
/*19*/ new [] { 1, 4, 7, 10, 13, 16, 19, 22, 25 },
/*20*/ new [] { 2, 5, 8, 11, 14, 17, 20, 23, 26 },
/*21*/ new [] { 3, 6, 9, 12, 15, 18, 21, 24, 27 },
/*22*/ new [] { 4, 7, 13, 16, 22, 25 },
/*23*/ new [] { 5, 8, 14, 17, 23, 26 },
/*24*/ new [] { 6, 9, 15, 18, 24, 27 },
/*25*/ new [] { 7, 16, 25 },
/*26*/ new [] { 8, 17, 26 },
/*27*/ new [] { 9, 18, 27 },
};
int numFields = validAssignments.Length - 1;
for (int i = 1; i <= numFields; i++)
{
for (int j = 1; j <= numFields; j++)
{
try
{
var comp = CreateCompilation(string.Format(text, i, j));
var errors = comp.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error);
if (!validAssignments[i].Contains(j))
{
var code = (ErrorCode)errors.Single().Code;
// UNDONE: which one will be used is predictable, but confirming that the behavior
// exactly matches dev10 is probably too tedious to be worthwhile
Assert.True(code == ErrorCode.ERR_NoImplicitConvCast || code == ErrorCode.ERR_NoImplicitConv, "Unexpected error code " + code);
}
else
{
Assert.Empty(errors);
}
}
catch (Exception)
{
Console.WriteLine("Failed on assignment d{0:d2} = d{1:d2}", i, j);
throw;
}
}
}
}
/// <remarks>Based on LambdaTests.TestLambdaErrors03</remarks>
[Fact]
[WorkItem(539538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539538")]
public void TestVarianceConversionCycle()
{
// To determine which overload is better, we have to try to convert D<IIn<I>> to D<I>
// and vice versa. The former is impossible and the latter is possible if and only
// if it is possible (i.e. cycle).
var text = @"
interface IIn<in TIn> { }
interface I : IIn<IIn<I>> { }
delegate T D<out T>();
class C
{
static void Goo(D<IIn<I>> x) { }
static void Goo(D<I> x) { }
static void M()
{
Goo(null);
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (13,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.Goo(D<IIn<I>>)' and 'C.Goo(D<I>)'
Diagnostic(ErrorCode.ERR_AmbigCall, "Goo").WithArguments("C.Goo(D<IIn<I>>)", "C.Goo(D<I>)"));
}
/// <remarks>http://blogs.msdn.com/b/ericlippert/archive/2008/05/07/covariance-and-contravariance-part-twelve-to-infinity-but-not-beyond.aspx</remarks>
[Fact]
[WorkItem(539538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539538")]
public void TestVarianceConversionInfiniteExpansion01()
{
// IC<double> is convertible to IN<IC<string>> if and only
// if IC<IC<double>> is convertible to IN<IC<IC<string>>>.
var text = @"
public interface IN<in U> {}
public interface IC<X> : IN<IN<IC<IC<X>>>> {}
class C
{
static void M()
{
IC<double> bar = null;
IN<IC<string>> goo = bar;
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (10,30): error CS0266: Cannot implicitly convert type 'IC<double>' to 'IN<IC<string>>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "bar").WithArguments("IC<double>", "IN<IC<string>>"));
}
/// <remarks>http://blogs.msdn.com/b/ericlippert/archive/2008/05/07/covariance-and-contravariance-part-twelve-to-infinity-but-not-beyond.aspx</remarks>
[Fact]
[WorkItem(539538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539538")]
public void TestVarianceConversionInfiniteExpansion02()
{
var text = @"
interface A<in B> where B : class
{
}
interface B<in A> where A : class
{
}
class X : A<B<X>>
{
}
class Y : B<A<Y>>
{
}
class Test
{
static void Main ()
{
A<Y> x = new X ();
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (22,19): error CS0266: Cannot implicitly convert type 'X' to 'A<Y>'. An explicit conversion exists (are you missing a cast?)
// A<Y> x = new X ();
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "new X ()").WithArguments("X", "A<Y>")
);
}
[WorkItem(539538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539538")]
[Fact]
public void TestVarianceConversionLongFailure()
{
// IC<double> is convertible to IN<IC<string>> if and only
// if IC<IC<double>> is convertible to IN<IC<IC<string>>>.
var text = @"
interface A : B<B<A>> {}
interface B<T> : C<C<T>> {}
interface C<T> : D<D<T>> {}
interface D<T> : E<E<T>> {}
interface E<T> : F<F<T>> {}
interface F<T> : N<N<T>> {}
interface X : Y<Y<N<N<X>>>> {}
interface Y<T> : Z<Z<T>> {}
interface Z<T> : W<W<T>> {}
interface W<T> : U<U<T>> {}
interface U<T> : V<V<T>> {}
interface V<T> : N<N<T>> {}
interface N<in T> {}
class M {
static void Main() {
A a = null;
N<X> nx = a;
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (22,15): error CS0266: Cannot implicitly convert type 'A' to 'N<X>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "a").WithArguments("A", "N<X>"));
}
[WorkItem(539538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539538")]
[WorkItem(529488, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529488")]
[Fact]
public void TestVarianceConversionLongSuccess_Breaking()
{
// IC<double> is convertible to IN<IC<string>> if and only
// if IC<IC<double>> is convertible to IN<IC<IC<string>>>.
var text = @"
interface A : B<B<A>> { }
interface B<T> : C<C<T>> { }
interface C<T> : D<D<T>> { }
interface D<T> : E<E<T>> { }
interface E<T> : F<F<T>> { }
interface F<T> : N<N<T>> { }
interface X : Y<Y<N<F<E<D<C<B<A>>>>>>>> { }
interface Y<T> : Z<Z<T>> { }
interface Z<T> : W<W<T>> { }
interface W<T> : U<U<T>> { }
interface U<T> : V<V<T>> { }
interface V<T> : N<N<T>> { }
interface N<in T> { }
class M
{
static void Main()
{
A a = null;
N<X> nx = a;
}
}
";
// There should not be any diagnostics, but we blow our stack and make a guess.
// NB: this is a breaking change.
CreateCompilation(text).VerifyDiagnostics(
// (24,19): error CS0266: Cannot implicitly convert type 'A' to 'N<X>'. An explicit conversion exists (are you missing a cast?)
// N<X> nx = a;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "a").WithArguments("A", "N<X>"));
}
[WorkItem(542482, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542482")]
[Fact]
public void CS1961ERR_UnexpectedVariance_ConstraintTypes()
{
var text =
@"interface IIn<in T> { }
interface IOut<out T> { }
class C<T> { }
interface I1<out T, in U, V>
{
void M<X>() where X : T, U, V;
}
interface I2<out T, in U, V>
{
void M<X>() where X : IOut<T>, IOut<U>, IOut<V>;
}
interface I3<out T, in U, V>
{
void M<X>() where X : IIn<T>, IIn<U>, IIn<V>;
}
interface I4<out T, in U, V>
{
void M1<X>() where X : C<T>;
void M2<X>() where X : C<U>;
void M3<X>() where X : C<V>;
}";
CreateCompilation(text).VerifyDiagnostics(
// (6,12): error CS1961: Invalid variance: The type parameter 'T' must be contravariantly valid on 'I1<T, U, V>.M<X>()'. 'T' is covariant.
// void M<X>() where X : T, U, V;
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "X").WithArguments("I1<T, U, V>.M<X>()", "T", "covariant", "contravariantly").WithLocation(6, 12),
// (10,12): error CS1961: Invalid variance: The type parameter 'T' must be contravariantly valid on 'I2<T, U, V>.M<X>()'. 'T' is covariant.
// void M<X>() where X : IOut<T>, IOut<U>, IOut<V>;
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "X").WithArguments("I2<T, U, V>.M<X>()", "T", "covariant", "contravariantly").WithLocation(10, 12),
// (14,12): error CS1961: Invalid variance: The type parameter 'U' must be covariantly valid on 'I3<T, U, V>.M<X>()'. 'U' is contravariant.
// void M<X>() where X : IIn<T>, IIn<U>, IIn<V>;
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "X").WithArguments("I3<T, U, V>.M<X>()", "U", "contravariant", "covariantly").WithLocation(14, 12),
// (18,13): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I4<T, U, V>.M1<X>()'. 'T' is covariant.
// void M1<X>() where X : C<T>;
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "X").WithArguments("I4<T, U, V>.M1<X>()", "T", "covariant", "invariantly").WithLocation(18, 13),
// (19,13): error CS1961: Invalid variance: The type parameter 'U' must be invariantly valid on 'I4<T, U, V>.M2<X>()'. 'U' is contravariant.
// void M2<X>() where X : C<U>;
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "X").WithArguments("I4<T, U, V>.M2<X>()", "U", "contravariant", "invariantly").WithLocation(19, 13));
}
[Fact]
public void CS1961ERR_UnexpectedVariance_ClassesAndStructs()
{
var text =
@"class C<T> { }
struct S<T> { }
interface I1<out T, U>
{
C<T> M(C<U> o);
}
interface I2<out T, U>
{
C<U> M(C<T> o);
}
interface I3<out T, U>
{
S<T> M(S<U> o);
}
interface I4<out T, U>
{
S<U> M(S<T> o);
}
interface I5<in T, U>
{
C<T> M(C<U> o);
}
interface I6<in T, U>
{
C<U> M(C<T> o);
}
interface I7<in T, U>
{
S<T> M(S<U> o);
}
interface I8<in T, U>
{
S<U> M(S<T> o);
}";
CreateCompilation(text).VerifyDiagnostics(
// (5,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I1<T, U>.M(C<U>)'. 'T' is covariant.
// C<T> M(C<U> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>").WithArguments("I1<T, U>.M(C<U>)", "T", "covariant", "invariantly").WithLocation(5, 5),
// (9,12): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I2<T, U>.M(C<T>)'. 'T' is covariant.
// C<U> M(C<T> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>").WithArguments("I2<T, U>.M(C<T>)", "T", "covariant", "invariantly").WithLocation(9, 12),
// (13,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I3<T, U>.M(S<U>)'. 'T' is covariant.
// S<T> M(S<U> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "S<T>").WithArguments("I3<T, U>.M(S<U>)", "T", "covariant", "invariantly").WithLocation(13, 5),
// (17,12): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I4<T, U>.M(S<T>)'. 'T' is covariant.
// S<U> M(S<T> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "S<T>").WithArguments("I4<T, U>.M(S<T>)", "T", "covariant", "invariantly").WithLocation(17, 12),
// (21,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I5<T, U>.M(C<U>)'. 'T' is contravariant.
// C<T> M(C<U> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>").WithArguments("I5<T, U>.M(C<U>)", "T", "contravariant", "invariantly").WithLocation(21, 5),
// (25,12): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I6<T, U>.M(C<T>)'. 'T' is contravariant.
// C<U> M(C<T> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>").WithArguments("I6<T, U>.M(C<T>)", "T", "contravariant", "invariantly").WithLocation(25, 12),
// (29,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I7<T, U>.M(S<U>)'. 'T' is contravariant.
// S<T> M(S<U> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "S<T>").WithArguments("I7<T, U>.M(S<U>)", "T", "contravariant", "invariantly").WithLocation(29, 5),
// (33,12): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I8<T, U>.M(S<T>)'. 'T' is contravariant.
// S<U> M(S<T> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "S<T>").WithArguments("I8<T, U>.M(S<T>)", "T", "contravariant", "invariantly").WithLocation(33, 12));
}
[WorkItem(602022, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602022")]
[Fact]
public void CS1961ERR_UnexpectedVariance_Enums()
{
var text =
@"class C<T>
{
public enum E { }
}
interface I1<out T, U>
{
C<T>.E M(C<U>.E o);
}
interface I2<out T, U>
{
C<U>.E M(C<T>.E o);
}
interface I3<in T, U>
{
C<T>.E M(C<U>.E o);
}
interface I4<in T, U>
{
C<U>.E M(C<T>.E o);
}";
CreateCompilation(text).VerifyDiagnostics(
// (7,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I1<T, U>.M(C<U>.E)'. 'T' is covariant.
// C<T>.E M(C<U>.E o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>.E").WithArguments("I1<T, U>.M(C<U>.E)", "T", "covariant", "invariantly").WithLocation(7, 5),
// (11,14): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I2<T, U>.M(C<T>.E)'. 'T' is covariant.
// C<U>.E M(C<T>.E o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>.E").WithArguments("I2<T, U>.M(C<T>.E)", "T", "covariant", "invariantly").WithLocation(11, 14),
// (15,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I3<T, U>.M(C<U>.E)'. 'T' is contravariant.
// C<T>.E M(C<U>.E o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>.E").WithArguments("I3<T, U>.M(C<U>.E)", "T", "contravariant", "invariantly").WithLocation(15, 5),
// (19,14): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I4<T, U>.M(C<T>.E)'. 'T' is contravariant.
// C<U>.E M(C<T>.E o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>.E").WithArguments("I4<T, U>.M(C<T>.E)", "T", "contravariant", "invariantly").WithLocation(19, 14));
}
[WorkItem(542794, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542794")]
[Fact]
public void ContravariantBaseInterface()
{
var text =
@"
interface IA<in T> { }
interface IB<in T> : IA<IB<T>> { }
";
CreateCompilation(text).VerifyDiagnostics(
// (3,17): error CS1961: Invalid variance: The type parameter 'T' must be covariantly valid on 'IA<IB<T>>'. 'T' is contravariant.
// interface IB<in T> : IA<IB<T>> { }
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T").WithArguments("IA<IB<T>>", "T", "contravariant", "covariantly").WithLocation(3, 17));
}
/// <summary>
/// Report errors on type parameter use
/// rather than declaration.
/// </summary>
[WorkItem(855750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/855750")]
[Fact]
public void ErrorLocations()
{
var text =
@"interface IIn<in T> { }
interface IOut<out T> { }
class C<T> { }
delegate void D<in T>();
interface I<out T, in U>
{
C<U> M(C<T> o);
IIn<T>[] P { get; }
U this[object o] { get; }
event D<U> E;
void M<X>()
where X : C<IIn<U>>, IOut<T>;
}
interface I<out T> :
I<T, T>
{
}";
CreateCompilation(text).VerifyDiagnostics(
// (7,5): error CS1961: Invalid variance: The type parameter 'U' must be invariantly valid on 'I<T, U>.M(C<T>)'. 'U' is contravariant.
// C<U> M(C<T> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<U>").WithArguments("I<T, U>.M(C<T>)", "U", "contravariant", "invariantly").WithLocation(7, 5),
// (7,12): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I<T, U>.M(C<T>)'. 'T' is covariant.
// C<U> M(C<T> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>").WithArguments("I<T, U>.M(C<T>)", "T", "covariant", "invariantly").WithLocation(7, 12),
// (8,5): error CS1961: Invalid variance: The type parameter 'T' must be contravariantly valid on 'I<T, U>.P'. 'T' is covariant.
// IIn<T>[] P { get; }
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<T>[]").WithArguments("I<T, U>.P", "T", "covariant", "contravariantly").WithLocation(8, 5),
// (9,5): error CS1961: Invalid variance: The type parameter 'U' must be covariantly valid on 'I<T, U>.this[object]'. 'U' is contravariant.
// U this[object o] { get; }
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "U").WithArguments("I<T, U>.this[object]", "U", "contravariant", "covariantly").WithLocation(9, 5),
// (10,16): error CS1961: Invalid variance: The type parameter 'U' must be covariantly valid on 'I<T, U>.E'. 'U' is contravariant.
// event D<U> E;
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "E").WithArguments("I<T, U>.E", "U", "contravariant", "covariantly").WithLocation(10, 16),
// (11,12): error CS1961: Invalid variance: The type parameter 'U' must be invariantly valid on 'I<T, U>.M<X>()'. 'U' is contravariant.
// void M<X>()
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "X").WithArguments("I<T, U>.M<X>()", "U", "contravariant", "invariantly").WithLocation(11, 12),
// (11,12): error CS1961: Invalid variance: The type parameter 'T' must be contravariantly valid on 'I<T, U>.M<X>()'. 'T' is covariant.
// void M<X>()
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "X").WithArguments("I<T, U>.M<X>()", "T", "covariant", "contravariantly").WithLocation(11, 12),
// (14,17): error CS1961: Invalid variance: The type parameter 'T' must be contravariantly valid on 'I<T, T>'. 'T' is covariant.
// interface I<out T> :
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T").WithArguments("I<T, T>", "T", "covariant", "contravariantly").WithLocation(14, 17));
}
[Fact]
public void CovarianceBoundariesForRefReadOnly_Parameters()
{
CreateCompilation(@"
interface ITest<in T>
{
void M(in T p);
}").VerifyDiagnostics(
// (4,15): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'ITest<T>.M(in T)'. 'T' is contravariant.
// void M(in T p);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T").WithArguments("ITest<T>.M(in T)", "T", "contravariant", "invariantly").WithLocation(4, 15));
}
[Fact]
public void CovarianceBoundariesForRefReadOnly_ReturnType()
{
CreateCompilation(@"
interface ITest<in T>
{
ref readonly T M();
}").VerifyDiagnostics(
// (4,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'ITest<T>.M()'. 'T' is contravariant.
// ref readonly T M();
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref readonly T").WithArguments("ITest<T>.M()", "T", "contravariant", "invariantly").WithLocation(4, 5));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class VarianceTests : CompilingTestBase
{
/// <summary>
/// Test generic interface assignment with type parameter variance.
/// </summary>
[Fact]
public void TestInterfaceAssignment()
{
var text = @"
interface I<in TIn, out TOut, T> {{ }}
class A {{ }}
class B : A {{ }}
class C : B {{ }}
class Test
{{
static I<A, A, A> i01 = null;
static I<A, A, B> i02 = null;
static I<A, A, C> i03 = null;
static I<A, B, A> i04 = null;
static I<A, B, B> i05 = null;
static I<A, B, C> i06 = null;
static I<A, C, A> i07 = null;
static I<A, C, B> i08 = null;
static I<A, C, C> i09 = null;
static I<B, A, A> i10 = null;
static I<B, A, B> i11 = null;
static I<B, A, C> i12 = null;
static I<B, B, A> i13 = null;
static I<B, B, B> i14 = null;
static I<B, B, C> i15 = null;
static I<B, C, A> i16 = null;
static I<B, C, B> i17 = null;
static I<B, C, C> i18 = null;
static I<C, A, A> i19 = null;
static I<C, A, B> i20 = null;
static I<C, A, C> i21 = null;
static I<C, B, A> i22 = null;
static I<C, B, B> i23 = null;
static I<C, B, C> i24 = null;
static I<C, C, A> i25 = null;
static I<C, C, B> i26 = null;
static I<C, C, C> i27 = null;
static void Main()
{{
i{0:d2} = i{1:d2};
}}
}}";
// Table comes from manual Dev10 testing
int[][] validAssignments = new int[][]
{
/*filler for 1-indexing*/ new int[0],
/*01*/
new [] { 1, 4, 7 },
/*02*/ new [] { 2, 5, 8 },
/*03*/ new [] { 3, 6, 9 },
/*04*/ new [] { 4, 7 },
/*05*/ new [] { 5, 8 },
/*06*/ new [] { 6, 9 },
/*07*/ new [] { 7 },
/*08*/ new [] { 8 },
/*09*/ new [] { 9 },
/*10*/ new [] { 1, 4, 7, 10, 13, 16 },
/*11*/ new [] { 2, 5, 8, 11, 14, 17 },
/*12*/ new [] { 3, 6, 9, 12, 15, 18 },
/*13*/ new [] { 4, 7, 13, 16 },
/*14*/ new [] { 5, 8, 14, 17 },
/*15*/ new [] { 6, 9, 15, 18 },
/*16*/ new [] { 7, 16 },
/*17*/ new [] { 8, 17 },
/*18*/ new [] { 9, 18 },
/*19*/ new [] { 1, 4, 7, 10, 13, 16, 19, 22, 25 },
/*20*/ new [] { 2, 5, 8, 11, 14, 17, 20, 23, 26 },
/*21*/ new [] { 3, 6, 9, 12, 15, 18, 21, 24, 27 },
/*22*/ new [] { 4, 7, 13, 16, 22, 25 },
/*23*/ new [] { 5, 8, 14, 17, 23, 26 },
/*24*/ new [] { 6, 9, 15, 18, 24, 27 },
/*25*/ new [] { 7, 16, 25 },
/*26*/ new [] { 8, 17, 26 },
/*27*/ new [] { 9, 18, 27 },
};
int numFields = validAssignments.Length - 1;
for (int i = 1; i <= numFields; i++)
{
for (int j = 1; j <= numFields; j++)
{
try
{
var comp = CreateCompilation(string.Format(text, i, j));
var errors = comp.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error);
if (!validAssignments[i].Contains(j))
{
Assert.Equal(ErrorCode.ERR_NoImplicitConvCast, (ErrorCode)errors.Single().Code);
}
else
{
Assert.Empty(errors);
}
}
catch (Exception)
{
Console.WriteLine("Failed on assignment i{0:d2} = i{1:d2}", i, j);
throw;
}
}
}
}
/// <summary>
/// Test generic interface assignment with type parameter variance.
/// </summary>
[Fact]
public void TestDelegateAssignment()
{
var text = @"
delegate TOut D<in TIn, out TOut, T>(TIn tIn, T t);
class A {{ }}
class B : A {{ }}
class C : B {{ }}
class Test
{{
static D<A, A, A> d01 = null;
static D<A, A, B> d02 = null;
static D<A, A, C> d03 = null;
static D<A, B, A> d04 = null;
static D<A, B, B> d05 = null;
static D<A, B, C> d06 = null;
static D<A, C, A> d07 = null;
static D<A, C, B> d08 = null;
static D<A, C, C> d09 = null;
static D<B, A, A> d10 = null;
static D<B, A, B> d11 = null;
static D<B, A, C> d12 = null;
static D<B, B, A> d13 = null;
static D<B, B, B> d14 = null;
static D<B, B, C> d15 = null;
static D<B, C, A> d16 = null;
static D<B, C, B> d17 = null;
static D<B, C, C> d18 = null;
static D<C, A, A> d19 = null;
static D<C, A, B> d20 = null;
static D<C, A, C> d21 = null;
static D<C, B, A> d22 = null;
static D<C, B, B> d23 = null;
static D<C, B, C> d24 = null;
static D<C, C, A> d25 = null;
static D<C, C, B> d26 = null;
static D<C, C, C> d27 = null;
static void Main()
{{
d{0:d2} = d{1:d2};
}}
}}";
// Table comes from manual Dev10 testing
int[][] validAssignments = new int[][]
{
/*filler for 1-indexing*/ new int[0],
/*01*/
new [] { 1, 4, 7 },
/*02*/ new [] { 2, 5, 8 },
/*03*/ new [] { 3, 6, 9 },
/*04*/ new [] { 4, 7 },
/*05*/ new [] { 5, 8 },
/*06*/ new [] { 6, 9 },
/*07*/ new [] { 7 },
/*08*/ new [] { 8 },
/*09*/ new [] { 9 },
/*10*/ new [] { 1, 4, 7, 10, 13, 16 },
/*11*/ new [] { 2, 5, 8, 11, 14, 17 },
/*12*/ new [] { 3, 6, 9, 12, 15, 18 },
/*13*/ new [] { 4, 7, 13, 16 },
/*14*/ new [] { 5, 8, 14, 17 },
/*15*/ new [] { 6, 9, 15, 18 },
/*16*/ new [] { 7, 16 },
/*17*/ new [] { 8, 17 },
/*18*/ new [] { 9, 18 },
/*19*/ new [] { 1, 4, 7, 10, 13, 16, 19, 22, 25 },
/*20*/ new [] { 2, 5, 8, 11, 14, 17, 20, 23, 26 },
/*21*/ new [] { 3, 6, 9, 12, 15, 18, 21, 24, 27 },
/*22*/ new [] { 4, 7, 13, 16, 22, 25 },
/*23*/ new [] { 5, 8, 14, 17, 23, 26 },
/*24*/ new [] { 6, 9, 15, 18, 24, 27 },
/*25*/ new [] { 7, 16, 25 },
/*26*/ new [] { 8, 17, 26 },
/*27*/ new [] { 9, 18, 27 },
};
int numFields = validAssignments.Length - 1;
for (int i = 1; i <= numFields; i++)
{
for (int j = 1; j <= numFields; j++)
{
try
{
var comp = CreateCompilation(string.Format(text, i, j));
var errors = comp.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error);
if (!validAssignments[i].Contains(j))
{
var code = (ErrorCode)errors.Single().Code;
// UNDONE: which one will be used is predictable, but confirming that the behavior
// exactly matches dev10 is probably too tedious to be worthwhile
Assert.True(code == ErrorCode.ERR_NoImplicitConvCast || code == ErrorCode.ERR_NoImplicitConv, "Unexpected error code " + code);
}
else
{
Assert.Empty(errors);
}
}
catch (Exception)
{
Console.WriteLine("Failed on assignment d{0:d2} = d{1:d2}", i, j);
throw;
}
}
}
}
/// <remarks>Based on LambdaTests.TestLambdaErrors03</remarks>
[Fact]
[WorkItem(539538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539538")]
public void TestVarianceConversionCycle()
{
// To determine which overload is better, we have to try to convert D<IIn<I>> to D<I>
// and vice versa. The former is impossible and the latter is possible if and only
// if it is possible (i.e. cycle).
var text = @"
interface IIn<in TIn> { }
interface I : IIn<IIn<I>> { }
delegate T D<out T>();
class C
{
static void Goo(D<IIn<I>> x) { }
static void Goo(D<I> x) { }
static void M()
{
Goo(null);
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (13,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.Goo(D<IIn<I>>)' and 'C.Goo(D<I>)'
Diagnostic(ErrorCode.ERR_AmbigCall, "Goo").WithArguments("C.Goo(D<IIn<I>>)", "C.Goo(D<I>)"));
}
/// <remarks>http://blogs.msdn.com/b/ericlippert/archive/2008/05/07/covariance-and-contravariance-part-twelve-to-infinity-but-not-beyond.aspx</remarks>
[Fact]
[WorkItem(539538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539538")]
public void TestVarianceConversionInfiniteExpansion01()
{
// IC<double> is convertible to IN<IC<string>> if and only
// if IC<IC<double>> is convertible to IN<IC<IC<string>>>.
var text = @"
public interface IN<in U> {}
public interface IC<X> : IN<IN<IC<IC<X>>>> {}
class C
{
static void M()
{
IC<double> bar = null;
IN<IC<string>> goo = bar;
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (10,30): error CS0266: Cannot implicitly convert type 'IC<double>' to 'IN<IC<string>>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "bar").WithArguments("IC<double>", "IN<IC<string>>"));
}
/// <remarks>http://blogs.msdn.com/b/ericlippert/archive/2008/05/07/covariance-and-contravariance-part-twelve-to-infinity-but-not-beyond.aspx</remarks>
[Fact]
[WorkItem(539538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539538")]
public void TestVarianceConversionInfiniteExpansion02()
{
var text = @"
interface A<in B> where B : class
{
}
interface B<in A> where A : class
{
}
class X : A<B<X>>
{
}
class Y : B<A<Y>>
{
}
class Test
{
static void Main ()
{
A<Y> x = new X ();
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (22,19): error CS0266: Cannot implicitly convert type 'X' to 'A<Y>'. An explicit conversion exists (are you missing a cast?)
// A<Y> x = new X ();
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "new X ()").WithArguments("X", "A<Y>")
);
}
[WorkItem(539538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539538")]
[Fact]
public void TestVarianceConversionLongFailure()
{
// IC<double> is convertible to IN<IC<string>> if and only
// if IC<IC<double>> is convertible to IN<IC<IC<string>>>.
var text = @"
interface A : B<B<A>> {}
interface B<T> : C<C<T>> {}
interface C<T> : D<D<T>> {}
interface D<T> : E<E<T>> {}
interface E<T> : F<F<T>> {}
interface F<T> : N<N<T>> {}
interface X : Y<Y<N<N<X>>>> {}
interface Y<T> : Z<Z<T>> {}
interface Z<T> : W<W<T>> {}
interface W<T> : U<U<T>> {}
interface U<T> : V<V<T>> {}
interface V<T> : N<N<T>> {}
interface N<in T> {}
class M {
static void Main() {
A a = null;
N<X> nx = a;
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (22,15): error CS0266: Cannot implicitly convert type 'A' to 'N<X>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "a").WithArguments("A", "N<X>"));
}
[WorkItem(539538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539538")]
[WorkItem(529488, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529488")]
[Fact]
public void TestVarianceConversionLongSuccess_Breaking()
{
// IC<double> is convertible to IN<IC<string>> if and only
// if IC<IC<double>> is convertible to IN<IC<IC<string>>>.
var text = @"
interface A : B<B<A>> { }
interface B<T> : C<C<T>> { }
interface C<T> : D<D<T>> { }
interface D<T> : E<E<T>> { }
interface E<T> : F<F<T>> { }
interface F<T> : N<N<T>> { }
interface X : Y<Y<N<F<E<D<C<B<A>>>>>>>> { }
interface Y<T> : Z<Z<T>> { }
interface Z<T> : W<W<T>> { }
interface W<T> : U<U<T>> { }
interface U<T> : V<V<T>> { }
interface V<T> : N<N<T>> { }
interface N<in T> { }
class M
{
static void Main()
{
A a = null;
N<X> nx = a;
}
}
";
// There should not be any diagnostics, but we blow our stack and make a guess.
// NB: this is a breaking change.
CreateCompilation(text).VerifyDiagnostics(
// (24,19): error CS0266: Cannot implicitly convert type 'A' to 'N<X>'. An explicit conversion exists (are you missing a cast?)
// N<X> nx = a;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "a").WithArguments("A", "N<X>"));
}
[WorkItem(542482, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542482")]
[Fact]
public void CS1961ERR_UnexpectedVariance_ConstraintTypes()
{
var text =
@"interface IIn<in T> { }
interface IOut<out T> { }
class C<T> { }
interface I1<out T, in U, V>
{
void M<X>() where X : T, U, V;
}
interface I2<out T, in U, V>
{
void M<X>() where X : IOut<T>, IOut<U>, IOut<V>;
}
interface I3<out T, in U, V>
{
void M<X>() where X : IIn<T>, IIn<U>, IIn<V>;
}
interface I4<out T, in U, V>
{
void M1<X>() where X : C<T>;
void M2<X>() where X : C<U>;
void M3<X>() where X : C<V>;
}";
CreateCompilation(text).VerifyDiagnostics(
// (6,12): error CS1961: Invalid variance: The type parameter 'T' must be contravariantly valid on 'I1<T, U, V>.M<X>()'. 'T' is covariant.
// void M<X>() where X : T, U, V;
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "X").WithArguments("I1<T, U, V>.M<X>()", "T", "covariant", "contravariantly").WithLocation(6, 12),
// (10,12): error CS1961: Invalid variance: The type parameter 'T' must be contravariantly valid on 'I2<T, U, V>.M<X>()'. 'T' is covariant.
// void M<X>() where X : IOut<T>, IOut<U>, IOut<V>;
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "X").WithArguments("I2<T, U, V>.M<X>()", "T", "covariant", "contravariantly").WithLocation(10, 12),
// (14,12): error CS1961: Invalid variance: The type parameter 'U' must be covariantly valid on 'I3<T, U, V>.M<X>()'. 'U' is contravariant.
// void M<X>() where X : IIn<T>, IIn<U>, IIn<V>;
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "X").WithArguments("I3<T, U, V>.M<X>()", "U", "contravariant", "covariantly").WithLocation(14, 12),
// (18,13): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I4<T, U, V>.M1<X>()'. 'T' is covariant.
// void M1<X>() where X : C<T>;
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "X").WithArguments("I4<T, U, V>.M1<X>()", "T", "covariant", "invariantly").WithLocation(18, 13),
// (19,13): error CS1961: Invalid variance: The type parameter 'U' must be invariantly valid on 'I4<T, U, V>.M2<X>()'. 'U' is contravariant.
// void M2<X>() where X : C<U>;
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "X").WithArguments("I4<T, U, V>.M2<X>()", "U", "contravariant", "invariantly").WithLocation(19, 13));
}
[Fact]
public void CS1961ERR_UnexpectedVariance_ClassesAndStructs()
{
var text =
@"class C<T> { }
struct S<T> { }
interface I1<out T, U>
{
C<T> M(C<U> o);
}
interface I2<out T, U>
{
C<U> M(C<T> o);
}
interface I3<out T, U>
{
S<T> M(S<U> o);
}
interface I4<out T, U>
{
S<U> M(S<T> o);
}
interface I5<in T, U>
{
C<T> M(C<U> o);
}
interface I6<in T, U>
{
C<U> M(C<T> o);
}
interface I7<in T, U>
{
S<T> M(S<U> o);
}
interface I8<in T, U>
{
S<U> M(S<T> o);
}";
CreateCompilation(text).VerifyDiagnostics(
// (5,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I1<T, U>.M(C<U>)'. 'T' is covariant.
// C<T> M(C<U> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>").WithArguments("I1<T, U>.M(C<U>)", "T", "covariant", "invariantly").WithLocation(5, 5),
// (9,12): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I2<T, U>.M(C<T>)'. 'T' is covariant.
// C<U> M(C<T> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>").WithArguments("I2<T, U>.M(C<T>)", "T", "covariant", "invariantly").WithLocation(9, 12),
// (13,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I3<T, U>.M(S<U>)'. 'T' is covariant.
// S<T> M(S<U> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "S<T>").WithArguments("I3<T, U>.M(S<U>)", "T", "covariant", "invariantly").WithLocation(13, 5),
// (17,12): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I4<T, U>.M(S<T>)'. 'T' is covariant.
// S<U> M(S<T> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "S<T>").WithArguments("I4<T, U>.M(S<T>)", "T", "covariant", "invariantly").WithLocation(17, 12),
// (21,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I5<T, U>.M(C<U>)'. 'T' is contravariant.
// C<T> M(C<U> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>").WithArguments("I5<T, U>.M(C<U>)", "T", "contravariant", "invariantly").WithLocation(21, 5),
// (25,12): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I6<T, U>.M(C<T>)'. 'T' is contravariant.
// C<U> M(C<T> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>").WithArguments("I6<T, U>.M(C<T>)", "T", "contravariant", "invariantly").WithLocation(25, 12),
// (29,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I7<T, U>.M(S<U>)'. 'T' is contravariant.
// S<T> M(S<U> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "S<T>").WithArguments("I7<T, U>.M(S<U>)", "T", "contravariant", "invariantly").WithLocation(29, 5),
// (33,12): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I8<T, U>.M(S<T>)'. 'T' is contravariant.
// S<U> M(S<T> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "S<T>").WithArguments("I8<T, U>.M(S<T>)", "T", "contravariant", "invariantly").WithLocation(33, 12));
}
[WorkItem(602022, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602022")]
[Fact]
public void CS1961ERR_UnexpectedVariance_Enums()
{
var text =
@"class C<T>
{
public enum E { }
}
interface I1<out T, U>
{
C<T>.E M(C<U>.E o);
}
interface I2<out T, U>
{
C<U>.E M(C<T>.E o);
}
interface I3<in T, U>
{
C<T>.E M(C<U>.E o);
}
interface I4<in T, U>
{
C<U>.E M(C<T>.E o);
}";
CreateCompilation(text).VerifyDiagnostics(
// (7,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I1<T, U>.M(C<U>.E)'. 'T' is covariant.
// C<T>.E M(C<U>.E o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>.E").WithArguments("I1<T, U>.M(C<U>.E)", "T", "covariant", "invariantly").WithLocation(7, 5),
// (11,14): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I2<T, U>.M(C<T>.E)'. 'T' is covariant.
// C<U>.E M(C<T>.E o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>.E").WithArguments("I2<T, U>.M(C<T>.E)", "T", "covariant", "invariantly").WithLocation(11, 14),
// (15,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I3<T, U>.M(C<U>.E)'. 'T' is contravariant.
// C<T>.E M(C<U>.E o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>.E").WithArguments("I3<T, U>.M(C<U>.E)", "T", "contravariant", "invariantly").WithLocation(15, 5),
// (19,14): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I4<T, U>.M(C<T>.E)'. 'T' is contravariant.
// C<U>.E M(C<T>.E o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>.E").WithArguments("I4<T, U>.M(C<T>.E)", "T", "contravariant", "invariantly").WithLocation(19, 14));
}
[WorkItem(542794, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542794")]
[Fact]
public void ContravariantBaseInterface()
{
var text =
@"
interface IA<in T> { }
interface IB<in T> : IA<IB<T>> { }
";
CreateCompilation(text).VerifyDiagnostics(
// (3,17): error CS1961: Invalid variance: The type parameter 'T' must be covariantly valid on 'IA<IB<T>>'. 'T' is contravariant.
// interface IB<in T> : IA<IB<T>> { }
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T").WithArguments("IA<IB<T>>", "T", "contravariant", "covariantly").WithLocation(3, 17));
}
/// <summary>
/// Report errors on type parameter use
/// rather than declaration.
/// </summary>
[WorkItem(855750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/855750")]
[Fact]
public void ErrorLocations()
{
var text =
@"interface IIn<in T> { }
interface IOut<out T> { }
class C<T> { }
delegate void D<in T>();
interface I<out T, in U>
{
C<U> M(C<T> o);
IIn<T>[] P { get; }
U this[object o] { get; }
event D<U> E;
void M<X>()
where X : C<IIn<U>>, IOut<T>;
}
interface I<out T> :
I<T, T>
{
}";
CreateCompilation(text).VerifyDiagnostics(
// (7,5): error CS1961: Invalid variance: The type parameter 'U' must be invariantly valid on 'I<T, U>.M(C<T>)'. 'U' is contravariant.
// C<U> M(C<T> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<U>").WithArguments("I<T, U>.M(C<T>)", "U", "contravariant", "invariantly").WithLocation(7, 5),
// (7,12): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I<T, U>.M(C<T>)'. 'T' is covariant.
// C<U> M(C<T> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>").WithArguments("I<T, U>.M(C<T>)", "T", "covariant", "invariantly").WithLocation(7, 12),
// (8,5): error CS1961: Invalid variance: The type parameter 'T' must be contravariantly valid on 'I<T, U>.P'. 'T' is covariant.
// IIn<T>[] P { get; }
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<T>[]").WithArguments("I<T, U>.P", "T", "covariant", "contravariantly").WithLocation(8, 5),
// (9,5): error CS1961: Invalid variance: The type parameter 'U' must be covariantly valid on 'I<T, U>.this[object]'. 'U' is contravariant.
// U this[object o] { get; }
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "U").WithArguments("I<T, U>.this[object]", "U", "contravariant", "covariantly").WithLocation(9, 5),
// (10,16): error CS1961: Invalid variance: The type parameter 'U' must be covariantly valid on 'I<T, U>.E'. 'U' is contravariant.
// event D<U> E;
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "E").WithArguments("I<T, U>.E", "U", "contravariant", "covariantly").WithLocation(10, 16),
// (11,12): error CS1961: Invalid variance: The type parameter 'U' must be invariantly valid on 'I<T, U>.M<X>()'. 'U' is contravariant.
// void M<X>()
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "X").WithArguments("I<T, U>.M<X>()", "U", "contravariant", "invariantly").WithLocation(11, 12),
// (11,12): error CS1961: Invalid variance: The type parameter 'T' must be contravariantly valid on 'I<T, U>.M<X>()'. 'T' is covariant.
// void M<X>()
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "X").WithArguments("I<T, U>.M<X>()", "T", "covariant", "contravariantly").WithLocation(11, 12),
// (14,17): error CS1961: Invalid variance: The type parameter 'T' must be contravariantly valid on 'I<T, T>'. 'T' is covariant.
// interface I<out T> :
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T").WithArguments("I<T, T>", "T", "covariant", "contravariantly").WithLocation(14, 17));
}
[Fact]
public void CovarianceBoundariesForRefReadOnly_Parameters()
{
CreateCompilation(@"
interface ITest<in T>
{
void M(in T p);
}").VerifyDiagnostics(
// (4,15): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'ITest<T>.M(in T)'. 'T' is contravariant.
// void M(in T p);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T").WithArguments("ITest<T>.M(in T)", "T", "contravariant", "invariantly").WithLocation(4, 15));
}
[Fact]
public void CovarianceBoundariesForRefReadOnly_ReturnType()
{
CreateCompilation(@"
interface ITest<in T>
{
ref readonly T M();
}").VerifyDiagnostics(
// (4,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'ITest<T>.M()'. 'T' is contravariant.
// ref readonly T M();
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref readonly T").WithArguments("ITest<T>.M()", "T", "contravariant", "invariantly").WithLocation(4, 5));
}
}
}
| -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/CodeStyle/Core/CodeFixes/xlf/CodeStyleFixesResources.zh-Hant.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="zh-Hant" original="../CodeStyleFixesResources.resx">
<body>
<trans-unit id="EmptyResource">
<source>Remove this value when another is added.</source>
<target state="translated">當新增另一個值時移除此值。</target>
<note>https://github.com/Microsoft/msbuild/issues/1661</note>
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="zh-Hant" original="../CodeStyleFixesResources.resx">
<body>
<trans-unit id="EmptyResource">
<source>Remove this value when another is added.</source>
<target state="translated">當新增另一個值時移除此值。</target>
<note>https://github.com/Microsoft/msbuild/issues/1661</note>
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Features/Core/Portable/RQName/RQNodeBuilder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Features.RQName.Nodes;
namespace Microsoft.CodeAnalysis.Features.RQName
{
internal static class RQNodeBuilder
{
/// <summary>
/// Builds the RQName for a given symbol.
/// </summary>
/// <returns>The node if it could be created, otherwise null</returns>
public static RQNode? Build(ISymbol symbol)
=> symbol switch
{
INamespaceSymbol namespaceSymbol => BuildNamespace(namespaceSymbol),
INamedTypeSymbol namedTypeSymbol => BuildUnconstructedNamedType(namedTypeSymbol),
IMethodSymbol methodSymbol => BuildMethod(methodSymbol),
IFieldSymbol fieldSymbol => BuildField(fieldSymbol),
IEventSymbol eventSymbol => BuildEvent(eventSymbol),
IPropertySymbol propertySymbol => BuildProperty(propertySymbol),
_ => null,
};
private static RQNamespace BuildNamespace(INamespaceSymbol @namespace)
=> new(RQNodeBuilder.GetNameParts(@namespace));
private static IList<string> GetNameParts(INamespaceSymbol @namespace)
{
var parts = new List<string>();
if (@namespace == null)
{
return parts;
}
while ([email protected])
{
parts.Add(@namespace.Name);
@namespace = @namespace.ContainingNamespace;
}
parts.Reverse();
return parts;
}
private static RQUnconstructedType? BuildUnconstructedNamedType(INamedTypeSymbol type)
{
// Anything that is a valid RQUnconstructed types is ALWAYS safe for public APIs
if (type == null)
{
return null;
}
// Anonymous types are unsupported
if (type.IsAnonymousType)
{
return null;
}
// the following types are supported for BuildType() used in signatures, but are not supported
// for UnconstructedTypes
if (type != type.ConstructedFrom || type.SpecialType == SpecialType.System_Void)
{
return null;
}
// make an RQUnconstructedType
var namespaceNames = RQNodeBuilder.GetNameParts(@type.ContainingNamespace);
var typeInfos = new List<RQUnconstructedTypeInfo>();
for (var currentType = type; currentType != null; currentType = currentType.ContainingType)
{
typeInfos.Insert(0, new RQUnconstructedTypeInfo(currentType.Name, currentType.TypeParameters.Length));
}
return new RQUnconstructedType(namespaceNames, typeInfos);
}
private static RQMember? BuildField(IFieldSymbol symbol)
{
var containingType = BuildUnconstructedNamedType(symbol.ContainingType);
if (containingType == null)
{
return null;
}
return new RQMemberVariable(containingType, symbol.Name);
}
private static RQProperty? BuildProperty(IPropertySymbol symbol)
{
RQMethodPropertyOrEventName name = symbol.IsIndexer ?
RQOrdinaryMethodPropertyOrEventName.CreateOrdinaryIndexerName() :
RQOrdinaryMethodPropertyOrEventName.CreateOrdinaryPropertyName(symbol.Name);
if (symbol.ExplicitInterfaceImplementations.Any())
{
if (symbol.ExplicitInterfaceImplementations.Length > 1)
{
return null;
}
var interfaceType = BuildType(symbol.ExplicitInterfaceImplementations.Single().ContainingType);
if (interfaceType != null)
{
name = new RQExplicitInterfaceMemberName(
interfaceType,
(RQOrdinaryMethodPropertyOrEventName)name);
}
}
var containingType = BuildUnconstructedNamedType(symbol.ContainingType);
if (containingType == null)
{
return null;
}
var parameterList = BuildParameterList(symbol.Parameters);
if (parameterList == null)
{
return null;
}
return new RQProperty(containingType, name, typeParameterCount: 0, parameters: parameterList);
}
private static IList<RQParameter>? BuildParameterList(ImmutableArray<IParameterSymbol> parameters)
{
var parameterList = new List<RQParameter>();
foreach (var parameter in parameters)
{
var parameterType = BuildType(parameter.Type);
if (parameterType == null)
{
return null;
}
if (parameter.RefKind == RefKind.Out)
{
parameterList.Add(new RQOutParameter(parameterType));
}
else if (parameter.RefKind == RefKind.Ref)
{
parameterList.Add(new RQRefParameter(parameterType));
}
else
{
parameterList.Add(new RQNormalParameter(parameterType));
}
}
return parameterList;
}
private static RQEvent? BuildEvent(IEventSymbol symbol)
{
var containingType = BuildUnconstructedNamedType(symbol.ContainingType);
if (containingType == null)
{
return null;
}
RQMethodPropertyOrEventName name = RQOrdinaryMethodPropertyOrEventName.CreateOrdinaryEventName(symbol.Name);
if (symbol.ExplicitInterfaceImplementations.Any())
{
if (symbol.ExplicitInterfaceImplementations.Length > 1)
{
return null;
}
var interfaceType = BuildType(symbol.ExplicitInterfaceImplementations.Single().ContainingType);
if (interfaceType != null)
{
name = new RQExplicitInterfaceMemberName(interfaceType, (RQOrdinaryMethodPropertyOrEventName)name);
}
}
return new RQEvent(containingType, name);
}
private static RQMethod? BuildMethod(IMethodSymbol symbol)
{
if (symbol.MethodKind is MethodKind.UserDefinedOperator or
MethodKind.BuiltinOperator or
MethodKind.EventAdd or
MethodKind.EventRemove or
MethodKind.PropertySet or
MethodKind.PropertyGet)
{
return null;
}
RQMethodPropertyOrEventName name;
if (symbol.MethodKind == MethodKind.Constructor)
{
name = RQOrdinaryMethodPropertyOrEventName.CreateConstructorName();
}
else if (symbol.MethodKind == MethodKind.Destructor)
{
name = RQOrdinaryMethodPropertyOrEventName.CreateDestructorName();
}
else
{
name = RQOrdinaryMethodPropertyOrEventName.CreateOrdinaryMethodName(symbol.Name);
}
if (symbol.ExplicitInterfaceImplementations.Any())
{
if (symbol.ExplicitInterfaceImplementations.Length > 1)
{
return null;
}
var interfaceType = BuildType(symbol.ExplicitInterfaceImplementations.Single().ContainingType);
if (interfaceType != null)
{
name = new RQExplicitInterfaceMemberName(interfaceType, (RQOrdinaryMethodPropertyOrEventName)name);
}
}
var containingType = BuildUnconstructedNamedType(symbol.ContainingType);
if (containingType == null)
{
return null;
}
var typeParamCount = symbol.TypeParameters.Length;
var parameterList = BuildParameterList(symbol.Parameters);
if (parameterList == null)
{
return null;
}
return new RQMethod(containingType, name, typeParamCount, parameterList);
}
private static RQType? BuildType(ITypeSymbol symbol)
{
if (symbol.IsAnonymousType)
{
return null;
}
if (symbol.SpecialType == SpecialType.System_Void)
{
return RQVoidType.Singleton;
}
else if (symbol is IPointerTypeSymbol pointerType)
{
var pointedAtType = BuildType(pointerType.PointedAtType);
if (pointedAtType == null)
{
return null;
}
return new RQPointerType(pointedAtType);
}
else if (symbol is IArrayTypeSymbol arrayType)
{
var elementType = BuildType(arrayType.ElementType);
if (elementType == null)
{
return null;
}
return new RQArrayType(arrayType.Rank, elementType);
}
else if (symbol.TypeKind == TypeKind.TypeParameter)
{
return new RQTypeVariableType(symbol.Name);
}
else if (symbol.TypeKind == TypeKind.Unknown)
{
return new RQErrorType(symbol.Name);
}
else if (symbol.TypeKind == TypeKind.Dynamic)
{
// NOTE: Because RQNames were defined as an interchange format before C# had "dynamic", and we didn't want
// all consumers to have to update their logic to crack the attributes about whether something is object or
// not, we just erase dynamic to object here.
return RQType.ObjectType;
}
else if (symbol is INamedTypeSymbol namedTypeSymbol)
{
var definingType = namedTypeSymbol.ConstructedFrom ?? namedTypeSymbol;
var typeChain = new List<INamedTypeSymbol>();
var type = namedTypeSymbol;
typeChain.Add(namedTypeSymbol);
while (type.ContainingType != null)
{
type = type.ContainingType;
typeChain.Add(type);
}
typeChain.Reverse();
var typeArgumentList = new List<RQType>();
foreach (var entry in typeChain)
{
foreach (var typeArgument in entry.TypeArguments)
{
var rqType = BuildType(typeArgument);
if (rqType == null)
{
return null;
}
typeArgumentList.Add(rqType);
}
}
var containingType = BuildUnconstructedNamedType(definingType);
if (containingType == null)
{
return null;
}
return new RQConstructedType(containingType, typeArgumentList);
}
else
{
return null;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Features.RQName.Nodes;
namespace Microsoft.CodeAnalysis.Features.RQName
{
internal static class RQNodeBuilder
{
/// <summary>
/// Builds the RQName for a given symbol.
/// </summary>
/// <returns>The node if it could be created, otherwise null</returns>
public static RQNode? Build(ISymbol symbol)
=> symbol switch
{
INamespaceSymbol namespaceSymbol => BuildNamespace(namespaceSymbol),
INamedTypeSymbol namedTypeSymbol => BuildUnconstructedNamedType(namedTypeSymbol),
IMethodSymbol methodSymbol => BuildMethod(methodSymbol),
IFieldSymbol fieldSymbol => BuildField(fieldSymbol),
IEventSymbol eventSymbol => BuildEvent(eventSymbol),
IPropertySymbol propertySymbol => BuildProperty(propertySymbol),
_ => null,
};
private static RQNamespace BuildNamespace(INamespaceSymbol @namespace)
=> new(RQNodeBuilder.GetNameParts(@namespace));
private static IList<string> GetNameParts(INamespaceSymbol @namespace)
{
var parts = new List<string>();
if (@namespace == null)
{
return parts;
}
while ([email protected])
{
parts.Add(@namespace.Name);
@namespace = @namespace.ContainingNamespace;
}
parts.Reverse();
return parts;
}
private static RQUnconstructedType? BuildUnconstructedNamedType(INamedTypeSymbol type)
{
// Anything that is a valid RQUnconstructed types is ALWAYS safe for public APIs
if (type == null)
{
return null;
}
// Anonymous types are unsupported
if (type.IsAnonymousType)
{
return null;
}
// the following types are supported for BuildType() used in signatures, but are not supported
// for UnconstructedTypes
if (type != type.ConstructedFrom || type.SpecialType == SpecialType.System_Void)
{
return null;
}
// make an RQUnconstructedType
var namespaceNames = RQNodeBuilder.GetNameParts(@type.ContainingNamespace);
var typeInfos = new List<RQUnconstructedTypeInfo>();
for (var currentType = type; currentType != null; currentType = currentType.ContainingType)
{
typeInfos.Insert(0, new RQUnconstructedTypeInfo(currentType.Name, currentType.TypeParameters.Length));
}
return new RQUnconstructedType(namespaceNames, typeInfos);
}
private static RQMember? BuildField(IFieldSymbol symbol)
{
var containingType = BuildUnconstructedNamedType(symbol.ContainingType);
if (containingType == null)
{
return null;
}
return new RQMemberVariable(containingType, symbol.Name);
}
private static RQProperty? BuildProperty(IPropertySymbol symbol)
{
RQMethodPropertyOrEventName name = symbol.IsIndexer ?
RQOrdinaryMethodPropertyOrEventName.CreateOrdinaryIndexerName() :
RQOrdinaryMethodPropertyOrEventName.CreateOrdinaryPropertyName(symbol.Name);
if (symbol.ExplicitInterfaceImplementations.Any())
{
if (symbol.ExplicitInterfaceImplementations.Length > 1)
{
return null;
}
var interfaceType = BuildType(symbol.ExplicitInterfaceImplementations.Single().ContainingType);
if (interfaceType != null)
{
name = new RQExplicitInterfaceMemberName(
interfaceType,
(RQOrdinaryMethodPropertyOrEventName)name);
}
}
var containingType = BuildUnconstructedNamedType(symbol.ContainingType);
if (containingType == null)
{
return null;
}
var parameterList = BuildParameterList(symbol.Parameters);
if (parameterList == null)
{
return null;
}
return new RQProperty(containingType, name, typeParameterCount: 0, parameters: parameterList);
}
private static IList<RQParameter>? BuildParameterList(ImmutableArray<IParameterSymbol> parameters)
{
var parameterList = new List<RQParameter>();
foreach (var parameter in parameters)
{
var parameterType = BuildType(parameter.Type);
if (parameterType == null)
{
return null;
}
if (parameter.RefKind == RefKind.Out)
{
parameterList.Add(new RQOutParameter(parameterType));
}
else if (parameter.RefKind == RefKind.Ref)
{
parameterList.Add(new RQRefParameter(parameterType));
}
else
{
parameterList.Add(new RQNormalParameter(parameterType));
}
}
return parameterList;
}
private static RQEvent? BuildEvent(IEventSymbol symbol)
{
var containingType = BuildUnconstructedNamedType(symbol.ContainingType);
if (containingType == null)
{
return null;
}
RQMethodPropertyOrEventName name = RQOrdinaryMethodPropertyOrEventName.CreateOrdinaryEventName(symbol.Name);
if (symbol.ExplicitInterfaceImplementations.Any())
{
if (symbol.ExplicitInterfaceImplementations.Length > 1)
{
return null;
}
var interfaceType = BuildType(symbol.ExplicitInterfaceImplementations.Single().ContainingType);
if (interfaceType != null)
{
name = new RQExplicitInterfaceMemberName(interfaceType, (RQOrdinaryMethodPropertyOrEventName)name);
}
}
return new RQEvent(containingType, name);
}
private static RQMethod? BuildMethod(IMethodSymbol symbol)
{
if (symbol.MethodKind is MethodKind.UserDefinedOperator or
MethodKind.BuiltinOperator or
MethodKind.EventAdd or
MethodKind.EventRemove or
MethodKind.PropertySet or
MethodKind.PropertyGet)
{
return null;
}
RQMethodPropertyOrEventName name;
if (symbol.MethodKind == MethodKind.Constructor)
{
name = RQOrdinaryMethodPropertyOrEventName.CreateConstructorName();
}
else if (symbol.MethodKind == MethodKind.Destructor)
{
name = RQOrdinaryMethodPropertyOrEventName.CreateDestructorName();
}
else
{
name = RQOrdinaryMethodPropertyOrEventName.CreateOrdinaryMethodName(symbol.Name);
}
if (symbol.ExplicitInterfaceImplementations.Any())
{
if (symbol.ExplicitInterfaceImplementations.Length > 1)
{
return null;
}
var interfaceType = BuildType(symbol.ExplicitInterfaceImplementations.Single().ContainingType);
if (interfaceType != null)
{
name = new RQExplicitInterfaceMemberName(interfaceType, (RQOrdinaryMethodPropertyOrEventName)name);
}
}
var containingType = BuildUnconstructedNamedType(symbol.ContainingType);
if (containingType == null)
{
return null;
}
var typeParamCount = symbol.TypeParameters.Length;
var parameterList = BuildParameterList(symbol.Parameters);
if (parameterList == null)
{
return null;
}
return new RQMethod(containingType, name, typeParamCount, parameterList);
}
private static RQType? BuildType(ITypeSymbol symbol)
{
if (symbol.IsAnonymousType)
{
return null;
}
if (symbol.SpecialType == SpecialType.System_Void)
{
return RQVoidType.Singleton;
}
else if (symbol is IPointerTypeSymbol pointerType)
{
var pointedAtType = BuildType(pointerType.PointedAtType);
if (pointedAtType == null)
{
return null;
}
return new RQPointerType(pointedAtType);
}
else if (symbol is IArrayTypeSymbol arrayType)
{
var elementType = BuildType(arrayType.ElementType);
if (elementType == null)
{
return null;
}
return new RQArrayType(arrayType.Rank, elementType);
}
else if (symbol.TypeKind == TypeKind.TypeParameter)
{
return new RQTypeVariableType(symbol.Name);
}
else if (symbol.TypeKind == TypeKind.Unknown)
{
return new RQErrorType(symbol.Name);
}
else if (symbol.TypeKind == TypeKind.Dynamic)
{
// NOTE: Because RQNames were defined as an interchange format before C# had "dynamic", and we didn't want
// all consumers to have to update their logic to crack the attributes about whether something is object or
// not, we just erase dynamic to object here.
return RQType.ObjectType;
}
else if (symbol is INamedTypeSymbol namedTypeSymbol)
{
var definingType = namedTypeSymbol.ConstructedFrom ?? namedTypeSymbol;
var typeChain = new List<INamedTypeSymbol>();
var type = namedTypeSymbol;
typeChain.Add(namedTypeSymbol);
while (type.ContainingType != null)
{
type = type.ContainingType;
typeChain.Add(type);
}
typeChain.Reverse();
var typeArgumentList = new List<RQType>();
foreach (var entry in typeChain)
{
foreach (var typeArgument in entry.TypeArguments)
{
var rqType = BuildType(typeArgument);
if (rqType == null)
{
return null;
}
typeArgumentList.Add(rqType);
}
}
var containingType = BuildUnconstructedNamedType(definingType);
if (containingType == null)
{
return null;
}
return new RQConstructedType(containingType, typeArgumentList);
}
else
{
return null;
}
}
}
}
| -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/VisualStudio/Xaml/Impl/Telemetry/IXamlLanguageServerFeedbackService.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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;
namespace Microsoft.VisualStudio.LanguageServices.Xaml.Telemetry
{
/// <summary>
/// Service that collects data for Telemetry in XamlLanguageServer
/// </summary>
internal interface IXamlLanguageServerFeedbackService
{
/// <summary>
/// Create a RequestScope of a request of given documentId
/// </summary>
IRequestScope CreateRequestScope(DocumentId? documentId, string methodName);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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;
namespace Microsoft.VisualStudio.LanguageServices.Xaml.Telemetry
{
/// <summary>
/// Service that collects data for Telemetry in XamlLanguageServer
/// </summary>
internal interface IXamlLanguageServerFeedbackService
{
/// <summary>
/// Create a RequestScope of a request of given documentId
/// </summary>
IRequestScope CreateRequestScope(DocumentId? documentId, string methodName);
}
}
| -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Workspaces/VisualBasic/Portable/xlf/VBWorkspaceResources.pl.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="pl" original="../VBWorkspaceResources.resx">
<body>
<trans-unit id="Namespace_can_not_be_added_in_this_destination">
<source>Namespace can not be added in this destination.</source>
<target state="translated">Do tego miejsca docelowego nie można dodać przestrzeni nazw.</target>
<note />
</trans-unit>
<trans-unit id="Only_attributes_expressions_or_statements_can_be_made_explicit">
<source>Only attributes, expressions or statements can be made explicit</source>
<target state="translated">Jako jawne można ustawić tylko atrybuty, wyrażenia lub instrukcje</target>
<note />
</trans-unit>
<trans-unit id="Remove_and_Sort_Imports">
<source>R&emove and Sort Imports</source>
<target state="translated">Usuń &i sortuj importy</target>
<note />
</trans-unit>
<trans-unit id="Sort_Imports">
<source>&Sort Imports</source>
<target state="translated">&Sortuj importy</target>
<note />
</trans-unit>
<trans-unit id="event_">
<source><event></source>
<target state="translated"><zdarzenie></target>
<note />
</trans-unit>
<trans-unit id="handler">
<source><handler></source>
<target state="translated"><proceduraObsługi></target>
<note />
</trans-unit>
<trans-unit id="The_expression_to_be_evaluated_and_converted">
<source>The expression to be evaluated and converted.</source>
<target state="translated">Wyrażenie, które ma zostać obliczone i przekonwertowane.</target>
<note />
</trans-unit>
<trans-unit id="The_name_of_the_data_type_to_which_the_value_of_expression_will_be_converted">
<source>The name of the data type to which the value of expression will be converted.</source>
<target state="translated">Nazwa typu danych, na który zostanie skonwertowana wartość wyrażenia.</target>
<note />
</trans-unit>
<trans-unit id="expression">
<source><expression></source>
<target state="translated"><wyrażenie></target>
<note />
</trans-unit>
<trans-unit id="typeName">
<source><typeName></source>
<target state="translated"><typeName></target>
<note />
</trans-unit>
<trans-unit id="Associates_an_event_with_an_event_handler_delegate_or_lambda_expression_at_run_time">
<source>Associates an event with an event handler, delegate or lambda expression at run time.</source>
<target state="translated">Kojarzy zdarzenie z procedurą obsługi zdarzeń, delegatem lub wyrażeniem lambda w czasie wykonywania.</target>
<note />
</trans-unit>
<trans-unit id="The_event_to_associate_an_event_handler_delegate_or_lambda_expression_with">
<source>The event to associate an event handler, delegate or lambda expression with.</source>
<target state="translated">Zdarzenie, z którym ma zostać skojarzona procedura obsługi zdarzeń, delegat lub wyrażenie lambda.</target>
<note />
</trans-unit>
<trans-unit id="The_event_handler_to_associate_with_the_event_This_may_take_the_form_of_AddressOf_eventHandler_delegate_lambdaExpression">
<source>The event handler to associate with the event. This may take the form of { AddressOf <eventHandler> | <delegate> | <lambdaExpression> }.</source>
<target state="translated">Procedura obsługi zdarzeń, która ma zostać skojarzona ze zdarzeniem. Może wyglądać następująco { AddressOf <proceduraObsługiZdarzeń> | <delegat> | <wyrażenieLambda> }.</target>
<note />
</trans-unit>
<trans-unit id="If_expression_evaluates_to_a_reference_or_Nullable_value_that_is_not_Nothing_the_function_returns_that_value_Otherwise_it_calculates_and_returns_expressionIfNothing">
<source>If <expression> evaluates to a reference or Nullable value that is not Nothing, the function returns that value. Otherwise, it calculates and returns <expressionIfNothing>.</source>
<target state="translated">Jeśli wynikiem obliczenia <wyrażenia> jest odwołanie lub wartość dopuszczająca wartość null inną niż Nothing, funkcja zwraca tę wartość. W przeciwnym razie oblicza ona i zwraca <wyrażenieObliczoneWPrzypadkuWartościNothing>.</target>
<note />
</trans-unit>
<trans-unit id="Returned_if_it_evaluates_to_a_reference_or_nullable_type_that_is_not_Nothing">
<source>Returned if it evaluates to a reference or nullable type that is not Nothing.</source>
<target state="translated">Ten element jest zwracany, jeśli wynikiem jego obliczenia jest odwołanie lub typ dopuszczający wartość null inny niż Nothing.</target>
<note />
</trans-unit>
<trans-unit id="Evaluated_and_returned_if_expression_evaluates_to_Nothing">
<source>Evaluated and returned if <expression> evaluates to Nothing.</source>
<target state="translated">Ten element jest obliczany i zwracany, jeśli wynikiem obliczenia <wyrażenia> jest Nothing.</target>
<note />
</trans-unit>
<trans-unit id="expressionIfNothing">
<source><expressionIfNothing></source>
<target state="translated"><expressionIfNothing></target>
<note />
</trans-unit>
<trans-unit id="Returns_the_result_of_explicitly_converting_an_expression_to_a_specified_data_type">
<source>Returns the result of explicitly converting an expression to a specified data type.</source>
<target state="translated">Zwraca wynik jawnej konwersji wyrażenia na określony typ danych.</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_type_conversion_operation_similar_to_CType_The_difference_is_that_CType_succeeds_as_long_as_there_is_a_valid_conversion_whereas_DirectCast_requires_that_one_type_inherit_from_or_implement_the_other_type">
<source>Introduces a type conversion operation similar to CType. The difference is that CType succeeds as long as there is a valid conversion, whereas DirectCast requires that one type inherit from or implement the other type.</source>
<target state="translated">Wprowadza operację konwersji typu podobną do CType. Różnica polega na tym, że do pomyślnego działania funkcji CType wymagana jest prawidłowa konwersja, a funkcja DirectCast wymaga, aby jeden typ dziedziczył lub implementował z innego typu.</target>
<note />
</trans-unit>
<trans-unit id="The_type_name_to_return_a_System_Type_object_for">
<source>The type name to return a System.Type object for.</source>
<target state="translated">Nazwa typu, dla którego ma zostać zwrócony obiekt System.Type.</target>
<note />
</trans-unit>
<trans-unit id="Returns_a_System_Type_object_for_the_specified_type_name">
<source>Returns a System.Type object for the specified type name.</source>
<target state="translated">Zwraca obiekt System.Type dla określonej nazwy typu.</target>
<note />
</trans-unit>
<trans-unit id="The_XML_namespace_prefix_to_return_a_System_Xml_Linq_XNamespace_object_for_If_this_is_omitted_the_object_for_the_default_XML_namespace_is_returned">
<source>The XML namespace prefix to return a System.Xml.Linq.XNamespace object for. If this is omitted, the object for the default XML namespace is returned.</source>
<target state="translated">Prefiks przestrzeni nazw XML, dla której ma zostać zwrócony obiekt System.Xml.Linq.XNamespace. W przypadku jego pominięcia zostaje zwrócony obiekt dla domyślnej przestrzeni nazw XML.</target>
<note />
</trans-unit>
<trans-unit id="xmlNamespacePrefix">
<source><xmlNamespacePrefix></source>
<target state="translated"><prefiksPrzestrzeniNazwXml></target>
<note />
</trans-unit>
<trans-unit id="Returns_the_System_Xml_Linq_XNamespace_object_corresponding_to_the_specified_XML_namespace_prefix">
<source>Returns the System.Xml.Linq.XNamespace object corresponding to the specified XML namespace prefix.</source>
<target state="translated">Zwraca obiekt System.Xml.Linq.XNamespace odpowiadający określonemu prefiksowi przestrzeni nazw XML.</target>
<note />
</trans-unit>
<trans-unit id="Replaces_a_specified_number_of_characters_in_a_String_variable_with_characters_from_another_string">
<source>Replaces a specified number of characters in a String variable with characters from another string.</source>
<target state="translated">Zastępuje określoną liczbę znaków w zmiennej ciągu znakami z innego ciągu.</target>
<note />
</trans-unit>
<trans-unit id="The_name_of_the_string_variable_to_modify">
<source>The name of the string variable to modify.</source>
<target state="translated">Nazwa zmiennej ciągu, która ma zostać zmodyfikowana.</target>
<note />
</trans-unit>
<trans-unit id="The_one_based_character_position_in_the_string_where_the_replacement_of_text_begins">
<source>The one-based character position in the string where the replacement of text begins.</source>
<target state="translated">Pozycja znaku (pierwszym indeksem jest jeden) w ciągu, w którym rozpoczyna się zastępowanie tekstu.</target>
<note />
</trans-unit>
<trans-unit id="The_number_of_characters_to_replace_If_omitted_the_length_of_stringExpression_is_used">
<source>The number of characters to replace. If omitted, the length of <stringExpression> is used.</source>
<target state="translated">Liczba znaków do zastąpienia. W przypadku pominięcia zostanie użyta długość <wyrażeniaCiągu>.</target>
<note />
</trans-unit>
<trans-unit id="stringName">
<source><stringName></source>
<target state="translated"><stringName></target>
<note />
</trans-unit>
<trans-unit id="startIndex">
<source><startIndex></source>
<target state="translated"><startIndex></target>
<note />
</trans-unit>
<trans-unit id="length">
<source><length></source>
<target state="translated"><długość></target>
<note />
</trans-unit>
<trans-unit id="stringExpression">
<source><stringExpression></source>
<target state="translated"><wyrażenieCiągu></target>
<note />
</trans-unit>
<trans-unit id="Converts_an_expression_to_the_0_data_type">
<source>Converts an expression to the {0} data type.</source>
<target state="translated">Konwertuje wyrażenie na typ danych {0}.</target>
<note />
</trans-unit>
<trans-unit id="Removes_the_association_between_an_event_and_an_event_handler_or_delegate_at_run_time">
<source>Removes the association between an event and an event handler or delegate at run time.</source>
<target state="translated">Usuwa skojarzenie między zdarzeniem i procedurą obsługi zdarzeń lub delegatem w czasie wykonywania.</target>
<note />
</trans-unit>
<trans-unit id="The_event_to_disassociate_an_event_handler_or_delegate_from">
<source>The event to disassociate an event handler or delegate from.</source>
<target state="translated">Zdarzenie, którego skojarzenie z procedurą obsługi zdarzeń lub delegatem ma zostać usunięte.</target>
<note />
</trans-unit>
<trans-unit id="The_event_handler_to_disassociate_from_the_event_This_may_take_the_form_of_AddressOf_eventHandler_delegate">
<source>The event handler to disassociate from the event. This may take the form of { AddressOf <eventHandler> | <delegate> }.</source>
<target state="translated">Procedura obsługi zdarzeń, której skojarzenie ze zdarzeniem ma zostać usunięte. Może wyglądać następująco { AddressOf <proceduraObsługiZdarzeń> | <delegat> }.</target>
<note />
</trans-unit>
<trans-unit id="If_condition_returns_True_the_function_calculates_and_returns_expressionIfTrue_Otherwise_it_returns_expressionIfFalse">
<source>If <condition> returns True, the function calculates and returns <expressionIfTrue>. Otherwise, it returns <expressionIfFalse>.</source>
<target state="translated">Jeśli w wyniku obliczenia <condition> zostanie zwrócona wartość True, funkcja obliczy i zwróci <expressionIfTrue>. W przeciwny razie zwróci <expressionIfFalse>.</target>
<note />
</trans-unit>
<trans-unit id="The_expression_to_evaluate">
<source>The expression to evaluate.</source>
<target state="translated">Wyrażenie, które ma zostać obliczone.</target>
<note />
</trans-unit>
<trans-unit id="Evaluated_and_returned_if_condition_evaluates_to_True">
<source>Evaluated and returned if <condition> evaluates to True.</source>
<target state="translated">Ten element jest obliczany i zwracany, jeśli wynikiem obliczenia <warunku> jest wartość True.</target>
<note />
</trans-unit>
<trans-unit id="Evaluated_and_returned_if_condition_evaluates_to_False">
<source>Evaluated and returned if <condition> evaluates to False.</source>
<target state="translated">Ten element jest obliczany i zwracany, jeśli wynikiem obliczenia <warunku> jest wartość False.</target>
<note />
</trans-unit>
<trans-unit id="condition">
<source><condition></source>
<target state="translated"><warunek></target>
<note />
</trans-unit>
<trans-unit id="expressionIfTrue">
<source><expressionIfTrue></source>
<target state="translated"><expressionIfTrue></target>
<note />
</trans-unit>
<trans-unit id="expressionIfFalse">
<source><expressionIfFalse></source>
<target state="translated"><expressionIfFalse></target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_type_conversion_operation_that_does_not_throw_an_exception_If_an_attempted_conversion_fails_TryCast_returns_Nothing_which_your_program_can_test_for">
<source>Introduces a type conversion operation that does not throw an exception. If an attempted conversion fails, TryCast returns Nothing, which your program can test for.</source>
<target state="translated">Wprowadza operację konwersji typu, która nie zgłasza wyjątku. Jeśli próba konwersji nie powiedzie się, element TryCast zwróci wartość Nothing, którą Twój program może użyć do testów.</target>
<note />
</trans-unit>
<trans-unit id="Node_does_not_descend_from_root">
<source>Node does not descend from root.</source>
<target state="translated">Węzeł nie jest elementem podrzędnym elementu głównego.</target>
<note />
</trans-unit>
<trans-unit id="Node_not_in_parent_s_child_list">
<source>Node not in parent's child list</source>
<target state="translated">Węzeł nie znajduje się na liście elementów podrzędnych elementu nadrzędnego</target>
<note />
</trans-unit>
<trans-unit id="Trivia_is_not_associated_with_token">
<source>Trivia is not associated with token</source>
<target state="translated">Elementy towarzyszące składni nie są skojarzone z tokenem</target>
<note />
</trans-unit>
<trans-unit id="typeOrMember">
<source><typeOrMember></source>
<target state="translated"><typeOrMember></target>
<note />
</trans-unit>
<trans-unit id="The_type_of_member_to_return_the_name_of">
<source>The type of member to return the name of.</source>
<target state="translated">Typ składowej, której nazwa ma zostać zwrócona.</target>
<note />
</trans-unit>
<trans-unit id="Produces_a_string_for_the_name_of_the_specified_type_or_member">
<source>Produces a string for the name of the specified type or member.</source>
<target state="translated">Tworzy ciąg nazwy określonego typu lub składowej.</target>
<note />
</trans-unit>
<trans-unit id="result">
<source><result></source>
<target state="translated"><wynik></target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="pl" original="../VBWorkspaceResources.resx">
<body>
<trans-unit id="Namespace_can_not_be_added_in_this_destination">
<source>Namespace can not be added in this destination.</source>
<target state="translated">Do tego miejsca docelowego nie można dodać przestrzeni nazw.</target>
<note />
</trans-unit>
<trans-unit id="Only_attributes_expressions_or_statements_can_be_made_explicit">
<source>Only attributes, expressions or statements can be made explicit</source>
<target state="translated">Jako jawne można ustawić tylko atrybuty, wyrażenia lub instrukcje</target>
<note />
</trans-unit>
<trans-unit id="Remove_and_Sort_Imports">
<source>R&emove and Sort Imports</source>
<target state="translated">Usuń &i sortuj importy</target>
<note />
</trans-unit>
<trans-unit id="Sort_Imports">
<source>&Sort Imports</source>
<target state="translated">&Sortuj importy</target>
<note />
</trans-unit>
<trans-unit id="event_">
<source><event></source>
<target state="translated"><zdarzenie></target>
<note />
</trans-unit>
<trans-unit id="handler">
<source><handler></source>
<target state="translated"><proceduraObsługi></target>
<note />
</trans-unit>
<trans-unit id="The_expression_to_be_evaluated_and_converted">
<source>The expression to be evaluated and converted.</source>
<target state="translated">Wyrażenie, które ma zostać obliczone i przekonwertowane.</target>
<note />
</trans-unit>
<trans-unit id="The_name_of_the_data_type_to_which_the_value_of_expression_will_be_converted">
<source>The name of the data type to which the value of expression will be converted.</source>
<target state="translated">Nazwa typu danych, na który zostanie skonwertowana wartość wyrażenia.</target>
<note />
</trans-unit>
<trans-unit id="expression">
<source><expression></source>
<target state="translated"><wyrażenie></target>
<note />
</trans-unit>
<trans-unit id="typeName">
<source><typeName></source>
<target state="translated"><typeName></target>
<note />
</trans-unit>
<trans-unit id="Associates_an_event_with_an_event_handler_delegate_or_lambda_expression_at_run_time">
<source>Associates an event with an event handler, delegate or lambda expression at run time.</source>
<target state="translated">Kojarzy zdarzenie z procedurą obsługi zdarzeń, delegatem lub wyrażeniem lambda w czasie wykonywania.</target>
<note />
</trans-unit>
<trans-unit id="The_event_to_associate_an_event_handler_delegate_or_lambda_expression_with">
<source>The event to associate an event handler, delegate or lambda expression with.</source>
<target state="translated">Zdarzenie, z którym ma zostać skojarzona procedura obsługi zdarzeń, delegat lub wyrażenie lambda.</target>
<note />
</trans-unit>
<trans-unit id="The_event_handler_to_associate_with_the_event_This_may_take_the_form_of_AddressOf_eventHandler_delegate_lambdaExpression">
<source>The event handler to associate with the event. This may take the form of { AddressOf <eventHandler> | <delegate> | <lambdaExpression> }.</source>
<target state="translated">Procedura obsługi zdarzeń, która ma zostać skojarzona ze zdarzeniem. Może wyglądać następująco { AddressOf <proceduraObsługiZdarzeń> | <delegat> | <wyrażenieLambda> }.</target>
<note />
</trans-unit>
<trans-unit id="If_expression_evaluates_to_a_reference_or_Nullable_value_that_is_not_Nothing_the_function_returns_that_value_Otherwise_it_calculates_and_returns_expressionIfNothing">
<source>If <expression> evaluates to a reference or Nullable value that is not Nothing, the function returns that value. Otherwise, it calculates and returns <expressionIfNothing>.</source>
<target state="translated">Jeśli wynikiem obliczenia <wyrażenia> jest odwołanie lub wartość dopuszczająca wartość null inną niż Nothing, funkcja zwraca tę wartość. W przeciwnym razie oblicza ona i zwraca <wyrażenieObliczoneWPrzypadkuWartościNothing>.</target>
<note />
</trans-unit>
<trans-unit id="Returned_if_it_evaluates_to_a_reference_or_nullable_type_that_is_not_Nothing">
<source>Returned if it evaluates to a reference or nullable type that is not Nothing.</source>
<target state="translated">Ten element jest zwracany, jeśli wynikiem jego obliczenia jest odwołanie lub typ dopuszczający wartość null inny niż Nothing.</target>
<note />
</trans-unit>
<trans-unit id="Evaluated_and_returned_if_expression_evaluates_to_Nothing">
<source>Evaluated and returned if <expression> evaluates to Nothing.</source>
<target state="translated">Ten element jest obliczany i zwracany, jeśli wynikiem obliczenia <wyrażenia> jest Nothing.</target>
<note />
</trans-unit>
<trans-unit id="expressionIfNothing">
<source><expressionIfNothing></source>
<target state="translated"><expressionIfNothing></target>
<note />
</trans-unit>
<trans-unit id="Returns_the_result_of_explicitly_converting_an_expression_to_a_specified_data_type">
<source>Returns the result of explicitly converting an expression to a specified data type.</source>
<target state="translated">Zwraca wynik jawnej konwersji wyrażenia na określony typ danych.</target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_type_conversion_operation_similar_to_CType_The_difference_is_that_CType_succeeds_as_long_as_there_is_a_valid_conversion_whereas_DirectCast_requires_that_one_type_inherit_from_or_implement_the_other_type">
<source>Introduces a type conversion operation similar to CType. The difference is that CType succeeds as long as there is a valid conversion, whereas DirectCast requires that one type inherit from or implement the other type.</source>
<target state="translated">Wprowadza operację konwersji typu podobną do CType. Różnica polega na tym, że do pomyślnego działania funkcji CType wymagana jest prawidłowa konwersja, a funkcja DirectCast wymaga, aby jeden typ dziedziczył lub implementował z innego typu.</target>
<note />
</trans-unit>
<trans-unit id="The_type_name_to_return_a_System_Type_object_for">
<source>The type name to return a System.Type object for.</source>
<target state="translated">Nazwa typu, dla którego ma zostać zwrócony obiekt System.Type.</target>
<note />
</trans-unit>
<trans-unit id="Returns_a_System_Type_object_for_the_specified_type_name">
<source>Returns a System.Type object for the specified type name.</source>
<target state="translated">Zwraca obiekt System.Type dla określonej nazwy typu.</target>
<note />
</trans-unit>
<trans-unit id="The_XML_namespace_prefix_to_return_a_System_Xml_Linq_XNamespace_object_for_If_this_is_omitted_the_object_for_the_default_XML_namespace_is_returned">
<source>The XML namespace prefix to return a System.Xml.Linq.XNamespace object for. If this is omitted, the object for the default XML namespace is returned.</source>
<target state="translated">Prefiks przestrzeni nazw XML, dla której ma zostać zwrócony obiekt System.Xml.Linq.XNamespace. W przypadku jego pominięcia zostaje zwrócony obiekt dla domyślnej przestrzeni nazw XML.</target>
<note />
</trans-unit>
<trans-unit id="xmlNamespacePrefix">
<source><xmlNamespacePrefix></source>
<target state="translated"><prefiksPrzestrzeniNazwXml></target>
<note />
</trans-unit>
<trans-unit id="Returns_the_System_Xml_Linq_XNamespace_object_corresponding_to_the_specified_XML_namespace_prefix">
<source>Returns the System.Xml.Linq.XNamespace object corresponding to the specified XML namespace prefix.</source>
<target state="translated">Zwraca obiekt System.Xml.Linq.XNamespace odpowiadający określonemu prefiksowi przestrzeni nazw XML.</target>
<note />
</trans-unit>
<trans-unit id="Replaces_a_specified_number_of_characters_in_a_String_variable_with_characters_from_another_string">
<source>Replaces a specified number of characters in a String variable with characters from another string.</source>
<target state="translated">Zastępuje określoną liczbę znaków w zmiennej ciągu znakami z innego ciągu.</target>
<note />
</trans-unit>
<trans-unit id="The_name_of_the_string_variable_to_modify">
<source>The name of the string variable to modify.</source>
<target state="translated">Nazwa zmiennej ciągu, która ma zostać zmodyfikowana.</target>
<note />
</trans-unit>
<trans-unit id="The_one_based_character_position_in_the_string_where_the_replacement_of_text_begins">
<source>The one-based character position in the string where the replacement of text begins.</source>
<target state="translated">Pozycja znaku (pierwszym indeksem jest jeden) w ciągu, w którym rozpoczyna się zastępowanie tekstu.</target>
<note />
</trans-unit>
<trans-unit id="The_number_of_characters_to_replace_If_omitted_the_length_of_stringExpression_is_used">
<source>The number of characters to replace. If omitted, the length of <stringExpression> is used.</source>
<target state="translated">Liczba znaków do zastąpienia. W przypadku pominięcia zostanie użyta długość <wyrażeniaCiągu>.</target>
<note />
</trans-unit>
<trans-unit id="stringName">
<source><stringName></source>
<target state="translated"><stringName></target>
<note />
</trans-unit>
<trans-unit id="startIndex">
<source><startIndex></source>
<target state="translated"><startIndex></target>
<note />
</trans-unit>
<trans-unit id="length">
<source><length></source>
<target state="translated"><długość></target>
<note />
</trans-unit>
<trans-unit id="stringExpression">
<source><stringExpression></source>
<target state="translated"><wyrażenieCiągu></target>
<note />
</trans-unit>
<trans-unit id="Converts_an_expression_to_the_0_data_type">
<source>Converts an expression to the {0} data type.</source>
<target state="translated">Konwertuje wyrażenie na typ danych {0}.</target>
<note />
</trans-unit>
<trans-unit id="Removes_the_association_between_an_event_and_an_event_handler_or_delegate_at_run_time">
<source>Removes the association between an event and an event handler or delegate at run time.</source>
<target state="translated">Usuwa skojarzenie między zdarzeniem i procedurą obsługi zdarzeń lub delegatem w czasie wykonywania.</target>
<note />
</trans-unit>
<trans-unit id="The_event_to_disassociate_an_event_handler_or_delegate_from">
<source>The event to disassociate an event handler or delegate from.</source>
<target state="translated">Zdarzenie, którego skojarzenie z procedurą obsługi zdarzeń lub delegatem ma zostać usunięte.</target>
<note />
</trans-unit>
<trans-unit id="The_event_handler_to_disassociate_from_the_event_This_may_take_the_form_of_AddressOf_eventHandler_delegate">
<source>The event handler to disassociate from the event. This may take the form of { AddressOf <eventHandler> | <delegate> }.</source>
<target state="translated">Procedura obsługi zdarzeń, której skojarzenie ze zdarzeniem ma zostać usunięte. Może wyglądać następująco { AddressOf <proceduraObsługiZdarzeń> | <delegat> }.</target>
<note />
</trans-unit>
<trans-unit id="If_condition_returns_True_the_function_calculates_and_returns_expressionIfTrue_Otherwise_it_returns_expressionIfFalse">
<source>If <condition> returns True, the function calculates and returns <expressionIfTrue>. Otherwise, it returns <expressionIfFalse>.</source>
<target state="translated">Jeśli w wyniku obliczenia <condition> zostanie zwrócona wartość True, funkcja obliczy i zwróci <expressionIfTrue>. W przeciwny razie zwróci <expressionIfFalse>.</target>
<note />
</trans-unit>
<trans-unit id="The_expression_to_evaluate">
<source>The expression to evaluate.</source>
<target state="translated">Wyrażenie, które ma zostać obliczone.</target>
<note />
</trans-unit>
<trans-unit id="Evaluated_and_returned_if_condition_evaluates_to_True">
<source>Evaluated and returned if <condition> evaluates to True.</source>
<target state="translated">Ten element jest obliczany i zwracany, jeśli wynikiem obliczenia <warunku> jest wartość True.</target>
<note />
</trans-unit>
<trans-unit id="Evaluated_and_returned_if_condition_evaluates_to_False">
<source>Evaluated and returned if <condition> evaluates to False.</source>
<target state="translated">Ten element jest obliczany i zwracany, jeśli wynikiem obliczenia <warunku> jest wartość False.</target>
<note />
</trans-unit>
<trans-unit id="condition">
<source><condition></source>
<target state="translated"><warunek></target>
<note />
</trans-unit>
<trans-unit id="expressionIfTrue">
<source><expressionIfTrue></source>
<target state="translated"><expressionIfTrue></target>
<note />
</trans-unit>
<trans-unit id="expressionIfFalse">
<source><expressionIfFalse></source>
<target state="translated"><expressionIfFalse></target>
<note />
</trans-unit>
<trans-unit id="Introduces_a_type_conversion_operation_that_does_not_throw_an_exception_If_an_attempted_conversion_fails_TryCast_returns_Nothing_which_your_program_can_test_for">
<source>Introduces a type conversion operation that does not throw an exception. If an attempted conversion fails, TryCast returns Nothing, which your program can test for.</source>
<target state="translated">Wprowadza operację konwersji typu, która nie zgłasza wyjątku. Jeśli próba konwersji nie powiedzie się, element TryCast zwróci wartość Nothing, którą Twój program może użyć do testów.</target>
<note />
</trans-unit>
<trans-unit id="Node_does_not_descend_from_root">
<source>Node does not descend from root.</source>
<target state="translated">Węzeł nie jest elementem podrzędnym elementu głównego.</target>
<note />
</trans-unit>
<trans-unit id="Node_not_in_parent_s_child_list">
<source>Node not in parent's child list</source>
<target state="translated">Węzeł nie znajduje się na liście elementów podrzędnych elementu nadrzędnego</target>
<note />
</trans-unit>
<trans-unit id="Trivia_is_not_associated_with_token">
<source>Trivia is not associated with token</source>
<target state="translated">Elementy towarzyszące składni nie są skojarzone z tokenem</target>
<note />
</trans-unit>
<trans-unit id="typeOrMember">
<source><typeOrMember></source>
<target state="translated"><typeOrMember></target>
<note />
</trans-unit>
<trans-unit id="The_type_of_member_to_return_the_name_of">
<source>The type of member to return the name of.</source>
<target state="translated">Typ składowej, której nazwa ma zostać zwrócona.</target>
<note />
</trans-unit>
<trans-unit id="Produces_a_string_for_the_name_of_the_specified_type_or_member">
<source>Produces a string for the name of the specified type or member.</source>
<target state="translated">Tworzy ciąg nazwy określonego typu lub składowej.</target>
<note />
</trans-unit>
<trans-unit id="result">
<source><result></source>
<target state="translated"><wynik></target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/Features/Core/Portable/Structure/BlockStructureService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Structure
{
internal abstract class BlockStructureService : ILanguageService
{
/// <summary>
/// Gets the service corresponding to the specified document.
/// </summary>
public static BlockStructureService GetService(Document document)
=> document.GetLanguageService<BlockStructureService>();
/// <summary>
/// The language from <see cref="LanguageNames"/> this service corresponds to.
/// </summary>
public abstract string Language { get; }
public abstract Task<BlockStructure> GetBlockStructureAsync(Document document, CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Structure
{
internal abstract class BlockStructureService : ILanguageService
{
/// <summary>
/// Gets the service corresponding to the specified document.
/// </summary>
public static BlockStructureService GetService(Document document)
=> document.GetLanguageService<BlockStructureService>();
/// <summary>
/// The language from <see cref="LanguageNames"/> this service corresponds to.
/// </summary>
public abstract string Language { get; }
public abstract Task<BlockStructure> GetBlockStructureAsync(Document document, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 55,119 | Add imports that no longer automatically added | These resolve local build errors in main. | JoeRobich | 2021-07-26T16:43:28Z | 2021-07-26T19:24:46Z | fc4a667def0a2779a565766ccc91ccf0e9d6330d | 1453f20221fbd626b5195bf0c8653078e53f292e | Add imports that no longer automatically added. These resolve local build errors in main. | ./src/VisualStudio/Core/Def/Implementation/CallHierarchy/Finders/BaseMemberFinder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Shared.TestHooks;
namespace Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy.Finders
{
internal class BaseMemberFinder : AbstractCallFinder
{
private readonly string _text;
public BaseMemberFinder(ISymbol symbol, ProjectId projectId, IAsynchronousOperationListener asyncListener, CallHierarchyProvider provider)
: base(symbol, projectId, asyncListener, provider)
{
_text = string.Format(EditorFeaturesResources.Calls_To_Base_Member_0, symbol.ToDisplayString());
}
public override string DisplayName => _text;
protected override async Task<IEnumerable<SymbolCallerInfo>> GetCallersAsync(ISymbol symbol, Project project, IImmutableSet<Document> documents, CancellationToken cancellationToken)
{
var calls = await SymbolFinder.FindCallersAsync(symbol, project.Solution, documents, cancellationToken).ConfigureAwait(false);
return calls.Where(c => c.IsDirect);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Shared.TestHooks;
namespace Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy.Finders
{
internal class BaseMemberFinder : AbstractCallFinder
{
private readonly string _text;
public BaseMemberFinder(ISymbol symbol, ProjectId projectId, IAsynchronousOperationListener asyncListener, CallHierarchyProvider provider)
: base(symbol, projectId, asyncListener, provider)
{
_text = string.Format(EditorFeaturesResources.Calls_To_Base_Member_0, symbol.ToDisplayString());
}
public override string DisplayName => _text;
protected override async Task<IEnumerable<SymbolCallerInfo>> GetCallersAsync(ISymbol symbol, Project project, IImmutableSet<Document> documents, CancellationToken cancellationToken)
{
var calls = await SymbolFinder.FindCallersAsync(symbol, project.Solution, documents, cancellationToken).ConfigureAwait(false);
return calls.Where(c => c.IsDirect);
}
}
}
| -1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Compilers/CSharp/Portable/Emitter/EditAndContinue/EmitHelpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection.Metadata;
using System.Threading;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Emit
{
internal static class EmitHelpers
{
internal static EmitDifferenceResult EmitDifference(
CSharpCompilation compilation,
EmitBaseline baseline,
IEnumerable<SemanticEdit> edits,
Func<ISymbol, bool> isAddedSymbol,
Stream metadataStream,
Stream ilStream,
Stream pdbStream,
CompilationTestData? testData,
CancellationToken cancellationToken)
{
var diagnostics = DiagnosticBag.GetInstance();
var emitOptions = EmitOptions.Default.WithDebugInformationFormat(baseline.HasPortablePdb ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb);
var runtimeMDVersion = compilation.GetRuntimeMetadataVersion(emitOptions, diagnostics);
var serializationProperties = compilation.ConstructModuleSerializationProperties(emitOptions, runtimeMDVersion, baseline.ModuleVersionId);
var manifestResources = SpecializedCollections.EmptyEnumerable<ResourceDescription>();
var updatedMethods = ArrayBuilder<MethodDefinitionHandle>.GetInstance();
var updatedTypes = ArrayBuilder<TypeDefinitionHandle>.GetInstance();
PEDeltaAssemblyBuilder moduleBeingBuilt;
try
{
moduleBeingBuilt = new PEDeltaAssemblyBuilder(
compilation.SourceAssembly,
emitOptions: emitOptions,
outputKind: compilation.Options.OutputKind,
serializationProperties: serializationProperties,
manifestResources: manifestResources,
previousGeneration: baseline,
edits: edits,
isAddedSymbol: isAddedSymbol);
}
catch (NotSupportedException e)
{
// TODO: https://github.com/dotnet/roslyn/issues/9004
diagnostics.Add(ErrorCode.ERR_ModuleEmitFailure, NoLocation.Singleton, compilation.AssemblyName, e.Message);
return new EmitDifferenceResult(success: false, diagnostics: diagnostics.ToReadOnlyAndFree(), baseline: null, updatedMethods: updatedMethods.ToImmutableAndFree(), updatedTypes: updatedTypes.ToImmutableAndFree());
}
if (testData != null)
{
moduleBeingBuilt.SetMethodTestData(testData.Methods);
testData.Module = moduleBeingBuilt;
}
var definitionMap = moduleBeingBuilt.PreviousDefinitions;
var changes = moduleBeingBuilt.EncSymbolChanges;
Debug.Assert(changes != null);
EmitBaseline? newBaseline = null;
if (compilation.Compile(
moduleBeingBuilt,
emittingPdb: true,
diagnostics: diagnostics,
filterOpt: s => changes.RequiresCompilation(s.GetISymbol()),
cancellationToken: cancellationToken))
{
// Map the definitions from the previous compilation to the current compilation.
// This must be done after compiling above since synthesized definitions
// (generated when compiling method bodies) may be required.
var mappedBaseline = MapToCompilation(compilation, moduleBeingBuilt);
newBaseline = compilation.SerializeToDeltaStreams(
moduleBeingBuilt,
mappedBaseline,
definitionMap,
changes,
metadataStream,
ilStream,
pdbStream,
updatedMethods,
updatedTypes,
diagnostics,
testData?.SymWriterFactory,
emitOptions.PdbFilePath,
cancellationToken);
}
return new EmitDifferenceResult(
success: newBaseline != null,
diagnostics: diagnostics.ToReadOnlyAndFree(),
baseline: newBaseline,
updatedMethods: updatedMethods.ToImmutableAndFree(),
updatedTypes: updatedTypes.ToImmutableAndFree());
}
/// <summary>
/// Return a version of the baseline with all definitions mapped to this compilation.
/// Definitions from the initial generation, from metadata, are not mapped since
/// the initial generation is always included as metadata. That is, the symbols from
/// types, methods, ... in the TypesAdded, MethodsAdded, ... collections are replaced
/// by the corresponding symbols from the current compilation.
/// </summary>
private static EmitBaseline MapToCompilation(
CSharpCompilation compilation,
PEDeltaAssemblyBuilder moduleBeingBuilt)
{
var previousGeneration = moduleBeingBuilt.PreviousGeneration;
RoslynDebug.Assert(previousGeneration.Compilation != compilation);
if (previousGeneration.Ordinal == 0)
{
// Initial generation, nothing to map. (Since the initial generation
// is always loaded from metadata in the context of the current
// compilation, there's no separate mapping step.)
return previousGeneration;
}
RoslynDebug.AssertNotNull(previousGeneration.Compilation);
RoslynDebug.AssertNotNull(previousGeneration.PEModuleBuilder);
var currentSynthesizedMembers = moduleBeingBuilt.GetAllSynthesizedMembers();
// Mapping from previous compilation to the current.
var anonymousTypeMap = moduleBeingBuilt.GetAnonymousTypeMap();
var sourceAssembly = ((CSharpCompilation)previousGeneration.Compilation).SourceAssembly;
var sourceContext = new EmitContext((PEModuleBuilder)previousGeneration.PEModuleBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true);
var otherContext = new EmitContext(moduleBeingBuilt, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true);
var matcher = new CSharpSymbolMatcher(
anonymousTypeMap,
sourceAssembly,
sourceContext,
compilation.SourceAssembly,
otherContext,
currentSynthesizedMembers);
var mappedSynthesizedMembers = matcher.MapSynthesizedMembers(previousGeneration.SynthesizedMembers, currentSynthesizedMembers);
// TODO: can we reuse some data from the previous matcher?
var matcherWithAllSynthesizedMembers = new CSharpSymbolMatcher(
anonymousTypeMap,
sourceAssembly,
sourceContext,
compilation.SourceAssembly,
otherContext,
mappedSynthesizedMembers);
return matcherWithAllSynthesizedMembers.MapBaselineToCompilation(
previousGeneration,
compilation,
moduleBeingBuilt,
mappedSynthesizedMembers);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Reflection.Metadata;
using System.Threading;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Emit
{
internal static class EmitHelpers
{
internal static EmitDifferenceResult EmitDifference(
CSharpCompilation compilation,
EmitBaseline baseline,
IEnumerable<SemanticEdit> edits,
Func<ISymbol, bool> isAddedSymbol,
Stream metadataStream,
Stream ilStream,
Stream pdbStream,
CompilationTestData? testData,
CancellationToken cancellationToken)
{
var diagnostics = DiagnosticBag.GetInstance();
var emitOptions = EmitOptions.Default.WithDebugInformationFormat(baseline.HasPortablePdb ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb);
var runtimeMDVersion = compilation.GetRuntimeMetadataVersion(emitOptions, diagnostics);
var serializationProperties = compilation.ConstructModuleSerializationProperties(emitOptions, runtimeMDVersion, baseline.ModuleVersionId);
var manifestResources = SpecializedCollections.EmptyEnumerable<ResourceDescription>();
PEDeltaAssemblyBuilder moduleBeingBuilt;
try
{
moduleBeingBuilt = new PEDeltaAssemblyBuilder(
compilation.SourceAssembly,
emitOptions: emitOptions,
outputKind: compilation.Options.OutputKind,
serializationProperties: serializationProperties,
manifestResources: manifestResources,
previousGeneration: baseline,
edits: edits,
isAddedSymbol: isAddedSymbol);
}
catch (NotSupportedException e)
{
// TODO: https://github.com/dotnet/roslyn/issues/9004
diagnostics.Add(ErrorCode.ERR_ModuleEmitFailure, NoLocation.Singleton, compilation.AssemblyName, e.Message);
return new EmitDifferenceResult(
success: false,
diagnostics: diagnostics.ToReadOnlyAndFree(),
baseline: null,
updatedMethods: ImmutableArray<MethodDefinitionHandle>.Empty,
changedTypes: ImmutableArray<TypeDefinitionHandle>.Empty);
}
if (testData != null)
{
moduleBeingBuilt.SetMethodTestData(testData.Methods);
testData.Module = moduleBeingBuilt;
}
var definitionMap = moduleBeingBuilt.PreviousDefinitions;
var changes = moduleBeingBuilt.EncSymbolChanges;
Debug.Assert(changes != null);
EmitBaseline? newBaseline = null;
var updatedMethods = ArrayBuilder<MethodDefinitionHandle>.GetInstance();
var changedTypes = ArrayBuilder<TypeDefinitionHandle>.GetInstance();
if (compilation.Compile(
moduleBeingBuilt,
emittingPdb: true,
diagnostics: diagnostics,
filterOpt: s => changes.RequiresCompilation(s.GetISymbol()),
cancellationToken: cancellationToken))
{
// Map the definitions from the previous compilation to the current compilation.
// This must be done after compiling above since synthesized definitions
// (generated when compiling method bodies) may be required.
var mappedBaseline = MapToCompilation(compilation, moduleBeingBuilt);
newBaseline = compilation.SerializeToDeltaStreams(
moduleBeingBuilt,
mappedBaseline,
definitionMap,
changes,
metadataStream,
ilStream,
pdbStream,
updatedMethods,
changedTypes,
diagnostics,
testData?.SymWriterFactory,
emitOptions.PdbFilePath,
cancellationToken);
}
return new EmitDifferenceResult(
success: newBaseline != null,
diagnostics: diagnostics.ToReadOnlyAndFree(),
baseline: newBaseline,
updatedMethods: updatedMethods.ToImmutableAndFree(),
changedTypes: changedTypes.ToImmutableAndFree());
}
/// <summary>
/// Return a version of the baseline with all definitions mapped to this compilation.
/// Definitions from the initial generation, from metadata, are not mapped since
/// the initial generation is always included as metadata. That is, the symbols from
/// types, methods, ... in the TypesAdded, MethodsAdded, ... collections are replaced
/// by the corresponding symbols from the current compilation.
/// </summary>
private static EmitBaseline MapToCompilation(
CSharpCompilation compilation,
PEDeltaAssemblyBuilder moduleBeingBuilt)
{
var previousGeneration = moduleBeingBuilt.PreviousGeneration;
RoslynDebug.Assert(previousGeneration.Compilation != compilation);
if (previousGeneration.Ordinal == 0)
{
// Initial generation, nothing to map. (Since the initial generation
// is always loaded from metadata in the context of the current
// compilation, there's no separate mapping step.)
return previousGeneration;
}
RoslynDebug.AssertNotNull(previousGeneration.Compilation);
RoslynDebug.AssertNotNull(previousGeneration.PEModuleBuilder);
var currentSynthesizedMembers = moduleBeingBuilt.GetAllSynthesizedMembers();
// Mapping from previous compilation to the current.
var anonymousTypeMap = moduleBeingBuilt.GetAnonymousTypeMap();
var sourceAssembly = ((CSharpCompilation)previousGeneration.Compilation).SourceAssembly;
var sourceContext = new EmitContext((PEModuleBuilder)previousGeneration.PEModuleBuilder, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true);
var otherContext = new EmitContext(moduleBeingBuilt, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true);
var matcher = new CSharpSymbolMatcher(
anonymousTypeMap,
sourceAssembly,
sourceContext,
compilation.SourceAssembly,
otherContext,
currentSynthesizedMembers);
var mappedSynthesizedMembers = matcher.MapSynthesizedMembers(previousGeneration.SynthesizedMembers, currentSynthesizedMembers);
// TODO: can we reuse some data from the previous matcher?
var matcherWithAllSynthesizedMembers = new CSharpSymbolMatcher(
anonymousTypeMap,
sourceAssembly,
sourceContext,
compilation.SourceAssembly,
otherContext,
mappedSynthesizedMembers);
return matcherWithAllSynthesizedMembers.MapBaselineToCompilation(
previousGeneration,
compilation,
moduleBeingBuilt,
mappedSynthesizedMembers);
}
}
}
| 1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Compilers/CSharp/Test/Emit/Emit/EditAndContinue/EditAndContinueStateMachineTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.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;
using static Roslyn.Test.Utilities.TestMetadata;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests
{
public class EditAndContinueStateMachineTests : EditAndContinueTestBase
{
[Fact]
[WorkItem(1068894, "DevDiv"), WorkItem(1137300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1137300")]
public void AddIteratorMethod()
{
var source0 = WithWindowsLineBreaks(
@"using System.Collections.Generic;
class C
{
static IEnumerable<object> F()
{
yield return 0;
}
}");
var source1 = WithWindowsLineBreaks(
@"using System.Collections.Generic;
class C
{
static IEnumerable<object> F()
{
yield return 0;
}
static IEnumerable<int> G()
{
yield return 1;
}
}");
var compilation0 = CreateCompilationWithMscorlib40(new[] { Parse(source0, "a.cs") }, options: TestOptions.DebugDll);
var compilation1 = CreateCompilationWithMscorlib40(new[] { Parse(source1, "a.cs") }, options: TestOptions.DebugDll);
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.G"))));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifyUpdatedTypes("0x02000002");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(17, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(18, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(19, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(20, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(21, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(22, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(23, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(24, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(25, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(26, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(27, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(28, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(29, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(21, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(22, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(23, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(24, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(25, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(26, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(2, TableIndex.PropertyMap, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(4, TableIndex.Field, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(5, TableIndex.Field, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(6, TableIndex.Field, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(14, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(15, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(16, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(17, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(18, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(19, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
Row(3, TableIndex.Property, EditAndContinueOperation.Default),
Row(2, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
Row(4, TableIndex.Property, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(8, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(9, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(11, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(13, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(14, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default),
Row(6, TableIndex.InterfaceImpl, EditAndContinueOperation.Default),
Row(7, TableIndex.InterfaceImpl, EditAndContinueOperation.Default),
Row(8, TableIndex.InterfaceImpl, EditAndContinueOperation.Default),
Row(9, TableIndex.InterfaceImpl, EditAndContinueOperation.Default),
Row(10, TableIndex.InterfaceImpl, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(16, TableIndex.TypeRef),
Handle(17, TableIndex.TypeRef),
Handle(18, TableIndex.TypeRef),
Handle(19, TableIndex.TypeRef),
Handle(20, TableIndex.TypeRef),
Handle(21, TableIndex.TypeRef),
Handle(22, TableIndex.TypeRef),
Handle(23, TableIndex.TypeRef),
Handle(24, TableIndex.TypeRef),
Handle(25, TableIndex.TypeRef),
Handle(26, TableIndex.TypeRef),
Handle(4, TableIndex.TypeDef),
Handle(4, TableIndex.Field),
Handle(5, TableIndex.Field),
Handle(6, TableIndex.Field),
Handle(11, TableIndex.MethodDef),
Handle(12, TableIndex.MethodDef),
Handle(13, TableIndex.MethodDef),
Handle(14, TableIndex.MethodDef),
Handle(15, TableIndex.MethodDef),
Handle(16, TableIndex.MethodDef),
Handle(17, TableIndex.MethodDef),
Handle(18, TableIndex.MethodDef),
Handle(19, TableIndex.MethodDef),
Handle(2, TableIndex.Param),
Handle(6, TableIndex.InterfaceImpl),
Handle(7, TableIndex.InterfaceImpl),
Handle(8, TableIndex.InterfaceImpl),
Handle(9, TableIndex.InterfaceImpl),
Handle(10, TableIndex.InterfaceImpl),
Handle(17, TableIndex.MemberRef),
Handle(18, TableIndex.MemberRef),
Handle(19, TableIndex.MemberRef),
Handle(20, TableIndex.MemberRef),
Handle(21, TableIndex.MemberRef),
Handle(22, TableIndex.MemberRef),
Handle(23, TableIndex.MemberRef),
Handle(24, TableIndex.MemberRef),
Handle(25, TableIndex.MemberRef),
Handle(26, TableIndex.MemberRef),
Handle(27, TableIndex.MemberRef),
Handle(28, TableIndex.MemberRef),
Handle(29, TableIndex.MemberRef),
Handle(12, TableIndex.CustomAttribute),
Handle(13, TableIndex.CustomAttribute),
Handle(14, TableIndex.CustomAttribute),
Handle(15, TableIndex.CustomAttribute),
Handle(16, TableIndex.CustomAttribute),
Handle(17, TableIndex.CustomAttribute),
Handle(18, TableIndex.CustomAttribute),
Handle(19, TableIndex.CustomAttribute),
Handle(3, TableIndex.StandAloneSig),
Handle(4, TableIndex.StandAloneSig),
Handle(2, TableIndex.PropertyMap),
Handle(3, TableIndex.Property),
Handle(4, TableIndex.Property),
Handle(3, TableIndex.MethodSemantics),
Handle(4, TableIndex.MethodSemantics),
Handle(8, TableIndex.MethodImpl),
Handle(9, TableIndex.MethodImpl),
Handle(10, TableIndex.MethodImpl),
Handle(11, TableIndex.MethodImpl),
Handle(12, TableIndex.MethodImpl),
Handle(13, TableIndex.MethodImpl),
Handle(14, TableIndex.MethodImpl),
Handle(3, TableIndex.TypeSpec),
Handle(4, TableIndex.TypeSpec),
Handle(2, TableIndex.AssemblyRef),
Handle(2, TableIndex.NestedClass));
diff1.VerifyPdb(Enumerable.Range(0x06000001, 0x20), @"
<symbols>
<files>
<file id=""1"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""61-E4-46-A3-DE-2B-DE-69-1A-31-07-F6-EA-02-CE-B0-5F-38-03-79"" />
</files>
<methods>
<method token=""0x600000b"">
<customDebugInfo>
<forwardIterator name=""<G>d__1#1"" />
</customDebugInfo>
</method>
<method token=""0x600000e"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x1f"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x20"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""24"" document=""1"" />
<entry offset=""0x30"" hidden=""true"" document=""1"" />
<entry offset=""0x37"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x39"">
<namespace name=""System.Collections.Generic"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void AddAsyncMethod()
{
var source0 = @"
using System.Threading.Tasks;
class C
{
}";
var source1 = @"
using System.Threading.Tasks;
class C
{
static async Task<int> F()
{
await Task.FromResult(10);
return 20;
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var v0 = CompileAndVerify(compilation0);
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.F"))));
using (var md1 = diff1.GetMetadata())
{
var reader1 = md1.Reader;
// Add state machine type and its members:
// - Method '.ctor'
// - Method 'MoveNext'
// - Method 'SetStateMachine'
// - Field '<>1__state'
// - Field '<>t__builder'
// - Field '<>u__1'
// Add method F()
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(2, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(3, TableIndex.Field, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(1, TableIndex.NestedClass, EditAndContinueOperation.Default),
Row(1, TableIndex.InterfaceImpl, EditAndContinueOperation.Default));
}
}
[Fact]
public void MethodToIteratorMethod()
{
var source0 = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
return new int[] { 1, 2, 3 };
}
}";
var source1 = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
yield return 2;
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var v0 = CompileAndVerify(compilation0);
using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData))
{
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
using (var md1 = diff1.GetMetadata())
{
CheckEncLogDefinitions(md1.Reader,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(2, TableIndex.Field, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(3, TableIndex.Field, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(4, TableIndex.Field, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
Row(1, TableIndex.Property, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
Row(2, TableIndex.Property, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(7, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default),
Row(1, TableIndex.InterfaceImpl, EditAndContinueOperation.Default),
Row(2, TableIndex.InterfaceImpl, EditAndContinueOperation.Default),
Row(3, TableIndex.InterfaceImpl, EditAndContinueOperation.Default),
Row(4, TableIndex.InterfaceImpl, EditAndContinueOperation.Default),
Row(5, TableIndex.InterfaceImpl, EditAndContinueOperation.Default));
}
}
}
[Fact]
public void MethodToAsyncMethod()
{
var source0 = @"
using System.Threading.Tasks;
class C
{
static Task<int> F()
{
return Task.FromResult(1);
}
}";
var source1 = @"
using System.Threading.Tasks;
class C
{
static async Task<int> F()
{
return await Task.FromResult(1);
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var v0 = CompileAndVerify(compilation0);
using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData))
{
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
using (var md1 = diff1.GetMetadata())
{
CheckEncLogDefinitions(md1.Reader,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(2, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(3, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(4, TableIndex.Field, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(1, TableIndex.NestedClass, EditAndContinueOperation.Default),
Row(1, TableIndex.InterfaceImpl, EditAndContinueOperation.Default));
}
}
}
[Fact]
public void IteratorMethodToMethod()
{
var source0 = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
yield return 2;
}
}";
var source1 = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
return new int[] { 1, 2, 3 };
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var v0 = CompileAndVerify(compilation0);
using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData))
{
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
using (var md1 = diff1.GetMetadata())
{
CheckAttributes(md1.Reader,
new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // row id 0 == delete
CheckEncLogDefinitions(md1.Reader,
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Delete IteratorStateMachineAttribute
}
}
}
[Fact]
public void AsyncMethodToMethod()
{
var source0 = @"
using System.Threading.Tasks;
class C
{
static async Task<int> F()
{
return await Task.FromResult(1);
}
}";
var source1 = @"
using System.Threading.Tasks;
class C
{
static Task<int> F()
{
return Task.FromResult(1);
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var v0 = CompileAndVerify(compilation0);
using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData))
{
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
using (var md1 = diff1.GetMetadata())
{
CheckAttributes(md1.Reader,
new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef)), // row id 0 == delete
new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // row id 0 == delete
CheckEncLogDefinitions(md1.Reader,
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Delete AsyncStateMachineAttribute
Row(2, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Delete DebuggerStepThroughAttribute
}
}
}
[Fact]
public void AsyncMethodOverloads()
{
var source0 = @"
using System.Threading.Tasks;
class C
{
static async Task<int> F(long a)
{
return await Task.FromResult(1);
}
static async Task<int> F(int a)
{
return await Task.FromResult(1);
}
static async Task<int> F(short a)
{
return await Task.FromResult(1);
}
}";
var source1 = @"
using System.Threading.Tasks;
class C
{
static async Task<int> F(short a)
{
return await Task.FromResult(2);
}
static async Task<int> F(long a)
{
return await Task.FromResult(3);
}
static async Task<int> F(int a)
{
return await Task.FromResult(4);
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var v0 = CompileAndVerify(compilation0);
using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData))
{
var methodShort0 = compilation0.GetMembers("C.F").Single(m => m.ToTestDisplayString() == "System.Threading.Tasks.Task<System.Int32> C.F(System.Int16 a)");
var methodShort1 = compilation1.GetMembers("C.F").Single(m => m.ToTestDisplayString() == "System.Threading.Tasks.Task<System.Int32> C.F(System.Int16 a)");
var methodInt0 = compilation0.GetMembers("C.F").Single(m => m.ToTestDisplayString() == "System.Threading.Tasks.Task<System.Int32> C.F(System.Int32 a)");
var methodInt1 = compilation1.GetMembers("C.F").Single(m => m.ToTestDisplayString() == "System.Threading.Tasks.Task<System.Int32> C.F(System.Int32 a)");
var methodLong0 = compilation0.GetMembers("C.F").Single(m => m.ToTestDisplayString() == "System.Threading.Tasks.Task<System.Int32> C.F(System.Int64 a)");
var methodLong1 = compilation1.GetMembers("C.F").Single(m => m.ToTestDisplayString() == "System.Threading.Tasks.Task<System.Int32> C.F(System.Int64 a)");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, methodShort0, methodShort1, preserveLocalVariables: true),
SemanticEdit.Create(SemanticEditKind.Update, methodInt0, methodInt1, preserveLocalVariables: true),
SemanticEdit.Create(SemanticEditKind.Update, methodLong0, methodLong1, preserveLocalVariables: true)
));
using (var md1 = diff1.GetMetadata())
{
// notice no TypeDefs, FieldDefs
CheckEncLogDefinitions(md1.Reader,
Row(7, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(8, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(9, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(10, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(11, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(12, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(2, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
}
}
[Fact]
public void UpdateIterator_NoVariables()
{
var source0 = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
yield return 1;
}
}";
var source1 = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
yield return 2;
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var v0 = CompileAndVerify(compilation0);
using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData))
{
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: true)));
// only methods with sequence points should be listed in UpdatedMethods:
diff1.VerifyUpdatedMethods("0x06000005");
// Verify delta metadata contains expected rows.
using (var md1 = diff1.GetMetadata())
{
// Verify that no new TypeDefs, FieldDefs or MethodDefs were added,
// 3 methods were updated:
// - the kick-off method (might be changed if the method previously wasn't an iterator)
// - Finally method
// - MoveNext method
CheckEncLogDefinitions(md1.Reader,
Row(3, 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.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @"
{
// Code size 57 (0x39)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
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_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_0030
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<F>d__0.<>1__state""
IL_001f: nop
IL_0020: ldarg.0
IL_0021: ldc.i4.2
IL_0022: stfld ""int C.<F>d__0.<>2__current""
IL_0027: ldarg.0
IL_0028: ldc.i4.1
IL_0029: stfld ""int C.<F>d__0.<>1__state""
IL_002e: ldc.i4.1
IL_002f: ret
IL_0030: ldarg.0
IL_0031: ldc.i4.m1
IL_0032: stfld ""int C.<F>d__0.<>1__state""
IL_0037: ldc.i4.0
IL_0038: ret
}");
v0.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @"
{
// Code size 57 (0x39)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
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_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_0030
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<F>d__0.<>1__state""
IL_001f: nop
IL_0020: ldarg.0
IL_0021: ldc.i4.1
IL_0022: stfld ""int C.<F>d__0.<>2__current""
IL_0027: ldarg.0
IL_0028: ldc.i4.1
IL_0029: stfld ""int C.<F>d__0.<>1__state""
IL_002e: ldc.i4.1
IL_002f: ret
IL_0030: ldarg.0
IL_0031: ldc.i4.m1
IL_0032: stfld ""int C.<F>d__0.<>1__state""
IL_0037: ldc.i4.0
IL_0038: ret
}");
}
}
}
[Fact]
public void UpdateAsync_NoVariables()
{
var source0 = WithWindowsLineBreaks(@"
using System.Threading.Tasks;
class C
{
static async Task<int> F()
{
await Task.FromResult(1);
return 2;
}
}");
var source1 = WithWindowsLineBreaks(@"
using System.Threading.Tasks;
class C
{
static async Task<int> F()
{
await Task.FromResult(10);
return 20;
}
}");
var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var v0 = CompileAndVerify(compilation0);
using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData))
{
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: true)));
// only methods with sequence points should be listed in UpdatedMethods:
diff1.VerifyUpdatedMethods("0x06000004");
diff1.VerifyUpdatedTypes("0x02000002", "0x02000003");
using (var md1 = diff1.GetMetadata())
{
// Verify that no new TypeDefs, FieldDefs or MethodDefs were added,
// 2 methods were updated:
// - the kick-off method (might be changed if the method previously wasn't async)
// - MoveNext method
CheckEncLogDefinitions(md1.Reader,
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(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(2, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
diff1.VerifyIL("C.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @"
{
// Code size 162 (0xa2)
.maxstack 3
.locals init (int V_0,
int V_1,
System.Runtime.CompilerServices.TaskAwaiter<int> V_2,
C.<F>d__0 V_3,
System.Exception V_4)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_000c
IL_000a: br.s IL_000e
IL_000c: br.s IL_0049
IL_000e: nop
IL_000f: ldc.i4.s 10
IL_0011: call ""System.Threading.Tasks.Task<int> System.Threading.Tasks.Task.FromResult<int>(int)""
IL_0016: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_001b: stloc.2
IL_001c: ldloca.s V_2
IL_001e: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_0023: brtrue.s IL_0065
IL_0025: ldarg.0
IL_0026: ldc.i4.0
IL_0027: dup
IL_0028: stloc.0
IL_0029: stfld ""int C.<F>d__0.<>1__state""
IL_002e: ldarg.0
IL_002f: ldloc.2
IL_0030: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1""
IL_0035: ldarg.0
IL_0036: stloc.3
IL_0037: ldarg.0
IL_0038: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_003d: ldloca.s V_2
IL_003f: ldloca.s V_3
IL_0041: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, C.<F>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref C.<F>d__0)""
IL_0046: nop
IL_0047: leave.s IL_00a1
IL_0049: ldarg.0
IL_004a: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1""
IL_004f: stloc.2
IL_0050: ldarg.0
IL_0051: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1""
IL_0056: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_005c: ldarg.0
IL_005d: ldc.i4.m1
IL_005e: dup
IL_005f: stloc.0
IL_0060: stfld ""int C.<F>d__0.<>1__state""
IL_0065: ldloca.s V_2
IL_0067: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_006c: pop
IL_006d: ldc.i4.s 20
IL_006f: stloc.1
IL_0070: leave.s IL_008c
}
catch System.Exception
{
IL_0072: stloc.s V_4
IL_0074: ldarg.0
IL_0075: ldc.i4.s -2
IL_0077: stfld ""int C.<F>d__0.<>1__state""
IL_007c: ldarg.0
IL_007d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_0082: ldloc.s V_4
IL_0084: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)""
IL_0089: nop
IL_008a: leave.s IL_00a1
}
IL_008c: ldarg.0
IL_008d: ldc.i4.s -2
IL_008f: stfld ""int C.<F>d__0.<>1__state""
IL_0094: ldarg.0
IL_0095: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_009a: ldloc.1
IL_009b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)""
IL_00a0: nop
IL_00a1: ret
}");
v0.VerifyIL("C.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @"
{
// Code size 160 (0xa0)
.maxstack 3
.locals init (int V_0,
int V_1,
System.Runtime.CompilerServices.TaskAwaiter<int> V_2,
C.<F>d__0 V_3,
System.Exception V_4)
~IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
.try
{
~IL_0007: ldloc.0
IL_0008: brfalse.s IL_000c
IL_000a: br.s IL_000e
IL_000c: br.s IL_0048
-IL_000e: nop
-IL_000f: ldc.i4.1
IL_0010: call ""System.Threading.Tasks.Task<int> System.Threading.Tasks.Task.FromResult<int>(int)""
IL_0015: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_001a: stloc.2
~IL_001b: ldloca.s V_2
IL_001d: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_0022: brtrue.s IL_0064
IL_0024: ldarg.0
IL_0025: ldc.i4.0
IL_0026: dup
IL_0027: stloc.0
IL_0028: stfld ""int C.<F>d__0.<>1__state""
<IL_002d: ldarg.0
IL_002e: ldloc.2
IL_002f: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1""
IL_0034: ldarg.0
IL_0035: stloc.3
IL_0036: ldarg.0
IL_0037: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_003c: ldloca.s V_2
IL_003e: ldloca.s V_3
IL_0040: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, C.<F>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref C.<F>d__0)""
IL_0045: nop
IL_0046: leave.s IL_009f
>IL_0048: ldarg.0
IL_0049: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1""
IL_004e: stloc.2
IL_004f: ldarg.0
IL_0050: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1""
IL_0055: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_005b: ldarg.0
IL_005c: ldc.i4.m1
IL_005d: dup
IL_005e: stloc.0
IL_005f: stfld ""int C.<F>d__0.<>1__state""
IL_0064: ldloca.s V_2
IL_0066: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_006b: pop
-IL_006c: ldc.i4.2
IL_006d: stloc.1
IL_006e: leave.s IL_008a
}
catch System.Exception
{
~IL_0070: stloc.s V_4
IL_0072: ldarg.0
IL_0073: ldc.i4.s -2
IL_0075: stfld ""int C.<F>d__0.<>1__state""
IL_007a: ldarg.0
IL_007b: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_0080: ldloc.s V_4
IL_0082: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)""
IL_0087: nop
IL_0088: leave.s IL_009f
}
-IL_008a: ldarg.0
IL_008b: ldc.i4.s -2
IL_008d: stfld ""int C.<F>d__0.<>1__state""
~IL_0092: ldarg.0
IL_0093: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_0098: ldloc.1
IL_0099: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)""
IL_009e: nop
IL_009f: ret
}", sequencePoints: "C+<F>d__0.MoveNext");
v0.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>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""20"" offset=""0"" />
<slot kind=""33"" offset=""11"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" hidden=""true"" document=""1"" />
<entry offset=""0xe"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0xf"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""34"" document=""1"" />
<entry offset=""0x1b"" hidden=""true"" document=""1"" />
<entry offset=""0x6c"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""18"" document=""1"" />
<entry offset=""0x70"" hidden=""true"" document=""1"" />
<entry offset=""0x8a"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
<entry offset=""0x92"" hidden=""true"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xa0"">
<namespace name=""System.Threading.Tasks"" />
</scope>
<asyncInfo>
<kickoffMethod declaringType=""C"" methodName=""F"" />
<await yield=""0x2d"" resume=""0x48"" declaringType=""C+<F>d__0"" methodName=""MoveNext"" />
</asyncInfo>
</method>
</methods>
</symbols>");
}
}
}
[Fact]
public void UpdateIterator_UserDefinedVariables_NoChange()
{
var source0 = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> F(int p)
{
int x = p;
yield return 1;
}
}";
var source1 = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> F(int p)
{
int x = p;
yield return 2;
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1);
var v0 = CompileAndVerify(compilation0);
var symReader = v0.CreateSymReader();
using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData))
{
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, symReader.GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
// Verify delta metadata contains expected rows.
using (var md1 = diff1.GetMetadata())
{
// Verify that no new TypeDefs, FieldDefs or MethodDefs were added,
// 3 methods were updated:
// - the kick-off method (might be changed if the method previously wasn't an iterator)
// - Finally method
// - MoveNext method
CheckEncLogDefinitions(md1.Reader,
Row(3, 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.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @"
{
// Code size 69 (0x45)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
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_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_003c
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<F>d__0.<>1__state""
IL_001f: nop
IL_0020: ldarg.0
IL_0021: ldarg.0
IL_0022: ldfld ""int C.<F>d__0.p""
IL_0027: stfld ""int C.<F>d__0.<x>5__1""
IL_002c: ldarg.0
IL_002d: ldc.i4.2
IL_002e: stfld ""int C.<F>d__0.<>2__current""
IL_0033: ldarg.0
IL_0034: ldc.i4.1
IL_0035: stfld ""int C.<F>d__0.<>1__state""
IL_003a: ldc.i4.1
IL_003b: ret
IL_003c: ldarg.0
IL_003d: ldc.i4.m1
IL_003e: stfld ""int C.<F>d__0.<>1__state""
IL_0043: ldc.i4.0
IL_0044: ret
}");
}
}
}
[Fact]
public void UpdateIterator_UserDefinedVariables_AddVariable()
{
var source0 = @"
using System;
using System.Collections.Generic;
class C
{
static IEnumerable<int> F(int p)
{
int x = p;
yield return x;
}
}";
var source1 = @"
using System;
using System.Collections.Generic;
class C
{
static IEnumerable<int> F(int p)
{
int y = 1234;
int x = p;
yield return y;
Console.WriteLine(x);
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1);
var v0 = CompileAndVerify(compilation0);
var symReader = v0.CreateSymReader();
using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData))
{
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, symReader.GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
// Verify delta metadata contains expected rows.
using (var md1 = diff1.GetMetadata())
{
// 1 field def added & 3 methods updated
CheckEncLogDefinitions(md1.Reader,
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(7, TableIndex.Field, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @"
{
// Code size 97 (0x61)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
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_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_004c
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<F>d__0.<>1__state""
IL_001f: nop
IL_0020: ldarg.0
IL_0021: ldc.i4 0x4d2
IL_0026: stfld ""int C.<F>d__0.<y>5__2""
IL_002b: ldarg.0
IL_002c: ldarg.0
IL_002d: ldfld ""int C.<F>d__0.p""
IL_0032: stfld ""int C.<F>d__0.<x>5__1""
IL_0037: ldarg.0
IL_0038: ldarg.0
IL_0039: ldfld ""int C.<F>d__0.<y>5__2""
IL_003e: stfld ""int C.<F>d__0.<>2__current""
IL_0043: ldarg.0
IL_0044: ldc.i4.1
IL_0045: stfld ""int C.<F>d__0.<>1__state""
IL_004a: ldc.i4.1
IL_004b: ret
IL_004c: ldarg.0
IL_004d: ldc.i4.m1
IL_004e: stfld ""int C.<F>d__0.<>1__state""
IL_0053: ldarg.0
IL_0054: ldfld ""int C.<F>d__0.<x>5__1""
IL_0059: call ""void System.Console.WriteLine(int)""
IL_005e: nop
IL_005f: ldc.i4.0
IL_0060: ret
}");
}
}
}
[Fact]
public void UpdateIterator_UserDefinedVariables_AddAndRemoveVariable()
{
var source0 = @"
using System;
using System.Collections.Generic;
class C
{
static IEnumerable<int> F(int p)
{
int x = p;
yield return x;
}
}";
var source1 = @"
using System;
using System.Collections.Generic;
class C
{
static IEnumerable<int> F(int p)
{
int y = 1234;
yield return y;
Console.WriteLine(p);
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1);
var v0 = CompileAndVerify(compilation0);
var symReader = v0.CreateSymReader();
using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData))
{
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, symReader.GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
// Verify delta metadata contains expected rows.
using (var md1 = diff1.GetMetadata())
{
// 1 field def added & 3 methods updated
CheckEncLogDefinitions(md1.Reader,
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(7, TableIndex.Field, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @"
{
// Code size 85 (0x55)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
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_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_0040
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<F>d__0.<>1__state""
IL_001f: nop
IL_0020: ldarg.0
IL_0021: ldc.i4 0x4d2
IL_0026: stfld ""int C.<F>d__0.<y>5__2""
IL_002b: ldarg.0
IL_002c: ldarg.0
IL_002d: ldfld ""int C.<F>d__0.<y>5__2""
IL_0032: stfld ""int C.<F>d__0.<>2__current""
IL_0037: ldarg.0
IL_0038: ldc.i4.1
IL_0039: stfld ""int C.<F>d__0.<>1__state""
IL_003e: ldc.i4.1
IL_003f: ret
IL_0040: ldarg.0
IL_0041: ldc.i4.m1
IL_0042: stfld ""int C.<F>d__0.<>1__state""
IL_0047: ldarg.0
IL_0048: ldfld ""int C.<F>d__0.p""
IL_004d: call ""void System.Console.WriteLine(int)""
IL_0052: nop
IL_0053: ldc.i4.0
IL_0054: ret
}");
}
}
}
[Fact]
public void UpdateIterator_UserDefinedVariables_ChangeVariableType()
{
var source0 = @"
using System;
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
var x = 1;
yield return 1;
Console.WriteLine(x);
}
}";
var source1 = @"
using System;
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
var x = 1.0;
yield return 2;
Console.WriteLine(x);
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1);
var v0 = CompileAndVerify(compilation0);
var symReader = v0.CreateSymReader();
using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData))
{
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, symReader.GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
// Verify delta metadata contains expected rows.
using (var md1 = diff1.GetMetadata())
{
// 1 field def added & 3 methods updated
CheckEncLogDefinitions(md1.Reader,
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(5, TableIndex.Field, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @"
{
// Code size 84 (0x54)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
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_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_003f
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<F>d__0.<>1__state""
IL_001f: nop
IL_0020: ldarg.0
IL_0021: ldc.r8 1
IL_002a: stfld ""double C.<F>d__0.<x>5__2""
IL_002f: ldarg.0
IL_0030: ldc.i4.2
IL_0031: stfld ""int C.<F>d__0.<>2__current""
IL_0036: ldarg.0
IL_0037: ldc.i4.1
IL_0038: stfld ""int C.<F>d__0.<>1__state""
IL_003d: ldc.i4.1
IL_003e: ret
IL_003f: ldarg.0
IL_0040: ldc.i4.m1
IL_0041: stfld ""int C.<F>d__0.<>1__state""
IL_0046: ldarg.0
IL_0047: ldfld ""double C.<F>d__0.<x>5__2""
IL_004c: call ""void System.Console.WriteLine(double)""
IL_0051: nop
IL_0052: ldc.i4.0
IL_0053: ret
}");
}
}
}
[Fact]
public void UpdateIterator_SynthesizedVariables_ChangeVariableType()
{
var source0 = @"
using System;
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
foreach (object item in new[] { 1 }) { yield return 1; }
}
}";
var source1 = @"
using System;
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
foreach (object item in new[] { 1.0 }) { yield return 1; }
}
}";
// Rude edit but the compiler should handle it.
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1);
var v0 = CompileAndVerify(compilation0, symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state: int",
"<>2__current: int",
"<>l__initialThreadId: int",
"<>s__1: int[]",
"<>s__2: int",
"<item>5__3: object"
}, module.GetFieldNamesAndTypes("C.<F>d__0"));
});
var symReader = v0.CreateSymReader();
using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData))
{
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, symReader.GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapByKind(method0, SyntaxKind.ForEachStatement), preserveLocalVariables: true)));
// Verify delta metadata contains expected rows.
using (var md1 = diff1.GetMetadata())
{
// 1 field def added & 3 methods updated
CheckEncLogDefinitions(md1.Reader,
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(7, TableIndex.Field, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @"
{
// Code size 161 (0xa1)
.maxstack 5
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
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_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_006b
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<F>d__0.<>1__state""
IL_001f: nop
IL_0020: nop
IL_0021: ldarg.0
IL_0022: ldc.i4.1
IL_0023: newarr ""double""
IL_0028: dup
IL_0029: ldc.i4.0
IL_002a: ldc.r8 1
IL_0033: stelem.r8
IL_0034: stfld ""double[] C.<F>d__0.<>s__4""
IL_0039: ldarg.0
IL_003a: ldc.i4.0
IL_003b: stfld ""int C.<F>d__0.<>s__2""
IL_0040: br.s IL_0088
IL_0042: ldarg.0
IL_0043: ldarg.0
IL_0044: ldfld ""double[] C.<F>d__0.<>s__4""
IL_0049: ldarg.0
IL_004a: ldfld ""int C.<F>d__0.<>s__2""
IL_004f: ldelem.r8
IL_0050: box ""double""
IL_0055: stfld ""object C.<F>d__0.<item>5__3""
IL_005a: nop
IL_005b: ldarg.0
IL_005c: ldc.i4.1
IL_005d: stfld ""int C.<F>d__0.<>2__current""
IL_0062: ldarg.0
IL_0063: ldc.i4.1
IL_0064: stfld ""int C.<F>d__0.<>1__state""
IL_0069: ldc.i4.1
IL_006a: ret
IL_006b: ldarg.0
IL_006c: ldc.i4.m1
IL_006d: stfld ""int C.<F>d__0.<>1__state""
IL_0072: nop
IL_0073: ldarg.0
IL_0074: ldnull
IL_0075: stfld ""object C.<F>d__0.<item>5__3""
IL_007a: ldarg.0
IL_007b: ldarg.0
IL_007c: ldfld ""int C.<F>d__0.<>s__2""
IL_0081: ldc.i4.1
IL_0082: add
IL_0083: stfld ""int C.<F>d__0.<>s__2""
IL_0088: ldarg.0
IL_0089: ldfld ""int C.<F>d__0.<>s__2""
IL_008e: ldarg.0
IL_008f: ldfld ""double[] C.<F>d__0.<>s__4""
IL_0094: ldlen
IL_0095: conv.i4
IL_0096: blt.s IL_0042
IL_0098: ldarg.0
IL_0099: ldnull
IL_009a: stfld ""double[] C.<F>d__0.<>s__4""
IL_009f: ldc.i4.0
IL_00a0: ret
}");
}
}
}
[Fact]
public void HoistedVariables_MultipleGenerations()
{
var source0 = @"
using System.Threading.Tasks;
class C
{
static async Task<int> F() // testing type changes G0 -> G1, G1 -> G2
{
bool a1 = true;
int a2 = 3;
await Task.Delay(0);
return 1;
}
static async Task<int> G() // testing G1 -> G3
{
C c = new C();
bool a1 = true;
await Task.Delay(0);
return 1;
}
static async Task<int> H() // testing G0 -> G3
{
C c = new C();
bool a1 = true;
await Task.Delay(0);
return 1;
}
}";
var source1 = @"
using System.Threading.Tasks;
class C
{
static async Task<int> F() // updated
{
C a1 = new C();
int a2 = 3;
await Task.Delay(0);
return 1;
}
static async Task<int> G() // updated
{
C c = new C();
bool a1 = true;
await Task.Delay(0);
return 2;
}
static async Task<int> H()
{
C c = new C();
bool a1 = true;
await Task.Delay(0);
return 1;
}
}";
var source2 = @"
using System.Threading.Tasks;
class C
{
static async Task<int> F() // updated
{
bool a1 = true;
C a2 = new C();
await Task.Delay(0);
return 1;
}
static async Task<int> G()
{
C c = new C();
bool a1 = true;
await Task.Delay(0);
return 2;
}
static async Task<int> H()
{
C c = new C();
bool a1 = true;
await Task.Delay(0);
return 1;
}
}";
var source3 = @"
using System.Threading.Tasks;
class C
{
static async Task<int> F()
{
bool a1 = true;
C a2 = new C();
await Task.Delay(0);
return 1;
}
static async Task<int> G() // updated
{
C c = new C();
C a1 = new C();
await Task.Delay(0);
return 1;
}
static async Task<int> H() // updated
{
C c = new C();
C a1 = new C();
await Task.Delay(0);
return 1;
}
}";
// Rude edit but the compiler should handle it.
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
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 g0 = compilation0.GetMember<MethodSymbol>("C.G");
var g1 = compilation1.GetMember<MethodSymbol>("C.G");
var g2 = compilation2.GetMember<MethodSymbol>("C.G");
var g3 = compilation3.GetMember<MethodSymbol>("C.G");
var h0 = compilation0.GetMember<MethodSymbol>("C.H");
var h1 = compilation1.GetMember<MethodSymbol>("C.H");
var h2 = compilation2.GetMember<MethodSymbol>("C.H");
var h3 = compilation3.GetMember<MethodSymbol>("C.H");
var v0 = CompileAndVerify(compilation0, symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state: int",
"<>t__builder: System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>",
"<a1>5__1: bool",
"<a2>5__2: int",
"<>u__1: System.Runtime.CompilerServices.TaskAwaiter"
}, module.GetFieldNamesAndTypes("C.<F>d__0"));
});
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true),
SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetEquivalentNodesMap(g1, g0), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<F>d__0, <G>d__1}",
"C.<F>d__0: {<>1__state, <>t__builder, <a1>5__3, <a2>5__2, <>u__1, MoveNext, SetStateMachine}",
"C.<G>d__1: {<>1__state, <>t__builder, <c>5__1, <a1>5__2, <>u__1, MoveNext, SetStateMachine}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetEquivalentNodesMap(f2, f1), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<F>d__0, <G>d__1}",
"C.<F>d__0: {<>1__state, <>t__builder, <a1>5__4, <a2>5__5, <>u__1, MoveNext, SetStateMachine, <a1>5__3, <a2>5__2}",
"C.<G>d__1: {<>1__state, <>t__builder, <c>5__1, <a1>5__2, <>u__1, MoveNext, SetStateMachine}");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, g2, g3, GetEquivalentNodesMap(g3, g2), preserveLocalVariables: true),
SemanticEdit.Create(SemanticEditKind.Update, h2, h3, GetEquivalentNodesMap(h3, h2), preserveLocalVariables: true)));
diff3.VerifySynthesizedMembers(
"C: {<G>d__1, <H>d__2, <F>d__0}",
"C.<F>d__0: {<>1__state, <>t__builder, <a1>5__4, <a2>5__5, <>u__1, MoveNext, SetStateMachine, <a1>5__3, <a2>5__2}",
"C.<G>d__1: {<>1__state, <>t__builder, <c>5__1, <a1>5__3, <>u__1, MoveNext, SetStateMachine, <a1>5__2}",
"C.<H>d__2: {<>1__state, <>t__builder, <c>5__1, <a1>5__3, <>u__1, MoveNext, SetStateMachine}");
// Verify delta metadata contains expected rows.
var md1 = diff1.GetMetadata();
var md2 = diff2.GetMetadata();
var md3 = diff3.GetMetadata();
// 1 field def added & 4 methods updated (MoveNext and kickoff for F and G)
CheckEncLogDefinitions(md1.Reader,
Row(7, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(8, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(9, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(10, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(16, TableIndex.Field, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(2, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
diff1.VerifyIL("C.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @"
{
// Code size 192 (0xc0)
.maxstack 3
.locals init (int V_0,
int V_1,
System.Runtime.CompilerServices.TaskAwaiter V_2,
C.<F>d__0 V_3,
System.Exception V_4)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_000c
IL_000a: br.s IL_000e
IL_000c: br.s IL_005a
IL_000e: nop
IL_000f: ldarg.0
IL_0010: newobj ""C..ctor()""
IL_0015: stfld ""C C.<F>d__0.<a1>5__3""
IL_001a: ldarg.0
IL_001b: ldc.i4.3
IL_001c: stfld ""int C.<F>d__0.<a2>5__2""
IL_0021: ldc.i4.0
IL_0022: call ""System.Threading.Tasks.Task System.Threading.Tasks.Task.Delay(int)""
IL_0027: callvirt ""System.Runtime.CompilerServices.TaskAwaiter System.Threading.Tasks.Task.GetAwaiter()""
IL_002c: stloc.2
IL_002d: ldloca.s V_2
IL_002f: call ""bool System.Runtime.CompilerServices.TaskAwaiter.IsCompleted.get""
IL_0034: brtrue.s IL_0076
IL_0036: ldarg.0
IL_0037: ldc.i4.0
IL_0038: dup
IL_0039: stloc.0
IL_003a: stfld ""int C.<F>d__0.<>1__state""
IL_003f: ldarg.0
IL_0040: ldloc.2
IL_0041: stfld ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1""
IL_0046: ldarg.0
IL_0047: stloc.3
IL_0048: ldarg.0
IL_0049: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_004e: ldloca.s V_2
IL_0050: ldloca.s V_3
IL_0052: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter, C.<F>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter, ref C.<F>d__0)""
IL_0057: nop
IL_0058: leave.s IL_00bf
IL_005a: ldarg.0
IL_005b: ldfld ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1""
IL_0060: stloc.2
IL_0061: ldarg.0
IL_0062: ldflda ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1""
IL_0067: initobj ""System.Runtime.CompilerServices.TaskAwaiter""
IL_006d: ldarg.0
IL_006e: ldc.i4.m1
IL_006f: dup
IL_0070: stloc.0
IL_0071: stfld ""int C.<F>d__0.<>1__state""
IL_0076: ldloca.s V_2
IL_0078: call ""void System.Runtime.CompilerServices.TaskAwaiter.GetResult()""
IL_007d: nop
IL_007e: ldc.i4.1
IL_007f: stloc.1
IL_0080: leave.s IL_00a3
}
catch System.Exception
{
IL_0082: stloc.s V_4
IL_0084: ldarg.0
IL_0085: ldc.i4.s -2
IL_0087: stfld ""int C.<F>d__0.<>1__state""
IL_008c: ldarg.0
IL_008d: ldnull
IL_008e: stfld ""C C.<F>d__0.<a1>5__3""
IL_0093: ldarg.0
IL_0094: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_0099: ldloc.s V_4
IL_009b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)""
IL_00a0: nop
IL_00a1: leave.s IL_00bf
}
IL_00a3: ldarg.0
IL_00a4: ldc.i4.s -2
IL_00a6: stfld ""int C.<F>d__0.<>1__state""
IL_00ab: ldarg.0
IL_00ac: ldnull
IL_00ad: stfld ""C C.<F>d__0.<a1>5__3""
IL_00b2: ldarg.0
IL_00b3: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_00b8: ldloc.1
IL_00b9: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)""
IL_00be: nop
IL_00bf: ret
}");
// 2 field defs added (both variables a1 and a2 of F changed their types) & 2 methods updated
CheckEncLogDefinitions(md2.Reader,
Row(11, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(12, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(17, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(18, TableIndex.Field, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(2, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
diff2.VerifyIL("C.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @"
{
// Code size 192 (0xc0)
.maxstack 3
.locals init (int V_0,
int V_1,
System.Runtime.CompilerServices.TaskAwaiter V_2,
C.<F>d__0 V_3,
System.Exception V_4)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_000c
IL_000a: br.s IL_000e
IL_000c: br.s IL_005a
IL_000e: nop
IL_000f: ldarg.0
IL_0010: ldc.i4.1
IL_0011: stfld ""bool C.<F>d__0.<a1>5__4""
IL_0016: ldarg.0
IL_0017: newobj ""C..ctor()""
IL_001c: stfld ""C C.<F>d__0.<a2>5__5""
IL_0021: ldc.i4.0
IL_0022: call ""System.Threading.Tasks.Task System.Threading.Tasks.Task.Delay(int)""
IL_0027: callvirt ""System.Runtime.CompilerServices.TaskAwaiter System.Threading.Tasks.Task.GetAwaiter()""
IL_002c: stloc.2
IL_002d: ldloca.s V_2
IL_002f: call ""bool System.Runtime.CompilerServices.TaskAwaiter.IsCompleted.get""
IL_0034: brtrue.s IL_0076
IL_0036: ldarg.0
IL_0037: ldc.i4.0
IL_0038: dup
IL_0039: stloc.0
IL_003a: stfld ""int C.<F>d__0.<>1__state""
IL_003f: ldarg.0
IL_0040: ldloc.2
IL_0041: stfld ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1""
IL_0046: ldarg.0
IL_0047: stloc.3
IL_0048: ldarg.0
IL_0049: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_004e: ldloca.s V_2
IL_0050: ldloca.s V_3
IL_0052: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter, C.<F>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter, ref C.<F>d__0)""
IL_0057: nop
IL_0058: leave.s IL_00bf
IL_005a: ldarg.0
IL_005b: ldfld ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1""
IL_0060: stloc.2
IL_0061: ldarg.0
IL_0062: ldflda ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1""
IL_0067: initobj ""System.Runtime.CompilerServices.TaskAwaiter""
IL_006d: ldarg.0
IL_006e: ldc.i4.m1
IL_006f: dup
IL_0070: stloc.0
IL_0071: stfld ""int C.<F>d__0.<>1__state""
IL_0076: ldloca.s V_2
IL_0078: call ""void System.Runtime.CompilerServices.TaskAwaiter.GetResult()""
IL_007d: nop
IL_007e: ldc.i4.1
IL_007f: stloc.1
IL_0080: leave.s IL_00a3
}
catch System.Exception
{
IL_0082: stloc.s V_4
IL_0084: ldarg.0
IL_0085: ldc.i4.s -2
IL_0087: stfld ""int C.<F>d__0.<>1__state""
IL_008c: ldarg.0
IL_008d: ldnull
IL_008e: stfld ""C C.<F>d__0.<a2>5__5""
IL_0093: ldarg.0
IL_0094: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_0099: ldloc.s V_4
IL_009b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)""
IL_00a0: nop
IL_00a1: leave.s IL_00bf
}
IL_00a3: ldarg.0
IL_00a4: ldc.i4.s -2
IL_00a6: stfld ""int C.<F>d__0.<>1__state""
IL_00ab: ldarg.0
IL_00ac: ldnull
IL_00ad: stfld ""C C.<F>d__0.<a2>5__5""
IL_00b2: ldarg.0
IL_00b3: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_00b8: ldloc.1
IL_00b9: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)""
IL_00be: nop
IL_00bf: ret
}");
// 2 field defs added - variables of G and H changed their types; 4 methods updated: G, H kickoff and MoveNext
CheckEncLogDefinitions(md3.Reader,
Row(13, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(14, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(15, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(16, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(19, TableIndex.Field, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(20, TableIndex.Field, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void HoistedVariables_Dynamic1()
{
var template = @"
using System;
using System.Collections.Generic;
class C
{
public IEnumerable<int> F()
{
dynamic <N:0>x = 1</N:0>;
yield return 1;
Console.WriteLine((int)x + <<VALUE>>);
}
}
";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
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 baselineIL0 = @"
{
// Code size 147 (0x93)
.maxstack 3
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
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_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_003c
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<F>d__0.<>1__state""
IL_001f: nop
IL_0020: ldarg.0
IL_0021: ldc.i4.1
IL_0022: box ""int""
IL_0027: stfld ""dynamic C.<F>d__0.<x>5__1""
IL_002c: ldarg.0
IL_002d: ldc.i4.1
IL_002e: stfld ""int C.<F>d__0.<>2__current""
IL_0033: ldarg.0
IL_0034: ldc.i4.1
IL_0035: stfld ""int C.<F>d__0.<>1__state""
IL_003a: ldc.i4.1
IL_003b: ret
IL_003c: ldarg.0
IL_003d: ldc.i4.m1
IL_003e: stfld ""int C.<F>d__0.<>1__state""
IL_0043: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_0048: brfalse.s IL_004c
IL_004a: br.s IL_0071
IL_004c: ldc.i4.s 16
IL_004e: ldtoken ""int""
IL_0053: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0058: ldtoken ""C""
IL_005d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0062: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_0067: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_006c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_0071: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_0076: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target""
IL_007b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_0080: ldarg.0
IL_0081: ldfld ""dynamic C.<F>d__0.<x>5__1""
IL_0086: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_008b: call ""void System.Console.WriteLine(int)""
IL_0090: nop
IL_0091: ldc.i4.0
IL_0092: ret
}";
v0.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL0);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var baselineIL = @"
{
// Code size 149 (0x95)
.maxstack 3
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
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_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_003c
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<F>d__0.<>1__state""
IL_001f: nop
IL_0020: ldarg.0
IL_0021: ldc.i4.1
IL_0022: box ""int""
IL_0027: stfld ""dynamic C.<F>d__0.<x>5__1""
IL_002c: ldarg.0
IL_002d: ldc.i4.1
IL_002e: stfld ""int C.<F>d__0.<>2__current""
IL_0033: ldarg.0
IL_0034: ldc.i4.1
IL_0035: stfld ""int C.<F>d__0.<>1__state""
IL_003a: ldc.i4.1
IL_003b: ret
IL_003c: ldarg.0
IL_003d: ldc.i4.m1
IL_003e: stfld ""int C.<F>d__0.<>1__state""
IL_0043: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<<DYNAMIC_CONTAINER_NAME>>.<>p__0""
IL_0048: brfalse.s IL_004c
IL_004a: br.s IL_0071
IL_004c: ldc.i4.s 16
IL_004e: ldtoken ""int""
IL_0053: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0058: ldtoken ""C""
IL_005d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0062: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_0067: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_006c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<<DYNAMIC_CONTAINER_NAME>>.<>p__0""
IL_0071: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<<DYNAMIC_CONTAINER_NAME>>.<>p__0""
IL_0076: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target""
IL_007b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<<DYNAMIC_CONTAINER_NAME>>.<>p__0""
IL_0080: ldarg.0
IL_0081: ldfld ""dynamic C.<F>d__0.<x>5__1""
IL_0086: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_008b: ldc.i4.<<VALUE>>
IL_008c: add
IL_008d: call ""void System.Console.WriteLine(int)""
IL_0092: nop
IL_0093: ldc.i4.0
IL_0094: ret
}";
diff1.VerifySynthesizedMembers(
"C: {<>o__0#1, <F>d__0}",
"C.<>o__0#1: {<>p__0}",
"C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}");
diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "1").Replace("<<DYNAMIC_CONTAINER_NAME>>", "<>o__0#1"));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<>o__0#2, <F>d__0, <>o__0#1}",
"C.<>o__0#1: {<>p__0}",
"C.<>o__0#2: {<>p__0}",
"C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}");
diff2.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "2").Replace("<<DYNAMIC_CONTAINER_NAME>>", "<>o__0#2"));
}
[Fact]
public void HoistedVariables_Dynamic2()
{
var source0 = MarkedSource(@"
using System;
using System.Collections.Generic;
class C
{
private static IEnumerable<string> F()
{
dynamic <N:0>d = ""x""</N:0>;
yield return d;
Console.WriteLine(0);
}
}
");
var source1 = MarkedSource(@"
using System;
using System.Collections.Generic;
class C
{
private static IEnumerable<string> F()
{
dynamic <N:0>d = ""x""</N:0>;
yield return d.ToString();
Console.WriteLine(1);
}
}
");
var source2 = MarkedSource(@"
using System;
using System.Collections.Generic;
class C
{
private static IEnumerable<string> F()
{
dynamic <N:0>d = ""x""</N:0>;
yield return d;
Console.WriteLine(2);
}
}
");
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation0.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
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)));
diff1.VerifySynthesizedMembers(
"C: {<>o__0#1, <F>d__0}",
"C.<>o__0#1: {<>p__0, <>p__1}",
"C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <d>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.String>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.String>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.String>.Current, System.Collections.IEnumerator.Current}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<>o__0#2, <F>d__0, <>o__0#1}",
"C.<>o__0#1: {<>p__0, <>p__1}",
"C.<>o__0#2: {<>p__0}",
"C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <d>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.String>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.String>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.String>.Current, System.Collections.IEnumerator.Current}");
}
[Fact]
public void Awaiters1()
{
var source0 = @"
using System.Threading.Tasks;
class C
{
static Task<bool> A1() => null;
static Task<int> A2() => null;
static Task<double> A3() => null;
static async Task<int> F()
{
await A1();
await A2();
return 1;
}
static async Task<int> G()
{
await A2();
await A1();
return 1;
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
CompileAndVerify(compilation0, symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state: int",
"<>t__builder: System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>",
"<>u__1: System.Runtime.CompilerServices.TaskAwaiter<bool>",
"<>u__2: System.Runtime.CompilerServices.TaskAwaiter<int>"
}, module.GetFieldNamesAndTypes("C.<F>d__3"));
Assert.Equal(new[]
{
"<>1__state: int",
"<>t__builder: System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>",
"<>u__1: System.Runtime.CompilerServices.TaskAwaiter<int>",
"<>u__2: System.Runtime.CompilerServices.TaskAwaiter<bool>"
}, module.GetFieldNamesAndTypes("C.<G>d__4"));
});
}
[Fact]
public void Awaiters_MultipleGenerations()
{
var source0 = @"
using System.Threading.Tasks;
class C
{
static Task<bool> A1() => null;
static Task<int> A2() => null;
static Task<C> A3() => null;
static async Task<int> F() // testing type changes G0 -> G1, G1 -> G2
{
await A1();
await A2();
return 1;
}
static async Task<int> G() // testing G1 -> G3
{
await A1();
return 1;
}
static async Task<int> H() // testing G0 -> G3
{
await A1();
return 1;
}
}";
var source1 = @"
using System.Threading.Tasks;
class C
{
static Task<bool> A1() => null;
static Task<int> A2() => null;
static Task<C> A3() => null;
static async Task<int> F() // updated
{
await A3();
await A2();
return 1;
}
static async Task<int> G() // updated
{
await A1();
return 2;
}
static async Task<int> H()
{
await A1();
return 1;
}
}";
var source2 = @"
using System.Threading.Tasks;
class C
{
static Task<bool> A1() => null;
static Task<int> A2() => null;
static Task<C> A3() => null;
static async Task<int> F() // updated
{
await A1();
await A3();
return 1;
}
static async Task<int> G()
{
await A1();
return 2;
}
static async Task<int> H()
{
await A1();
return 1;
}
}";
var source3 = @"
using System.Threading.Tasks;
class C
{
static Task<bool> A1() => null;
static Task<int> A2() => null;
static Task<C> A3() => null;
static async Task<int> F()
{
await A1();
await A3();
return 1;
}
static async Task<int> G() // updated
{
await A3();
return 1;
}
static async Task<int> H() // updated
{
await A3();
return 1;
}
}";
// Rude edit but the compiler should handle it.
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 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 g0 = compilation0.GetMember<MethodSymbol>("C.G");
var g1 = compilation1.GetMember<MethodSymbol>("C.G");
var g2 = compilation2.GetMember<MethodSymbol>("C.G");
var g3 = compilation3.GetMember<MethodSymbol>("C.G");
var h0 = compilation0.GetMember<MethodSymbol>("C.H");
var h1 = compilation1.GetMember<MethodSymbol>("C.H");
var h2 = compilation2.GetMember<MethodSymbol>("C.H");
var h3 = compilation3.GetMember<MethodSymbol>("C.H");
var v0 = CompileAndVerify(compilation0, symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state: int",
"<>t__builder: System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>",
"<>u__1: System.Runtime.CompilerServices.TaskAwaiter<bool>",
"<>u__2: System.Runtime.CompilerServices.TaskAwaiter<int>"
}, module.GetFieldNamesAndTypes("C.<F>d__3"));
});
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapByKind(f0, SyntaxKind.Block), preserveLocalVariables: true),
SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapByKind(g0, SyntaxKind.Block), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<F>d__3, <G>d__4}",
"C.<F>d__3: {<>1__state, <>t__builder, <>u__3, <>u__2, MoveNext, SetStateMachine}",
"C.<G>d__4: {<>1__state, <>t__builder, <>u__1, MoveNext, SetStateMachine}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapByKind(f1, SyntaxKind.Block), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<F>d__3, <G>d__4}",
"C.<F>d__3: {<>1__state, <>t__builder, <>u__4, <>u__3, MoveNext, SetStateMachine, <>u__2}",
"C.<G>d__4: {<>1__state, <>t__builder, <>u__1, MoveNext, SetStateMachine}");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, g2, g3, GetSyntaxMapByKind(g2, SyntaxKind.Block), preserveLocalVariables: true),
SemanticEdit.Create(SemanticEditKind.Update, h2, h3, GetSyntaxMapByKind(h2, SyntaxKind.Block), preserveLocalVariables: true)));
diff3.VerifySynthesizedMembers(
"C: {<G>d__4, <H>d__5, <F>d__3}",
"C.<G>d__4: {<>1__state, <>t__builder, <>u__2, MoveNext, SetStateMachine, <>u__1}",
"C.<H>d__5: {<>1__state, <>t__builder, <>u__2, MoveNext, SetStateMachine}",
"C.<F>d__3: {<>1__state, <>t__builder, <>u__4, <>u__3, MoveNext, SetStateMachine, <>u__2}");
// Verify delta metadata contains expected rows.
var md1 = diff1.GetMetadata();
var md2 = diff2.GetMetadata();
var md3 = diff3.GetMetadata();
// 1 field def added & 4 methods updated (MoveNext and kickoff for F and G)
CheckEncLogDefinitions(md1.Reader,
Row(7, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(8, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(9, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(10, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(11, TableIndex.Field, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
// Note that the new awaiter is allocated slot <>u__3 since <>u__1 and <>u__2 are taken.
diff1.VerifyIL("C.<F>d__3.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @"
{
// Code size 268 (0x10c)
.maxstack 3
.locals init (int V_0,
int V_1,
System.Runtime.CompilerServices.TaskAwaiter<C> V_2,
C.<F>d__3 V_3,
System.Runtime.CompilerServices.TaskAwaiter<int> V_4,
System.Exception V_5)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__3.<>1__state""
IL_0006: stloc.0
.try
{
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_0055
IL_0014: br IL_00b3
IL_0019: nop
IL_001a: call ""System.Threading.Tasks.Task<C> C.A3()""
IL_001f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<C> System.Threading.Tasks.Task<C>.GetAwaiter()""
IL_0024: stloc.2
IL_0025: ldloca.s V_2
IL_0027: call ""bool System.Runtime.CompilerServices.TaskAwaiter<C>.IsCompleted.get""
IL_002c: brtrue.s IL_0071
IL_002e: ldarg.0
IL_002f: ldc.i4.0
IL_0030: dup
IL_0031: stloc.0
IL_0032: stfld ""int C.<F>d__3.<>1__state""
IL_0037: ldarg.0
IL_0038: ldloc.2
IL_0039: stfld ""System.Runtime.CompilerServices.TaskAwaiter<C> C.<F>d__3.<>u__3""
IL_003e: ldarg.0
IL_003f: stloc.3
IL_0040: ldarg.0
IL_0041: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder""
IL_0046: ldloca.s V_2
IL_0048: ldloca.s V_3
IL_004a: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<C>, C.<F>d__3>(ref System.Runtime.CompilerServices.TaskAwaiter<C>, ref C.<F>d__3)""
IL_004f: nop
IL_0050: leave IL_010b
IL_0055: ldarg.0
IL_0056: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<C> C.<F>d__3.<>u__3""
IL_005b: stloc.2
IL_005c: ldarg.0
IL_005d: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<C> C.<F>d__3.<>u__3""
IL_0062: initobj ""System.Runtime.CompilerServices.TaskAwaiter<C>""
IL_0068: ldarg.0
IL_0069: ldc.i4.m1
IL_006a: dup
IL_006b: stloc.0
IL_006c: stfld ""int C.<F>d__3.<>1__state""
IL_0071: ldloca.s V_2
IL_0073: call ""C System.Runtime.CompilerServices.TaskAwaiter<C>.GetResult()""
IL_0078: pop
IL_0079: call ""System.Threading.Tasks.Task<int> C.A2()""
IL_007e: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_0083: stloc.s V_4
IL_0085: ldloca.s V_4
IL_0087: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_008c: brtrue.s IL_00d0
IL_008e: ldarg.0
IL_008f: ldc.i4.1
IL_0090: dup
IL_0091: stloc.0
IL_0092: stfld ""int C.<F>d__3.<>1__state""
IL_0097: ldarg.0
IL_0098: ldloc.s V_4
IL_009a: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__3.<>u__2""
IL_009f: ldarg.0
IL_00a0: stloc.3
IL_00a1: ldarg.0
IL_00a2: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder""
IL_00a7: ldloca.s V_4
IL_00a9: ldloca.s V_3
IL_00ab: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, C.<F>d__3>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref C.<F>d__3)""
IL_00b0: nop
IL_00b1: leave.s IL_010b
IL_00b3: ldarg.0
IL_00b4: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__3.<>u__2""
IL_00b9: stloc.s V_4
IL_00bb: ldarg.0
IL_00bc: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__3.<>u__2""
IL_00c1: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_00c7: ldarg.0
IL_00c8: ldc.i4.m1
IL_00c9: dup
IL_00ca: stloc.0
IL_00cb: stfld ""int C.<F>d__3.<>1__state""
IL_00d0: ldloca.s V_4
IL_00d2: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_00d7: pop
IL_00d8: ldc.i4.1
IL_00d9: stloc.1
IL_00da: leave.s IL_00f6
}
catch System.Exception
{
IL_00dc: stloc.s V_5
IL_00de: ldarg.0
IL_00df: ldc.i4.s -2
IL_00e1: stfld ""int C.<F>d__3.<>1__state""
IL_00e6: ldarg.0
IL_00e7: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder""
IL_00ec: ldloc.s V_5
IL_00ee: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)""
IL_00f3: nop
IL_00f4: leave.s IL_010b
}
IL_00f6: ldarg.0
IL_00f7: ldc.i4.s -2
IL_00f9: stfld ""int C.<F>d__3.<>1__state""
IL_00fe: ldarg.0
IL_00ff: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder""
IL_0104: ldloc.1
IL_0105: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)""
IL_010a: nop
IL_010b: ret
}");
// 1 field def added & 2 methods updated
CheckEncLogDefinitions(md2.Reader,
Row(11, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(12, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(12, TableIndex.Field, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
// Note that the new awaiters are allocated slots <>u__4, <>u__5.
diff2.VerifyIL("C.<F>d__3.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @"
{
// Code size 268 (0x10c)
.maxstack 3
.locals init (int V_0,
int V_1,
System.Runtime.CompilerServices.TaskAwaiter<bool> V_2,
C.<F>d__3 V_3,
System.Runtime.CompilerServices.TaskAwaiter<C> V_4,
System.Exception V_5)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__3.<>1__state""
IL_0006: stloc.0
.try
{
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_0055
IL_0014: br IL_00b3
IL_0019: nop
IL_001a: call ""System.Threading.Tasks.Task<bool> C.A1()""
IL_001f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<bool> System.Threading.Tasks.Task<bool>.GetAwaiter()""
IL_0024: stloc.2
IL_0025: ldloca.s V_2
IL_0027: call ""bool System.Runtime.CompilerServices.TaskAwaiter<bool>.IsCompleted.get""
IL_002c: brtrue.s IL_0071
IL_002e: ldarg.0
IL_002f: ldc.i4.0
IL_0030: dup
IL_0031: stloc.0
IL_0032: stfld ""int C.<F>d__3.<>1__state""
IL_0037: ldarg.0
IL_0038: ldloc.2
IL_0039: stfld ""System.Runtime.CompilerServices.TaskAwaiter<bool> C.<F>d__3.<>u__4""
IL_003e: ldarg.0
IL_003f: stloc.3
IL_0040: ldarg.0
IL_0041: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder""
IL_0046: ldloca.s V_2
IL_0048: ldloca.s V_3
IL_004a: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<bool>, C.<F>d__3>(ref System.Runtime.CompilerServices.TaskAwaiter<bool>, ref C.<F>d__3)""
IL_004f: nop
IL_0050: leave IL_010b
IL_0055: ldarg.0
IL_0056: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<bool> C.<F>d__3.<>u__4""
IL_005b: stloc.2
IL_005c: ldarg.0
IL_005d: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<bool> C.<F>d__3.<>u__4""
IL_0062: initobj ""System.Runtime.CompilerServices.TaskAwaiter<bool>""
IL_0068: ldarg.0
IL_0069: ldc.i4.m1
IL_006a: dup
IL_006b: stloc.0
IL_006c: stfld ""int C.<F>d__3.<>1__state""
IL_0071: ldloca.s V_2
IL_0073: call ""bool System.Runtime.CompilerServices.TaskAwaiter<bool>.GetResult()""
IL_0078: pop
IL_0079: call ""System.Threading.Tasks.Task<C> C.A3()""
IL_007e: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<C> System.Threading.Tasks.Task<C>.GetAwaiter()""
IL_0083: stloc.s V_4
IL_0085: ldloca.s V_4
IL_0087: call ""bool System.Runtime.CompilerServices.TaskAwaiter<C>.IsCompleted.get""
IL_008c: brtrue.s IL_00d0
IL_008e: ldarg.0
IL_008f: ldc.i4.1
IL_0090: dup
IL_0091: stloc.0
IL_0092: stfld ""int C.<F>d__3.<>1__state""
IL_0097: ldarg.0
IL_0098: ldloc.s V_4
IL_009a: stfld ""System.Runtime.CompilerServices.TaskAwaiter<C> C.<F>d__3.<>u__3""
IL_009f: ldarg.0
IL_00a0: stloc.3
IL_00a1: ldarg.0
IL_00a2: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder""
IL_00a7: ldloca.s V_4
IL_00a9: ldloca.s V_3
IL_00ab: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<C>, C.<F>d__3>(ref System.Runtime.CompilerServices.TaskAwaiter<C>, ref C.<F>d__3)""
IL_00b0: nop
IL_00b1: leave.s IL_010b
IL_00b3: ldarg.0
IL_00b4: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<C> C.<F>d__3.<>u__3""
IL_00b9: stloc.s V_4
IL_00bb: ldarg.0
IL_00bc: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<C> C.<F>d__3.<>u__3""
IL_00c1: initobj ""System.Runtime.CompilerServices.TaskAwaiter<C>""
IL_00c7: ldarg.0
IL_00c8: ldc.i4.m1
IL_00c9: dup
IL_00ca: stloc.0
IL_00cb: stfld ""int C.<F>d__3.<>1__state""
IL_00d0: ldloca.s V_4
IL_00d2: call ""C System.Runtime.CompilerServices.TaskAwaiter<C>.GetResult()""
IL_00d7: pop
IL_00d8: ldc.i4.1
IL_00d9: stloc.1
IL_00da: leave.s IL_00f6
}
catch System.Exception
{
IL_00dc: stloc.s V_5
IL_00de: ldarg.0
IL_00df: ldc.i4.s -2
IL_00e1: stfld ""int C.<F>d__3.<>1__state""
IL_00e6: ldarg.0
IL_00e7: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder""
IL_00ec: ldloc.s V_5
IL_00ee: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)""
IL_00f3: nop
IL_00f4: leave.s IL_010b
}
IL_00f6: ldarg.0
IL_00f7: ldc.i4.s -2
IL_00f9: stfld ""int C.<F>d__3.<>1__state""
IL_00fe: ldarg.0
IL_00ff: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder""
IL_0104: ldloc.1
IL_0105: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)""
IL_010a: nop
IL_010b: ret
}");
// 2 field defs added - G and H awaiters & 4 methods updated: G, H kickoff and MoveNext
CheckEncLogDefinitions(md3.Reader,
Row(13, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(14, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(15, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(16, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(13, TableIndex.Field, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(14, TableIndex.Field, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(15, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void SynthesizedMembersMerging()
{
var source0 = @"
using System.Collections.Generic;
public class C
{
}";
var source1 = @"
using System.Collections.Generic;
public class C
{
public static IEnumerable<int> F()
{
yield return 1;
yield return 2;
}
}";
var source2 = @"
using System.Collections.Generic;
public class C
{
public static IEnumerable<int> F()
{
yield return 1;
yield return 3;
}
}";
var source3 = @"
using System.Collections.Generic;
public class C
{
public static IEnumerable<int> F()
{
yield return 1;
yield return 3;
}
public static void G()
{
System.Console.WriteLine(1);
}
}";
var source4 = @"
using System.Collections.Generic;
public class C
{
public static IEnumerable<int> F()
{
yield return 1;
yield return 3;
}
public static void G()
{
System.Console.WriteLine(1);
}
public static IEnumerable<int> H()
{
yield return 1;
}
}";
// Rude edit but the compiler should handle it.
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 compilation4 = compilation3.WithSource(source4);
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var f3 = compilation3.GetMember<MethodSymbol>("C.F");
var g3 = compilation3.GetMember<MethodSymbol>("C.G");
var h4 = compilation4.GetMember<MethodSymbol>("C.H");
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)));
diff1.VerifySynthesizedMembers(
"C: {<F>d__0#1}",
"C.<F>d__0#1: {<>1__state, <>2__current, <>l__initialThreadId, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapByKind(f1, SyntaxKind.Block), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<F>d__0#1}",
"C.<F>d__0#1: {<>1__state, <>2__current, <>l__initialThreadId, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, g3)));
diff3.VerifySynthesizedMembers(
"C: {<F>d__0#1}",
"C.<F>d__0#1: {<>1__state, <>2__current, <>l__initialThreadId, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}");
var diff4 = compilation4.EmitDifference(
diff3.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, h4)));
diff4.VerifySynthesizedMembers(
"C: {<H>d__2#4, <F>d__0#1}",
"C.<F>d__0#1: {<>1__state, <>2__current, <>l__initialThreadId, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}",
"C.<H>d__2#4: {<>1__state, <>2__current, <>l__initialThreadId, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}");
}
[Fact]
public void UniqueSynthesizedNames()
{
var source0 = @"
using System.Collections.Generic;
public class C
{
public static IEnumerable<int> F() { yield return 1; }
}";
var source1 = @"
using System.Collections.Generic;
public class C
{
public static IEnumerable<int> F(int a) { yield return 2; }
public static IEnumerable<int> F() { yield return 1; }
}";
var source2 = @"
using System.Collections.Generic;
public class C
{
public static IEnumerable<int> F(int a) { yield return 2; }
public static IEnumerable<int> F(byte a) { yield return 3; }
public static IEnumerable<int> F() { yield return 1; }
}";
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 generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f_int1)));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f_byte2)));
var reader0 = md0.MetadataReader;
var reader1 = diff1.GetMetadata().Reader;
var reader2 = diff2.GetMetadata().Reader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<F>d__0");
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<F>d__0#1");
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<F>d__1#2");
}
[Fact]
public void UpdateAsyncLambda()
{
var source0 = MarkedSource(
@"using System;
using System.Threading.Tasks;
class C
{
static void F()
{
Func<Task> <N:0>g1 = <N:1>async () =>
{
await A1();
await A2();
}</N:1></N:0>;
}
static Task<bool> A1() => null;
static Task<int> A2() => null;
static Task<double> A3() => null;
}");
var source1 = MarkedSource(
@"using System;
using System.Threading.Tasks;
class C
{
static int G() => 1;
static void F()
{
Func<Task> <N:0>g1 = <N:1>async () =>
{
await A2();
await A1();
}</N:1></N:0>;
}
static Task<bool> A1() => null;
static Task<int> A2() => null;
static Task<double> A3() => null;
}");
var source2 = MarkedSource(
@"using System;
using System.Threading.Tasks;
class C
{
static int G() => 1;
static void F()
{
Func<Task> <N:0>g1 = <N:1>async () =>
{
await A1();
await A2();
}</N:1></N:0>;
}
static Task<bool> A1() => null;
static Task<int> A2() => null;
static Task<double> A3() => null;
}");
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0, symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state: int",
"<>t__builder: System.Runtime.CompilerServices.AsyncTaskMethodBuilder",
"<>4__this: C.<>c",
"<>u__1: System.Runtime.CompilerServices.TaskAwaiter<bool>",
"<>u__2: System.Runtime.CompilerServices.TaskAwaiter<int>"
}, module.GetFieldNamesAndTypes("C.<>c.<<F>b__0_0>d"));
});
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// note that the types of the awaiter fields <>u__1, <>u__2 are the same as in the previous generation:
diff1.VerifySynthesizedFields("C.<>c.<<F>b__0_0>d",
"<>1__state: int",
"<>t__builder: System.Runtime.CompilerServices.AsyncTaskMethodBuilder",
"<>4__this: C.<>c",
"<>u__1: System.Runtime.CompilerServices.TaskAwaiter<bool>",
"<>u__2: System.Runtime.CompilerServices.TaskAwaiter<int>");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
// note that the types of the awaiter fields <>u__1, <>u__2 are the same as in the previous generation:
diff2.VerifySynthesizedFields("C.<>c.<<F>b__0_0>d",
"<>1__state: int",
"<>t__builder: System.Runtime.CompilerServices.AsyncTaskMethodBuilder",
"<>4__this: C.<>c",
"<>u__1: System.Runtime.CompilerServices.TaskAwaiter<bool>",
"<>u__2: System.Runtime.CompilerServices.TaskAwaiter<int>");
}
[Fact, WorkItem(1170899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1170899")]
public void HoistedAnonymousTypes1()
{
var source0 = MarkedSource(@"
using System;
using System.Collections.Generic;
class C
{
public IEnumerable<int> F()
{
var <N:0>x = new { A = 1 }</N:0>;
yield return 1;
Console.WriteLine(x.A + 1);
}
}
");
var source1 = MarkedSource(@"
using System;
using System.Collections.Generic;
class C
{
public IEnumerable<int> F()
{
var <N:0>x = new { A = 1 }</N:0>;
yield return 1;
Console.WriteLine(x.A + 2);
}
}
");
var source2 = MarkedSource(@"
using System;
using System.Collections.Generic;
class C
{
public IEnumerable<int> F()
{
var <N:0>x = new { A = 1 }</N:0>;
yield return 1;
Console.WriteLine(x.A + 3);
}
}
");
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
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 baselineIL = @"
{
// Code size 88 (0x58)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
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_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_003c
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<F>d__0.<>1__state""
IL_001f: nop
IL_0020: ldarg.0
IL_0021: ldc.i4.1
IL_0022: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0027: stfld ""<anonymous type: int A> C.<F>d__0.<x>5__1""
IL_002c: ldarg.0
IL_002d: ldc.i4.1
IL_002e: stfld ""int C.<F>d__0.<>2__current""
IL_0033: ldarg.0
IL_0034: ldc.i4.1
IL_0035: stfld ""int C.<F>d__0.<>1__state""
IL_003a: ldc.i4.1
IL_003b: ret
IL_003c: ldarg.0
IL_003d: ldc.i4.m1
IL_003e: stfld ""int C.<F>d__0.<>1__state""
IL_0043: ldarg.0
IL_0044: ldfld ""<anonymous type: int A> C.<F>d__0.<x>5__1""
IL_0049: callvirt ""int <>f__AnonymousType0<int>.A.get""
IL_004e: ldc.i4.<<VALUE>>
IL_004f: add
IL_0050: call ""void System.Console.WriteLine(int)""
IL_0055: nop
IL_0056: ldc.i4.0
IL_0057: ret
}";
v0.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "1"));
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyUpdatedTypes("0x02000003", "0x02000004");
diff1.VerifySynthesizedMembers(
"C: {<F>d__0}",
"C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "2"));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifyUpdatedTypes("0x02000003", "0x02000004");
diff2.VerifySynthesizedMembers(
"C: {<F>d__0}",
"C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "3"));
}
[Fact, WorkItem(3192, "https://github.com/dotnet/roslyn/issues/3192")]
public void HoistedAnonymousTypes_Nested()
{
var source0 = MarkedSource(@"
using System;
using System.Collections.Generic;
class C
{
public IEnumerable<int> F()
{
var <N:0>x = new[] { new { A = new { B = 1 } } }</N:0>;
yield return 1;
Console.WriteLine(x[0].A.B + 1);
}
}
");
var source1 = MarkedSource(@"
using System;
using System.Collections.Generic;
class C
{
public IEnumerable<int> F()
{
var <N:0>x = new[] { new { A = new { B = 1 } } }</N:0>;
yield return 1;
Console.WriteLine(x[0].A.B + 2);
}
}
");
var source2 = MarkedSource(@"
using System;
using System.Collections.Generic;
class C
{
public IEnumerable<int> F()
{
var <N:0>x = new[] { new { A = new { B = 1 } } }</N:0>;
yield return 1;
Console.WriteLine(x[0].A.B + 3);
}
}
");
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
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 baselineIL = @"
{
// Code size 109 (0x6d)
.maxstack 5
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
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_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_004a
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<F>d__0.<>1__state""
IL_001f: nop
IL_0020: ldarg.0
IL_0021: ldc.i4.1
IL_0022: newarr ""<>f__AnonymousType0<<anonymous type: int B>>""
IL_0027: dup
IL_0028: ldc.i4.0
IL_0029: ldc.i4.1
IL_002a: newobj ""<>f__AnonymousType1<int>..ctor(int)""
IL_002f: newobj ""<>f__AnonymousType0<<anonymous type: int B>>..ctor(<anonymous type: int B>)""
IL_0034: stelem.ref
IL_0035: stfld ""<anonymous type: <anonymous type: int B> A>[] C.<F>d__0.<x>5__1""
IL_003a: ldarg.0
IL_003b: ldc.i4.1
IL_003c: stfld ""int C.<F>d__0.<>2__current""
IL_0041: ldarg.0
IL_0042: ldc.i4.1
IL_0043: stfld ""int C.<F>d__0.<>1__state""
IL_0048: ldc.i4.1
IL_0049: ret
IL_004a: ldarg.0
IL_004b: ldc.i4.m1
IL_004c: stfld ""int C.<F>d__0.<>1__state""
IL_0051: ldarg.0
IL_0052: ldfld ""<anonymous type: <anonymous type: int B> A>[] C.<F>d__0.<x>5__1""
IL_0057: ldc.i4.0
IL_0058: ldelem.ref
IL_0059: callvirt ""<anonymous type: int B> <>f__AnonymousType0<<anonymous type: int B>>.A.get""
IL_005e: callvirt ""int <>f__AnonymousType1<int>.B.get""
IL_0063: ldc.i4.<<VALUE>>
IL_0064: add
IL_0065: call ""void System.Console.WriteLine(int)""
IL_006a: nop
IL_006b: ldc.i4.0
IL_006c: ret
}";
v0.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "1"));
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<F>d__0}",
"C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<B>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "2"));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<F>d__0}",
"C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<B>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "3"));
}
[Fact, WorkItem(3192, "https://github.com/dotnet/roslyn/issues/3192")]
public void HoistedGenericTypes()
{
var source0 = MarkedSource(@"
using System;
using System.Collections.Generic;
class Z<T1>
{
public class S<T2> { public T1 a = default(T1); public T2 b = default(T2); }
}
class C
{
public IEnumerable<int> F()
{
var <N:0>x = new Z<double>.S<int>()</N:0>;
yield return 1;
Console.WriteLine(x.a + x.b + 1);
}
}
");
var source1 = MarkedSource(@"
using System;
using System.Collections.Generic;
class Z<T1>
{
public class S<T2> { public T1 a = default(T1); public T2 b = default(T2); }
}
class C
{
public IEnumerable<int> F()
{
var <N:0>x = new Z<double>.S<int>()</N:0>;
yield return 1;
Console.WriteLine(x.a + x.b + 2);
}
}
");
var source2 = MarkedSource(@"
using System;
using System.Collections.Generic;
class Z<T1>
{
public class S<T2> { public T1 a = default(T1); public T2 b = default(T2); }
}
class C
{
public IEnumerable<int> F()
{
var <N:0>x = new Z<double>.S<int>()</N:0>;
yield return 1;
Console.WriteLine(x.a + x.b + 3);
}
}
");
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
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 baselineIL = @"
{
// Code size 108 (0x6c)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
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_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_003b
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<F>d__0.<>1__state""
IL_001f: nop
IL_0020: ldarg.0
IL_0021: newobj ""Z<double>.S<int>..ctor()""
IL_0026: stfld ""Z<double>.S<int> C.<F>d__0.<x>5__1""
IL_002b: ldarg.0
IL_002c: ldc.i4.1
IL_002d: stfld ""int C.<F>d__0.<>2__current""
IL_0032: ldarg.0
IL_0033: ldc.i4.1
IL_0034: stfld ""int C.<F>d__0.<>1__state""
IL_0039: ldc.i4.1
IL_003a: ret
IL_003b: ldarg.0
IL_003c: ldc.i4.m1
IL_003d: stfld ""int C.<F>d__0.<>1__state""
IL_0042: ldarg.0
IL_0043: ldfld ""Z<double>.S<int> C.<F>d__0.<x>5__1""
IL_0048: ldfld ""double Z<double>.S<int>.a""
IL_004d: ldarg.0
IL_004e: ldfld ""Z<double>.S<int> C.<F>d__0.<x>5__1""
IL_0053: ldfld ""int Z<double>.S<int>.b""
IL_0058: conv.r8
IL_0059: add
IL_005a: ldc.r8 <<VALUE>>
IL_0063: add
IL_0064: call ""void System.Console.WriteLine(double)""
IL_0069: nop
IL_006a: ldc.i4.0
IL_006b: ret
}";
v0.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "1"));
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<F>d__0}",
"C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}");
diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "2"));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<F>d__0}",
"C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}");
diff2.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "3"));
}
[Fact]
public void HoistedAnonymousTypes_Dynamic()
{
var template = @"
using System;
using System.Collections.Generic;
class C
{
public IEnumerable<int> F()
{
var <N:0>x = new { A = (dynamic)null, B = 1 }</N:0>;
yield return 1;
Console.WriteLine(x.B + <<VALUE>>);
}
}
";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
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 baselineIL0 = @"
{
// Code size 87 (0x57)
.maxstack 3
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
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_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_003d
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<F>d__0.<>1__state""
IL_001f: nop
IL_0020: ldarg.0
IL_0021: ldnull
IL_0022: ldc.i4.1
IL_0023: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)""
IL_0028: stfld ""<anonymous type: dynamic A, int B> C.<F>d__0.<x>5__1""
IL_002d: ldarg.0
IL_002e: ldc.i4.1
IL_002f: stfld ""int C.<F>d__0.<>2__current""
IL_0034: ldarg.0
IL_0035: ldc.i4.1
IL_0036: stfld ""int C.<F>d__0.<>1__state""
IL_003b: ldc.i4.1
IL_003c: ret
IL_003d: ldarg.0
IL_003e: ldc.i4.m1
IL_003f: stfld ""int C.<F>d__0.<>1__state""
IL_0044: ldarg.0
IL_0045: ldfld ""<anonymous type: dynamic A, int B> C.<F>d__0.<x>5__1""
IL_004a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get""
IL_004f: call ""void System.Console.WriteLine(int)""
IL_0054: nop
IL_0055: ldc.i4.0
IL_0056: ret
}";
v0.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL0);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var baselineIL = @"
{
// Code size 89 (0x59)
.maxstack 3
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
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_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_003d
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<F>d__0.<>1__state""
IL_001f: nop
IL_0020: ldarg.0
IL_0021: ldnull
IL_0022: ldc.i4.1
IL_0023: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)""
IL_0028: stfld ""<anonymous type: dynamic A, int B> C.<F>d__0.<x>5__1""
IL_002d: ldarg.0
IL_002e: ldc.i4.1
IL_002f: stfld ""int C.<F>d__0.<>2__current""
IL_0034: ldarg.0
IL_0035: ldc.i4.1
IL_0036: stfld ""int C.<F>d__0.<>1__state""
IL_003b: ldc.i4.1
IL_003c: ret
IL_003d: ldarg.0
IL_003e: ldc.i4.m1
IL_003f: stfld ""int C.<F>d__0.<>1__state""
IL_0044: ldarg.0
IL_0045: ldfld ""<anonymous type: dynamic A, int B> C.<F>d__0.<x>5__1""
IL_004a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get""
IL_004f: ldc.i4.<<VALUE>>
IL_0050: add
IL_0051: call ""void System.Console.WriteLine(int)""
IL_0056: nop
IL_0057: ldc.i4.0
IL_0058: ret
}";
diff1.VerifySynthesizedMembers(
"C: {<F>d__0}",
"C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}",
"<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.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: {<F>d__0}",
"C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}",
"<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "2"));
}
[Fact, WorkItem(3192, "https://github.com/dotnet/roslyn/issues/3192")]
public void HoistedAnonymousTypes_Delete()
{
var source0 = MarkedSource(@"
using System.Linq;
using System.Threading.Tasks;
class C
{
static async Task<int> F()
{
var <N:1>x = from b in new[] { 1, 2, 3 } <N:0>select new { A = b }</N:0></N:1>;
return <N:2>await Task.FromResult(1)</N:2>;
}
}
");
var source1 = MarkedSource(@"
using System.Linq;
using System.Threading.Tasks;
class C
{
static async Task<int> F()
{
var <N:1>x = from b in new[] { 1, 2, 3 } <N:0>select new { A = b }</N:0></N:1>;
var y = x.First();
return <N:2>await Task.FromResult(1)</N:2>;
}
}
");
var source2 = source0;
var source3 = source1;
var source4 = source0;
var source5 = source1;
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation0.WithSource(source2.Tree);
var compilation3 = compilation0.WithSource(source3.Tree);
var compilation4 = compilation0.WithSource(source4.Tree);
var compilation5 = compilation0.WithSource(source5.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 f4 = compilation4.GetMember<MethodSymbol>("C.F");
var f5 = compilation5.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
// y is added
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<>c, <F>d__0}",
"C.<>c: {<>9__0_0, <F>b__0_0}",
"C.<F>d__0: {<>1__state, <>t__builder, <x>5__1, <y>5__3, <>s__2, <>u__1, MoveNext, SetStateMachine}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
// y is removed
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
// Synthesized members collection still includes y field since members are only added to it and never deleted.
// The corresponding CLR field is also present.
diff2.VerifySynthesizedMembers(
"C: {<>c, <F>d__0}",
"C.<>c: {<>9__0_0, <F>b__0_0}",
"C.<F>d__0: {<>1__state, <>t__builder, <x>5__1, <>s__2, <>u__1, MoveNext, SetStateMachine, <y>5__3}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
// y is added and a new slot index is allocated for it
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f2, f3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables: true)));
diff3.VerifySynthesizedMembers(
"C: {<>c, <F>d__0}",
"C.<>c: {<>9__0_0, <F>b__0_0}",
"C.<F>d__0: {<>1__state, <>t__builder, <x>5__1, <y>5__4, <>s__2, <>u__1, MoveNext, SetStateMachine, <y>5__3}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
// y is removed
var diff4 = compilation4.EmitDifference(
diff3.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f3, f4, GetSyntaxMapFromMarkers(source3, source4), preserveLocalVariables: true)));
diff4.VerifySynthesizedMembers(
"C: {<>c, <F>d__0}",
"C.<>c: {<>9__0_0, <F>b__0_0}",
"C.<F>d__0: {<>1__state, <>t__builder, <x>5__1, <>s__2, <>u__1, MoveNext, SetStateMachine, <y>5__4, <y>5__3}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
// y is added
var diff5 = compilation5.EmitDifference(
diff4.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f4, f5, GetSyntaxMapFromMarkers(source4, source5), preserveLocalVariables: true)));
diff5.VerifySynthesizedMembers(
"C: {<>c, <F>d__0}",
"C.<>c: {<>9__0_0, <F>b__0_0}",
"C.<F>d__0: {<>1__state, <>t__builder, <x>5__1, <y>5__5, <>s__2, <>u__1, MoveNext, SetStateMachine, <y>5__4, <y>5__3}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
}
[Fact]
public void HoistedAnonymousTypes_Dynamic2()
{
var source0 = MarkedSource(@"
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
args = Iterator().ToArray();
}
private static IEnumerable<string> Iterator()
{
string[] <N:15>args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" }</N:15>;
var <N:16>list = false ? null : new { Head = (dynamic)null, Tail = (dynamic)null }</N:16>;
for (int <N:18>i = 0</N:18>; i < 10; i++)
{
var <N:6>result =
from a in args
<N:0>let x = a.Reverse()</N:0>
<N:1>let y = x.Reverse()</N:1>
<N:2>where x.SequenceEqual(y)</N:2>
orderby <N:3>a.Length ascending</N:3>, <N:4>a descending</N:4>
<N:5>select new { Value = a, Length = x.Count() }</N:5></N:6>;
var <N:8>linked = result.Aggregate(
false ? new { Head = (string)null, Tail = (dynamic)null } : null,
<N:7>(total, curr) => new { Head = curr.Value, Tail = (dynamic)total }</N:7>)</N:8>;
while (linked != null)
{
<N:9>yield return linked.Head</N:9>;
linked = linked.Tail;
}
var <N:14>newArgs =
from a in result
<N:10>let value = a.Value</N:10>
<N:11>let length = a.Length</N:11>
<N:12>where value.Length == length</N:12>
<N:13>select value + value</N:13></N:14>;
args = args.Concat(newArgs).ToArray();
list = new { Head = (dynamic)i, Tail = (dynamic)list };
System.Diagnostics.Debugger.Break();
}
System.Diagnostics.Debugger.Break();
}
}
");
var source1 = MarkedSource(@"
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
args = Iterator().ToArray();
}
private static IEnumerable<string> Iterator()
{
string[] <N:15>args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" }</N:15>;
var <N:16>list = false ? null : new { Head = (dynamic)null, Tail = (dynamic)null }</N:16>;
for (int <N:18>i = 0</N:18>; i < 10; i++)
{
var <N:6>result =
from a in args
<N:0>let x = a.Reverse()</N:0>
<N:1>let y = x.Reverse()</N:1>
<N:2>where x.SequenceEqual(y)</N:2>
orderby <N:3>a.Length ascending</N:3>, <N:4>a descending</N:4>
<N:5>select new { Value = a, Length = x.Count() }</N:5></N:6>;
var <N:8>linked = result.Aggregate(
false ? new { Head = (string)null, Tail = (dynamic)null } : null,
<N:7>(total, curr) => new { Head = curr.Value, Tail = (dynamic)total }</N:7>)</N:8>;
var <N:17>temp = list</N:17>;
while (temp != null)
{
<N:9>yield return temp.Head</N:9>;
temp = temp.Tail;
}
var <N:14>newArgs =
from a in result
<N:10>let value = a.Value</N:10>
<N:11>let length = a.Length</N:11>
<N:12>where value.Length == length</N:12>
<N:13>select value + value</N:13></N:14>;
args = args.Concat(newArgs).ToArray();
list = new { Head = (dynamic)i, Tail = (dynamic)list };
System.Diagnostics.Debugger.Break();
}
System.Diagnostics.Debugger.Break();
}
}
");
var source2 = MarkedSource(@"
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
args = Iterator().ToArray();
}
private static IEnumerable<string> Iterator()
{
string[] <N:15>args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" }</N:15>;
var <N:16>list = false ? null : new { Head = (dynamic)null, Tail = (dynamic)null }</N:16>;
for (int <N:18>i = 0</N:18>; i < 10; i++)
{
var <N:6>result =
from a in args
<N:0>let x = a.Reverse()</N:0>
<N:1>let y = x.Reverse()</N:1>
<N:2>where x.SequenceEqual(y)</N:2>
orderby <N:3>a.Length ascending</N:3>, <N:4>a descending</N:4>
<N:5>select new { Value = a, Length = x.Count() }</N:5></N:6>;
var <N:8>linked = result.Aggregate(
false ? new { Head = (string)null, Tail = (dynamic)null } : null,
<N:7>(total, curr) => new { Head = curr.Value, Tail = (dynamic)total }</N:7>)</N:8>;
var <N:17>temp = list</N:17>;
while (temp != null)
{
<N:9>yield return temp.Head.ToString()</N:9>;
temp = temp.Tail;
}
var <N:14>newArgs =
from a in result
<N:10>let value = a.Value</N:10>
<N:11>let length = a.Length</N:11>
<N:12>where value.Length == length</N:12>
<N:13>select value + value</N:13></N:14>;
args = args.Concat(newArgs).ToArray();
list = new { Head = (dynamic)i, Tail = (dynamic)list };
System.Diagnostics.Debugger.Break();
}
System.Diagnostics.Debugger.Break();
}
}
");
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("Program.Iterator");
var f1 = compilation1.GetMember<MethodSymbol>("Program.Iterator");
var f2 = compilation2.GetMember<MethodSymbol>("Program.Iterator");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
v0.VerifyIL("Program.<Iterator>d__1.System.Collections.IEnumerator.MoveNext()", @"
{
// Code size 798 (0x31e)
.maxstack 5
.locals init (int V_0,
bool V_1,
int V_2,
bool V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Iterator>d__1.<>1__state""
IL_0006: stloc.0
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_001b
IL_0014: br IL_019b
IL_0019: ldc.i4.0
IL_001a: ret
IL_001b: ldarg.0
IL_001c: ldc.i4.m1
IL_001d: stfld ""int Program.<Iterator>d__1.<>1__state""
IL_0022: nop
IL_0023: ldarg.0
IL_0024: ldc.i4.4
IL_0025: newarr ""string""
IL_002a: dup
IL_002b: ldc.i4.0
IL_002c: ldstr ""a""
IL_0031: stelem.ref
IL_0032: dup
IL_0033: ldc.i4.1
IL_0034: ldstr ""bB""
IL_0039: stelem.ref
IL_003a: dup
IL_003b: ldc.i4.2
IL_003c: ldstr ""Cc""
IL_0041: stelem.ref
IL_0042: dup
IL_0043: ldc.i4.3
IL_0044: ldstr ""DD""
IL_0049: stelem.ref
IL_004a: stfld ""string[] Program.<Iterator>d__1.<args>5__1""
IL_004f: ldarg.0
IL_0050: ldnull
IL_0051: ldnull
IL_0052: newobj ""<>f__AnonymousType0<dynamic, dynamic>..ctor(dynamic, dynamic)""
IL_0057: stfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<list>5__2""
IL_005c: ldarg.0
IL_005d: ldc.i4.0
IL_005e: stfld ""int Program.<Iterator>d__1.<i>5__3""
IL_0063: br IL_0305
IL_0068: nop
IL_0069: ldarg.0
IL_006a: ldarg.0
IL_006b: ldfld ""string[] Program.<Iterator>d__1.<args>5__1""
IL_0070: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> Program.<>c.<>9__1_0""
IL_0075: dup
IL_0076: brtrue.s IL_008f
IL_0078: pop
IL_0079: ldsfld ""Program.<>c Program.<>c.<>9""
IL_007e: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> Program.<>c.<Iterator>b__1_0(string)""
IL_0084: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)""
IL_0089: dup
IL_008a: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> Program.<>c.<>9__1_0""
IL_008f: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)""
IL_0094: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> Program.<>c.<>9__1_1""
IL_0099: dup
IL_009a: brtrue.s IL_00b3
IL_009c: pop
IL_009d: ldsfld ""Program.<>c Program.<>c.<>9""
IL_00a2: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> Program.<>c.<Iterator>b__1_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)""
IL_00a8: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)""
IL_00ad: dup
IL_00ae: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> Program.<>c.<>9__1_1""
IL_00b3: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)""
IL_00b8: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> Program.<>c.<>9__1_2""
IL_00bd: dup
IL_00be: brtrue.s IL_00d7
IL_00c0: pop
IL_00c1: ldsfld ""Program.<>c Program.<>c.<>9""
IL_00c6: ldftn ""bool Program.<>c.<Iterator>b__1_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_00cc: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)""
IL_00d1: dup
IL_00d2: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> Program.<>c.<>9__1_2""
IL_00d7: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)""
IL_00dc: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int> Program.<>c.<>9__1_3""
IL_00e1: dup
IL_00e2: brtrue.s IL_00fb
IL_00e4: pop
IL_00e5: ldsfld ""Program.<>c Program.<>c.<>9""
IL_00ea: ldftn ""int Program.<>c.<Iterator>b__1_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_00f0: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int>..ctor(object, System.IntPtr)""
IL_00f5: dup
IL_00f6: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int> Program.<>c.<>9__1_3""
IL_00fb: call ""System.Linq.IOrderedEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.OrderBy<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int>)""
IL_0100: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string> Program.<>c.<>9__1_4""
IL_0105: dup
IL_0106: brtrue.s IL_011f
IL_0108: pop
IL_0109: ldsfld ""Program.<>c Program.<>c.<>9""
IL_010e: ldftn ""string Program.<>c.<Iterator>b__1_4(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_0114: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string>..ctor(object, System.IntPtr)""
IL_0119: dup
IL_011a: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string> Program.<>c.<>9__1_4""
IL_011f: call ""System.Linq.IOrderedEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.ThenByDescending<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string>(System.Linq.IOrderedEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string>)""
IL_0124: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> Program.<>c.<>9__1_5""
IL_0129: dup
IL_012a: brtrue.s IL_0143
IL_012c: pop
IL_012d: ldsfld ""Program.<>c Program.<>c.<>9""
IL_0132: ldftn ""<anonymous type: string Value, int Length> Program.<>c.<Iterator>b__1_5(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_0138: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)""
IL_013d: dup
IL_013e: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> Program.<>c.<>9__1_5""
IL_0143: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)""
IL_0148: stfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4""
IL_014d: ldarg.0
IL_014e: ldarg.0
IL_014f: ldfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4""
IL_0154: ldnull
IL_0155: ldsfld ""System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>> Program.<>c.<>9__1_6""
IL_015a: dup
IL_015b: brtrue.s IL_0174
IL_015d: pop
IL_015e: ldsfld ""Program.<>c Program.<>c.<>9""
IL_0163: ldftn ""<anonymous type: string Head, dynamic Tail> Program.<>c.<Iterator>b__1_6(<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>)""
IL_0169: newobj ""System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>>..ctor(object, System.IntPtr)""
IL_016e: dup
IL_016f: stsfld ""System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>> Program.<>c.<>9__1_6""
IL_0174: call ""<anonymous type: string Head, dynamic Tail> System.Linq.Enumerable.Aggregate<<anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>>(System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>>, <anonymous type: string Head, dynamic Tail>, System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>>)""
IL_0179: stfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5""
IL_017e: br.s IL_01f5
IL_0180: nop
IL_0181: ldarg.0
IL_0182: ldarg.0
IL_0183: ldfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5""
IL_0188: callvirt ""string <>f__AnonymousType0<string, dynamic>.Head.get""
IL_018d: stfld ""string Program.<Iterator>d__1.<>2__current""
IL_0192: ldarg.0
IL_0193: ldc.i4.1
IL_0194: stfld ""int Program.<Iterator>d__1.<>1__state""
IL_0199: ldc.i4.1
IL_019a: ret
IL_019b: ldarg.0
IL_019c: ldc.i4.m1
IL_019d: stfld ""int Program.<Iterator>d__1.<>1__state""
IL_01a2: ldarg.0
IL_01a3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>> Program.<>o__1.<>p__0""
IL_01a8: brfalse.s IL_01ac
IL_01aa: br.s IL_01d0
IL_01ac: ldc.i4.0
IL_01ad: ldtoken ""<>f__AnonymousType0<string, dynamic>""
IL_01b2: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_01b7: ldtoken ""Program""
IL_01bc: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_01c1: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_01c6: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_01cb: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>> Program.<>o__1.<>p__0""
IL_01d0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>> Program.<>o__1.<>p__0""
IL_01d5: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>>.Target""
IL_01da: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>> Program.<>o__1.<>p__0""
IL_01df: ldarg.0
IL_01e0: ldfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5""
IL_01e5: callvirt ""dynamic <>f__AnonymousType0<string, dynamic>.Tail.get""
IL_01ea: callvirt ""<anonymous type: string Head, dynamic Tail> System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_01ef: stfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5""
IL_01f4: nop
IL_01f5: ldarg.0
IL_01f6: ldfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5""
IL_01fb: ldnull
IL_01fc: cgt.un
IL_01fe: stloc.1
IL_01ff: ldloc.1
IL_0200: brtrue IL_0180
IL_0205: ldarg.0
IL_0206: ldarg.0
IL_0207: ldfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4""
IL_020c: ldsfld ""System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>> Program.<>c.<>9__1_7""
IL_0211: dup
IL_0212: brtrue.s IL_022b
IL_0214: pop
IL_0215: ldsfld ""Program.<>c Program.<>c.<>9""
IL_021a: ldftn ""<anonymous type: <anonymous type: string Value, int Length> a, string value> Program.<>c.<Iterator>b__1_7(<anonymous type: string Value, int Length>)""
IL_0220: newobj ""System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>>..ctor(object, System.IntPtr)""
IL_0225: dup
IL_0226: stsfld ""System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>> Program.<>c.<>9__1_7""
IL_022b: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string Value, int Length> a, string value>> System.Linq.Enumerable.Select<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>>(System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>>, System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>>)""
IL_0230: ldsfld ""System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> Program.<>c.<>9__1_8""
IL_0235: dup
IL_0236: brtrue.s IL_024f
IL_0238: pop
IL_0239: ldsfld ""Program.<>c Program.<>c.<>9""
IL_023e: ldftn ""<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length> Program.<>c.<Iterator>b__1_8(<anonymous type: <anonymous type: string Value, int Length> a, string value>)""
IL_0244: newobj ""System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>..ctor(object, System.IntPtr)""
IL_0249: dup
IL_024a: stsfld ""System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> Program.<>c.<>9__1_8""
IL_024f: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string Value, int Length> a, string value>>, System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>)""
IL_0254: ldsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool> Program.<>c.<>9__1_9""
IL_0259: dup
IL_025a: brtrue.s IL_0273
IL_025c: pop
IL_025d: ldsfld ""Program.<>c Program.<>c.<>9""
IL_0262: ldftn ""bool Program.<>c.<Iterator>b__1_9(<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>)""
IL_0268: newobj ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool>..ctor(object, System.IntPtr)""
IL_026d: dup
IL_026e: stsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool> Program.<>c.<>9__1_9""
IL_0273: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>, System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool>)""
IL_0278: ldsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string> Program.<>c.<>9__1_10""
IL_027d: dup
IL_027e: brtrue.s IL_0297
IL_0280: pop
IL_0281: ldsfld ""Program.<>c Program.<>c.<>9""
IL_0286: ldftn ""string Program.<>c.<Iterator>b__1_10(<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>)""
IL_028c: newobj ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string>..ctor(object, System.IntPtr)""
IL_0291: dup
IL_0292: stsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string> Program.<>c.<>9__1_10""
IL_0297: call ""System.Collections.Generic.IEnumerable<string> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>, System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string>)""
IL_029c: stfld ""System.Collections.Generic.IEnumerable<string> Program.<Iterator>d__1.<newArgs>5__6""
IL_02a1: ldarg.0
IL_02a2: ldarg.0
IL_02a3: ldfld ""string[] Program.<Iterator>d__1.<args>5__1""
IL_02a8: ldarg.0
IL_02a9: ldfld ""System.Collections.Generic.IEnumerable<string> Program.<Iterator>d__1.<newArgs>5__6""
IL_02ae: call ""System.Collections.Generic.IEnumerable<string> System.Linq.Enumerable.Concat<string>(System.Collections.Generic.IEnumerable<string>, System.Collections.Generic.IEnumerable<string>)""
IL_02b3: call ""string[] System.Linq.Enumerable.ToArray<string>(System.Collections.Generic.IEnumerable<string>)""
IL_02b8: stfld ""string[] Program.<Iterator>d__1.<args>5__1""
IL_02bd: ldarg.0
IL_02be: ldarg.0
IL_02bf: ldfld ""int Program.<Iterator>d__1.<i>5__3""
IL_02c4: box ""int""
IL_02c9: ldarg.0
IL_02ca: ldfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<list>5__2""
IL_02cf: newobj ""<>f__AnonymousType0<dynamic, dynamic>..ctor(dynamic, dynamic)""
IL_02d4: stfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<list>5__2""
IL_02d9: call ""void System.Diagnostics.Debugger.Break()""
IL_02de: nop
IL_02df: nop
IL_02e0: ldarg.0
IL_02e1: ldnull
IL_02e2: stfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4""
IL_02e7: ldarg.0
IL_02e8: ldnull
IL_02e9: stfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5""
IL_02ee: ldarg.0
IL_02ef: ldnull
IL_02f0: stfld ""System.Collections.Generic.IEnumerable<string> Program.<Iterator>d__1.<newArgs>5__6""
IL_02f5: ldarg.0
IL_02f6: ldfld ""int Program.<Iterator>d__1.<i>5__3""
IL_02fb: stloc.2
IL_02fc: ldarg.0
IL_02fd: ldloc.2
IL_02fe: ldc.i4.1
IL_02ff: add
IL_0300: stfld ""int Program.<Iterator>d__1.<i>5__3""
IL_0305: ldarg.0
IL_0306: ldfld ""int Program.<Iterator>d__1.<i>5__3""
IL_030b: ldc.i4.s 10
IL_030d: clt
IL_030f: stloc.3
IL_0310: ldloc.3
IL_0311: brtrue IL_0068
IL_0316: call ""void System.Diagnostics.Debugger.Break()""
IL_031b: nop
IL_031c: ldc.i4.0
IL_031d: ret
}");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"Program.<>o__1#1: {<>p__0, <>p__1}",
"Program: {<>o__1#1, <>c, <Iterator>d__1}",
"Program.<>c: {<>9__1_0, <>9__1_1, <>9__1_2, <>9__1_3, <>9__1_4, <>9__1_5, <>9__1_6, <>9__1_7, <>9__1_8, <>9__1_9, <>9__1_10, <Iterator>b__1_0, <Iterator>b__1_1, <Iterator>b__1_2, <Iterator>b__1_3, <Iterator>b__1_4, <Iterator>b__1_5, <Iterator>b__1_6, <Iterator>b__1_7, <Iterator>b__1_8, <Iterator>b__1_9, <Iterator>b__1_10}",
"Program.<Iterator>d__1: {<>1__state, <>2__current, <>l__initialThreadId, <args>5__1, <list>5__2, <i>5__3, <result>5__4, <linked>5__5, <temp>5__7, <newArgs>5__6, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.String>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.String>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.String>.Current, System.Collections.IEnumerator.Current}",
"<>f__AnonymousType4<<a>j__TPar, <value>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType3<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType5<<<>h__TransparentIdentifier0>j__TPar, <length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType2<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<Head>j__TPar, <Tail>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("Program.<Iterator>d__1.System.Collections.IEnumerator.MoveNext()", @"
{
// Code size 885 (0x375)
.maxstack 5
.locals init (int V_0,
bool V_1,
int V_2,
bool V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Iterator>d__1.<>1__state""
IL_0006: stloc.0
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_001b
IL_0014: br IL_01eb
IL_0019: ldc.i4.0
IL_001a: ret
IL_001b: ldarg.0
IL_001c: ldc.i4.m1
IL_001d: stfld ""int Program.<Iterator>d__1.<>1__state""
IL_0022: nop
IL_0023: ldarg.0
IL_0024: ldc.i4.4
IL_0025: newarr ""string""
IL_002a: dup
IL_002b: ldc.i4.0
IL_002c: ldstr ""a""
IL_0031: stelem.ref
IL_0032: dup
IL_0033: ldc.i4.1
IL_0034: ldstr ""bB""
IL_0039: stelem.ref
IL_003a: dup
IL_003b: ldc.i4.2
IL_003c: ldstr ""Cc""
IL_0041: stelem.ref
IL_0042: dup
IL_0043: ldc.i4.3
IL_0044: ldstr ""DD""
IL_0049: stelem.ref
IL_004a: stfld ""string[] Program.<Iterator>d__1.<args>5__1""
IL_004f: ldarg.0
IL_0050: ldnull
IL_0051: ldnull
IL_0052: newobj ""<>f__AnonymousType0<dynamic, dynamic>..ctor(dynamic, dynamic)""
IL_0057: stfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<list>5__2""
IL_005c: ldarg.0
IL_005d: ldc.i4.0
IL_005e: stfld ""int Program.<Iterator>d__1.<i>5__3""
IL_0063: br IL_035c
IL_0068: nop
IL_0069: ldarg.0
IL_006a: ldarg.0
IL_006b: ldfld ""string[] Program.<Iterator>d__1.<args>5__1""
IL_0070: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> Program.<>c.<>9__1_0""
IL_0075: dup
IL_0076: brtrue.s IL_008f
IL_0078: pop
IL_0079: ldsfld ""Program.<>c Program.<>c.<>9""
IL_007e: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> Program.<>c.<Iterator>b__1_0(string)""
IL_0084: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)""
IL_0089: dup
IL_008a: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> Program.<>c.<>9__1_0""
IL_008f: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)""
IL_0094: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> Program.<>c.<>9__1_1""
IL_0099: dup
IL_009a: brtrue.s IL_00b3
IL_009c: pop
IL_009d: ldsfld ""Program.<>c Program.<>c.<>9""
IL_00a2: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> Program.<>c.<Iterator>b__1_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)""
IL_00a8: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)""
IL_00ad: dup
IL_00ae: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> Program.<>c.<>9__1_1""
IL_00b3: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)""
IL_00b8: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> Program.<>c.<>9__1_2""
IL_00bd: dup
IL_00be: brtrue.s IL_00d7
IL_00c0: pop
IL_00c1: ldsfld ""Program.<>c Program.<>c.<>9""
IL_00c6: ldftn ""bool Program.<>c.<Iterator>b__1_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_00cc: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)""
IL_00d1: dup
IL_00d2: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> Program.<>c.<>9__1_2""
IL_00d7: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)""
IL_00dc: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int> Program.<>c.<>9__1_3""
IL_00e1: dup
IL_00e2: brtrue.s IL_00fb
IL_00e4: pop
IL_00e5: ldsfld ""Program.<>c Program.<>c.<>9""
IL_00ea: ldftn ""int Program.<>c.<Iterator>b__1_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_00f0: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int>..ctor(object, System.IntPtr)""
IL_00f5: dup
IL_00f6: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int> Program.<>c.<>9__1_3""
IL_00fb: call ""System.Linq.IOrderedEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.OrderBy<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int>)""
IL_0100: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string> Program.<>c.<>9__1_4""
IL_0105: dup
IL_0106: brtrue.s IL_011f
IL_0108: pop
IL_0109: ldsfld ""Program.<>c Program.<>c.<>9""
IL_010e: ldftn ""string Program.<>c.<Iterator>b__1_4(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_0114: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string>..ctor(object, System.IntPtr)""
IL_0119: dup
IL_011a: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string> Program.<>c.<>9__1_4""
IL_011f: call ""System.Linq.IOrderedEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.ThenByDescending<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string>(System.Linq.IOrderedEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string>)""
IL_0124: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> Program.<>c.<>9__1_5""
IL_0129: dup
IL_012a: brtrue.s IL_0143
IL_012c: pop
IL_012d: ldsfld ""Program.<>c Program.<>c.<>9""
IL_0132: ldftn ""<anonymous type: string Value, int Length> Program.<>c.<Iterator>b__1_5(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_0138: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)""
IL_013d: dup
IL_013e: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> Program.<>c.<>9__1_5""
IL_0143: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)""
IL_0148: stfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4""
IL_014d: ldarg.0
IL_014e: ldarg.0
IL_014f: ldfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4""
IL_0154: ldnull
IL_0155: ldsfld ""System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>> Program.<>c.<>9__1_6""
IL_015a: dup
IL_015b: brtrue.s IL_0174
IL_015d: pop
IL_015e: ldsfld ""Program.<>c Program.<>c.<>9""
IL_0163: ldftn ""<anonymous type: string Head, dynamic Tail> Program.<>c.<Iterator>b__1_6(<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>)""
IL_0169: newobj ""System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>>..ctor(object, System.IntPtr)""
IL_016e: dup
IL_016f: stsfld ""System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>> Program.<>c.<>9__1_6""
IL_0174: call ""<anonymous type: string Head, dynamic Tail> System.Linq.Enumerable.Aggregate<<anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>>(System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>>, <anonymous type: string Head, dynamic Tail>, System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>>)""
IL_0179: stfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5""
IL_017e: ldarg.0
IL_017f: ldarg.0
IL_0180: ldfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<list>5__2""
IL_0185: stfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<temp>5__7""
IL_018a: br IL_0245
IL_018f: nop
IL_0190: ldarg.0
IL_0191: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>> Program.<>o__1#1.<>p__0""
IL_0196: brfalse.s IL_019a
IL_0198: br.s IL_01be
IL_019a: ldc.i4.0
IL_019b: ldtoken ""string""
IL_01a0: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_01a5: ldtoken ""Program""
IL_01aa: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_01af: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_01b4: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_01b9: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>> Program.<>o__1#1.<>p__0""
IL_01be: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>> Program.<>o__1#1.<>p__0""
IL_01c3: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>>.Target""
IL_01c8: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>> Program.<>o__1#1.<>p__0""
IL_01cd: ldarg.0
IL_01ce: ldfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<temp>5__7""
IL_01d3: callvirt ""dynamic <>f__AnonymousType0<dynamic, dynamic>.Head.get""
IL_01d8: callvirt ""string System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_01dd: stfld ""string Program.<Iterator>d__1.<>2__current""
IL_01e2: ldarg.0
IL_01e3: ldc.i4.1
IL_01e4: stfld ""int Program.<Iterator>d__1.<>1__state""
IL_01e9: ldc.i4.1
IL_01ea: ret
IL_01eb: ldarg.0
IL_01ec: ldc.i4.m1
IL_01ed: stfld ""int Program.<Iterator>d__1.<>1__state""
IL_01f2: ldarg.0
IL_01f3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>> Program.<>o__1#1.<>p__1""
IL_01f8: brfalse.s IL_01fc
IL_01fa: br.s IL_0220
IL_01fc: ldc.i4.0
IL_01fd: ldtoken ""<>f__AnonymousType0<dynamic, dynamic>""
IL_0202: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0207: ldtoken ""Program""
IL_020c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0211: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_0216: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_021b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>> Program.<>o__1#1.<>p__1""
IL_0220: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>> Program.<>o__1#1.<>p__1""
IL_0225: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>>.Target""
IL_022a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>> Program.<>o__1#1.<>p__1""
IL_022f: ldarg.0
IL_0230: ldfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<temp>5__7""
IL_0235: callvirt ""dynamic <>f__AnonymousType0<dynamic, dynamic>.Tail.get""
IL_023a: callvirt ""<anonymous type: dynamic Head, dynamic Tail> System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_023f: stfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<temp>5__7""
IL_0244: nop
IL_0245: ldarg.0
IL_0246: ldfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<temp>5__7""
IL_024b: ldnull
IL_024c: cgt.un
IL_024e: stloc.1
IL_024f: ldloc.1
IL_0250: brtrue IL_018f
IL_0255: ldarg.0
IL_0256: ldarg.0
IL_0257: ldfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4""
IL_025c: ldsfld ""System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>> Program.<>c.<>9__1_7""
IL_0261: dup
IL_0262: brtrue.s IL_027b
IL_0264: pop
IL_0265: ldsfld ""Program.<>c Program.<>c.<>9""
IL_026a: ldftn ""<anonymous type: <anonymous type: string Value, int Length> a, string value> Program.<>c.<Iterator>b__1_7(<anonymous type: string Value, int Length>)""
IL_0270: newobj ""System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>>..ctor(object, System.IntPtr)""
IL_0275: dup
IL_0276: stsfld ""System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>> Program.<>c.<>9__1_7""
IL_027b: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string Value, int Length> a, string value>> System.Linq.Enumerable.Select<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>>(System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>>, System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>>)""
IL_0280: ldsfld ""System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> Program.<>c.<>9__1_8""
IL_0285: dup
IL_0286: brtrue.s IL_029f
IL_0288: pop
IL_0289: ldsfld ""Program.<>c Program.<>c.<>9""
IL_028e: ldftn ""<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length> Program.<>c.<Iterator>b__1_8(<anonymous type: <anonymous type: string Value, int Length> a, string value>)""
IL_0294: newobj ""System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>..ctor(object, System.IntPtr)""
IL_0299: dup
IL_029a: stsfld ""System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> Program.<>c.<>9__1_8""
IL_029f: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string Value, int Length> a, string value>>, System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>)""
IL_02a4: ldsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool> Program.<>c.<>9__1_9""
IL_02a9: dup
IL_02aa: brtrue.s IL_02c3
IL_02ac: pop
IL_02ad: ldsfld ""Program.<>c Program.<>c.<>9""
IL_02b2: ldftn ""bool Program.<>c.<Iterator>b__1_9(<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>)""
IL_02b8: newobj ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool>..ctor(object, System.IntPtr)""
IL_02bd: dup
IL_02be: stsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool> Program.<>c.<>9__1_9""
IL_02c3: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>, System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool>)""
IL_02c8: ldsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string> Program.<>c.<>9__1_10""
IL_02cd: dup
IL_02ce: brtrue.s IL_02e7
IL_02d0: pop
IL_02d1: ldsfld ""Program.<>c Program.<>c.<>9""
IL_02d6: ldftn ""string Program.<>c.<Iterator>b__1_10(<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>)""
IL_02dc: newobj ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string>..ctor(object, System.IntPtr)""
IL_02e1: dup
IL_02e2: stsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string> Program.<>c.<>9__1_10""
IL_02e7: call ""System.Collections.Generic.IEnumerable<string> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>, System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string>)""
IL_02ec: stfld ""System.Collections.Generic.IEnumerable<string> Program.<Iterator>d__1.<newArgs>5__6""
IL_02f1: ldarg.0
IL_02f2: ldarg.0
IL_02f3: ldfld ""string[] Program.<Iterator>d__1.<args>5__1""
IL_02f8: ldarg.0
IL_02f9: ldfld ""System.Collections.Generic.IEnumerable<string> Program.<Iterator>d__1.<newArgs>5__6""
IL_02fe: call ""System.Collections.Generic.IEnumerable<string> System.Linq.Enumerable.Concat<string>(System.Collections.Generic.IEnumerable<string>, System.Collections.Generic.IEnumerable<string>)""
IL_0303: call ""string[] System.Linq.Enumerable.ToArray<string>(System.Collections.Generic.IEnumerable<string>)""
IL_0308: stfld ""string[] Program.<Iterator>d__1.<args>5__1""
IL_030d: ldarg.0
IL_030e: ldarg.0
IL_030f: ldfld ""int Program.<Iterator>d__1.<i>5__3""
IL_0314: box ""int""
IL_0319: ldarg.0
IL_031a: ldfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<list>5__2""
IL_031f: newobj ""<>f__AnonymousType0<dynamic, dynamic>..ctor(dynamic, dynamic)""
IL_0324: stfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<list>5__2""
IL_0329: call ""void System.Diagnostics.Debugger.Break()""
IL_032e: nop
IL_032f: nop
IL_0330: ldarg.0
IL_0331: ldnull
IL_0332: stfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4""
IL_0337: ldarg.0
IL_0338: ldnull
IL_0339: stfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5""
IL_033e: ldarg.0
IL_033f: ldnull
IL_0340: stfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<temp>5__7""
IL_0345: ldarg.0
IL_0346: ldnull
IL_0347: stfld ""System.Collections.Generic.IEnumerable<string> Program.<Iterator>d__1.<newArgs>5__6""
IL_034c: ldarg.0
IL_034d: ldfld ""int Program.<Iterator>d__1.<i>5__3""
IL_0352: stloc.2
IL_0353: ldarg.0
IL_0354: ldloc.2
IL_0355: ldc.i4.1
IL_0356: add
IL_0357: stfld ""int Program.<Iterator>d__1.<i>5__3""
IL_035c: ldarg.0
IL_035d: ldfld ""int Program.<Iterator>d__1.<i>5__3""
IL_0362: ldc.i4.s 10
IL_0364: clt
IL_0366: stloc.3
IL_0367: ldloc.3
IL_0368: brtrue IL_0068
IL_036d: call ""void System.Diagnostics.Debugger.Break()""
IL_0372: nop
IL_0373: ldc.i4.0
IL_0374: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"Program.<>o__1#1: {<>p__0, <>p__1}",
"Program.<>o__1#2: {<>p__0, <>p__1, <>p__2}",
"Program: {<>o__1#2, <>c, <Iterator>d__1, <>o__1#1}",
"Program.<>c: {<>9__1_0, <>9__1_1, <>9__1_2, <>9__1_3, <>9__1_4, <>9__1_5, <>9__1_6, <>9__1_7, <>9__1_8, <>9__1_9, <>9__1_10, <Iterator>b__1_0, <Iterator>b__1_1, <Iterator>b__1_2, <Iterator>b__1_3, <Iterator>b__1_4, <Iterator>b__1_5, <Iterator>b__1_6, <Iterator>b__1_7, <Iterator>b__1_8, <Iterator>b__1_9, <Iterator>b__1_10}",
"Program.<Iterator>d__1: {<>1__state, <>2__current, <>l__initialThreadId, <args>5__1, <list>5__2, <i>5__3, <result>5__4, <linked>5__5, <temp>5__7, <newArgs>5__6, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.String>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.String>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.String>.Current, System.Collections.IEnumerator.Current}",
"<>f__AnonymousType4<<a>j__TPar, <value>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType3<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<Head>j__TPar, <Tail>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType5<<<>h__TransparentIdentifier0>j__TPar, <length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType2<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}");
}
[Fact, WorkItem(9119, "https://github.com/dotnet/roslyn/issues/9119")]
public void MissingIteratorStateMachineAttribute()
{
var source0 = MarkedSource(@"
using System;
using System.Collections.Generic;
class C
{
public IEnumerable<int> F()
{
int <N:0>a = 0</N:0>;
<N:1>yield return 0;</N:1>
Console.WriteLine(a);
}
}
");
var source1 = MarkedSource(@"
using System;
using System.Collections.Generic;
class C
{
public IEnumerable<int> F()
{
int <N:0>a = 1</N:0>;
<N:1>yield return 1;</N:1>
Console.WriteLine(a);
}
}
");
var compilation0 = CreateCompilationWithMscorlib40(new[] { source0.Tree }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
// older versions of mscorlib don't contain IteratorStateMachineAttribute
Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor));
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
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.EmitResult.Diagnostics.Verify(
// (7,29): error CS7043: Cannot update 'C.F()'; attribute 'System.Runtime.CompilerServices.IteratorStateMachineAttribute' is missing.
Diagnostic(ErrorCode.ERR_EncUpdateFailedMissingAttribute, "F").WithArguments("C.F()", "System.Runtime.CompilerServices.IteratorStateMachineAttribute").WithLocation(7, 29));
}
[Fact, WorkItem(9119, "https://github.com/dotnet/roslyn/issues/9119")]
public void BadIteratorStateMachineAttribute()
{
var source0 = MarkedSource(@"
using System;
using System.Collections.Generic;
namespace System.Runtime.CompilerServices
{
public class IteratorStateMachineAttribute : Attribute { }
}
class C
{
public IEnumerable<int> F()
{
int <N:0>a = 0</N:0>;
<N:1>yield return 0;</N:1>
Console.WriteLine(a);
}
}
");
var source1 = MarkedSource(@"
using System;
using System.Collections.Generic;
namespace System.Runtime.CompilerServices
{
public class IteratorStateMachineAttribute : Attribute { }
}
class C
{
public IEnumerable<int> F()
{
int <N:0>a = 1</N:0>;
<N:1>yield return 1;</N:1>
Console.WriteLine(a);
}
}
");
var compilation0 = CreateCompilation(new[] { source0.Tree }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
// the ctor is missing a parameter
Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor));
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
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.EmitResult.Diagnostics.Verify(
// (12,29): error CS7043: Cannot update 'C.F()'; attribute 'System.Runtime.CompilerServices.IteratorStateMachineAttribute' is missing.
// public IEnumerable<int> F()
Diagnostic(ErrorCode.ERR_EncUpdateFailedMissingAttribute, "F").WithArguments("C.F()", "System.Runtime.CompilerServices.IteratorStateMachineAttribute").WithLocation(12, 29));
}
[Fact]
public void AddedIteratorStateMachineAttribute()
{
var source0 = MarkedSource(@"
using System;
using System.Collections.Generic;
class C
{
public IEnumerable<int> F()
{
int <N:0>a = 0</N:0>;
<N:1>yield return 0;</N:1>
Console.WriteLine(a);
}
}
");
var source1 = MarkedSource(@"
using System;
using System.Collections.Generic;
namespace System.Runtime.CompilerServices
{
public class IteratorStateMachineAttribute : Attribute { public IteratorStateMachineAttribute(Type type) { } }
}
class C
{
public IEnumerable<int> F()
{
int <N:0>a = 1</N:0>;
<N:1>yield return 1;</N:1>
Console.WriteLine(a);
}
}
");
var compilation0 = CreateCompilationWithMscorlib40(new[] { source0.Tree }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
// older versions of mscorlib don't contain IteratorStateMachineAttribute
Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor));
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var ism1 = compilation1.GetMember<TypeSymbol>("System.Runtime.CompilerServices.IteratorStateMachineAttribute");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, ism1),
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// We conclude the original method wasn't a state machine.
// The IDE however reports a Rude Edit in that case.
diff1.EmitResult.Diagnostics.Verify();
}
[Fact]
public void SourceIteratorStateMachineAttribute()
{
var source0 = MarkedSource(@"
using System;
using System.Collections.Generic;
namespace System.Runtime.CompilerServices
{
public class IteratorStateMachineAttribute : Attribute { public IteratorStateMachineAttribute(Type type) { } }
}
class C
{
public IEnumerable<int> F()
{
int <N:0>a = 0</N:0>;
<N:1>yield return 0;</N:1>
Console.WriteLine(a);
}
}
");
var source1 = MarkedSource(@"
using System;
using System.Collections.Generic;
namespace System.Runtime.CompilerServices
{
public class IteratorStateMachineAttribute : Attribute { public IteratorStateMachineAttribute(Type type) { } }
}
class C
{
public IEnumerable<int> F()
{
int <N:0>a = 1</N:0>;
<N:1>yield return 1;</N:1>
Console.WriteLine(a);
}
}
");
var compilation0 = CreateCompilation(new[] { source0.Tree }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
// older versions of mscorlib don't contain IteratorStateMachineAttribute
Assert.NotNull(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor));
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
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.EmitResult.Diagnostics.Verify();
}
[Fact, WorkItem(9119, "https://github.com/dotnet/roslyn/issues/9119")]
public void MissingAsyncStateMachineAttribute()
{
var source0 = MarkedSource(@"
using System.Threading.Tasks;
class C
{
public async Task<int> F()
{
int <N:0>a = 0</N:0>;
<N:1>await new Task();</N:1>
return a;
}
}
");
var source1 = MarkedSource(@"
using System.Threading.Tasks;
class C
{
public async Task<int> F()
{
int <N:0>a = 1</N:0>;
<N:1>await new Task();</N:1>
return a;
}
}
");
var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { TestReferences.NetFx.Minimal.mincorlib, TestReferences.NetFx.Minimal.minasync }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
// older versions of mscorlib don't contain AsyncStateMachineAttribute, IteratorStateMachineAttribute
Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor));
Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor));
var v0 = CompileAndVerify(compilation0, verify: Verification.Fails);
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.EmitResult.Diagnostics.Verify(
// (6,28): error CS7043: Cannot update 'C.F()'; attribute 'System.Runtime.CompilerServices.AsyncStateMachineAttribute' is missing.
Diagnostic(ErrorCode.ERR_EncUpdateFailedMissingAttribute, "F").WithArguments("C.F()", "System.Runtime.CompilerServices.AsyncStateMachineAttribute").WithLocation(6, 28));
}
[Fact]
public void AddedAsyncStateMachineAttribute()
{
var source0 = MarkedSource(@"
using System.Threading.Tasks;
class C
{
public async Task<int> F()
{
int <N:0>a = 0</N:0>;
<N:1>await new Task<int>();</N:1>
return a;
}
}
");
var source1 = MarkedSource(@"
using System.Threading.Tasks;
namespace System.Runtime.CompilerServices
{
public class AsyncStateMachineAttribute : Attribute { public AsyncStateMachineAttribute(Type type) { } }
}
class C
{
public async Task<int> F()
{
int <N:0>a = 1</N:0>;
<N:1>await new Task<int>();</N:1>
return a;
}
}
");
var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { TestReferences.NetFx.Minimal.mincorlib, TestReferences.NetFx.Minimal.minasync }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
// older versions of mscorlib don't contain IteratorStateMachineAttribute
Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor));
var v0 = CompileAndVerify(compilation0, verify: Verification.Fails);
v0.VerifyDiagnostics();
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var asm1 = compilation1.GetMember<TypeSymbol>("System.Runtime.CompilerServices.AsyncStateMachineAttribute");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, asm1),
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
}
[Fact]
public void SourceAsyncStateMachineAttribute()
{
var source0 = MarkedSource(@"
using System.Threading.Tasks;
namespace System.Runtime.CompilerServices
{
public class AsyncStateMachineAttribute : Attribute { public AsyncStateMachineAttribute(Type type) { } }
}
class C
{
public async Task<int> F()
{
int <N:0>a = 0</N:0>;
<N:1>await new Task<int>();</N:1>
return a;
}
}
");
var source1 = MarkedSource(@"
using System.Threading.Tasks;
namespace System.Runtime.CompilerServices
{
public class AsyncStateMachineAttribute : Attribute { public AsyncStateMachineAttribute(Type type) { } }
}
class C
{
public async Task<int> F()
{
int <N:0>a = 1</N:0>;
<N:1>await new Task<int>();</N:1>
return a;
}
}
");
var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { TestReferences.NetFx.Minimal.mincorlib, TestReferences.NetFx.Minimal.minasync }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
Assert.NotNull(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor));
var v0 = CompileAndVerify(compilation0, verify: Verification.Fails);
v0.VerifyDiagnostics();
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.EmitResult.Diagnostics.Verify();
}
[Fact, WorkItem(10190, "https://github.com/dotnet/roslyn/issues/10190")]
public void NonAsyncToAsync()
{
var source0 = MarkedSource(@"
using System.Threading.Tasks;
class C
{
public Task<int> F()
{
int <N:0>a = 0</N:0>;
<N:1>return Task.FromResult(a);</N:1>
}
}
");
var source1 = MarkedSource(@"
using System.Threading.Tasks;
class C
{
public async Task<int> F()
{
int <N:0>a = 1</N:0>;
<N:1>return await Task.FromResult(a);</N:1>
}
}
");
var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { Net451.mscorlib }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
Assert.NotNull(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor));
var v0 = CompileAndVerify(compilation0, verify: Verification.Passes);
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.EmitResult.Diagnostics.Verify();
}
[Fact]
public void NonAsyncToAsync_MissingAttribute()
{
var source0 = MarkedSource(@"
using System.Threading.Tasks;
class C
{
public Task<int> F()
{
int <N:0>a = 0</N:0>;
a++;
<N:1>return new Task<int>();</N:1>
}
}
");
var source1 = MarkedSource(@"
using System.Threading.Tasks;
class C
{
public async Task<int> F()
{
int <N:0>a = 1</N:0>;
a++;
<N:1>return await new Task<int>();</N:1>
}
}
");
var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { TestReferences.NetFx.Minimal.mincorlib, TestReferences.NetFx.Minimal.minasync }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor));
var v0 = CompileAndVerify(compilation0, verify: Verification.Fails);
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.EmitResult.Diagnostics.Verify(
// (6,28): error CS7043: Cannot update 'C.F()'; attribute 'System.Runtime.CompilerServices.AsyncStateMachineAttribute' is missing.
Diagnostic(ErrorCode.ERR_EncUpdateFailedMissingAttribute, "F").WithArguments("C.F()", "System.Runtime.CompilerServices.AsyncStateMachineAttribute").WithLocation(6, 28));
}
[Fact]
public void NonIteratorToIterator_MissingAttribute()
{
var source0 = MarkedSource(@"
using System.Collections.Generic;
class C
{
public IEnumerable<int> F()
{
int <N:0>a = 0</N:0>;
<N:1>return new int[] { a };</N:1>
}
}
");
var source1 = MarkedSource(@"
using System.Collections.Generic;
class C
{
public IEnumerable<int> F()
{
int <N:0>a = 1</N:0>;
<N:1>yield return a;</N:1>
}
}
");
var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { Net20.mscorlib }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor));
var v0 = CompileAndVerify(compilation0, verify: Verification.Passes);
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.EmitResult.Diagnostics.Verify(
// (6,29): error CS7043: Cannot update 'C.F()'; attribute 'System.Runtime.CompilerServices.IteratorStateMachineAttribute' is missing.
Diagnostic(ErrorCode.ERR_EncUpdateFailedMissingAttribute, "F").WithArguments("C.F()", "System.Runtime.CompilerServices.IteratorStateMachineAttribute").WithLocation(6, 29));
}
[Fact]
public void NonIteratorToIterator_SourceAttribute()
{
var source0 = MarkedSource(@"
using System.Collections.Generic;
namespace System.Runtime.CompilerServices
{
public class IteratorStateMachineAttribute : Attribute { public IteratorStateMachineAttribute(Type type) { } }
}
class C
{
public IEnumerable<int> F()
{
int <N:0>a = 0</N:0>;
<N:1>return new int[] { a };</N:1>
}
}
");
var source1 = MarkedSource(@"
using System.Collections.Generic;
namespace System.Runtime.CompilerServices
{
public class IteratorStateMachineAttribute : Attribute { public IteratorStateMachineAttribute(Type type) { } }
}
class C
{
public IEnumerable<int> F()
{
int <N:0>a = 1</N:0>;
<N:1>yield return a;</N:1>
}
}
");
var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { Net20.mscorlib }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
Assert.NotNull(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor));
var v0 = CompileAndVerify(compilation0, verify: Verification.Passes);
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.EmitResult.Diagnostics.Verify();
}
[Fact]
public void NonAsyncToAsyncLambda()
{
var source0 = MarkedSource(@"
using System.Threading.Tasks;
class C
{
public object F()
{
return new System.Func<Task<int>>(<N:2>() =>
<N:3>{
int <N:0>a = 0</N:0>;
<N:1>return Task.FromResult(a);</N:1>
}</N:3></N:2>);
}
}
");
var source1 = MarkedSource(@"
using System.Threading.Tasks;
class C
{
public object F()
{
return new System.Func<Task<int>>(<N:2>async () =>
<N:3>{
int <N:0>a = 0</N:0>;
<N:1>return await Task.FromResult(a);</N:1>
}</N:3></N:2>);
}
}
");
var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { Net451.mscorlib }, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
Assert.NotNull(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor));
var v0 = CompileAndVerify(compilation0, verify: Verification.Passes);
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.EmitResult.Diagnostics.Verify();
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <F>b__0_0, <<F>b__0_0>d}",
"C.<>c.<<F>b__0_0>d: {<>1__state, <>t__builder, <>4__this, <a>5__1, <>s__2, <>u__1, MoveNext, SetStateMachine}");
}
[Fact]
public void AsyncMethodWithNullableParameterAddingNullCheck()
{
var source0 = MarkedSource(@"
using System;
using System.Threading.Tasks;
#nullable enable
class C
{
static T id<T>(T t) => t;
static Task<T> G<T>(Func<T> f) => Task.FromResult(f());
static T H<T>(Func<T> f) => f();
public async void F(string? x)
<N:4>{</N:4>
var <N:2>y = await G(<N:0>() => new { A = id(x) }</N:0>)</N:2>;
var <N:3>z = H(<N:1>() => y.A</N:1>)</N:3>;
}
}
", options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9));
var source1 = MarkedSource(@"
using System;
using System.Threading.Tasks;
#nullable enable
class C
{
static T id<T>(T t) => t;
static Task<T> G<T>(Func<T> f) => Task.FromResult(f());
static T H<T>(Func<T> f) => f();
public async void F(string? x)
<N:4>{</N:4>
if (x is null) throw new Exception();
var <N:2>y = await G(<N:0>() => new { A = id(x) }</N:0>)</N:2>;
var <N:3>z = H(<N:1>() => y.A</N:1>)</N:3>;
}
}
", options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9));
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
Assert.NotNull(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor));
var v0 = CompileAndVerify(compilation0, verify: Verification.Passes);
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.EmitResult.Diagnostics.Verify();
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass3_0: {x, y, <F>b__1, <F>b__0}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}",
"System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"Microsoft: {CodeAnalysis}",
"System.Runtime: {CompilerServices, CompilerServices}",
"C: {<>c__DisplayClass3_0, <F>d__3}",
"<global namespace>: {Microsoft, System, System}",
"System: {Runtime, Runtime}",
"C.<F>d__3: {<>1__state, <>t__builder, x, <>4__this, <>8__4, <z>5__2, <>s__5, <>u__1, MoveNext, SetStateMachine}");
diff1.VerifyIL("C.<>c__DisplayClass3_0.<F>b__1()", @"
{
// Code size 17 (0x11)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""string C.<>c__DisplayClass3_0.x""
IL_0006: call ""string C.id<string>(string)""
IL_000b: newobj ""<>f__AnonymousType0<string>..ctor(string)""
IL_0010: ret
}
");
diff1.VerifyIL("C.<>c__DisplayClass3_0.<F>b__0()", @"
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""<anonymous type: string A> C.<>c__DisplayClass3_0.y""
IL_0006: callvirt ""string <>f__AnonymousType0<string>.A.get""
IL_000b: ret
}
");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
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;
using static Roslyn.Test.Utilities.TestMetadata;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests
{
public class EditAndContinueStateMachineTests : EditAndContinueTestBase
{
[Fact]
[WorkItem(1068894, "DevDiv"), WorkItem(1137300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1137300")]
public void AddIteratorMethod()
{
var source0 = WithWindowsLineBreaks(@"
using System.Collections.Generic;
class C
{
}
");
var source1 = WithWindowsLineBreaks(@"
using System.Collections.Generic;
class C
{
static IEnumerable<int> G()
{
yield return 1;
}
}
");
var compilation0 = CreateCompilation(Parse(source0, "a.cs"), options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(Parse(source1, "a.cs"));
var g1 = compilation1.GetMember<MethodSymbol>("C.G");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var reader0 = md0.MetadataReader;
// gen 1
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, g1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.UpdatedMethods);
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C", "<G>d__0#1");
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(2, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(3, TableIndex.Field, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
Row(1, TableIndex.Property, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
Row(2, TableIndex.Property, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(7, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(1, TableIndex.NestedClass, EditAndContinueOperation.Default),
Row(1, TableIndex.InterfaceImpl, EditAndContinueOperation.Default),
Row(2, TableIndex.InterfaceImpl, EditAndContinueOperation.Default),
Row(3, TableIndex.InterfaceImpl, EditAndContinueOperation.Default),
Row(4, TableIndex.InterfaceImpl, EditAndContinueOperation.Default),
Row(5, TableIndex.InterfaceImpl, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(3, TableIndex.TypeDef),
Handle(1, TableIndex.Field),
Handle(2, TableIndex.Field),
Handle(3, TableIndex.Field),
Handle(2, TableIndex.MethodDef),
Handle(3, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(5, TableIndex.MethodDef),
Handle(6, TableIndex.MethodDef),
Handle(7, TableIndex.MethodDef),
Handle(8, TableIndex.MethodDef),
Handle(9, TableIndex.MethodDef),
Handle(10, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(1, TableIndex.InterfaceImpl),
Handle(2, TableIndex.InterfaceImpl),
Handle(3, TableIndex.InterfaceImpl),
Handle(4, TableIndex.InterfaceImpl),
Handle(5, TableIndex.InterfaceImpl),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute),
Handle(6, TableIndex.CustomAttribute),
Handle(7, TableIndex.CustomAttribute),
Handle(8, TableIndex.CustomAttribute),
Handle(9, TableIndex.CustomAttribute),
Handle(10, TableIndex.CustomAttribute),
Handle(11, TableIndex.CustomAttribute),
Handle(12, TableIndex.CustomAttribute),
Handle(1, TableIndex.StandAloneSig),
Handle(2, TableIndex.StandAloneSig),
Handle(1, TableIndex.PropertyMap),
Handle(1, TableIndex.Property),
Handle(2, TableIndex.Property),
Handle(1, TableIndex.MethodSemantics),
Handle(2, TableIndex.MethodSemantics),
Handle(1, TableIndex.MethodImpl),
Handle(2, TableIndex.MethodImpl),
Handle(3, TableIndex.MethodImpl),
Handle(4, TableIndex.MethodImpl),
Handle(5, TableIndex.MethodImpl),
Handle(6, TableIndex.MethodImpl),
Handle(7, TableIndex.MethodImpl),
Handle(1, TableIndex.NestedClass));
diff1.VerifyPdb(Enumerable.Range(0x06000001, 0x20), @"
<symbols>
<files>
<file id=""1"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""66-9A-93-25-E7-42-DC-A9-DD-D1-61-3F-D9-45-A8-E1-39-8C-37-79"" />
</files>
<methods>
<method token=""0x6000002"">
<customDebugInfo>
<forwardIterator name=""<G>d__0#1"" />
</customDebugInfo>
</method>
<method token=""0x6000005"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x1f"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" />
<entry offset=""0x20"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""24"" document=""1"" />
<entry offset=""0x30"" hidden=""true"" document=""1"" />
<entry offset=""0x37"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x39"">
<namespace name=""System.Collections.Generic"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void AddAsyncMethod()
{
var source0 = @"
using System.Threading.Tasks;
class C
{
}";
var source1 = @"
using System.Threading.Tasks;
class C
{
static async Task<int> F()
{
await Task.FromResult(10);
return 20;
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var v0 = CompileAndVerify(compilation0);
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData), EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.F"))));
using (var md1 = diff1.GetMetadata())
{
var reader1 = md1.Reader;
// Add state machine type and its members:
// - Method '.ctor'
// - Method 'MoveNext'
// - Method 'SetStateMachine'
// - Field '<>1__state'
// - Field '<>t__builder'
// - Field '<>u__1'
// Add method F()
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(2, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(3, TableIndex.Field, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(1, TableIndex.NestedClass, EditAndContinueOperation.Default),
Row(1, TableIndex.InterfaceImpl, EditAndContinueOperation.Default));
}
}
[Fact]
public void MethodToIteratorMethod()
{
var source0 = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
return new int[] { 1, 2, 3 };
}
}";
var source1 = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
yield return 2;
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var v0 = CompileAndVerify(compilation0);
using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData))
{
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
using (var md1 = diff1.GetMetadata())
{
CheckEncLogDefinitions(md1.Reader,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(2, TableIndex.Field, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(3, TableIndex.Field, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(4, TableIndex.Field, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
Row(1, TableIndex.Property, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
Row(2, TableIndex.Property, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(7, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default),
Row(1, TableIndex.InterfaceImpl, EditAndContinueOperation.Default),
Row(2, TableIndex.InterfaceImpl, EditAndContinueOperation.Default),
Row(3, TableIndex.InterfaceImpl, EditAndContinueOperation.Default),
Row(4, TableIndex.InterfaceImpl, EditAndContinueOperation.Default),
Row(5, TableIndex.InterfaceImpl, EditAndContinueOperation.Default));
}
}
}
[Fact]
public void MethodToAsyncMethod()
{
var source0 = @"
using System.Threading.Tasks;
class C
{
static Task<int> F()
{
return Task.FromResult(1);
}
}";
var source1 = @"
using System.Threading.Tasks;
class C
{
static async Task<int> F()
{
return await Task.FromResult(1);
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var v0 = CompileAndVerify(compilation0);
using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData))
{
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
using (var md1 = diff1.GetMetadata())
{
CheckEncLogDefinitions(md1.Reader,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(2, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(3, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(4, TableIndex.Field, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default),
Row(1, TableIndex.NestedClass, EditAndContinueOperation.Default),
Row(1, TableIndex.InterfaceImpl, EditAndContinueOperation.Default));
}
}
}
[Fact]
public void IteratorMethodToMethod()
{
var source0 = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
yield return 2;
}
}";
var source1 = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
return new int[] { 1, 2, 3 };
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var v0 = CompileAndVerify(compilation0);
using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData))
{
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
using (var md1 = diff1.GetMetadata())
{
CheckAttributes(md1.Reader,
new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // row id 0 == delete
CheckEncLogDefinitions(md1.Reader,
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Delete IteratorStateMachineAttribute
}
}
}
[Fact]
public void AsyncMethodToMethod()
{
var source0 = @"
using System.Threading.Tasks;
class C
{
static async Task<int> F()
{
return await Task.FromResult(1);
}
}";
var source1 = @"
using System.Threading.Tasks;
class C
{
static Task<int> F()
{
return Task.FromResult(1);
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var v0 = CompileAndVerify(compilation0);
using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData))
{
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
using (var md1 = diff1.GetMetadata())
{
CheckAttributes(md1.Reader,
new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef)), // row id 0 == delete
new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // row id 0 == delete
CheckEncLogDefinitions(md1.Reader,
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Delete AsyncStateMachineAttribute
Row(2, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Delete DebuggerStepThroughAttribute
}
}
}
[Fact]
public void AsyncMethodOverloads()
{
var source0 = @"
using System.Threading.Tasks;
class C
{
static async Task<int> F(long a)
{
return await Task.FromResult(1);
}
static async Task<int> F(int a)
{
return await Task.FromResult(1);
}
static async Task<int> F(short a)
{
return await Task.FromResult(1);
}
}";
var source1 = @"
using System.Threading.Tasks;
class C
{
static async Task<int> F(short a)
{
return await Task.FromResult(2);
}
static async Task<int> F(long a)
{
return await Task.FromResult(3);
}
static async Task<int> F(int a)
{
return await Task.FromResult(4);
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var v0 = CompileAndVerify(compilation0);
using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData))
{
var methodShort0 = compilation0.GetMembers("C.F").Single(m => m.ToTestDisplayString() == "System.Threading.Tasks.Task<System.Int32> C.F(System.Int16 a)");
var methodShort1 = compilation1.GetMembers("C.F").Single(m => m.ToTestDisplayString() == "System.Threading.Tasks.Task<System.Int32> C.F(System.Int16 a)");
var methodInt0 = compilation0.GetMembers("C.F").Single(m => m.ToTestDisplayString() == "System.Threading.Tasks.Task<System.Int32> C.F(System.Int32 a)");
var methodInt1 = compilation1.GetMembers("C.F").Single(m => m.ToTestDisplayString() == "System.Threading.Tasks.Task<System.Int32> C.F(System.Int32 a)");
var methodLong0 = compilation0.GetMembers("C.F").Single(m => m.ToTestDisplayString() == "System.Threading.Tasks.Task<System.Int32> C.F(System.Int64 a)");
var methodLong1 = compilation1.GetMembers("C.F").Single(m => m.ToTestDisplayString() == "System.Threading.Tasks.Task<System.Int32> C.F(System.Int64 a)");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, methodShort0, methodShort1, preserveLocalVariables: true),
SemanticEdit.Create(SemanticEditKind.Update, methodInt0, methodInt1, preserveLocalVariables: true),
SemanticEdit.Create(SemanticEditKind.Update, methodLong0, methodLong1, preserveLocalVariables: true)
));
using (var md1 = diff1.GetMetadata())
{
// notice no TypeDefs, FieldDefs
CheckEncLogDefinitions(md1.Reader,
Row(7, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(8, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(9, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(10, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(11, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(12, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(2, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
}
}
[Fact]
public void UpdateIterator_NoVariables()
{
var source0 = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
yield return 1;
}
}";
var source1 = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
yield return 2;
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var v0 = CompileAndVerify(compilation0);
using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: true)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { md0.MetadataReader, reader1 };
// only methods with sequence points should be listed in UpdatedMethods:
CheckNames(readers, diff1.EmitResult.UpdatedMethods, "MoveNext");
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C", "<F>d__0");
// Verify that no new TypeDefs, FieldDefs or MethodDefs were added,
// 3 methods were updated:
// - the kick-off method (might be changed if the method previously wasn't an iterator)
// - Finally method
// - MoveNext method
CheckEncLogDefinitions(md1.Reader,
Row(3, 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.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @"
{
// Code size 57 (0x39)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
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_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_0030
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<F>d__0.<>1__state""
IL_001f: nop
IL_0020: ldarg.0
IL_0021: ldc.i4.2
IL_0022: stfld ""int C.<F>d__0.<>2__current""
IL_0027: ldarg.0
IL_0028: ldc.i4.1
IL_0029: stfld ""int C.<F>d__0.<>1__state""
IL_002e: ldc.i4.1
IL_002f: ret
IL_0030: ldarg.0
IL_0031: ldc.i4.m1
IL_0032: stfld ""int C.<F>d__0.<>1__state""
IL_0037: ldc.i4.0
IL_0038: ret
}");
v0.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @"
{
// Code size 57 (0x39)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
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_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_0030
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<F>d__0.<>1__state""
IL_001f: nop
IL_0020: ldarg.0
IL_0021: ldc.i4.1
IL_0022: stfld ""int C.<F>d__0.<>2__current""
IL_0027: ldarg.0
IL_0028: ldc.i4.1
IL_0029: stfld ""int C.<F>d__0.<>1__state""
IL_002e: ldc.i4.1
IL_002f: ret
IL_0030: ldarg.0
IL_0031: ldc.i4.m1
IL_0032: stfld ""int C.<F>d__0.<>1__state""
IL_0037: ldc.i4.0
IL_0038: ret
}");
}
[Fact]
public void UpdateAsync_NoVariables()
{
var source0 = WithWindowsLineBreaks(@"
using System.Threading.Tasks;
class C
{
static async Task<int> F()
{
await Task.FromResult(1);
return 2;
}
}");
var source1 = WithWindowsLineBreaks(@"
using System.Threading.Tasks;
class C
{
static async Task<int> F()
{
await Task.FromResult(10);
return 20;
}
}");
var compilation0 = CreateCompilationWithMscorlib45(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var v0 = CompileAndVerify(compilation0);
using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { md0.MetadataReader, reader1 };
// only methods with sequence points should be listed in UpdatedMethods:
CheckNames(readers, diff1.EmitResult.UpdatedMethods, "MoveNext");
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C", "<F>d__0");
// Verify that no new TypeDefs, FieldDefs or MethodDefs were added,
// 2 methods were updated:
// - the kick-off method (might be changed if the method previously wasn't async)
// - MoveNext method
CheckEncLogDefinitions(md1.Reader,
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(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(2, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
diff1.VerifyIL("C.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @"
{
// Code size 162 (0xa2)
.maxstack 3
.locals init (int V_0,
int V_1,
System.Runtime.CompilerServices.TaskAwaiter<int> V_2,
C.<F>d__0 V_3,
System.Exception V_4)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_000c
IL_000a: br.s IL_000e
IL_000c: br.s IL_0049
IL_000e: nop
IL_000f: ldc.i4.s 10
IL_0011: call ""System.Threading.Tasks.Task<int> System.Threading.Tasks.Task.FromResult<int>(int)""
IL_0016: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_001b: stloc.2
IL_001c: ldloca.s V_2
IL_001e: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_0023: brtrue.s IL_0065
IL_0025: ldarg.0
IL_0026: ldc.i4.0
IL_0027: dup
IL_0028: stloc.0
IL_0029: stfld ""int C.<F>d__0.<>1__state""
IL_002e: ldarg.0
IL_002f: ldloc.2
IL_0030: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1""
IL_0035: ldarg.0
IL_0036: stloc.3
IL_0037: ldarg.0
IL_0038: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_003d: ldloca.s V_2
IL_003f: ldloca.s V_3
IL_0041: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, C.<F>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref C.<F>d__0)""
IL_0046: nop
IL_0047: leave.s IL_00a1
IL_0049: ldarg.0
IL_004a: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1""
IL_004f: stloc.2
IL_0050: ldarg.0
IL_0051: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1""
IL_0056: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_005c: ldarg.0
IL_005d: ldc.i4.m1
IL_005e: dup
IL_005f: stloc.0
IL_0060: stfld ""int C.<F>d__0.<>1__state""
IL_0065: ldloca.s V_2
IL_0067: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_006c: pop
IL_006d: ldc.i4.s 20
IL_006f: stloc.1
IL_0070: leave.s IL_008c
}
catch System.Exception
{
IL_0072: stloc.s V_4
IL_0074: ldarg.0
IL_0075: ldc.i4.s -2
IL_0077: stfld ""int C.<F>d__0.<>1__state""
IL_007c: ldarg.0
IL_007d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_0082: ldloc.s V_4
IL_0084: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)""
IL_0089: nop
IL_008a: leave.s IL_00a1
}
IL_008c: ldarg.0
IL_008d: ldc.i4.s -2
IL_008f: stfld ""int C.<F>d__0.<>1__state""
IL_0094: ldarg.0
IL_0095: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_009a: ldloc.1
IL_009b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)""
IL_00a0: nop
IL_00a1: ret
}");
v0.VerifyIL("C.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @"
{
// Code size 160 (0xa0)
.maxstack 3
.locals init (int V_0,
int V_1,
System.Runtime.CompilerServices.TaskAwaiter<int> V_2,
C.<F>d__0 V_3,
System.Exception V_4)
~IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
.try
{
~IL_0007: ldloc.0
IL_0008: brfalse.s IL_000c
IL_000a: br.s IL_000e
IL_000c: br.s IL_0048
-IL_000e: nop
-IL_000f: ldc.i4.1
IL_0010: call ""System.Threading.Tasks.Task<int> System.Threading.Tasks.Task.FromResult<int>(int)""
IL_0015: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_001a: stloc.2
~IL_001b: ldloca.s V_2
IL_001d: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_0022: brtrue.s IL_0064
IL_0024: ldarg.0
IL_0025: ldc.i4.0
IL_0026: dup
IL_0027: stloc.0
IL_0028: stfld ""int C.<F>d__0.<>1__state""
<IL_002d: ldarg.0
IL_002e: ldloc.2
IL_002f: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1""
IL_0034: ldarg.0
IL_0035: stloc.3
IL_0036: ldarg.0
IL_0037: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_003c: ldloca.s V_2
IL_003e: ldloca.s V_3
IL_0040: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, C.<F>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref C.<F>d__0)""
IL_0045: nop
IL_0046: leave.s IL_009f
>IL_0048: ldarg.0
IL_0049: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1""
IL_004e: stloc.2
IL_004f: ldarg.0
IL_0050: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__0.<>u__1""
IL_0055: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_005b: ldarg.0
IL_005c: ldc.i4.m1
IL_005d: dup
IL_005e: stloc.0
IL_005f: stfld ""int C.<F>d__0.<>1__state""
IL_0064: ldloca.s V_2
IL_0066: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_006b: pop
-IL_006c: ldc.i4.2
IL_006d: stloc.1
IL_006e: leave.s IL_008a
}
catch System.Exception
{
~IL_0070: stloc.s V_4
IL_0072: ldarg.0
IL_0073: ldc.i4.s -2
IL_0075: stfld ""int C.<F>d__0.<>1__state""
IL_007a: ldarg.0
IL_007b: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_0080: ldloc.s V_4
IL_0082: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)""
IL_0087: nop
IL_0088: leave.s IL_009f
}
-IL_008a: ldarg.0
IL_008b: ldc.i4.s -2
IL_008d: stfld ""int C.<F>d__0.<>1__state""
~IL_0092: ldarg.0
IL_0093: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_0098: ldloc.1
IL_0099: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)""
IL_009e: nop
IL_009f: ret
}", sequencePoints: "C+<F>d__0.MoveNext");
v0.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>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""27"" offset=""0"" />
<slot kind=""20"" offset=""0"" />
<slot kind=""33"" offset=""11"" />
<slot kind=""temp"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" hidden=""true"" document=""1"" />
<entry offset=""0x7"" hidden=""true"" document=""1"" />
<entry offset=""0xe"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
<entry offset=""0xf"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""34"" document=""1"" />
<entry offset=""0x1b"" hidden=""true"" document=""1"" />
<entry offset=""0x6c"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""18"" document=""1"" />
<entry offset=""0x70"" hidden=""true"" document=""1"" />
<entry offset=""0x8a"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" />
<entry offset=""0x92"" hidden=""true"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xa0"">
<namespace name=""System.Threading.Tasks"" />
</scope>
<asyncInfo>
<kickoffMethod declaringType=""C"" methodName=""F"" />
<await yield=""0x2d"" resume=""0x48"" declaringType=""C+<F>d__0"" methodName=""MoveNext"" />
</asyncInfo>
</method>
</methods>
</symbols>");
}
[Fact]
public void UpdateIterator_UserDefinedVariables_NoChange()
{
var source0 = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> F(int p)
{
int x = p;
yield return 1;
}
}";
var source1 = @"
using System.Collections.Generic;
class C
{
static IEnumerable<int> F(int p)
{
int x = p;
yield return 2;
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1);
var v0 = CompileAndVerify(compilation0);
var symReader = v0.CreateSymReader();
using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData))
{
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, symReader.GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
// Verify delta metadata contains expected rows.
using (var md1 = diff1.GetMetadata())
{
// Verify that no new TypeDefs, FieldDefs or MethodDefs were added,
// 3 methods were updated:
// - the kick-off method (might be changed if the method previously wasn't an iterator)
// - Finally method
// - MoveNext method
CheckEncLogDefinitions(md1.Reader,
Row(3, 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.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @"
{
// Code size 69 (0x45)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
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_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_003c
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<F>d__0.<>1__state""
IL_001f: nop
IL_0020: ldarg.0
IL_0021: ldarg.0
IL_0022: ldfld ""int C.<F>d__0.p""
IL_0027: stfld ""int C.<F>d__0.<x>5__1""
IL_002c: ldarg.0
IL_002d: ldc.i4.2
IL_002e: stfld ""int C.<F>d__0.<>2__current""
IL_0033: ldarg.0
IL_0034: ldc.i4.1
IL_0035: stfld ""int C.<F>d__0.<>1__state""
IL_003a: ldc.i4.1
IL_003b: ret
IL_003c: ldarg.0
IL_003d: ldc.i4.m1
IL_003e: stfld ""int C.<F>d__0.<>1__state""
IL_0043: ldc.i4.0
IL_0044: ret
}");
}
}
}
[Fact]
public void UpdateIterator_UserDefinedVariables_AddVariable()
{
var source0 = @"
using System;
using System.Collections.Generic;
class C
{
static IEnumerable<int> F(int p)
{
int x = p;
yield return x;
}
}";
var source1 = @"
using System;
using System.Collections.Generic;
class C
{
static IEnumerable<int> F(int p)
{
int y = 1234;
int x = p;
yield return y;
Console.WriteLine(x);
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1);
var v0 = CompileAndVerify(compilation0);
var symReader = v0.CreateSymReader();
using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData))
{
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, symReader.GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
// Verify delta metadata contains expected rows.
using (var md1 = diff1.GetMetadata())
{
// 1 field def added & 3 methods updated
CheckEncLogDefinitions(md1.Reader,
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(7, TableIndex.Field, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @"
{
// Code size 97 (0x61)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
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_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_004c
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<F>d__0.<>1__state""
IL_001f: nop
IL_0020: ldarg.0
IL_0021: ldc.i4 0x4d2
IL_0026: stfld ""int C.<F>d__0.<y>5__2""
IL_002b: ldarg.0
IL_002c: ldarg.0
IL_002d: ldfld ""int C.<F>d__0.p""
IL_0032: stfld ""int C.<F>d__0.<x>5__1""
IL_0037: ldarg.0
IL_0038: ldarg.0
IL_0039: ldfld ""int C.<F>d__0.<y>5__2""
IL_003e: stfld ""int C.<F>d__0.<>2__current""
IL_0043: ldarg.0
IL_0044: ldc.i4.1
IL_0045: stfld ""int C.<F>d__0.<>1__state""
IL_004a: ldc.i4.1
IL_004b: ret
IL_004c: ldarg.0
IL_004d: ldc.i4.m1
IL_004e: stfld ""int C.<F>d__0.<>1__state""
IL_0053: ldarg.0
IL_0054: ldfld ""int C.<F>d__0.<x>5__1""
IL_0059: call ""void System.Console.WriteLine(int)""
IL_005e: nop
IL_005f: ldc.i4.0
IL_0060: ret
}");
}
}
}
[Fact]
public void UpdateIterator_UserDefinedVariables_AddAndRemoveVariable()
{
var source0 = @"
using System;
using System.Collections.Generic;
class C
{
static IEnumerable<int> F(int p)
{
int x = p;
yield return x;
}
}";
var source1 = @"
using System;
using System.Collections.Generic;
class C
{
static IEnumerable<int> F(int p)
{
int y = 1234;
yield return y;
Console.WriteLine(p);
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1);
var v0 = CompileAndVerify(compilation0);
var symReader = v0.CreateSymReader();
using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData))
{
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, symReader.GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
// Verify delta metadata contains expected rows.
using (var md1 = diff1.GetMetadata())
{
// 1 field def added & 3 methods updated
CheckEncLogDefinitions(md1.Reader,
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(7, TableIndex.Field, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @"
{
// Code size 85 (0x55)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
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_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_0040
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<F>d__0.<>1__state""
IL_001f: nop
IL_0020: ldarg.0
IL_0021: ldc.i4 0x4d2
IL_0026: stfld ""int C.<F>d__0.<y>5__2""
IL_002b: ldarg.0
IL_002c: ldarg.0
IL_002d: ldfld ""int C.<F>d__0.<y>5__2""
IL_0032: stfld ""int C.<F>d__0.<>2__current""
IL_0037: ldarg.0
IL_0038: ldc.i4.1
IL_0039: stfld ""int C.<F>d__0.<>1__state""
IL_003e: ldc.i4.1
IL_003f: ret
IL_0040: ldarg.0
IL_0041: ldc.i4.m1
IL_0042: stfld ""int C.<F>d__0.<>1__state""
IL_0047: ldarg.0
IL_0048: ldfld ""int C.<F>d__0.p""
IL_004d: call ""void System.Console.WriteLine(int)""
IL_0052: nop
IL_0053: ldc.i4.0
IL_0054: ret
}");
}
}
}
[Fact]
public void UpdateIterator_UserDefinedVariables_ChangeVariableType()
{
var source0 = @"
using System;
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
var x = 1;
yield return 1;
Console.WriteLine(x);
}
}";
var source1 = @"
using System;
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
var x = 1.0;
yield return 2;
Console.WriteLine(x);
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1);
var v0 = CompileAndVerify(compilation0);
var symReader = v0.CreateSymReader();
using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData))
{
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, symReader.GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
// Verify delta metadata contains expected rows.
using (var md1 = diff1.GetMetadata())
{
// 1 field def added & 3 methods updated
CheckEncLogDefinitions(md1.Reader,
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(5, TableIndex.Field, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @"
{
// Code size 84 (0x54)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
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_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_003f
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<F>d__0.<>1__state""
IL_001f: nop
IL_0020: ldarg.0
IL_0021: ldc.r8 1
IL_002a: stfld ""double C.<F>d__0.<x>5__2""
IL_002f: ldarg.0
IL_0030: ldc.i4.2
IL_0031: stfld ""int C.<F>d__0.<>2__current""
IL_0036: ldarg.0
IL_0037: ldc.i4.1
IL_0038: stfld ""int C.<F>d__0.<>1__state""
IL_003d: ldc.i4.1
IL_003e: ret
IL_003f: ldarg.0
IL_0040: ldc.i4.m1
IL_0041: stfld ""int C.<F>d__0.<>1__state""
IL_0046: ldarg.0
IL_0047: ldfld ""double C.<F>d__0.<x>5__2""
IL_004c: call ""void System.Console.WriteLine(double)""
IL_0051: nop
IL_0052: ldc.i4.0
IL_0053: ret
}");
}
}
}
[Fact]
public void UpdateIterator_SynthesizedVariables_ChangeVariableType()
{
var source0 = @"
using System;
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
foreach (object item in new[] { 1 }) { yield return 1; }
}
}";
var source1 = @"
using System;
using System.Collections.Generic;
class C
{
static IEnumerable<int> F()
{
foreach (object item in new[] { 1.0 }) { yield return 1; }
}
}";
// Rude edit but the compiler should handle it.
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1);
var v0 = CompileAndVerify(compilation0, symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state: int",
"<>2__current: int",
"<>l__initialThreadId: int",
"<>s__1: int[]",
"<>s__2: int",
"<item>5__3: object"
}, module.GetFieldNamesAndTypes("C.<F>d__0"));
});
var symReader = v0.CreateSymReader();
using (var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData))
{
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, symReader.GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapByKind(method0, SyntaxKind.ForEachStatement), preserveLocalVariables: true)));
// Verify delta metadata contains expected rows.
using (var md1 = diff1.GetMetadata())
{
// 1 field def added & 3 methods updated
CheckEncLogDefinitions(md1.Reader,
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(7, TableIndex.Field, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext", @"
{
// Code size 161 (0xa1)
.maxstack 5
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
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_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_006b
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<F>d__0.<>1__state""
IL_001f: nop
IL_0020: nop
IL_0021: ldarg.0
IL_0022: ldc.i4.1
IL_0023: newarr ""double""
IL_0028: dup
IL_0029: ldc.i4.0
IL_002a: ldc.r8 1
IL_0033: stelem.r8
IL_0034: stfld ""double[] C.<F>d__0.<>s__4""
IL_0039: ldarg.0
IL_003a: ldc.i4.0
IL_003b: stfld ""int C.<F>d__0.<>s__2""
IL_0040: br.s IL_0088
IL_0042: ldarg.0
IL_0043: ldarg.0
IL_0044: ldfld ""double[] C.<F>d__0.<>s__4""
IL_0049: ldarg.0
IL_004a: ldfld ""int C.<F>d__0.<>s__2""
IL_004f: ldelem.r8
IL_0050: box ""double""
IL_0055: stfld ""object C.<F>d__0.<item>5__3""
IL_005a: nop
IL_005b: ldarg.0
IL_005c: ldc.i4.1
IL_005d: stfld ""int C.<F>d__0.<>2__current""
IL_0062: ldarg.0
IL_0063: ldc.i4.1
IL_0064: stfld ""int C.<F>d__0.<>1__state""
IL_0069: ldc.i4.1
IL_006a: ret
IL_006b: ldarg.0
IL_006c: ldc.i4.m1
IL_006d: stfld ""int C.<F>d__0.<>1__state""
IL_0072: nop
IL_0073: ldarg.0
IL_0074: ldnull
IL_0075: stfld ""object C.<F>d__0.<item>5__3""
IL_007a: ldarg.0
IL_007b: ldarg.0
IL_007c: ldfld ""int C.<F>d__0.<>s__2""
IL_0081: ldc.i4.1
IL_0082: add
IL_0083: stfld ""int C.<F>d__0.<>s__2""
IL_0088: ldarg.0
IL_0089: ldfld ""int C.<F>d__0.<>s__2""
IL_008e: ldarg.0
IL_008f: ldfld ""double[] C.<F>d__0.<>s__4""
IL_0094: ldlen
IL_0095: conv.i4
IL_0096: blt.s IL_0042
IL_0098: ldarg.0
IL_0099: ldnull
IL_009a: stfld ""double[] C.<F>d__0.<>s__4""
IL_009f: ldc.i4.0
IL_00a0: ret
}");
}
}
}
[Fact]
public void HoistedVariables_MultipleGenerations()
{
var source0 = @"
using System.Threading.Tasks;
class C
{
static async Task<int> F() // testing type changes G0 -> G1, G1 -> G2
{
bool a1 = true;
int a2 = 3;
await Task.Delay(0);
return 1;
}
static async Task<int> G() // testing G1 -> G3
{
C c = new C();
bool a1 = true;
await Task.Delay(0);
return 1;
}
static async Task<int> H() // testing G0 -> G3
{
C c = new C();
bool a1 = true;
await Task.Delay(0);
return 1;
}
}";
var source1 = @"
using System.Threading.Tasks;
class C
{
static async Task<int> F() // updated
{
C a1 = new C();
int a2 = 3;
await Task.Delay(0);
return 1;
}
static async Task<int> G() // updated
{
C c = new C();
bool a1 = true;
await Task.Delay(0);
return 2;
}
static async Task<int> H()
{
C c = new C();
bool a1 = true;
await Task.Delay(0);
return 1;
}
}";
var source2 = @"
using System.Threading.Tasks;
class C
{
static async Task<int> F() // updated
{
bool a1 = true;
C a2 = new C();
await Task.Delay(0);
return 1;
}
static async Task<int> G()
{
C c = new C();
bool a1 = true;
await Task.Delay(0);
return 2;
}
static async Task<int> H()
{
C c = new C();
bool a1 = true;
await Task.Delay(0);
return 1;
}
}";
var source3 = @"
using System.Threading.Tasks;
class C
{
static async Task<int> F()
{
bool a1 = true;
C a2 = new C();
await Task.Delay(0);
return 1;
}
static async Task<int> G() // updated
{
C c = new C();
C a1 = new C();
await Task.Delay(0);
return 1;
}
static async Task<int> H() // updated
{
C c = new C();
C a1 = new C();
await Task.Delay(0);
return 1;
}
}";
// Rude edit but the compiler should handle it.
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
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 g0 = compilation0.GetMember<MethodSymbol>("C.G");
var g1 = compilation1.GetMember<MethodSymbol>("C.G");
var g2 = compilation2.GetMember<MethodSymbol>("C.G");
var g3 = compilation3.GetMember<MethodSymbol>("C.G");
var h0 = compilation0.GetMember<MethodSymbol>("C.H");
var h1 = compilation1.GetMember<MethodSymbol>("C.H");
var h2 = compilation2.GetMember<MethodSymbol>("C.H");
var h3 = compilation3.GetMember<MethodSymbol>("C.H");
var v0 = CompileAndVerify(compilation0, symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state: int",
"<>t__builder: System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>",
"<a1>5__1: bool",
"<a2>5__2: int",
"<>u__1: System.Runtime.CompilerServices.TaskAwaiter"
}, module.GetFieldNamesAndTypes("C.<F>d__0"));
});
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true),
SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetEquivalentNodesMap(g1, g0), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<F>d__0, <G>d__1}",
"C.<F>d__0: {<>1__state, <>t__builder, <a1>5__3, <a2>5__2, <>u__1, MoveNext, SetStateMachine}",
"C.<G>d__1: {<>1__state, <>t__builder, <c>5__1, <a1>5__2, <>u__1, MoveNext, SetStateMachine}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetEquivalentNodesMap(f2, f1), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<F>d__0, <G>d__1}",
"C.<F>d__0: {<>1__state, <>t__builder, <a1>5__4, <a2>5__5, <>u__1, MoveNext, SetStateMachine, <a1>5__3, <a2>5__2}",
"C.<G>d__1: {<>1__state, <>t__builder, <c>5__1, <a1>5__2, <>u__1, MoveNext, SetStateMachine}");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, g2, g3, GetEquivalentNodesMap(g3, g2), preserveLocalVariables: true),
SemanticEdit.Create(SemanticEditKind.Update, h2, h3, GetEquivalentNodesMap(h3, h2), preserveLocalVariables: true)));
diff3.VerifySynthesizedMembers(
"C: {<G>d__1, <H>d__2, <F>d__0}",
"C.<F>d__0: {<>1__state, <>t__builder, <a1>5__4, <a2>5__5, <>u__1, MoveNext, SetStateMachine, <a1>5__3, <a2>5__2}",
"C.<G>d__1: {<>1__state, <>t__builder, <c>5__1, <a1>5__3, <>u__1, MoveNext, SetStateMachine, <a1>5__2}",
"C.<H>d__2: {<>1__state, <>t__builder, <c>5__1, <a1>5__3, <>u__1, MoveNext, SetStateMachine}");
// Verify delta metadata contains expected rows.
var md1 = diff1.GetMetadata();
var md2 = diff2.GetMetadata();
var md3 = diff3.GetMetadata();
// 1 field def added & 4 methods updated (MoveNext and kickoff for F and G)
CheckEncLogDefinitions(md1.Reader,
Row(7, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(8, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(9, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(10, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(16, TableIndex.Field, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(2, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
diff1.VerifyIL("C.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @"
{
// Code size 192 (0xc0)
.maxstack 3
.locals init (int V_0,
int V_1,
System.Runtime.CompilerServices.TaskAwaiter V_2,
C.<F>d__0 V_3,
System.Exception V_4)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_000c
IL_000a: br.s IL_000e
IL_000c: br.s IL_005a
IL_000e: nop
IL_000f: ldarg.0
IL_0010: newobj ""C..ctor()""
IL_0015: stfld ""C C.<F>d__0.<a1>5__3""
IL_001a: ldarg.0
IL_001b: ldc.i4.3
IL_001c: stfld ""int C.<F>d__0.<a2>5__2""
IL_0021: ldc.i4.0
IL_0022: call ""System.Threading.Tasks.Task System.Threading.Tasks.Task.Delay(int)""
IL_0027: callvirt ""System.Runtime.CompilerServices.TaskAwaiter System.Threading.Tasks.Task.GetAwaiter()""
IL_002c: stloc.2
IL_002d: ldloca.s V_2
IL_002f: call ""bool System.Runtime.CompilerServices.TaskAwaiter.IsCompleted.get""
IL_0034: brtrue.s IL_0076
IL_0036: ldarg.0
IL_0037: ldc.i4.0
IL_0038: dup
IL_0039: stloc.0
IL_003a: stfld ""int C.<F>d__0.<>1__state""
IL_003f: ldarg.0
IL_0040: ldloc.2
IL_0041: stfld ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1""
IL_0046: ldarg.0
IL_0047: stloc.3
IL_0048: ldarg.0
IL_0049: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_004e: ldloca.s V_2
IL_0050: ldloca.s V_3
IL_0052: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter, C.<F>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter, ref C.<F>d__0)""
IL_0057: nop
IL_0058: leave.s IL_00bf
IL_005a: ldarg.0
IL_005b: ldfld ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1""
IL_0060: stloc.2
IL_0061: ldarg.0
IL_0062: ldflda ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1""
IL_0067: initobj ""System.Runtime.CompilerServices.TaskAwaiter""
IL_006d: ldarg.0
IL_006e: ldc.i4.m1
IL_006f: dup
IL_0070: stloc.0
IL_0071: stfld ""int C.<F>d__0.<>1__state""
IL_0076: ldloca.s V_2
IL_0078: call ""void System.Runtime.CompilerServices.TaskAwaiter.GetResult()""
IL_007d: nop
IL_007e: ldc.i4.1
IL_007f: stloc.1
IL_0080: leave.s IL_00a3
}
catch System.Exception
{
IL_0082: stloc.s V_4
IL_0084: ldarg.0
IL_0085: ldc.i4.s -2
IL_0087: stfld ""int C.<F>d__0.<>1__state""
IL_008c: ldarg.0
IL_008d: ldnull
IL_008e: stfld ""C C.<F>d__0.<a1>5__3""
IL_0093: ldarg.0
IL_0094: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_0099: ldloc.s V_4
IL_009b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)""
IL_00a0: nop
IL_00a1: leave.s IL_00bf
}
IL_00a3: ldarg.0
IL_00a4: ldc.i4.s -2
IL_00a6: stfld ""int C.<F>d__0.<>1__state""
IL_00ab: ldarg.0
IL_00ac: ldnull
IL_00ad: stfld ""C C.<F>d__0.<a1>5__3""
IL_00b2: ldarg.0
IL_00b3: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_00b8: ldloc.1
IL_00b9: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)""
IL_00be: nop
IL_00bf: ret
}");
// 2 field defs added (both variables a1 and a2 of F changed their types) & 2 methods updated
CheckEncLogDefinitions(md2.Reader,
Row(11, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(12, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(17, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(18, TableIndex.Field, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(2, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
diff2.VerifyIL("C.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @"
{
// Code size 192 (0xc0)
.maxstack 3
.locals init (int V_0,
int V_1,
System.Runtime.CompilerServices.TaskAwaiter V_2,
C.<F>d__0 V_3,
System.Exception V_4)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_000c
IL_000a: br.s IL_000e
IL_000c: br.s IL_005a
IL_000e: nop
IL_000f: ldarg.0
IL_0010: ldc.i4.1
IL_0011: stfld ""bool C.<F>d__0.<a1>5__4""
IL_0016: ldarg.0
IL_0017: newobj ""C..ctor()""
IL_001c: stfld ""C C.<F>d__0.<a2>5__5""
IL_0021: ldc.i4.0
IL_0022: call ""System.Threading.Tasks.Task System.Threading.Tasks.Task.Delay(int)""
IL_0027: callvirt ""System.Runtime.CompilerServices.TaskAwaiter System.Threading.Tasks.Task.GetAwaiter()""
IL_002c: stloc.2
IL_002d: ldloca.s V_2
IL_002f: call ""bool System.Runtime.CompilerServices.TaskAwaiter.IsCompleted.get""
IL_0034: brtrue.s IL_0076
IL_0036: ldarg.0
IL_0037: ldc.i4.0
IL_0038: dup
IL_0039: stloc.0
IL_003a: stfld ""int C.<F>d__0.<>1__state""
IL_003f: ldarg.0
IL_0040: ldloc.2
IL_0041: stfld ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1""
IL_0046: ldarg.0
IL_0047: stloc.3
IL_0048: ldarg.0
IL_0049: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_004e: ldloca.s V_2
IL_0050: ldloca.s V_3
IL_0052: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter, C.<F>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter, ref C.<F>d__0)""
IL_0057: nop
IL_0058: leave.s IL_00bf
IL_005a: ldarg.0
IL_005b: ldfld ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1""
IL_0060: stloc.2
IL_0061: ldarg.0
IL_0062: ldflda ""System.Runtime.CompilerServices.TaskAwaiter C.<F>d__0.<>u__1""
IL_0067: initobj ""System.Runtime.CompilerServices.TaskAwaiter""
IL_006d: ldarg.0
IL_006e: ldc.i4.m1
IL_006f: dup
IL_0070: stloc.0
IL_0071: stfld ""int C.<F>d__0.<>1__state""
IL_0076: ldloca.s V_2
IL_0078: call ""void System.Runtime.CompilerServices.TaskAwaiter.GetResult()""
IL_007d: nop
IL_007e: ldc.i4.1
IL_007f: stloc.1
IL_0080: leave.s IL_00a3
}
catch System.Exception
{
IL_0082: stloc.s V_4
IL_0084: ldarg.0
IL_0085: ldc.i4.s -2
IL_0087: stfld ""int C.<F>d__0.<>1__state""
IL_008c: ldarg.0
IL_008d: ldnull
IL_008e: stfld ""C C.<F>d__0.<a2>5__5""
IL_0093: ldarg.0
IL_0094: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_0099: ldloc.s V_4
IL_009b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)""
IL_00a0: nop
IL_00a1: leave.s IL_00bf
}
IL_00a3: ldarg.0
IL_00a4: ldc.i4.s -2
IL_00a6: stfld ""int C.<F>d__0.<>1__state""
IL_00ab: ldarg.0
IL_00ac: ldnull
IL_00ad: stfld ""C C.<F>d__0.<a2>5__5""
IL_00b2: ldarg.0
IL_00b3: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_00b8: ldloc.1
IL_00b9: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)""
IL_00be: nop
IL_00bf: ret
}");
// 2 field defs added - variables of G and H changed their types; 4 methods updated: G, H kickoff and MoveNext
CheckEncLogDefinitions(md3.Reader,
Row(13, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(14, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(15, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(16, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(19, TableIndex.Field, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(20, TableIndex.Field, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void HoistedVariables_Dynamic1()
{
var template = @"
using System;
using System.Collections.Generic;
class C
{
public IEnumerable<int> F()
{
dynamic <N:0>x = 1</N:0>;
yield return 1;
Console.WriteLine((int)x + <<VALUE>>);
}
}
";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
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 baselineIL0 = @"
{
// Code size 147 (0x93)
.maxstack 3
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
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_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_003c
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<F>d__0.<>1__state""
IL_001f: nop
IL_0020: ldarg.0
IL_0021: ldc.i4.1
IL_0022: box ""int""
IL_0027: stfld ""dynamic C.<F>d__0.<x>5__1""
IL_002c: ldarg.0
IL_002d: ldc.i4.1
IL_002e: stfld ""int C.<F>d__0.<>2__current""
IL_0033: ldarg.0
IL_0034: ldc.i4.1
IL_0035: stfld ""int C.<F>d__0.<>1__state""
IL_003a: ldc.i4.1
IL_003b: ret
IL_003c: ldarg.0
IL_003d: ldc.i4.m1
IL_003e: stfld ""int C.<F>d__0.<>1__state""
IL_0043: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_0048: brfalse.s IL_004c
IL_004a: br.s IL_0071
IL_004c: ldc.i4.s 16
IL_004e: ldtoken ""int""
IL_0053: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0058: ldtoken ""C""
IL_005d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0062: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_0067: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_006c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_0071: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_0076: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target""
IL_007b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_0080: ldarg.0
IL_0081: ldfld ""dynamic C.<F>d__0.<x>5__1""
IL_0086: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_008b: call ""void System.Console.WriteLine(int)""
IL_0090: nop
IL_0091: ldc.i4.0
IL_0092: ret
}";
v0.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL0);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var baselineIL = @"
{
// Code size 149 (0x95)
.maxstack 3
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
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_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_003c
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<F>d__0.<>1__state""
IL_001f: nop
IL_0020: ldarg.0
IL_0021: ldc.i4.1
IL_0022: box ""int""
IL_0027: stfld ""dynamic C.<F>d__0.<x>5__1""
IL_002c: ldarg.0
IL_002d: ldc.i4.1
IL_002e: stfld ""int C.<F>d__0.<>2__current""
IL_0033: ldarg.0
IL_0034: ldc.i4.1
IL_0035: stfld ""int C.<F>d__0.<>1__state""
IL_003a: ldc.i4.1
IL_003b: ret
IL_003c: ldarg.0
IL_003d: ldc.i4.m1
IL_003e: stfld ""int C.<F>d__0.<>1__state""
IL_0043: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<<DYNAMIC_CONTAINER_NAME>>.<>p__0""
IL_0048: brfalse.s IL_004c
IL_004a: br.s IL_0071
IL_004c: ldc.i4.s 16
IL_004e: ldtoken ""int""
IL_0053: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0058: ldtoken ""C""
IL_005d: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0062: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_0067: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_006c: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<<DYNAMIC_CONTAINER_NAME>>.<>p__0""
IL_0071: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<<DYNAMIC_CONTAINER_NAME>>.<>p__0""
IL_0076: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target""
IL_007b: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<<DYNAMIC_CONTAINER_NAME>>.<>p__0""
IL_0080: ldarg.0
IL_0081: ldfld ""dynamic C.<F>d__0.<x>5__1""
IL_0086: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_008b: ldc.i4.<<VALUE>>
IL_008c: add
IL_008d: call ""void System.Console.WriteLine(int)""
IL_0092: nop
IL_0093: ldc.i4.0
IL_0094: ret
}";
diff1.VerifySynthesizedMembers(
"C: {<>o__0#1, <F>d__0}",
"C.<>o__0#1: {<>p__0}",
"C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}");
diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "1").Replace("<<DYNAMIC_CONTAINER_NAME>>", "<>o__0#1"));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<>o__0#2, <F>d__0, <>o__0#1}",
"C.<>o__0#1: {<>p__0}",
"C.<>o__0#2: {<>p__0}",
"C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}");
diff2.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "2").Replace("<<DYNAMIC_CONTAINER_NAME>>", "<>o__0#2"));
}
[Fact]
public void HoistedVariables_Dynamic2()
{
var source0 = MarkedSource(@"
using System;
using System.Collections.Generic;
class C
{
private static IEnumerable<string> F()
{
dynamic <N:0>d = ""x""</N:0>;
yield return d;
Console.WriteLine(0);
}
}
");
var source1 = MarkedSource(@"
using System;
using System.Collections.Generic;
class C
{
private static IEnumerable<string> F()
{
dynamic <N:0>d = ""x""</N:0>;
yield return d.ToString();
Console.WriteLine(1);
}
}
");
var source2 = MarkedSource(@"
using System;
using System.Collections.Generic;
class C
{
private static IEnumerable<string> F()
{
dynamic <N:0>d = ""x""</N:0>;
yield return d;
Console.WriteLine(2);
}
}
");
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation0.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
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)));
diff1.VerifySynthesizedMembers(
"C: {<>o__0#1, <F>d__0}",
"C.<>o__0#1: {<>p__0, <>p__1}",
"C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <d>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.String>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.String>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.String>.Current, System.Collections.IEnumerator.Current}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<>o__0#2, <F>d__0, <>o__0#1}",
"C.<>o__0#1: {<>p__0, <>p__1}",
"C.<>o__0#2: {<>p__0}",
"C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <d>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.String>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.String>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.String>.Current, System.Collections.IEnumerator.Current}");
}
[Fact]
public void Awaiters1()
{
var source0 = @"
using System.Threading.Tasks;
class C
{
static Task<bool> A1() => null;
static Task<int> A2() => null;
static Task<double> A3() => null;
static async Task<int> F()
{
await A1();
await A2();
return 1;
}
static async Task<int> G()
{
await A2();
await A1();
return 1;
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
CompileAndVerify(compilation0, symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state: int",
"<>t__builder: System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>",
"<>u__1: System.Runtime.CompilerServices.TaskAwaiter<bool>",
"<>u__2: System.Runtime.CompilerServices.TaskAwaiter<int>"
}, module.GetFieldNamesAndTypes("C.<F>d__3"));
Assert.Equal(new[]
{
"<>1__state: int",
"<>t__builder: System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>",
"<>u__1: System.Runtime.CompilerServices.TaskAwaiter<int>",
"<>u__2: System.Runtime.CompilerServices.TaskAwaiter<bool>"
}, module.GetFieldNamesAndTypes("C.<G>d__4"));
});
}
[Fact]
public void Awaiters_MultipleGenerations()
{
var source0 = @"
using System.Threading.Tasks;
class C
{
static Task<bool> A1() => null;
static Task<int> A2() => null;
static Task<C> A3() => null;
static async Task<int> F() // testing type changes G0 -> G1, G1 -> G2
{
await A1();
await A2();
return 1;
}
static async Task<int> G() // testing G1 -> G3
{
await A1();
return 1;
}
static async Task<int> H() // testing G0 -> G3
{
await A1();
return 1;
}
}";
var source1 = @"
using System.Threading.Tasks;
class C
{
static Task<bool> A1() => null;
static Task<int> A2() => null;
static Task<C> A3() => null;
static async Task<int> F() // updated
{
await A3();
await A2();
return 1;
}
static async Task<int> G() // updated
{
await A1();
return 2;
}
static async Task<int> H()
{
await A1();
return 1;
}
}";
var source2 = @"
using System.Threading.Tasks;
class C
{
static Task<bool> A1() => null;
static Task<int> A2() => null;
static Task<C> A3() => null;
static async Task<int> F() // updated
{
await A1();
await A3();
return 1;
}
static async Task<int> G()
{
await A1();
return 2;
}
static async Task<int> H()
{
await A1();
return 1;
}
}";
var source3 = @"
using System.Threading.Tasks;
class C
{
static Task<bool> A1() => null;
static Task<int> A2() => null;
static Task<C> A3() => null;
static async Task<int> F()
{
await A1();
await A3();
return 1;
}
static async Task<int> G() // updated
{
await A3();
return 1;
}
static async Task<int> H() // updated
{
await A3();
return 1;
}
}";
// Rude edit but the compiler should handle it.
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 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 g0 = compilation0.GetMember<MethodSymbol>("C.G");
var g1 = compilation1.GetMember<MethodSymbol>("C.G");
var g2 = compilation2.GetMember<MethodSymbol>("C.G");
var g3 = compilation3.GetMember<MethodSymbol>("C.G");
var h0 = compilation0.GetMember<MethodSymbol>("C.H");
var h1 = compilation1.GetMember<MethodSymbol>("C.H");
var h2 = compilation2.GetMember<MethodSymbol>("C.H");
var h3 = compilation3.GetMember<MethodSymbol>("C.H");
var v0 = CompileAndVerify(compilation0, symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state: int",
"<>t__builder: System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>",
"<>u__1: System.Runtime.CompilerServices.TaskAwaiter<bool>",
"<>u__2: System.Runtime.CompilerServices.TaskAwaiter<int>"
}, module.GetFieldNamesAndTypes("C.<F>d__3"));
});
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapByKind(f0, SyntaxKind.Block), preserveLocalVariables: true),
SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapByKind(g0, SyntaxKind.Block), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<F>d__3, <G>d__4}",
"C.<F>d__3: {<>1__state, <>t__builder, <>u__3, <>u__2, MoveNext, SetStateMachine}",
"C.<G>d__4: {<>1__state, <>t__builder, <>u__1, MoveNext, SetStateMachine}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapByKind(f1, SyntaxKind.Block), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<F>d__3, <G>d__4}",
"C.<F>d__3: {<>1__state, <>t__builder, <>u__4, <>u__3, MoveNext, SetStateMachine, <>u__2}",
"C.<G>d__4: {<>1__state, <>t__builder, <>u__1, MoveNext, SetStateMachine}");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, g2, g3, GetSyntaxMapByKind(g2, SyntaxKind.Block), preserveLocalVariables: true),
SemanticEdit.Create(SemanticEditKind.Update, h2, h3, GetSyntaxMapByKind(h2, SyntaxKind.Block), preserveLocalVariables: true)));
diff3.VerifySynthesizedMembers(
"C: {<G>d__4, <H>d__5, <F>d__3}",
"C.<G>d__4: {<>1__state, <>t__builder, <>u__2, MoveNext, SetStateMachine, <>u__1}",
"C.<H>d__5: {<>1__state, <>t__builder, <>u__2, MoveNext, SetStateMachine}",
"C.<F>d__3: {<>1__state, <>t__builder, <>u__4, <>u__3, MoveNext, SetStateMachine, <>u__2}");
// Verify delta metadata contains expected rows.
var md1 = diff1.GetMetadata();
var md2 = diff2.GetMetadata();
var md3 = diff3.GetMetadata();
// 1 field def added & 4 methods updated (MoveNext and kickoff for F and G)
CheckEncLogDefinitions(md1.Reader,
Row(7, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(8, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(9, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(10, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(11, TableIndex.Field, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
// Note that the new awaiter is allocated slot <>u__3 since <>u__1 and <>u__2 are taken.
diff1.VerifyIL("C.<F>d__3.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @"
{
// Code size 268 (0x10c)
.maxstack 3
.locals init (int V_0,
int V_1,
System.Runtime.CompilerServices.TaskAwaiter<C> V_2,
C.<F>d__3 V_3,
System.Runtime.CompilerServices.TaskAwaiter<int> V_4,
System.Exception V_5)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__3.<>1__state""
IL_0006: stloc.0
.try
{
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_0055
IL_0014: br IL_00b3
IL_0019: nop
IL_001a: call ""System.Threading.Tasks.Task<C> C.A3()""
IL_001f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<C> System.Threading.Tasks.Task<C>.GetAwaiter()""
IL_0024: stloc.2
IL_0025: ldloca.s V_2
IL_0027: call ""bool System.Runtime.CompilerServices.TaskAwaiter<C>.IsCompleted.get""
IL_002c: brtrue.s IL_0071
IL_002e: ldarg.0
IL_002f: ldc.i4.0
IL_0030: dup
IL_0031: stloc.0
IL_0032: stfld ""int C.<F>d__3.<>1__state""
IL_0037: ldarg.0
IL_0038: ldloc.2
IL_0039: stfld ""System.Runtime.CompilerServices.TaskAwaiter<C> C.<F>d__3.<>u__3""
IL_003e: ldarg.0
IL_003f: stloc.3
IL_0040: ldarg.0
IL_0041: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder""
IL_0046: ldloca.s V_2
IL_0048: ldloca.s V_3
IL_004a: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<C>, C.<F>d__3>(ref System.Runtime.CompilerServices.TaskAwaiter<C>, ref C.<F>d__3)""
IL_004f: nop
IL_0050: leave IL_010b
IL_0055: ldarg.0
IL_0056: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<C> C.<F>d__3.<>u__3""
IL_005b: stloc.2
IL_005c: ldarg.0
IL_005d: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<C> C.<F>d__3.<>u__3""
IL_0062: initobj ""System.Runtime.CompilerServices.TaskAwaiter<C>""
IL_0068: ldarg.0
IL_0069: ldc.i4.m1
IL_006a: dup
IL_006b: stloc.0
IL_006c: stfld ""int C.<F>d__3.<>1__state""
IL_0071: ldloca.s V_2
IL_0073: call ""C System.Runtime.CompilerServices.TaskAwaiter<C>.GetResult()""
IL_0078: pop
IL_0079: call ""System.Threading.Tasks.Task<int> C.A2()""
IL_007e: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_0083: stloc.s V_4
IL_0085: ldloca.s V_4
IL_0087: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_008c: brtrue.s IL_00d0
IL_008e: ldarg.0
IL_008f: ldc.i4.1
IL_0090: dup
IL_0091: stloc.0
IL_0092: stfld ""int C.<F>d__3.<>1__state""
IL_0097: ldarg.0
IL_0098: ldloc.s V_4
IL_009a: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__3.<>u__2""
IL_009f: ldarg.0
IL_00a0: stloc.3
IL_00a1: ldarg.0
IL_00a2: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder""
IL_00a7: ldloca.s V_4
IL_00a9: ldloca.s V_3
IL_00ab: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, C.<F>d__3>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref C.<F>d__3)""
IL_00b0: nop
IL_00b1: leave.s IL_010b
IL_00b3: ldarg.0
IL_00b4: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__3.<>u__2""
IL_00b9: stloc.s V_4
IL_00bb: ldarg.0
IL_00bc: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__3.<>u__2""
IL_00c1: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_00c7: ldarg.0
IL_00c8: ldc.i4.m1
IL_00c9: dup
IL_00ca: stloc.0
IL_00cb: stfld ""int C.<F>d__3.<>1__state""
IL_00d0: ldloca.s V_4
IL_00d2: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_00d7: pop
IL_00d8: ldc.i4.1
IL_00d9: stloc.1
IL_00da: leave.s IL_00f6
}
catch System.Exception
{
IL_00dc: stloc.s V_5
IL_00de: ldarg.0
IL_00df: ldc.i4.s -2
IL_00e1: stfld ""int C.<F>d__3.<>1__state""
IL_00e6: ldarg.0
IL_00e7: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder""
IL_00ec: ldloc.s V_5
IL_00ee: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)""
IL_00f3: nop
IL_00f4: leave.s IL_010b
}
IL_00f6: ldarg.0
IL_00f7: ldc.i4.s -2
IL_00f9: stfld ""int C.<F>d__3.<>1__state""
IL_00fe: ldarg.0
IL_00ff: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder""
IL_0104: ldloc.1
IL_0105: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)""
IL_010a: nop
IL_010b: ret
}");
// 1 field def added & 2 methods updated
CheckEncLogDefinitions(md2.Reader,
Row(11, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(12, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(12, TableIndex.Field, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
// Note that the new awaiters are allocated slots <>u__4, <>u__5.
diff2.VerifyIL("C.<F>d__3.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @"
{
// Code size 268 (0x10c)
.maxstack 3
.locals init (int V_0,
int V_1,
System.Runtime.CompilerServices.TaskAwaiter<bool> V_2,
C.<F>d__3 V_3,
System.Runtime.CompilerServices.TaskAwaiter<C> V_4,
System.Exception V_5)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__3.<>1__state""
IL_0006: stloc.0
.try
{
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_0055
IL_0014: br IL_00b3
IL_0019: nop
IL_001a: call ""System.Threading.Tasks.Task<bool> C.A1()""
IL_001f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<bool> System.Threading.Tasks.Task<bool>.GetAwaiter()""
IL_0024: stloc.2
IL_0025: ldloca.s V_2
IL_0027: call ""bool System.Runtime.CompilerServices.TaskAwaiter<bool>.IsCompleted.get""
IL_002c: brtrue.s IL_0071
IL_002e: ldarg.0
IL_002f: ldc.i4.0
IL_0030: dup
IL_0031: stloc.0
IL_0032: stfld ""int C.<F>d__3.<>1__state""
IL_0037: ldarg.0
IL_0038: ldloc.2
IL_0039: stfld ""System.Runtime.CompilerServices.TaskAwaiter<bool> C.<F>d__3.<>u__4""
IL_003e: ldarg.0
IL_003f: stloc.3
IL_0040: ldarg.0
IL_0041: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder""
IL_0046: ldloca.s V_2
IL_0048: ldloca.s V_3
IL_004a: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<bool>, C.<F>d__3>(ref System.Runtime.CompilerServices.TaskAwaiter<bool>, ref C.<F>d__3)""
IL_004f: nop
IL_0050: leave IL_010b
IL_0055: ldarg.0
IL_0056: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<bool> C.<F>d__3.<>u__4""
IL_005b: stloc.2
IL_005c: ldarg.0
IL_005d: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<bool> C.<F>d__3.<>u__4""
IL_0062: initobj ""System.Runtime.CompilerServices.TaskAwaiter<bool>""
IL_0068: ldarg.0
IL_0069: ldc.i4.m1
IL_006a: dup
IL_006b: stloc.0
IL_006c: stfld ""int C.<F>d__3.<>1__state""
IL_0071: ldloca.s V_2
IL_0073: call ""bool System.Runtime.CompilerServices.TaskAwaiter<bool>.GetResult()""
IL_0078: pop
IL_0079: call ""System.Threading.Tasks.Task<C> C.A3()""
IL_007e: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<C> System.Threading.Tasks.Task<C>.GetAwaiter()""
IL_0083: stloc.s V_4
IL_0085: ldloca.s V_4
IL_0087: call ""bool System.Runtime.CompilerServices.TaskAwaiter<C>.IsCompleted.get""
IL_008c: brtrue.s IL_00d0
IL_008e: ldarg.0
IL_008f: ldc.i4.1
IL_0090: dup
IL_0091: stloc.0
IL_0092: stfld ""int C.<F>d__3.<>1__state""
IL_0097: ldarg.0
IL_0098: ldloc.s V_4
IL_009a: stfld ""System.Runtime.CompilerServices.TaskAwaiter<C> C.<F>d__3.<>u__3""
IL_009f: ldarg.0
IL_00a0: stloc.3
IL_00a1: ldarg.0
IL_00a2: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder""
IL_00a7: ldloca.s V_4
IL_00a9: ldloca.s V_3
IL_00ab: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<C>, C.<F>d__3>(ref System.Runtime.CompilerServices.TaskAwaiter<C>, ref C.<F>d__3)""
IL_00b0: nop
IL_00b1: leave.s IL_010b
IL_00b3: ldarg.0
IL_00b4: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<C> C.<F>d__3.<>u__3""
IL_00b9: stloc.s V_4
IL_00bb: ldarg.0
IL_00bc: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<C> C.<F>d__3.<>u__3""
IL_00c1: initobj ""System.Runtime.CompilerServices.TaskAwaiter<C>""
IL_00c7: ldarg.0
IL_00c8: ldc.i4.m1
IL_00c9: dup
IL_00ca: stloc.0
IL_00cb: stfld ""int C.<F>d__3.<>1__state""
IL_00d0: ldloca.s V_4
IL_00d2: call ""C System.Runtime.CompilerServices.TaskAwaiter<C>.GetResult()""
IL_00d7: pop
IL_00d8: ldc.i4.1
IL_00d9: stloc.1
IL_00da: leave.s IL_00f6
}
catch System.Exception
{
IL_00dc: stloc.s V_5
IL_00de: ldarg.0
IL_00df: ldc.i4.s -2
IL_00e1: stfld ""int C.<F>d__3.<>1__state""
IL_00e6: ldarg.0
IL_00e7: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder""
IL_00ec: ldloc.s V_5
IL_00ee: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)""
IL_00f3: nop
IL_00f4: leave.s IL_010b
}
IL_00f6: ldarg.0
IL_00f7: ldc.i4.s -2
IL_00f9: stfld ""int C.<F>d__3.<>1__state""
IL_00fe: ldarg.0
IL_00ff: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__3.<>t__builder""
IL_0104: ldloc.1
IL_0105: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)""
IL_010a: nop
IL_010b: ret
}");
// 2 field defs added - G and H awaiters & 4 methods updated: G, H kickoff and MoveNext
CheckEncLogDefinitions(md3.Reader,
Row(13, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(14, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(15, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(16, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(13, TableIndex.Field, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(14, TableIndex.Field, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(15, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void SynthesizedMembersMerging()
{
var source0 = @"
using System.Collections.Generic;
public class C
{
}";
var source1 = @"
using System.Collections.Generic;
public class C
{
public static IEnumerable<int> F()
{
yield return 1;
yield return 2;
}
}";
var source2 = @"
using System.Collections.Generic;
public class C
{
public static IEnumerable<int> F()
{
yield return 1;
yield return 3;
}
}";
var source3 = @"
using System.Collections.Generic;
public class C
{
public static IEnumerable<int> F()
{
yield return 1;
yield return 3;
}
public static void G()
{
System.Console.WriteLine(1);
}
}";
var source4 = @"
using System.Collections.Generic;
public class C
{
public static IEnumerable<int> F()
{
yield return 1;
yield return 3;
}
public static void G()
{
System.Console.WriteLine(1);
}
public static IEnumerable<int> H()
{
yield return 1;
}
}";
// Rude edit but the compiler should handle it.
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 compilation4 = compilation3.WithSource(source4);
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var f3 = compilation3.GetMember<MethodSymbol>("C.F");
var g3 = compilation3.GetMember<MethodSymbol>("C.G");
var h4 = compilation4.GetMember<MethodSymbol>("C.H");
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)));
diff1.VerifySynthesizedMembers(
"C: {<F>d__0#1}",
"C.<F>d__0#1: {<>1__state, <>2__current, <>l__initialThreadId, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapByKind(f1, SyntaxKind.Block), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<F>d__0#1}",
"C.<F>d__0#1: {<>1__state, <>2__current, <>l__initialThreadId, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, g3)));
diff3.VerifySynthesizedMembers(
"C: {<F>d__0#1}",
"C.<F>d__0#1: {<>1__state, <>2__current, <>l__initialThreadId, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}");
var diff4 = compilation4.EmitDifference(
diff3.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, h4)));
diff4.VerifySynthesizedMembers(
"C: {<H>d__2#4, <F>d__0#1}",
"C.<F>d__0#1: {<>1__state, <>2__current, <>l__initialThreadId, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}",
"C.<H>d__2#4: {<>1__state, <>2__current, <>l__initialThreadId, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}");
}
[Fact]
public void UniqueSynthesizedNames()
{
var source0 = @"
using System.Collections.Generic;
public class C
{
public static IEnumerable<int> F() { yield return 1; }
}";
var source1 = @"
using System.Collections.Generic;
public class C
{
public static IEnumerable<int> F(int a) { yield return 2; }
public static IEnumerable<int> F() { yield return 1; }
}";
var source2 = @"
using System.Collections.Generic;
public class C
{
public static IEnumerable<int> F(int a) { yield return 2; }
public static IEnumerable<int> F(byte a) { yield return 3; }
public static IEnumerable<int> F() { yield return 1; }
}";
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 generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f_int1)));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f_byte2)));
var reader0 = md0.MetadataReader;
var reader1 = diff1.GetMetadata().Reader;
var reader2 = diff2.GetMetadata().Reader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<F>d__0");
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<F>d__0#1");
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<F>d__1#2");
}
[Fact]
public void UpdateAsyncLambda()
{
var source0 = MarkedSource(
@"using System;
using System.Threading.Tasks;
class C
{
static void F()
{
Func<Task> <N:0>g1 = <N:1>async () =>
{
await A1();
await A2();
}</N:1></N:0>;
}
static Task<bool> A1() => null;
static Task<int> A2() => null;
static Task<double> A3() => null;
}");
var source1 = MarkedSource(
@"using System;
using System.Threading.Tasks;
class C
{
static int G() => 1;
static void F()
{
Func<Task> <N:0>g1 = <N:1>async () =>
{
await A2();
await A1();
}</N:1></N:0>;
}
static Task<bool> A1() => null;
static Task<int> A2() => null;
static Task<double> A3() => null;
}");
var source2 = MarkedSource(
@"using System;
using System.Threading.Tasks;
class C
{
static int G() => 1;
static void F()
{
Func<Task> <N:0>g1 = <N:1>async () =>
{
await A1();
await A2();
}</N:1></N:0>;
}
static Task<bool> A1() => null;
static Task<int> A2() => null;
static Task<double> A3() => null;
}");
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0, symbolValidator: module =>
{
Assert.Equal(new[]
{
"<>1__state: int",
"<>t__builder: System.Runtime.CompilerServices.AsyncTaskMethodBuilder",
"<>4__this: C.<>c",
"<>u__1: System.Runtime.CompilerServices.TaskAwaiter<bool>",
"<>u__2: System.Runtime.CompilerServices.TaskAwaiter<int>"
}, module.GetFieldNamesAndTypes("C.<>c.<<F>b__0_0>d"));
});
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// note that the types of the awaiter fields <>u__1, <>u__2 are the same as in the previous generation:
diff1.VerifySynthesizedFields("C.<>c.<<F>b__0_0>d",
"<>1__state: int",
"<>t__builder: System.Runtime.CompilerServices.AsyncTaskMethodBuilder",
"<>4__this: C.<>c",
"<>u__1: System.Runtime.CompilerServices.TaskAwaiter<bool>",
"<>u__2: System.Runtime.CompilerServices.TaskAwaiter<int>");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
// note that the types of the awaiter fields <>u__1, <>u__2 are the same as in the previous generation:
diff2.VerifySynthesizedFields("C.<>c.<<F>b__0_0>d",
"<>1__state: int",
"<>t__builder: System.Runtime.CompilerServices.AsyncTaskMethodBuilder",
"<>4__this: C.<>c",
"<>u__1: System.Runtime.CompilerServices.TaskAwaiter<bool>",
"<>u__2: System.Runtime.CompilerServices.TaskAwaiter<int>");
}
[Fact, WorkItem(1170899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1170899")]
public void HoistedAnonymousTypes1()
{
var source0 = MarkedSource(@"
using System;
using System.Collections.Generic;
class C
{
public IEnumerable<int> F()
{
var <N:0>x = new { A = 1 }</N:0>;
yield return 1;
Console.WriteLine(x.A + 1);
}
}
");
var source1 = MarkedSource(@"
using System;
using System.Collections.Generic;
class C
{
public IEnumerable<int> F()
{
var <N:0>x = new { A = 1 }</N:0>;
yield return 1;
Console.WriteLine(x.A + 2);
}
}
");
var source2 = MarkedSource(@"
using System;
using System.Collections.Generic;
class C
{
public IEnumerable<int> F()
{
var <N:0>x = new { A = 1 }</N:0>;
yield return 1;
Console.WriteLine(x.A + 3);
}
}
");
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
using 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 f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var baselineIL = @"
{
// Code size 88 (0x58)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
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_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_003c
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<F>d__0.<>1__state""
IL_001f: nop
IL_0020: ldarg.0
IL_0021: ldc.i4.1
IL_0022: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0027: stfld ""<anonymous type: int A> C.<F>d__0.<x>5__1""
IL_002c: ldarg.0
IL_002d: ldc.i4.1
IL_002e: stfld ""int C.<F>d__0.<>2__current""
IL_0033: ldarg.0
IL_0034: ldc.i4.1
IL_0035: stfld ""int C.<F>d__0.<>1__state""
IL_003a: ldc.i4.1
IL_003b: ret
IL_003c: ldarg.0
IL_003d: ldc.i4.m1
IL_003e: stfld ""int C.<F>d__0.<>1__state""
IL_0043: ldarg.0
IL_0044: ldfld ""<anonymous type: int A> C.<F>d__0.<x>5__1""
IL_0049: callvirt ""int <>f__AnonymousType0<int>.A.get""
IL_004e: ldc.i4.<<VALUE>>
IL_004f: add
IL_0050: call ""void System.Console.WriteLine(int)""
IL_0055: nop
IL_0056: ldc.i4.0
IL_0057: ret
}";
v0.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "1"));
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.UpdatedMethods, "MoveNext");
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C", "<F>d__0");
diff1.VerifySynthesizedMembers(
"C: {<F>d__0}",
"C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "2"));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, diff2.EmitResult.UpdatedMethods, "MoveNext");
CheckNames(readers, diff2.EmitResult.ChangedTypes, "C", "<F>d__0");
diff2.VerifySynthesizedMembers(
"C: {<F>d__0}",
"C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "3"));
}
[Fact, WorkItem(3192, "https://github.com/dotnet/roslyn/issues/3192")]
public void HoistedAnonymousTypes_Nested()
{
var source0 = MarkedSource(@"
using System;
using System.Collections.Generic;
class C
{
public IEnumerable<int> F()
{
var <N:0>x = new[] { new { A = new { B = 1 } } }</N:0>;
yield return 1;
Console.WriteLine(x[0].A.B + 1);
}
}
");
var source1 = MarkedSource(@"
using System;
using System.Collections.Generic;
class C
{
public IEnumerable<int> F()
{
var <N:0>x = new[] { new { A = new { B = 1 } } }</N:0>;
yield return 1;
Console.WriteLine(x[0].A.B + 2);
}
}
");
var source2 = MarkedSource(@"
using System;
using System.Collections.Generic;
class C
{
public IEnumerable<int> F()
{
var <N:0>x = new[] { new { A = new { B = 1 } } }</N:0>;
yield return 1;
Console.WriteLine(x[0].A.B + 3);
}
}
");
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
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 baselineIL = @"
{
// Code size 109 (0x6d)
.maxstack 5
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
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_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_004a
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<F>d__0.<>1__state""
IL_001f: nop
IL_0020: ldarg.0
IL_0021: ldc.i4.1
IL_0022: newarr ""<>f__AnonymousType0<<anonymous type: int B>>""
IL_0027: dup
IL_0028: ldc.i4.0
IL_0029: ldc.i4.1
IL_002a: newobj ""<>f__AnonymousType1<int>..ctor(int)""
IL_002f: newobj ""<>f__AnonymousType0<<anonymous type: int B>>..ctor(<anonymous type: int B>)""
IL_0034: stelem.ref
IL_0035: stfld ""<anonymous type: <anonymous type: int B> A>[] C.<F>d__0.<x>5__1""
IL_003a: ldarg.0
IL_003b: ldc.i4.1
IL_003c: stfld ""int C.<F>d__0.<>2__current""
IL_0041: ldarg.0
IL_0042: ldc.i4.1
IL_0043: stfld ""int C.<F>d__0.<>1__state""
IL_0048: ldc.i4.1
IL_0049: ret
IL_004a: ldarg.0
IL_004b: ldc.i4.m1
IL_004c: stfld ""int C.<F>d__0.<>1__state""
IL_0051: ldarg.0
IL_0052: ldfld ""<anonymous type: <anonymous type: int B> A>[] C.<F>d__0.<x>5__1""
IL_0057: ldc.i4.0
IL_0058: ldelem.ref
IL_0059: callvirt ""<anonymous type: int B> <>f__AnonymousType0<<anonymous type: int B>>.A.get""
IL_005e: callvirt ""int <>f__AnonymousType1<int>.B.get""
IL_0063: ldc.i4.<<VALUE>>
IL_0064: add
IL_0065: call ""void System.Console.WriteLine(int)""
IL_006a: nop
IL_006b: ldc.i4.0
IL_006c: ret
}";
v0.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "1"));
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<F>d__0}",
"C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<B>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "2"));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<F>d__0}",
"C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<B>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "3"));
}
[Fact, WorkItem(3192, "https://github.com/dotnet/roslyn/issues/3192")]
public void HoistedGenericTypes()
{
var source0 = MarkedSource(@"
using System;
using System.Collections.Generic;
class Z<T1>
{
public class S<T2> { public T1 a = default(T1); public T2 b = default(T2); }
}
class C
{
public IEnumerable<int> F()
{
var <N:0>x = new Z<double>.S<int>()</N:0>;
yield return 1;
Console.WriteLine(x.a + x.b + 1);
}
}
");
var source1 = MarkedSource(@"
using System;
using System.Collections.Generic;
class Z<T1>
{
public class S<T2> { public T1 a = default(T1); public T2 b = default(T2); }
}
class C
{
public IEnumerable<int> F()
{
var <N:0>x = new Z<double>.S<int>()</N:0>;
yield return 1;
Console.WriteLine(x.a + x.b + 2);
}
}
");
var source2 = MarkedSource(@"
using System;
using System.Collections.Generic;
class Z<T1>
{
public class S<T2> { public T1 a = default(T1); public T2 b = default(T2); }
}
class C
{
public IEnumerable<int> F()
{
var <N:0>x = new Z<double>.S<int>()</N:0>;
yield return 1;
Console.WriteLine(x.a + x.b + 3);
}
}
");
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
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 baselineIL = @"
{
// Code size 108 (0x6c)
.maxstack 2
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
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_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_003b
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<F>d__0.<>1__state""
IL_001f: nop
IL_0020: ldarg.0
IL_0021: newobj ""Z<double>.S<int>..ctor()""
IL_0026: stfld ""Z<double>.S<int> C.<F>d__0.<x>5__1""
IL_002b: ldarg.0
IL_002c: ldc.i4.1
IL_002d: stfld ""int C.<F>d__0.<>2__current""
IL_0032: ldarg.0
IL_0033: ldc.i4.1
IL_0034: stfld ""int C.<F>d__0.<>1__state""
IL_0039: ldc.i4.1
IL_003a: ret
IL_003b: ldarg.0
IL_003c: ldc.i4.m1
IL_003d: stfld ""int C.<F>d__0.<>1__state""
IL_0042: ldarg.0
IL_0043: ldfld ""Z<double>.S<int> C.<F>d__0.<x>5__1""
IL_0048: ldfld ""double Z<double>.S<int>.a""
IL_004d: ldarg.0
IL_004e: ldfld ""Z<double>.S<int> C.<F>d__0.<x>5__1""
IL_0053: ldfld ""int Z<double>.S<int>.b""
IL_0058: conv.r8
IL_0059: add
IL_005a: ldc.r8 <<VALUE>>
IL_0063: add
IL_0064: call ""void System.Console.WriteLine(double)""
IL_0069: nop
IL_006a: ldc.i4.0
IL_006b: ret
}";
v0.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "1"));
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<F>d__0}",
"C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}");
diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "2"));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<F>d__0}",
"C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}");
diff2.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "3"));
}
[Fact]
public void HoistedAnonymousTypes_Dynamic()
{
var template = @"
using System;
using System.Collections.Generic;
class C
{
public IEnumerable<int> F()
{
var <N:0>x = new { A = (dynamic)null, B = 1 }</N:0>;
yield return 1;
Console.WriteLine(x.B + <<VALUE>>);
}
}
";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
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 baselineIL0 = @"
{
// Code size 87 (0x57)
.maxstack 3
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
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_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_003d
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<F>d__0.<>1__state""
IL_001f: nop
IL_0020: ldarg.0
IL_0021: ldnull
IL_0022: ldc.i4.1
IL_0023: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)""
IL_0028: stfld ""<anonymous type: dynamic A, int B> C.<F>d__0.<x>5__1""
IL_002d: ldarg.0
IL_002e: ldc.i4.1
IL_002f: stfld ""int C.<F>d__0.<>2__current""
IL_0034: ldarg.0
IL_0035: ldc.i4.1
IL_0036: stfld ""int C.<F>d__0.<>1__state""
IL_003b: ldc.i4.1
IL_003c: ret
IL_003d: ldarg.0
IL_003e: ldc.i4.m1
IL_003f: stfld ""int C.<F>d__0.<>1__state""
IL_0044: ldarg.0
IL_0045: ldfld ""<anonymous type: dynamic A, int B> C.<F>d__0.<x>5__1""
IL_004a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get""
IL_004f: call ""void System.Console.WriteLine(int)""
IL_0054: nop
IL_0055: ldc.i4.0
IL_0056: ret
}";
v0.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL0);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var baselineIL = @"
{
// Code size 89 (0x59)
.maxstack 3
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
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_0016
IL_0012: br.s IL_0018
IL_0014: br.s IL_003d
IL_0016: ldc.i4.0
IL_0017: ret
IL_0018: ldarg.0
IL_0019: ldc.i4.m1
IL_001a: stfld ""int C.<F>d__0.<>1__state""
IL_001f: nop
IL_0020: ldarg.0
IL_0021: ldnull
IL_0022: ldc.i4.1
IL_0023: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)""
IL_0028: stfld ""<anonymous type: dynamic A, int B> C.<F>d__0.<x>5__1""
IL_002d: ldarg.0
IL_002e: ldc.i4.1
IL_002f: stfld ""int C.<F>d__0.<>2__current""
IL_0034: ldarg.0
IL_0035: ldc.i4.1
IL_0036: stfld ""int C.<F>d__0.<>1__state""
IL_003b: ldc.i4.1
IL_003c: ret
IL_003d: ldarg.0
IL_003e: ldc.i4.m1
IL_003f: stfld ""int C.<F>d__0.<>1__state""
IL_0044: ldarg.0
IL_0045: ldfld ""<anonymous type: dynamic A, int B> C.<F>d__0.<x>5__1""
IL_004a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get""
IL_004f: ldc.i4.<<VALUE>>
IL_0050: add
IL_0051: call ""void System.Console.WriteLine(int)""
IL_0056: nop
IL_0057: ldc.i4.0
IL_0058: ret
}";
diff1.VerifySynthesizedMembers(
"C: {<F>d__0}",
"C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}",
"<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.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: {<F>d__0}",
"C.<F>d__0: {<>1__state, <>2__current, <>l__initialThreadId, <>4__this, <x>5__1, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.Int32>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.Int32>.Current, System.Collections.IEnumerator.Current}",
"<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.<F>d__0.System.Collections.IEnumerator.MoveNext()", baselineIL.Replace("<<VALUE>>", "2"));
}
[Fact, WorkItem(3192, "https://github.com/dotnet/roslyn/issues/3192")]
public void HoistedAnonymousTypes_Delete()
{
var source0 = MarkedSource(@"
using System.Linq;
using System.Threading.Tasks;
class C
{
static async Task<int> F()
{
var <N:1>x = from b in new[] { 1, 2, 3 } <N:0>select new { A = b }</N:0></N:1>;
return <N:2>await Task.FromResult(1)</N:2>;
}
}
");
var source1 = MarkedSource(@"
using System.Linq;
using System.Threading.Tasks;
class C
{
static async Task<int> F()
{
var <N:1>x = from b in new[] { 1, 2, 3 } <N:0>select new { A = b }</N:0></N:1>;
var y = x.First();
return <N:2>await Task.FromResult(1)</N:2>;
}
}
");
var source2 = source0;
var source3 = source1;
var source4 = source0;
var source5 = source1;
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation0.WithSource(source2.Tree);
var compilation3 = compilation0.WithSource(source3.Tree);
var compilation4 = compilation0.WithSource(source4.Tree);
var compilation5 = compilation0.WithSource(source5.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 f4 = compilation4.GetMember<MethodSymbol>("C.F");
var f5 = compilation5.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
// y is added
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<>c, <F>d__0}",
"C.<>c: {<>9__0_0, <F>b__0_0}",
"C.<F>d__0: {<>1__state, <>t__builder, <x>5__1, <y>5__3, <>s__2, <>u__1, MoveNext, SetStateMachine}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
// y is removed
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
// Synthesized members collection still includes y field since members are only added to it and never deleted.
// The corresponding CLR field is also present.
diff2.VerifySynthesizedMembers(
"C: {<>c, <F>d__0}",
"C.<>c: {<>9__0_0, <F>b__0_0}",
"C.<F>d__0: {<>1__state, <>t__builder, <x>5__1, <>s__2, <>u__1, MoveNext, SetStateMachine, <y>5__3}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
// y is added and a new slot index is allocated for it
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f2, f3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables: true)));
diff3.VerifySynthesizedMembers(
"C: {<>c, <F>d__0}",
"C.<>c: {<>9__0_0, <F>b__0_0}",
"C.<F>d__0: {<>1__state, <>t__builder, <x>5__1, <y>5__4, <>s__2, <>u__1, MoveNext, SetStateMachine, <y>5__3}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
// y is removed
var diff4 = compilation4.EmitDifference(
diff3.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f3, f4, GetSyntaxMapFromMarkers(source3, source4), preserveLocalVariables: true)));
diff4.VerifySynthesizedMembers(
"C: {<>c, <F>d__0}",
"C.<>c: {<>9__0_0, <F>b__0_0}",
"C.<F>d__0: {<>1__state, <>t__builder, <x>5__1, <>s__2, <>u__1, MoveNext, SetStateMachine, <y>5__4, <y>5__3}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
// y is added
var diff5 = compilation5.EmitDifference(
diff4.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f4, f5, GetSyntaxMapFromMarkers(source4, source5), preserveLocalVariables: true)));
diff5.VerifySynthesizedMembers(
"C: {<>c, <F>d__0}",
"C.<>c: {<>9__0_0, <F>b__0_0}",
"C.<F>d__0: {<>1__state, <>t__builder, <x>5__1, <y>5__5, <>s__2, <>u__1, MoveNext, SetStateMachine, <y>5__4, <y>5__3}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
}
[Fact]
public void HoistedAnonymousTypes_Dynamic2()
{
var source0 = MarkedSource(@"
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
args = Iterator().ToArray();
}
private static IEnumerable<string> Iterator()
{
string[] <N:15>args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" }</N:15>;
var <N:16>list = false ? null : new { Head = (dynamic)null, Tail = (dynamic)null }</N:16>;
for (int <N:18>i = 0</N:18>; i < 10; i++)
{
var <N:6>result =
from a in args
<N:0>let x = a.Reverse()</N:0>
<N:1>let y = x.Reverse()</N:1>
<N:2>where x.SequenceEqual(y)</N:2>
orderby <N:3>a.Length ascending</N:3>, <N:4>a descending</N:4>
<N:5>select new { Value = a, Length = x.Count() }</N:5></N:6>;
var <N:8>linked = result.Aggregate(
false ? new { Head = (string)null, Tail = (dynamic)null } : null,
<N:7>(total, curr) => new { Head = curr.Value, Tail = (dynamic)total }</N:7>)</N:8>;
while (linked != null)
{
<N:9>yield return linked.Head</N:9>;
linked = linked.Tail;
}
var <N:14>newArgs =
from a in result
<N:10>let value = a.Value</N:10>
<N:11>let length = a.Length</N:11>
<N:12>where value.Length == length</N:12>
<N:13>select value + value</N:13></N:14>;
args = args.Concat(newArgs).ToArray();
list = new { Head = (dynamic)i, Tail = (dynamic)list };
System.Diagnostics.Debugger.Break();
}
System.Diagnostics.Debugger.Break();
}
}
");
var source1 = MarkedSource(@"
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
args = Iterator().ToArray();
}
private static IEnumerable<string> Iterator()
{
string[] <N:15>args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" }</N:15>;
var <N:16>list = false ? null : new { Head = (dynamic)null, Tail = (dynamic)null }</N:16>;
for (int <N:18>i = 0</N:18>; i < 10; i++)
{
var <N:6>result =
from a in args
<N:0>let x = a.Reverse()</N:0>
<N:1>let y = x.Reverse()</N:1>
<N:2>where x.SequenceEqual(y)</N:2>
orderby <N:3>a.Length ascending</N:3>, <N:4>a descending</N:4>
<N:5>select new { Value = a, Length = x.Count() }</N:5></N:6>;
var <N:8>linked = result.Aggregate(
false ? new { Head = (string)null, Tail = (dynamic)null } : null,
<N:7>(total, curr) => new { Head = curr.Value, Tail = (dynamic)total }</N:7>)</N:8>;
var <N:17>temp = list</N:17>;
while (temp != null)
{
<N:9>yield return temp.Head</N:9>;
temp = temp.Tail;
}
var <N:14>newArgs =
from a in result
<N:10>let value = a.Value</N:10>
<N:11>let length = a.Length</N:11>
<N:12>where value.Length == length</N:12>
<N:13>select value + value</N:13></N:14>;
args = args.Concat(newArgs).ToArray();
list = new { Head = (dynamic)i, Tail = (dynamic)list };
System.Diagnostics.Debugger.Break();
}
System.Diagnostics.Debugger.Break();
}
}
");
var source2 = MarkedSource(@"
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
args = Iterator().ToArray();
}
private static IEnumerable<string> Iterator()
{
string[] <N:15>args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" }</N:15>;
var <N:16>list = false ? null : new { Head = (dynamic)null, Tail = (dynamic)null }</N:16>;
for (int <N:18>i = 0</N:18>; i < 10; i++)
{
var <N:6>result =
from a in args
<N:0>let x = a.Reverse()</N:0>
<N:1>let y = x.Reverse()</N:1>
<N:2>where x.SequenceEqual(y)</N:2>
orderby <N:3>a.Length ascending</N:3>, <N:4>a descending</N:4>
<N:5>select new { Value = a, Length = x.Count() }</N:5></N:6>;
var <N:8>linked = result.Aggregate(
false ? new { Head = (string)null, Tail = (dynamic)null } : null,
<N:7>(total, curr) => new { Head = curr.Value, Tail = (dynamic)total }</N:7>)</N:8>;
var <N:17>temp = list</N:17>;
while (temp != null)
{
<N:9>yield return temp.Head.ToString()</N:9>;
temp = temp.Tail;
}
var <N:14>newArgs =
from a in result
<N:10>let value = a.Value</N:10>
<N:11>let length = a.Length</N:11>
<N:12>where value.Length == length</N:12>
<N:13>select value + value</N:13></N:14>;
args = args.Concat(newArgs).ToArray();
list = new { Head = (dynamic)i, Tail = (dynamic)list };
System.Diagnostics.Debugger.Break();
}
System.Diagnostics.Debugger.Break();
}
}
");
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("Program.Iterator");
var f1 = compilation1.GetMember<MethodSymbol>("Program.Iterator");
var f2 = compilation2.GetMember<MethodSymbol>("Program.Iterator");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
v0.VerifyIL("Program.<Iterator>d__1.System.Collections.IEnumerator.MoveNext()", @"
{
// Code size 798 (0x31e)
.maxstack 5
.locals init (int V_0,
bool V_1,
int V_2,
bool V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Iterator>d__1.<>1__state""
IL_0006: stloc.0
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_001b
IL_0014: br IL_019b
IL_0019: ldc.i4.0
IL_001a: ret
IL_001b: ldarg.0
IL_001c: ldc.i4.m1
IL_001d: stfld ""int Program.<Iterator>d__1.<>1__state""
IL_0022: nop
IL_0023: ldarg.0
IL_0024: ldc.i4.4
IL_0025: newarr ""string""
IL_002a: dup
IL_002b: ldc.i4.0
IL_002c: ldstr ""a""
IL_0031: stelem.ref
IL_0032: dup
IL_0033: ldc.i4.1
IL_0034: ldstr ""bB""
IL_0039: stelem.ref
IL_003a: dup
IL_003b: ldc.i4.2
IL_003c: ldstr ""Cc""
IL_0041: stelem.ref
IL_0042: dup
IL_0043: ldc.i4.3
IL_0044: ldstr ""DD""
IL_0049: stelem.ref
IL_004a: stfld ""string[] Program.<Iterator>d__1.<args>5__1""
IL_004f: ldarg.0
IL_0050: ldnull
IL_0051: ldnull
IL_0052: newobj ""<>f__AnonymousType0<dynamic, dynamic>..ctor(dynamic, dynamic)""
IL_0057: stfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<list>5__2""
IL_005c: ldarg.0
IL_005d: ldc.i4.0
IL_005e: stfld ""int Program.<Iterator>d__1.<i>5__3""
IL_0063: br IL_0305
IL_0068: nop
IL_0069: ldarg.0
IL_006a: ldarg.0
IL_006b: ldfld ""string[] Program.<Iterator>d__1.<args>5__1""
IL_0070: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> Program.<>c.<>9__1_0""
IL_0075: dup
IL_0076: brtrue.s IL_008f
IL_0078: pop
IL_0079: ldsfld ""Program.<>c Program.<>c.<>9""
IL_007e: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> Program.<>c.<Iterator>b__1_0(string)""
IL_0084: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)""
IL_0089: dup
IL_008a: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> Program.<>c.<>9__1_0""
IL_008f: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)""
IL_0094: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> Program.<>c.<>9__1_1""
IL_0099: dup
IL_009a: brtrue.s IL_00b3
IL_009c: pop
IL_009d: ldsfld ""Program.<>c Program.<>c.<>9""
IL_00a2: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> Program.<>c.<Iterator>b__1_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)""
IL_00a8: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)""
IL_00ad: dup
IL_00ae: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> Program.<>c.<>9__1_1""
IL_00b3: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)""
IL_00b8: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> Program.<>c.<>9__1_2""
IL_00bd: dup
IL_00be: brtrue.s IL_00d7
IL_00c0: pop
IL_00c1: ldsfld ""Program.<>c Program.<>c.<>9""
IL_00c6: ldftn ""bool Program.<>c.<Iterator>b__1_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_00cc: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)""
IL_00d1: dup
IL_00d2: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> Program.<>c.<>9__1_2""
IL_00d7: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)""
IL_00dc: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int> Program.<>c.<>9__1_3""
IL_00e1: dup
IL_00e2: brtrue.s IL_00fb
IL_00e4: pop
IL_00e5: ldsfld ""Program.<>c Program.<>c.<>9""
IL_00ea: ldftn ""int Program.<>c.<Iterator>b__1_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_00f0: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int>..ctor(object, System.IntPtr)""
IL_00f5: dup
IL_00f6: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int> Program.<>c.<>9__1_3""
IL_00fb: call ""System.Linq.IOrderedEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.OrderBy<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int>)""
IL_0100: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string> Program.<>c.<>9__1_4""
IL_0105: dup
IL_0106: brtrue.s IL_011f
IL_0108: pop
IL_0109: ldsfld ""Program.<>c Program.<>c.<>9""
IL_010e: ldftn ""string Program.<>c.<Iterator>b__1_4(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_0114: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string>..ctor(object, System.IntPtr)""
IL_0119: dup
IL_011a: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string> Program.<>c.<>9__1_4""
IL_011f: call ""System.Linq.IOrderedEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.ThenByDescending<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string>(System.Linq.IOrderedEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string>)""
IL_0124: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> Program.<>c.<>9__1_5""
IL_0129: dup
IL_012a: brtrue.s IL_0143
IL_012c: pop
IL_012d: ldsfld ""Program.<>c Program.<>c.<>9""
IL_0132: ldftn ""<anonymous type: string Value, int Length> Program.<>c.<Iterator>b__1_5(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_0138: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)""
IL_013d: dup
IL_013e: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> Program.<>c.<>9__1_5""
IL_0143: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)""
IL_0148: stfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4""
IL_014d: ldarg.0
IL_014e: ldarg.0
IL_014f: ldfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4""
IL_0154: ldnull
IL_0155: ldsfld ""System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>> Program.<>c.<>9__1_6""
IL_015a: dup
IL_015b: brtrue.s IL_0174
IL_015d: pop
IL_015e: ldsfld ""Program.<>c Program.<>c.<>9""
IL_0163: ldftn ""<anonymous type: string Head, dynamic Tail> Program.<>c.<Iterator>b__1_6(<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>)""
IL_0169: newobj ""System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>>..ctor(object, System.IntPtr)""
IL_016e: dup
IL_016f: stsfld ""System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>> Program.<>c.<>9__1_6""
IL_0174: call ""<anonymous type: string Head, dynamic Tail> System.Linq.Enumerable.Aggregate<<anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>>(System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>>, <anonymous type: string Head, dynamic Tail>, System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>>)""
IL_0179: stfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5""
IL_017e: br.s IL_01f5
IL_0180: nop
IL_0181: ldarg.0
IL_0182: ldarg.0
IL_0183: ldfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5""
IL_0188: callvirt ""string <>f__AnonymousType0<string, dynamic>.Head.get""
IL_018d: stfld ""string Program.<Iterator>d__1.<>2__current""
IL_0192: ldarg.0
IL_0193: ldc.i4.1
IL_0194: stfld ""int Program.<Iterator>d__1.<>1__state""
IL_0199: ldc.i4.1
IL_019a: ret
IL_019b: ldarg.0
IL_019c: ldc.i4.m1
IL_019d: stfld ""int Program.<Iterator>d__1.<>1__state""
IL_01a2: ldarg.0
IL_01a3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>> Program.<>o__1.<>p__0""
IL_01a8: brfalse.s IL_01ac
IL_01aa: br.s IL_01d0
IL_01ac: ldc.i4.0
IL_01ad: ldtoken ""<>f__AnonymousType0<string, dynamic>""
IL_01b2: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_01b7: ldtoken ""Program""
IL_01bc: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_01c1: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_01c6: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_01cb: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>> Program.<>o__1.<>p__0""
IL_01d0: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>> Program.<>o__1.<>p__0""
IL_01d5: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>>.Target""
IL_01da: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>> Program.<>o__1.<>p__0""
IL_01df: ldarg.0
IL_01e0: ldfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5""
IL_01e5: callvirt ""dynamic <>f__AnonymousType0<string, dynamic>.Tail.get""
IL_01ea: callvirt ""<anonymous type: string Head, dynamic Tail> System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: string Head, dynamic Tail>>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_01ef: stfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5""
IL_01f4: nop
IL_01f5: ldarg.0
IL_01f6: ldfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5""
IL_01fb: ldnull
IL_01fc: cgt.un
IL_01fe: stloc.1
IL_01ff: ldloc.1
IL_0200: brtrue IL_0180
IL_0205: ldarg.0
IL_0206: ldarg.0
IL_0207: ldfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4""
IL_020c: ldsfld ""System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>> Program.<>c.<>9__1_7""
IL_0211: dup
IL_0212: brtrue.s IL_022b
IL_0214: pop
IL_0215: ldsfld ""Program.<>c Program.<>c.<>9""
IL_021a: ldftn ""<anonymous type: <anonymous type: string Value, int Length> a, string value> Program.<>c.<Iterator>b__1_7(<anonymous type: string Value, int Length>)""
IL_0220: newobj ""System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>>..ctor(object, System.IntPtr)""
IL_0225: dup
IL_0226: stsfld ""System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>> Program.<>c.<>9__1_7""
IL_022b: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string Value, int Length> a, string value>> System.Linq.Enumerable.Select<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>>(System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>>, System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>>)""
IL_0230: ldsfld ""System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> Program.<>c.<>9__1_8""
IL_0235: dup
IL_0236: brtrue.s IL_024f
IL_0238: pop
IL_0239: ldsfld ""Program.<>c Program.<>c.<>9""
IL_023e: ldftn ""<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length> Program.<>c.<Iterator>b__1_8(<anonymous type: <anonymous type: string Value, int Length> a, string value>)""
IL_0244: newobj ""System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>..ctor(object, System.IntPtr)""
IL_0249: dup
IL_024a: stsfld ""System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> Program.<>c.<>9__1_8""
IL_024f: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string Value, int Length> a, string value>>, System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>)""
IL_0254: ldsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool> Program.<>c.<>9__1_9""
IL_0259: dup
IL_025a: brtrue.s IL_0273
IL_025c: pop
IL_025d: ldsfld ""Program.<>c Program.<>c.<>9""
IL_0262: ldftn ""bool Program.<>c.<Iterator>b__1_9(<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>)""
IL_0268: newobj ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool>..ctor(object, System.IntPtr)""
IL_026d: dup
IL_026e: stsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool> Program.<>c.<>9__1_9""
IL_0273: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>, System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool>)""
IL_0278: ldsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string> Program.<>c.<>9__1_10""
IL_027d: dup
IL_027e: brtrue.s IL_0297
IL_0280: pop
IL_0281: ldsfld ""Program.<>c Program.<>c.<>9""
IL_0286: ldftn ""string Program.<>c.<Iterator>b__1_10(<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>)""
IL_028c: newobj ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string>..ctor(object, System.IntPtr)""
IL_0291: dup
IL_0292: stsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string> Program.<>c.<>9__1_10""
IL_0297: call ""System.Collections.Generic.IEnumerable<string> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>, System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string>)""
IL_029c: stfld ""System.Collections.Generic.IEnumerable<string> Program.<Iterator>d__1.<newArgs>5__6""
IL_02a1: ldarg.0
IL_02a2: ldarg.0
IL_02a3: ldfld ""string[] Program.<Iterator>d__1.<args>5__1""
IL_02a8: ldarg.0
IL_02a9: ldfld ""System.Collections.Generic.IEnumerable<string> Program.<Iterator>d__1.<newArgs>5__6""
IL_02ae: call ""System.Collections.Generic.IEnumerable<string> System.Linq.Enumerable.Concat<string>(System.Collections.Generic.IEnumerable<string>, System.Collections.Generic.IEnumerable<string>)""
IL_02b3: call ""string[] System.Linq.Enumerable.ToArray<string>(System.Collections.Generic.IEnumerable<string>)""
IL_02b8: stfld ""string[] Program.<Iterator>d__1.<args>5__1""
IL_02bd: ldarg.0
IL_02be: ldarg.0
IL_02bf: ldfld ""int Program.<Iterator>d__1.<i>5__3""
IL_02c4: box ""int""
IL_02c9: ldarg.0
IL_02ca: ldfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<list>5__2""
IL_02cf: newobj ""<>f__AnonymousType0<dynamic, dynamic>..ctor(dynamic, dynamic)""
IL_02d4: stfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<list>5__2""
IL_02d9: call ""void System.Diagnostics.Debugger.Break()""
IL_02de: nop
IL_02df: nop
IL_02e0: ldarg.0
IL_02e1: ldnull
IL_02e2: stfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4""
IL_02e7: ldarg.0
IL_02e8: ldnull
IL_02e9: stfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5""
IL_02ee: ldarg.0
IL_02ef: ldnull
IL_02f0: stfld ""System.Collections.Generic.IEnumerable<string> Program.<Iterator>d__1.<newArgs>5__6""
IL_02f5: ldarg.0
IL_02f6: ldfld ""int Program.<Iterator>d__1.<i>5__3""
IL_02fb: stloc.2
IL_02fc: ldarg.0
IL_02fd: ldloc.2
IL_02fe: ldc.i4.1
IL_02ff: add
IL_0300: stfld ""int Program.<Iterator>d__1.<i>5__3""
IL_0305: ldarg.0
IL_0306: ldfld ""int Program.<Iterator>d__1.<i>5__3""
IL_030b: ldc.i4.s 10
IL_030d: clt
IL_030f: stloc.3
IL_0310: ldloc.3
IL_0311: brtrue IL_0068
IL_0316: call ""void System.Diagnostics.Debugger.Break()""
IL_031b: nop
IL_031c: ldc.i4.0
IL_031d: ret
}");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"Program.<>o__1#1: {<>p__0, <>p__1}",
"Program: {<>o__1#1, <>c, <Iterator>d__1}",
"Program.<>c: {<>9__1_0, <>9__1_1, <>9__1_2, <>9__1_3, <>9__1_4, <>9__1_5, <>9__1_6, <>9__1_7, <>9__1_8, <>9__1_9, <>9__1_10, <Iterator>b__1_0, <Iterator>b__1_1, <Iterator>b__1_2, <Iterator>b__1_3, <Iterator>b__1_4, <Iterator>b__1_5, <Iterator>b__1_6, <Iterator>b__1_7, <Iterator>b__1_8, <Iterator>b__1_9, <Iterator>b__1_10}",
"Program.<Iterator>d__1: {<>1__state, <>2__current, <>l__initialThreadId, <args>5__1, <list>5__2, <i>5__3, <result>5__4, <linked>5__5, <temp>5__7, <newArgs>5__6, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.String>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.String>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.String>.Current, System.Collections.IEnumerator.Current}",
"<>f__AnonymousType4<<a>j__TPar, <value>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType3<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType5<<<>h__TransparentIdentifier0>j__TPar, <length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType2<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<Head>j__TPar, <Tail>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("Program.<Iterator>d__1.System.Collections.IEnumerator.MoveNext()", @"
{
// Code size 885 (0x375)
.maxstack 5
.locals init (int V_0,
bool V_1,
int V_2,
bool V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<Iterator>d__1.<>1__state""
IL_0006: stloc.0
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_001b
IL_0014: br IL_01eb
IL_0019: ldc.i4.0
IL_001a: ret
IL_001b: ldarg.0
IL_001c: ldc.i4.m1
IL_001d: stfld ""int Program.<Iterator>d__1.<>1__state""
IL_0022: nop
IL_0023: ldarg.0
IL_0024: ldc.i4.4
IL_0025: newarr ""string""
IL_002a: dup
IL_002b: ldc.i4.0
IL_002c: ldstr ""a""
IL_0031: stelem.ref
IL_0032: dup
IL_0033: ldc.i4.1
IL_0034: ldstr ""bB""
IL_0039: stelem.ref
IL_003a: dup
IL_003b: ldc.i4.2
IL_003c: ldstr ""Cc""
IL_0041: stelem.ref
IL_0042: dup
IL_0043: ldc.i4.3
IL_0044: ldstr ""DD""
IL_0049: stelem.ref
IL_004a: stfld ""string[] Program.<Iterator>d__1.<args>5__1""
IL_004f: ldarg.0
IL_0050: ldnull
IL_0051: ldnull
IL_0052: newobj ""<>f__AnonymousType0<dynamic, dynamic>..ctor(dynamic, dynamic)""
IL_0057: stfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<list>5__2""
IL_005c: ldarg.0
IL_005d: ldc.i4.0
IL_005e: stfld ""int Program.<Iterator>d__1.<i>5__3""
IL_0063: br IL_035c
IL_0068: nop
IL_0069: ldarg.0
IL_006a: ldarg.0
IL_006b: ldfld ""string[] Program.<Iterator>d__1.<args>5__1""
IL_0070: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> Program.<>c.<>9__1_0""
IL_0075: dup
IL_0076: brtrue.s IL_008f
IL_0078: pop
IL_0079: ldsfld ""Program.<>c Program.<>c.<>9""
IL_007e: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> Program.<>c.<Iterator>b__1_0(string)""
IL_0084: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)""
IL_0089: dup
IL_008a: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> Program.<>c.<>9__1_0""
IL_008f: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)""
IL_0094: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> Program.<>c.<>9__1_1""
IL_0099: dup
IL_009a: brtrue.s IL_00b3
IL_009c: pop
IL_009d: ldsfld ""Program.<>c Program.<>c.<>9""
IL_00a2: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> Program.<>c.<Iterator>b__1_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)""
IL_00a8: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)""
IL_00ad: dup
IL_00ae: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> Program.<>c.<>9__1_1""
IL_00b3: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)""
IL_00b8: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> Program.<>c.<>9__1_2""
IL_00bd: dup
IL_00be: brtrue.s IL_00d7
IL_00c0: pop
IL_00c1: ldsfld ""Program.<>c Program.<>c.<>9""
IL_00c6: ldftn ""bool Program.<>c.<Iterator>b__1_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_00cc: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)""
IL_00d1: dup
IL_00d2: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> Program.<>c.<>9__1_2""
IL_00d7: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)""
IL_00dc: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int> Program.<>c.<>9__1_3""
IL_00e1: dup
IL_00e2: brtrue.s IL_00fb
IL_00e4: pop
IL_00e5: ldsfld ""Program.<>c Program.<>c.<>9""
IL_00ea: ldftn ""int Program.<>c.<Iterator>b__1_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_00f0: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int>..ctor(object, System.IntPtr)""
IL_00f5: dup
IL_00f6: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int> Program.<>c.<>9__1_3""
IL_00fb: call ""System.Linq.IOrderedEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.OrderBy<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, int>)""
IL_0100: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string> Program.<>c.<>9__1_4""
IL_0105: dup
IL_0106: brtrue.s IL_011f
IL_0108: pop
IL_0109: ldsfld ""Program.<>c Program.<>c.<>9""
IL_010e: ldftn ""string Program.<>c.<Iterator>b__1_4(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_0114: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string>..ctor(object, System.IntPtr)""
IL_0119: dup
IL_011a: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string> Program.<>c.<>9__1_4""
IL_011f: call ""System.Linq.IOrderedEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.ThenByDescending<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string>(System.Linq.IOrderedEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, string>)""
IL_0124: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> Program.<>c.<>9__1_5""
IL_0129: dup
IL_012a: brtrue.s IL_0143
IL_012c: pop
IL_012d: ldsfld ""Program.<>c Program.<>c.<>9""
IL_0132: ldftn ""<anonymous type: string Value, int Length> Program.<>c.<Iterator>b__1_5(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_0138: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)""
IL_013d: dup
IL_013e: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> Program.<>c.<>9__1_5""
IL_0143: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)""
IL_0148: stfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4""
IL_014d: ldarg.0
IL_014e: ldarg.0
IL_014f: ldfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4""
IL_0154: ldnull
IL_0155: ldsfld ""System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>> Program.<>c.<>9__1_6""
IL_015a: dup
IL_015b: brtrue.s IL_0174
IL_015d: pop
IL_015e: ldsfld ""Program.<>c Program.<>c.<>9""
IL_0163: ldftn ""<anonymous type: string Head, dynamic Tail> Program.<>c.<Iterator>b__1_6(<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>)""
IL_0169: newobj ""System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>>..ctor(object, System.IntPtr)""
IL_016e: dup
IL_016f: stsfld ""System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>> Program.<>c.<>9__1_6""
IL_0174: call ""<anonymous type: string Head, dynamic Tail> System.Linq.Enumerable.Aggregate<<anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>>(System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>>, <anonymous type: string Head, dynamic Tail>, System.Func<<anonymous type: string Head, dynamic Tail>, <anonymous type: string Value, int Length>, <anonymous type: string Head, dynamic Tail>>)""
IL_0179: stfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5""
IL_017e: ldarg.0
IL_017f: ldarg.0
IL_0180: ldfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<list>5__2""
IL_0185: stfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<temp>5__7""
IL_018a: br IL_0245
IL_018f: nop
IL_0190: ldarg.0
IL_0191: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>> Program.<>o__1#1.<>p__0""
IL_0196: brfalse.s IL_019a
IL_0198: br.s IL_01be
IL_019a: ldc.i4.0
IL_019b: ldtoken ""string""
IL_01a0: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_01a5: ldtoken ""Program""
IL_01aa: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_01af: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_01b4: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_01b9: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>> Program.<>o__1#1.<>p__0""
IL_01be: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>> Program.<>o__1#1.<>p__0""
IL_01c3: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>>.Target""
IL_01c8: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>> Program.<>o__1#1.<>p__0""
IL_01cd: ldarg.0
IL_01ce: ldfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<temp>5__7""
IL_01d3: callvirt ""dynamic <>f__AnonymousType0<dynamic, dynamic>.Head.get""
IL_01d8: callvirt ""string System.Func<System.Runtime.CompilerServices.CallSite, dynamic, string>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_01dd: stfld ""string Program.<Iterator>d__1.<>2__current""
IL_01e2: ldarg.0
IL_01e3: ldc.i4.1
IL_01e4: stfld ""int Program.<Iterator>d__1.<>1__state""
IL_01e9: ldc.i4.1
IL_01ea: ret
IL_01eb: ldarg.0
IL_01ec: ldc.i4.m1
IL_01ed: stfld ""int Program.<Iterator>d__1.<>1__state""
IL_01f2: ldarg.0
IL_01f3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>> Program.<>o__1#1.<>p__1""
IL_01f8: brfalse.s IL_01fc
IL_01fa: br.s IL_0220
IL_01fc: ldc.i4.0
IL_01fd: ldtoken ""<>f__AnonymousType0<dynamic, dynamic>""
IL_0202: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0207: ldtoken ""Program""
IL_020c: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0211: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_0216: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_021b: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>> Program.<>o__1#1.<>p__1""
IL_0220: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>> Program.<>o__1#1.<>p__1""
IL_0225: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>>.Target""
IL_022a: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>> Program.<>o__1#1.<>p__1""
IL_022f: ldarg.0
IL_0230: ldfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<temp>5__7""
IL_0235: callvirt ""dynamic <>f__AnonymousType0<dynamic, dynamic>.Tail.get""
IL_023a: callvirt ""<anonymous type: dynamic Head, dynamic Tail> System.Func<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: dynamic Head, dynamic Tail>>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_023f: stfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<temp>5__7""
IL_0244: nop
IL_0245: ldarg.0
IL_0246: ldfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<temp>5__7""
IL_024b: ldnull
IL_024c: cgt.un
IL_024e: stloc.1
IL_024f: ldloc.1
IL_0250: brtrue IL_018f
IL_0255: ldarg.0
IL_0256: ldarg.0
IL_0257: ldfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4""
IL_025c: ldsfld ""System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>> Program.<>c.<>9__1_7""
IL_0261: dup
IL_0262: brtrue.s IL_027b
IL_0264: pop
IL_0265: ldsfld ""Program.<>c Program.<>c.<>9""
IL_026a: ldftn ""<anonymous type: <anonymous type: string Value, int Length> a, string value> Program.<>c.<Iterator>b__1_7(<anonymous type: string Value, int Length>)""
IL_0270: newobj ""System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>>..ctor(object, System.IntPtr)""
IL_0275: dup
IL_0276: stsfld ""System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>> Program.<>c.<>9__1_7""
IL_027b: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string Value, int Length> a, string value>> System.Linq.Enumerable.Select<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>>(System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>>, System.Func<<anonymous type: string Value, int Length>, <anonymous type: <anonymous type: string Value, int Length> a, string value>>)""
IL_0280: ldsfld ""System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> Program.<>c.<>9__1_8""
IL_0285: dup
IL_0286: brtrue.s IL_029f
IL_0288: pop
IL_0289: ldsfld ""Program.<>c Program.<>c.<>9""
IL_028e: ldftn ""<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length> Program.<>c.<Iterator>b__1_8(<anonymous type: <anonymous type: string Value, int Length> a, string value>)""
IL_0294: newobj ""System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>..ctor(object, System.IntPtr)""
IL_0299: dup
IL_029a: stsfld ""System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> Program.<>c.<>9__1_8""
IL_029f: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string Value, int Length> a, string value>>, System.Func<<anonymous type: <anonymous type: string Value, int Length> a, string value>, <anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>)""
IL_02a4: ldsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool> Program.<>c.<>9__1_9""
IL_02a9: dup
IL_02aa: brtrue.s IL_02c3
IL_02ac: pop
IL_02ad: ldsfld ""Program.<>c Program.<>c.<>9""
IL_02b2: ldftn ""bool Program.<>c.<Iterator>b__1_9(<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>)""
IL_02b8: newobj ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool>..ctor(object, System.IntPtr)""
IL_02bd: dup
IL_02be: stsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool> Program.<>c.<>9__1_9""
IL_02c3: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>, System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, bool>)""
IL_02c8: ldsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string> Program.<>c.<>9__1_10""
IL_02cd: dup
IL_02ce: brtrue.s IL_02e7
IL_02d0: pop
IL_02d1: ldsfld ""Program.<>c Program.<>c.<>9""
IL_02d6: ldftn ""string Program.<>c.<Iterator>b__1_10(<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>)""
IL_02dc: newobj ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string>..ctor(object, System.IntPtr)""
IL_02e1: dup
IL_02e2: stsfld ""System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string> Program.<>c.<>9__1_10""
IL_02e7: call ""System.Collections.Generic.IEnumerable<string> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>>, System.Func<<anonymous type: <anonymous type: <anonymous type: string Value, int Length> a, string value> <>h__TransparentIdentifier0, int length>, string>)""
IL_02ec: stfld ""System.Collections.Generic.IEnumerable<string> Program.<Iterator>d__1.<newArgs>5__6""
IL_02f1: ldarg.0
IL_02f2: ldarg.0
IL_02f3: ldfld ""string[] Program.<Iterator>d__1.<args>5__1""
IL_02f8: ldarg.0
IL_02f9: ldfld ""System.Collections.Generic.IEnumerable<string> Program.<Iterator>d__1.<newArgs>5__6""
IL_02fe: call ""System.Collections.Generic.IEnumerable<string> System.Linq.Enumerable.Concat<string>(System.Collections.Generic.IEnumerable<string>, System.Collections.Generic.IEnumerable<string>)""
IL_0303: call ""string[] System.Linq.Enumerable.ToArray<string>(System.Collections.Generic.IEnumerable<string>)""
IL_0308: stfld ""string[] Program.<Iterator>d__1.<args>5__1""
IL_030d: ldarg.0
IL_030e: ldarg.0
IL_030f: ldfld ""int Program.<Iterator>d__1.<i>5__3""
IL_0314: box ""int""
IL_0319: ldarg.0
IL_031a: ldfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<list>5__2""
IL_031f: newobj ""<>f__AnonymousType0<dynamic, dynamic>..ctor(dynamic, dynamic)""
IL_0324: stfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<list>5__2""
IL_0329: call ""void System.Diagnostics.Debugger.Break()""
IL_032e: nop
IL_032f: nop
IL_0330: ldarg.0
IL_0331: ldnull
IL_0332: stfld ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> Program.<Iterator>d__1.<result>5__4""
IL_0337: ldarg.0
IL_0338: ldnull
IL_0339: stfld ""<anonymous type: string Head, dynamic Tail> Program.<Iterator>d__1.<linked>5__5""
IL_033e: ldarg.0
IL_033f: ldnull
IL_0340: stfld ""<anonymous type: dynamic Head, dynamic Tail> Program.<Iterator>d__1.<temp>5__7""
IL_0345: ldarg.0
IL_0346: ldnull
IL_0347: stfld ""System.Collections.Generic.IEnumerable<string> Program.<Iterator>d__1.<newArgs>5__6""
IL_034c: ldarg.0
IL_034d: ldfld ""int Program.<Iterator>d__1.<i>5__3""
IL_0352: stloc.2
IL_0353: ldarg.0
IL_0354: ldloc.2
IL_0355: ldc.i4.1
IL_0356: add
IL_0357: stfld ""int Program.<Iterator>d__1.<i>5__3""
IL_035c: ldarg.0
IL_035d: ldfld ""int Program.<Iterator>d__1.<i>5__3""
IL_0362: ldc.i4.s 10
IL_0364: clt
IL_0366: stloc.3
IL_0367: ldloc.3
IL_0368: brtrue IL_0068
IL_036d: call ""void System.Diagnostics.Debugger.Break()""
IL_0372: nop
IL_0373: ldc.i4.0
IL_0374: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"Program.<>o__1#1: {<>p__0, <>p__1}",
"Program.<>o__1#2: {<>p__0, <>p__1, <>p__2}",
"Program: {<>o__1#2, <>c, <Iterator>d__1, <>o__1#1}",
"Program.<>c: {<>9__1_0, <>9__1_1, <>9__1_2, <>9__1_3, <>9__1_4, <>9__1_5, <>9__1_6, <>9__1_7, <>9__1_8, <>9__1_9, <>9__1_10, <Iterator>b__1_0, <Iterator>b__1_1, <Iterator>b__1_2, <Iterator>b__1_3, <Iterator>b__1_4, <Iterator>b__1_5, <Iterator>b__1_6, <Iterator>b__1_7, <Iterator>b__1_8, <Iterator>b__1_9, <Iterator>b__1_10}",
"Program.<Iterator>d__1: {<>1__state, <>2__current, <>l__initialThreadId, <args>5__1, <list>5__2, <i>5__3, <result>5__4, <linked>5__5, <temp>5__7, <newArgs>5__6, System.IDisposable.Dispose, MoveNext, System.Collections.Generic.IEnumerator<System.String>.get_Current, System.Collections.IEnumerator.Reset, System.Collections.IEnumerator.get_Current, System.Collections.Generic.IEnumerable<System.String>.GetEnumerator, System.Collections.IEnumerable.GetEnumerator, System.Collections.Generic.IEnumerator<System.String>.Current, System.Collections.IEnumerator.Current}",
"<>f__AnonymousType4<<a>j__TPar, <value>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType3<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<Head>j__TPar, <Tail>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType5<<<>h__TransparentIdentifier0>j__TPar, <length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType2<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}");
}
[Fact, WorkItem(9119, "https://github.com/dotnet/roslyn/issues/9119")]
public void MissingIteratorStateMachineAttribute()
{
var source0 = MarkedSource(@"
using System;
using System.Collections.Generic;
class C
{
public IEnumerable<int> F()
{
int <N:0>a = 0</N:0>;
<N:1>yield return 0;</N:1>
Console.WriteLine(a);
}
}
");
var source1 = MarkedSource(@"
using System;
using System.Collections.Generic;
class C
{
public IEnumerable<int> F()
{
int <N:0>a = 1</N:0>;
<N:1>yield return 1;</N:1>
Console.WriteLine(a);
}
}
");
var compilation0 = CreateCompilationWithMscorlib40(new[] { source0.Tree }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
// older versions of mscorlib don't contain IteratorStateMachineAttribute
Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor));
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
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.EmitResult.Diagnostics.Verify(
// (7,29): error CS7043: Cannot update 'C.F()'; attribute 'System.Runtime.CompilerServices.IteratorStateMachineAttribute' is missing.
Diagnostic(ErrorCode.ERR_EncUpdateFailedMissingAttribute, "F").WithArguments("C.F()", "System.Runtime.CompilerServices.IteratorStateMachineAttribute").WithLocation(7, 29));
}
[Fact, WorkItem(9119, "https://github.com/dotnet/roslyn/issues/9119")]
public void BadIteratorStateMachineAttribute()
{
var source0 = MarkedSource(@"
using System;
using System.Collections.Generic;
namespace System.Runtime.CompilerServices
{
public class IteratorStateMachineAttribute : Attribute { }
}
class C
{
public IEnumerable<int> F()
{
int <N:0>a = 0</N:0>;
<N:1>yield return 0;</N:1>
Console.WriteLine(a);
}
}
");
var source1 = MarkedSource(@"
using System;
using System.Collections.Generic;
namespace System.Runtime.CompilerServices
{
public class IteratorStateMachineAttribute : Attribute { }
}
class C
{
public IEnumerable<int> F()
{
int <N:0>a = 1</N:0>;
<N:1>yield return 1;</N:1>
Console.WriteLine(a);
}
}
");
var compilation0 = CreateCompilation(new[] { source0.Tree }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
// the ctor is missing a parameter
Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor));
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
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.EmitResult.Diagnostics.Verify(
// (12,29): error CS7043: Cannot update 'C.F()'; attribute 'System.Runtime.CompilerServices.IteratorStateMachineAttribute' is missing.
// public IEnumerable<int> F()
Diagnostic(ErrorCode.ERR_EncUpdateFailedMissingAttribute, "F").WithArguments("C.F()", "System.Runtime.CompilerServices.IteratorStateMachineAttribute").WithLocation(12, 29));
}
[Fact]
public void AddedIteratorStateMachineAttribute()
{
var source0 = MarkedSource(@"
using System;
using System.Collections.Generic;
class C
{
public IEnumerable<int> F()
{
int <N:0>a = 0</N:0>;
<N:1>yield return 0;</N:1>
Console.WriteLine(a);
}
}
");
var source1 = MarkedSource(@"
using System;
using System.Collections.Generic;
namespace System.Runtime.CompilerServices
{
public class IteratorStateMachineAttribute : Attribute { public IteratorStateMachineAttribute(Type type) { } }
}
class C
{
public IEnumerable<int> F()
{
int <N:0>a = 1</N:0>;
<N:1>yield return 1;</N:1>
Console.WriteLine(a);
}
}
");
var compilation0 = CreateCompilationWithMscorlib40(new[] { source0.Tree }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
// older versions of mscorlib don't contain IteratorStateMachineAttribute
Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor));
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var ism1 = compilation1.GetMember<TypeSymbol>("System.Runtime.CompilerServices.IteratorStateMachineAttribute");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, ism1),
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// We conclude the original method wasn't a state machine.
// The IDE however reports a Rude Edit in that case.
diff1.EmitResult.Diagnostics.Verify();
}
[Fact]
public void SourceIteratorStateMachineAttribute()
{
var source0 = MarkedSource(@"
using System;
using System.Collections.Generic;
namespace System.Runtime.CompilerServices
{
public class IteratorStateMachineAttribute : Attribute { public IteratorStateMachineAttribute(Type type) { } }
}
class C
{
public IEnumerable<int> F()
{
int <N:0>a = 0</N:0>;
<N:1>yield return 0;</N:1>
Console.WriteLine(a);
}
}
");
var source1 = MarkedSource(@"
using System;
using System.Collections.Generic;
namespace System.Runtime.CompilerServices
{
public class IteratorStateMachineAttribute : Attribute { public IteratorStateMachineAttribute(Type type) { } }
}
class C
{
public IEnumerable<int> F()
{
int <N:0>a = 1</N:0>;
<N:1>yield return 1;</N:1>
Console.WriteLine(a);
}
}
");
var compilation0 = CreateCompilation(new[] { source0.Tree }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
// older versions of mscorlib don't contain IteratorStateMachineAttribute
Assert.NotNull(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor));
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
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.EmitResult.Diagnostics.Verify();
}
[Fact, WorkItem(9119, "https://github.com/dotnet/roslyn/issues/9119")]
public void MissingAsyncStateMachineAttribute()
{
var source0 = MarkedSource(@"
using System.Threading.Tasks;
class C
{
public async Task<int> F()
{
int <N:0>a = 0</N:0>;
<N:1>await new Task();</N:1>
return a;
}
}
");
var source1 = MarkedSource(@"
using System.Threading.Tasks;
class C
{
public async Task<int> F()
{
int <N:0>a = 1</N:0>;
<N:1>await new Task();</N:1>
return a;
}
}
");
var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { TestReferences.NetFx.Minimal.mincorlib, TestReferences.NetFx.Minimal.minasync }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
// older versions of mscorlib don't contain AsyncStateMachineAttribute, IteratorStateMachineAttribute
Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor));
Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor));
var v0 = CompileAndVerify(compilation0, verify: Verification.Fails);
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.EmitResult.Diagnostics.Verify(
// (6,28): error CS7043: Cannot update 'C.F()'; attribute 'System.Runtime.CompilerServices.AsyncStateMachineAttribute' is missing.
Diagnostic(ErrorCode.ERR_EncUpdateFailedMissingAttribute, "F").WithArguments("C.F()", "System.Runtime.CompilerServices.AsyncStateMachineAttribute").WithLocation(6, 28));
}
[Fact]
public void AddedAsyncStateMachineAttribute()
{
var source0 = MarkedSource(@"
using System.Threading.Tasks;
class C
{
public async Task<int> F()
{
int <N:0>a = 0</N:0>;
<N:1>await new Task<int>();</N:1>
return a;
}
}
");
var source1 = MarkedSource(@"
using System.Threading.Tasks;
namespace System.Runtime.CompilerServices
{
public class AsyncStateMachineAttribute : Attribute { public AsyncStateMachineAttribute(Type type) { } }
}
class C
{
public async Task<int> F()
{
int <N:0>a = 1</N:0>;
<N:1>await new Task<int>();</N:1>
return a;
}
}
");
var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { TestReferences.NetFx.Minimal.mincorlib, TestReferences.NetFx.Minimal.minasync }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
// older versions of mscorlib don't contain IteratorStateMachineAttribute
Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor));
var v0 = CompileAndVerify(compilation0, verify: Verification.Fails);
v0.VerifyDiagnostics();
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var asm1 = compilation1.GetMember<TypeSymbol>("System.Runtime.CompilerServices.AsyncStateMachineAttribute");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, asm1),
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
}
[Fact]
public void SourceAsyncStateMachineAttribute()
{
var source0 = MarkedSource(@"
using System.Threading.Tasks;
namespace System.Runtime.CompilerServices
{
public class AsyncStateMachineAttribute : Attribute { public AsyncStateMachineAttribute(Type type) { } }
}
class C
{
public async Task<int> F()
{
int <N:0>a = 0</N:0>;
<N:1>await new Task<int>();</N:1>
return a;
}
}
");
var source1 = MarkedSource(@"
using System.Threading.Tasks;
namespace System.Runtime.CompilerServices
{
public class AsyncStateMachineAttribute : Attribute { public AsyncStateMachineAttribute(Type type) { } }
}
class C
{
public async Task<int> F()
{
int <N:0>a = 1</N:0>;
<N:1>await new Task<int>();</N:1>
return a;
}
}
");
var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { TestReferences.NetFx.Minimal.mincorlib, TestReferences.NetFx.Minimal.minasync }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
Assert.NotNull(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor));
var v0 = CompileAndVerify(compilation0, verify: Verification.Fails);
v0.VerifyDiagnostics();
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.EmitResult.Diagnostics.Verify();
}
[Fact, WorkItem(10190, "https://github.com/dotnet/roslyn/issues/10190")]
public void NonAsyncToAsync()
{
var source0 = MarkedSource(@"
using System.Threading.Tasks;
class C
{
public Task<int> F()
{
int <N:0>a = 0</N:0>;
<N:1>return Task.FromResult(a);</N:1>
}
}
");
var source1 = MarkedSource(@"
using System.Threading.Tasks;
class C
{
public async Task<int> F()
{
int <N:0>a = 1</N:0>;
<N:1>return await Task.FromResult(a);</N:1>
}
}
");
var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { Net451.mscorlib }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
Assert.NotNull(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor));
var v0 = CompileAndVerify(compilation0, verify: Verification.Passes);
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.EmitResult.Diagnostics.Verify();
}
[Fact]
public void NonAsyncToAsync_MissingAttribute()
{
var source0 = MarkedSource(@"
using System.Threading.Tasks;
class C
{
public Task<int> F()
{
int <N:0>a = 0</N:0>;
a++;
<N:1>return new Task<int>();</N:1>
}
}
");
var source1 = MarkedSource(@"
using System.Threading.Tasks;
class C
{
public async Task<int> F()
{
int <N:0>a = 1</N:0>;
a++;
<N:1>return await new Task<int>();</N:1>
}
}
");
var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { TestReferences.NetFx.Minimal.mincorlib, TestReferences.NetFx.Minimal.minasync }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor));
var v0 = CompileAndVerify(compilation0, verify: Verification.Fails);
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.EmitResult.Diagnostics.Verify(
// (6,28): error CS7043: Cannot update 'C.F()'; attribute 'System.Runtime.CompilerServices.AsyncStateMachineAttribute' is missing.
Diagnostic(ErrorCode.ERR_EncUpdateFailedMissingAttribute, "F").WithArguments("C.F()", "System.Runtime.CompilerServices.AsyncStateMachineAttribute").WithLocation(6, 28));
}
[Fact]
public void NonIteratorToIterator_MissingAttribute()
{
var source0 = MarkedSource(@"
using System.Collections.Generic;
class C
{
public IEnumerable<int> F()
{
int <N:0>a = 0</N:0>;
<N:1>return new int[] { a };</N:1>
}
}
");
var source1 = MarkedSource(@"
using System.Collections.Generic;
class C
{
public IEnumerable<int> F()
{
int <N:0>a = 1</N:0>;
<N:1>yield return a;</N:1>
}
}
");
var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { Net20.mscorlib }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
Assert.Null(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor));
var v0 = CompileAndVerify(compilation0, verify: Verification.Passes);
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.EmitResult.Diagnostics.Verify(
// (6,29): error CS7043: Cannot update 'C.F()'; attribute 'System.Runtime.CompilerServices.IteratorStateMachineAttribute' is missing.
Diagnostic(ErrorCode.ERR_EncUpdateFailedMissingAttribute, "F").WithArguments("C.F()", "System.Runtime.CompilerServices.IteratorStateMachineAttribute").WithLocation(6, 29));
}
[Fact]
public void NonIteratorToIterator_SourceAttribute()
{
var source0 = MarkedSource(@"
using System.Collections.Generic;
namespace System.Runtime.CompilerServices
{
public class IteratorStateMachineAttribute : Attribute { public IteratorStateMachineAttribute(Type type) { } }
}
class C
{
public IEnumerable<int> F()
{
int <N:0>a = 0</N:0>;
<N:1>return new int[] { a };</N:1>
}
}
");
var source1 = MarkedSource(@"
using System.Collections.Generic;
namespace System.Runtime.CompilerServices
{
public class IteratorStateMachineAttribute : Attribute { public IteratorStateMachineAttribute(Type type) { } }
}
class C
{
public IEnumerable<int> F()
{
int <N:0>a = 1</N:0>;
<N:1>yield return a;</N:1>
}
}
");
var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { Net20.mscorlib }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
Assert.NotNull(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_IteratorStateMachineAttribute__ctor));
var v0 = CompileAndVerify(compilation0, verify: Verification.Passes);
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.EmitResult.Diagnostics.Verify();
}
[Fact]
public void NonAsyncToAsyncLambda()
{
var source0 = MarkedSource(@"
using System.Threading.Tasks;
class C
{
public object F()
{
return new System.Func<Task<int>>(<N:2>() =>
<N:3>{
int <N:0>a = 0</N:0>;
<N:1>return Task.FromResult(a);</N:1>
}</N:3></N:2>);
}
}
");
var source1 = MarkedSource(@"
using System.Threading.Tasks;
class C
{
public object F()
{
return new System.Func<Task<int>>(<N:2>async () =>
<N:3>{
int <N:0>a = 0</N:0>;
<N:1>return await Task.FromResult(a);</N:1>
}</N:3></N:2>);
}
}
");
var compilation0 = CreateEmptyCompilation(new[] { source0.Tree }, new[] { Net451.mscorlib }, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
Assert.NotNull(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor));
var v0 = CompileAndVerify(compilation0, verify: Verification.Passes);
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.EmitResult.Diagnostics.Verify();
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <F>b__0_0, <<F>b__0_0>d}",
"C.<>c.<<F>b__0_0>d: {<>1__state, <>t__builder, <>4__this, <a>5__1, <>s__2, <>u__1, MoveNext, SetStateMachine}");
}
[Fact]
public void AsyncMethodWithNullableParameterAddingNullCheck()
{
var source0 = MarkedSource(@"
using System;
using System.Threading.Tasks;
#nullable enable
class C
{
static T id<T>(T t) => t;
static Task<T> G<T>(Func<T> f) => Task.FromResult(f());
static T H<T>(Func<T> f) => f();
public async void F(string? x)
<N:4>{</N:4>
var <N:2>y = await G(<N:0>() => new { A = id(x) }</N:0>)</N:2>;
var <N:3>z = H(<N:1>() => y.A</N:1>)</N:3>;
}
}
", options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9));
var source1 = MarkedSource(@"
using System;
using System.Threading.Tasks;
#nullable enable
class C
{
static T id<T>(T t) => t;
static Task<T> G<T>(Func<T> f) => Task.FromResult(f());
static T H<T>(Func<T> f) => f();
public async void F(string? x)
<N:4>{</N:4>
if (x is null) throw new Exception();
var <N:2>y = await G(<N:0>() => new { A = id(x) }</N:0>)</N:2>;
var <N:3>z = H(<N:1>() => y.A</N:1>)</N:3>;
}
}
", options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9));
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
Assert.NotNull(compilation0.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor));
var v0 = CompileAndVerify(compilation0, verify: Verification.Passes);
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.EmitResult.Diagnostics.Verify();
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass3_0: {x, y, <F>b__1, <F>b__0}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}",
"System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"Microsoft: {CodeAnalysis}",
"System.Runtime: {CompilerServices, CompilerServices}",
"C: {<>c__DisplayClass3_0, <F>d__3}",
"<global namespace>: {Microsoft, System, System}",
"System: {Runtime, Runtime}",
"C.<F>d__3: {<>1__state, <>t__builder, x, <>4__this, <>8__4, <z>5__2, <>s__5, <>u__1, MoveNext, SetStateMachine}");
diff1.VerifyIL("C.<>c__DisplayClass3_0.<F>b__1()", @"
{
// Code size 17 (0x11)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""string C.<>c__DisplayClass3_0.x""
IL_0006: call ""string C.id<string>(string)""
IL_000b: newobj ""<>f__AnonymousType0<string>..ctor(string)""
IL_0010: ret
}
");
diff1.VerifyIL("C.<>c__DisplayClass3_0.<F>b__0()", @"
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""<anonymous type: string A> C.<>c__DisplayClass3_0.y""
IL_0006: callvirt ""string <>f__AnonymousType0<string>.A.get""
IL_000b: ret
}
");
}
}
}
| 1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Compilers/CSharp/Test/Emit/Emit/EditAndContinue/EditAndContinueTestBase.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.UnitTests;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.Metadata.Tools;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests
{
public abstract class EditAndContinueTestBase : EmitMetadataTestBase
{
// PDB reader can only be accessed from a single thread, so avoid concurrent compilation:
protected readonly CSharpCompilationOptions ComSafeDebugDll = TestOptions.DebugDll.WithConcurrentBuild(false);
internal static readonly Func<MethodDefinitionHandle, EditAndContinueMethodDebugInformation> EmptyLocalsProvider = handle => default(EditAndContinueMethodDebugInformation);
internal static string Visualize(ModuleMetadata baseline, params PinnedMetadata[] deltas)
{
var result = new StringWriter();
new MetadataVisualizer(new[] { baseline.MetadataReader }.Concat(deltas.Select(d => d.Reader)).ToArray(), result).VisualizeAllGenerations();
return result.ToString();
}
internal static SourceWithMarkedNodes MarkedSource(string markedSource, string fileName = "", CSharpParseOptions options = null, bool removeTags = false)
{
return new SourceWithMarkedNodes(markedSource, s => Parse(s, fileName, options), s => (int)(SyntaxKind)typeof(SyntaxKind).GetField(s).GetValue(null), removeTags);
}
internal static Func<SyntaxNode, SyntaxNode> GetSyntaxMapFromMarkers(SourceWithMarkedNodes source0, SourceWithMarkedNodes source1)
{
return SourceWithMarkedNodes.GetSyntaxMap(source0, source1);
}
internal static ImmutableArray<SyntaxNode> GetAllLocals(MethodSymbol method)
{
var sourceMethod = method as SourceMemberMethodSymbol;
if (sourceMethod == null)
{
return ImmutableArray<SyntaxNode>.Empty;
}
return LocalVariableDeclaratorsCollector.GetDeclarators(sourceMethod);
}
internal static Func<SyntaxNode, SyntaxNode> GetSyntaxMapByKind(MethodSymbol method0, params SyntaxKind[] kinds)
{
return newNode =>
{
foreach (SyntaxKind kind in kinds)
{
if (newNode.IsKind(kind))
{
return method0.DeclaringSyntaxReferences.Single().SyntaxTree.GetRoot().DescendantNodes().Single(n => n.IsKind(kind));
}
}
return null;
};
}
internal static Func<SyntaxNode, SyntaxNode> GetEquivalentNodesMap(MethodSymbol method1, MethodSymbol method0)
{
var tree1 = method1.Locations[0].SourceTree;
var tree0 = method0.Locations[0].SourceTree;
Assert.NotEqual(tree1, tree0);
var locals0 = GetAllLocals(method0);
return s =>
{
var s1 = s;
Assert.Equal(s1.SyntaxTree, tree1);
foreach (var s0 in locals0)
{
if (!SyntaxFactory.AreEquivalent(s0, s1))
{
continue;
}
// Make sure the containing statements are the same.
var p0 = GetNearestStatement(s0);
var p1 = GetNearestStatement(s1);
if (SyntaxFactory.AreEquivalent(p0, p1))
{
return s0;
}
}
return null;
};
}
internal static string GetLocalName(SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.VariableDeclarator:
return ((VariableDeclaratorSyntax)node).Identifier.ToString();
default:
throw new NotImplementedException();
}
}
internal static StatementSyntax GetNearestStatement(SyntaxNode node)
{
while (node != null)
{
var statement = node as StatementSyntax;
if (statement != null)
{
return statement;
}
node = node.Parent;
}
return null;
}
internal static EditAndContinueLogEntry Row(int rowNumber, TableIndex table, EditAndContinueOperation operation)
{
return new EditAndContinueLogEntry(MetadataTokens.Handle(table, rowNumber), operation);
}
internal static EntityHandle Handle(int rowNumber, TableIndex table)
{
return MetadataTokens.Handle(table, rowNumber);
}
private static bool IsDefinition(HandleKind kind)
=> kind is not (HandleKind.AssemblyReference or HandleKind.ModuleReference or HandleKind.TypeReference or HandleKind.MemberReference or HandleKind.TypeSpecification or HandleKind.MethodSpecification);
internal static void CheckEncLog(MetadataReader reader, params EditAndContinueLogEntry[] rows)
{
AssertEx.Equal(rows, reader.GetEditAndContinueLogEntries(), itemInspector: EncLogRowToString);
}
/// <summary>
/// Checks that the EncLog contains specified definition rows. References are ignored as they are usually not interesting to validate. They are emitted as needed.
/// </summary>
internal static void CheckEncLogDefinitions(MetadataReader reader, params EditAndContinueLogEntry[] rows)
{
AssertEx.Equal(rows, reader.GetEditAndContinueLogEntries().Where(e => IsDefinition(e.Handle.Kind)), itemInspector: EncLogRowToString);
}
internal static void CheckEncMap(MetadataReader reader, params EntityHandle[] handles)
{
AssertEx.Equal(handles, reader.GetEditAndContinueMapEntries(), itemInspector: EncMapRowToString);
}
internal static void CheckEncMapDefinitions(MetadataReader reader, params EntityHandle[] handles)
{
AssertEx.Equal(handles, reader.GetEditAndContinueMapEntries().Where(e => IsDefinition(e.Kind)), itemInspector: EncMapRowToString);
}
internal static void CheckAttributes(MetadataReader reader, params CustomAttributeRow[] rows)
{
AssertEx.Equal(rows, reader.GetCustomAttributeRows(), itemInspector: AttributeRowToString);
}
internal static void CheckNames(MetadataReader reader, IEnumerable<StringHandle> handles, params string[] expectedNames)
{
CheckNames(new[] { reader }, handles, expectedNames);
}
internal static void CheckNames(IEnumerable<MetadataReader> readers, IEnumerable<StringHandle> handles, params string[] expectedNames)
{
var actualNames = readers.GetStrings(handles);
AssertEx.Equal(expectedNames, actualNames);
}
internal static void CheckNames(IList<MetadataReader> readers, IEnumerable<(StringHandle Namespace, StringHandle Name)> handles, params string[] expectedNames)
{
var actualNames = handles.Select(handlePair => string.Join(".", readers.GetString(handlePair.Namespace), readers.GetString(handlePair.Name))).ToArray();
AssertEx.Equal(expectedNames, actualNames);
}
internal static string EncLogRowToString(EditAndContinueLogEntry row)
{
TableIndex tableIndex;
MetadataTokens.TryGetTableIndex(row.Handle.Kind, out tableIndex);
return string.Format(
"Row({0}, TableIndex.{1}, EditAndContinueOperation.{2})",
MetadataTokens.GetRowNumber(row.Handle),
tableIndex,
row.Operation);
}
internal static string EncMapRowToString(EntityHandle handle)
{
TableIndex tableIndex;
MetadataTokens.TryGetTableIndex(handle.Kind, out tableIndex);
return string.Format(
"Handle({0}, TableIndex.{1})",
MetadataTokens.GetRowNumber(handle),
tableIndex);
}
internal static string AttributeRowToString(CustomAttributeRow row)
{
TableIndex parentTableIndex, constructorTableIndex;
MetadataTokens.TryGetTableIndex(row.ParentToken.Kind, out parentTableIndex);
MetadataTokens.TryGetTableIndex(row.ConstructorToken.Kind, out constructorTableIndex);
return string.Format(
"new CustomAttributeRow(Handle({0}, TableIndex.{1}), Handle({2}, TableIndex.{3}))",
MetadataTokens.GetRowNumber(row.ParentToken),
parentTableIndex,
MetadataTokens.GetRowNumber(row.ConstructorToken),
constructorTableIndex);
}
internal static void SaveImages(string outputDirectory, CompilationVerifier baseline, params CompilationDifference[] diffs)
{
bool IsPortablePdb(ImmutableArray<byte> image) => image[0] == 'B' && image[1] == 'S' && image[2] == 'J' && image[3] == 'B';
string baseName = baseline.Compilation.AssemblyName;
string extSuffix = IsPortablePdb(baseline.EmittedAssemblyPdb) ? "x" : "";
Directory.CreateDirectory(outputDirectory);
File.WriteAllBytes(Path.Combine(outputDirectory, baseName + ".dll" + extSuffix), baseline.EmittedAssemblyData.ToArray());
File.WriteAllBytes(Path.Combine(outputDirectory, baseName + ".pdb" + extSuffix), baseline.EmittedAssemblyPdb.ToArray());
for (int i = 0; i < diffs.Length; i++)
{
File.WriteAllBytes(Path.Combine(outputDirectory, $"{baseName}.{i + 1}.metadata{extSuffix}"), diffs[i].MetadataDelta.ToArray());
File.WriteAllBytes(Path.Combine(outputDirectory, $"{baseName}.{i + 1}.pdb{extSuffix}"), diffs[i].PdbDelta.ToArray());
}
}
}
public static class EditAndContinueTestExtensions
{
internal static CSharpCompilation WithSource(this CSharpCompilation compilation, CSharpTestSource newSource)
{
return compilation.RemoveAllSyntaxTrees().AddSyntaxTrees(newSource.GetSyntaxTrees(TestOptions.Regular));
}
internal static CSharpCompilation WithSource(this CSharpCompilation compilation, SyntaxTree newTree)
{
return compilation.RemoveAllSyntaxTrees().AddSyntaxTrees(newTree);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.UnitTests;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.Metadata.Tools;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests
{
public abstract class EditAndContinueTestBase : EmitMetadataTestBase
{
// PDB reader can only be accessed from a single thread, so avoid concurrent compilation:
protected readonly CSharpCompilationOptions ComSafeDebugDll = TestOptions.DebugDll.WithConcurrentBuild(false);
internal static readonly Func<MethodDefinitionHandle, EditAndContinueMethodDebugInformation> EmptyLocalsProvider = handle => default(EditAndContinueMethodDebugInformation);
internal static string Visualize(ModuleMetadata baseline, params PinnedMetadata[] deltas)
{
var result = new StringWriter();
new MetadataVisualizer(new[] { baseline.MetadataReader }.Concat(deltas.Select(d => d.Reader)).ToArray(), result).VisualizeAllGenerations();
return result.ToString();
}
internal static SourceWithMarkedNodes MarkedSource(string markedSource, string fileName = "", CSharpParseOptions options = null, bool removeTags = false)
{
return new SourceWithMarkedNodes(markedSource, s => Parse(s, fileName, options), s => (int)(SyntaxKind)typeof(SyntaxKind).GetField(s).GetValue(null), removeTags);
}
internal static Func<SyntaxNode, SyntaxNode> GetSyntaxMapFromMarkers(SourceWithMarkedNodes source0, SourceWithMarkedNodes source1)
{
return SourceWithMarkedNodes.GetSyntaxMap(source0, source1);
}
internal static ImmutableArray<SyntaxNode> GetAllLocals(MethodSymbol method)
{
var sourceMethod = method as SourceMemberMethodSymbol;
if (sourceMethod == null)
{
return ImmutableArray<SyntaxNode>.Empty;
}
return LocalVariableDeclaratorsCollector.GetDeclarators(sourceMethod);
}
internal static Func<SyntaxNode, SyntaxNode> GetSyntaxMapByKind(MethodSymbol method0, params SyntaxKind[] kinds)
{
return newNode =>
{
foreach (SyntaxKind kind in kinds)
{
if (newNode.IsKind(kind))
{
return method0.DeclaringSyntaxReferences.Single().SyntaxTree.GetRoot().DescendantNodes().Single(n => n.IsKind(kind));
}
}
return null;
};
}
internal static Func<SyntaxNode, SyntaxNode> GetEquivalentNodesMap(MethodSymbol method1, MethodSymbol method0)
{
var tree1 = method1.Locations[0].SourceTree;
var tree0 = method0.Locations[0].SourceTree;
Assert.NotEqual(tree1, tree0);
var locals0 = GetAllLocals(method0);
return s =>
{
var s1 = s;
Assert.Equal(s1.SyntaxTree, tree1);
foreach (var s0 in locals0)
{
if (!SyntaxFactory.AreEquivalent(s0, s1))
{
continue;
}
// Make sure the containing statements are the same.
var p0 = GetNearestStatement(s0);
var p1 = GetNearestStatement(s1);
if (SyntaxFactory.AreEquivalent(p0, p1))
{
return s0;
}
}
return null;
};
}
internal static string GetLocalName(SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.VariableDeclarator:
return ((VariableDeclaratorSyntax)node).Identifier.ToString();
default:
throw new NotImplementedException();
}
}
internal static StatementSyntax GetNearestStatement(SyntaxNode node)
{
while (node != null)
{
var statement = node as StatementSyntax;
if (statement != null)
{
return statement;
}
node = node.Parent;
}
return null;
}
internal static EditAndContinueLogEntry Row(int rowNumber, TableIndex table, EditAndContinueOperation operation)
{
return new EditAndContinueLogEntry(MetadataTokens.Handle(table, rowNumber), operation);
}
internal static EntityHandle Handle(int rowNumber, TableIndex table)
{
return MetadataTokens.Handle(table, rowNumber);
}
private static bool IsDefinition(HandleKind kind)
=> kind is not (HandleKind.AssemblyReference or HandleKind.ModuleReference or HandleKind.TypeReference or HandleKind.MemberReference or HandleKind.TypeSpecification or HandleKind.MethodSpecification);
internal static void CheckEncLog(MetadataReader reader, params EditAndContinueLogEntry[] rows)
{
AssertEx.Equal(rows, reader.GetEditAndContinueLogEntries(), itemInspector: EncLogRowToString);
}
/// <summary>
/// Checks that the EncLog contains specified definition rows. References are ignored as they are usually not interesting to validate. They are emitted as needed.
/// </summary>
internal static void CheckEncLogDefinitions(MetadataReader reader, params EditAndContinueLogEntry[] rows)
{
AssertEx.Equal(rows, reader.GetEditAndContinueLogEntries().Where(e => IsDefinition(e.Handle.Kind)), itemInspector: EncLogRowToString);
}
internal static void CheckEncMap(MetadataReader reader, params EntityHandle[] handles)
{
AssertEx.Equal(handles, reader.GetEditAndContinueMapEntries(), itemInspector: EncMapRowToString);
}
internal static void CheckEncMapDefinitions(MetadataReader reader, params EntityHandle[] handles)
{
AssertEx.Equal(handles, reader.GetEditAndContinueMapEntries().Where(e => IsDefinition(e.Kind)), itemInspector: EncMapRowToString);
}
internal static void CheckAttributes(MetadataReader reader, params CustomAttributeRow[] rows)
{
AssertEx.Equal(rows, reader.GetCustomAttributeRows(), itemInspector: AttributeRowToString);
}
internal static void CheckNames(MetadataReader reader, IEnumerable<StringHandle> handles, params string[] expectedNames)
{
CheckNames(new[] { reader }, handles, expectedNames);
}
internal static void CheckNames(IEnumerable<MetadataReader> readers, IEnumerable<StringHandle> handles, params string[] expectedNames)
{
var actualNames = readers.GetStrings(handles);
AssertEx.Equal(expectedNames, actualNames);
}
internal static void CheckNames(IList<MetadataReader> readers, IEnumerable<(StringHandle Namespace, StringHandle Name)> handles, params string[] expectedNames)
{
var actualNames = handles.Select(handlePair => string.Join(".", readers.GetString(handlePair.Namespace), readers.GetString(handlePair.Name))).ToArray();
AssertEx.Equal(expectedNames, actualNames);
}
public static void CheckNames(IList<MetadataReader> readers, ImmutableArray<TypeDefinitionHandle> typeHandles, params string[] expectedNames)
=> CheckNames(readers, typeHandles, (reader, handle) => reader.GetTypeDefinition((TypeDefinitionHandle)handle).Name, handle => handle, expectedNames);
public static void CheckNames(IList<MetadataReader> readers, ImmutableArray<MethodDefinitionHandle> methodHandles, params string[] expectedNames)
=> CheckNames(readers, methodHandles, (reader, handle) => reader.GetMethodDefinition((MethodDefinitionHandle)handle).Name, handle => handle, expectedNames);
private static void CheckNames<THandle>(
IList<MetadataReader> readers,
ImmutableArray<THandle> entityHandles,
Func<MetadataReader, Handle, StringHandle> getName,
Func<THandle, Handle> toHandle,
string[] expectedNames)
{
var aggregator = new MetadataAggregator(readers[0], readers.Skip(1).ToArray());
AssertEx.Equal(expectedNames, entityHandles.Select(handle =>
{
var genEntityHandle = aggregator.GetGenerationHandle(toHandle(handle), out int typeGeneration);
var nameHandle = getName(readers[typeGeneration], genEntityHandle);
var genNameHandle = (StringHandle)aggregator.GetGenerationHandle(nameHandle, out int nameGeneration);
return readers[nameGeneration].GetString(genNameHandle);
}));
}
internal static string EncLogRowToString(EditAndContinueLogEntry row)
{
TableIndex tableIndex;
MetadataTokens.TryGetTableIndex(row.Handle.Kind, out tableIndex);
return string.Format(
"Row({0}, TableIndex.{1}, EditAndContinueOperation.{2})",
MetadataTokens.GetRowNumber(row.Handle),
tableIndex,
row.Operation);
}
internal static string EncMapRowToString(EntityHandle handle)
{
TableIndex tableIndex;
MetadataTokens.TryGetTableIndex(handle.Kind, out tableIndex);
return string.Format(
"Handle({0}, TableIndex.{1})",
MetadataTokens.GetRowNumber(handle),
tableIndex);
}
internal static string AttributeRowToString(CustomAttributeRow row)
{
TableIndex parentTableIndex, constructorTableIndex;
MetadataTokens.TryGetTableIndex(row.ParentToken.Kind, out parentTableIndex);
MetadataTokens.TryGetTableIndex(row.ConstructorToken.Kind, out constructorTableIndex);
return string.Format(
"new CustomAttributeRow(Handle({0}, TableIndex.{1}), Handle({2}, TableIndex.{3}))",
MetadataTokens.GetRowNumber(row.ParentToken),
parentTableIndex,
MetadataTokens.GetRowNumber(row.ConstructorToken),
constructorTableIndex);
}
internal static void SaveImages(string outputDirectory, CompilationVerifier baseline, params CompilationDifference[] diffs)
{
bool IsPortablePdb(ImmutableArray<byte> image) => image[0] == 'B' && image[1] == 'S' && image[2] == 'J' && image[3] == 'B';
string baseName = baseline.Compilation.AssemblyName;
string extSuffix = IsPortablePdb(baseline.EmittedAssemblyPdb) ? "x" : "";
Directory.CreateDirectory(outputDirectory);
File.WriteAllBytes(Path.Combine(outputDirectory, baseName + ".dll" + extSuffix), baseline.EmittedAssemblyData.ToArray());
File.WriteAllBytes(Path.Combine(outputDirectory, baseName + ".pdb" + extSuffix), baseline.EmittedAssemblyPdb.ToArray());
for (int i = 0; i < diffs.Length; i++)
{
File.WriteAllBytes(Path.Combine(outputDirectory, $"{baseName}.{i + 1}.metadata{extSuffix}"), diffs[i].MetadataDelta.ToArray());
File.WriteAllBytes(Path.Combine(outputDirectory, $"{baseName}.{i + 1}.pdb{extSuffix}"), diffs[i].PdbDelta.ToArray());
}
}
}
public static class EditAndContinueTestExtensions
{
internal static CSharpCompilation WithSource(this CSharpCompilation compilation, CSharpTestSource newSource)
{
return compilation.RemoveAllSyntaxTrees().AddSyntaxTrees(newSource.GetSyntaxTrees(TestOptions.Regular));
}
internal static CSharpCompilation WithSource(this CSharpCompilation compilation, SyntaxTree newTree)
{
return compilation.RemoveAllSyntaxTrees().AddSyntaxTrees(newTree);
}
}
}
| 1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Compilers/CSharp/Test/Emit/Emit/EditAndContinue/EditAndContinueTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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 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
{
/// <summary>
/// Tip: debug EncVariableSlotAllocator.TryGetPreviousClosure or other TryGet methods to figure out missing markers in your test.
/// </summary>
public class EditAndContinueTests : EditAndContinueTestBase
{
private static IEnumerable<string> DumpTypeRefs(MetadataReader[] readers)
{
var currentGenerationReader = readers.Last();
foreach (var typeRefHandle in currentGenerationReader.TypeReferences)
{
var typeRef = currentGenerationReader.GetTypeReference(typeRefHandle);
yield return $"[0x{MetadataTokens.GetToken(typeRef.ResolutionScope):x8}] {readers.GetString(typeRef.Namespace)}.{readers.GetString(typeRef.Name)}";
}
}
[Fact]
public void DeltaHeapsStartWithEmptyItem()
{
var source0 =
@"class C
{
static string F() { return null; }
}";
var source1 =
@"class C
{
static string F() { return ""a""; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var diff1 = compilation1.EmitDifference(
EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider),
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var s = MetadataTokens.StringHandle(0);
Assert.Equal("", reader1.GetString(s));
var b = MetadataTokens.BlobHandle(0);
Assert.Equal(0, reader1.GetBlobBytes(b).Length);
var us = MetadataTokens.UserStringHandle(0);
Assert.Equal("", reader1.GetUserString(us));
}
[Fact]
public void Delta_AssemblyDefTable()
{
var source0 = @"public class C { public static void F() { System.Console.WriteLine(1); } }";
var source1 = @"public class C { public static void F() { System.Console.WriteLine(2); } }";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
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.Update, f0, f1, preserveLocalVariables: true)));
// AssemblyDef record is not emitted to delta since changes in assembly identity are not allowed:
Assert.True(md0.MetadataReader.IsAssembly);
Assert.False(diff1.GetMetadata().Reader.IsAssembly);
}
[Fact]
public void SemanticErrors_MethodBody()
{
var source0 = MarkedSource(@"
class C
{
static void E()
{
int x = 1;
System.Console.WriteLine(x);
}
static void G()
{
System.Console.WriteLine(1);
}
}");
var source1 = MarkedSource(@"
class C
{
static void E()
{
int x = Unknown(2);
System.Console.WriteLine(x);
}
static void G()
{
System.Console.WriteLine(2);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var e0 = compilation0.GetMember<MethodSymbol>("C.E");
var e1 = compilation1.GetMember<MethodSymbol>("C.E");
var g0 = compilation0.GetMember<MethodSymbol>("C.G");
var g1 = compilation1.GetMember<MethodSymbol>("C.G");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
// Semantic errors are reported only for the bodies of members being emitted.
var diffError = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diffError.EmitResult.Diagnostics.Verify(
// (6,17): error CS0103: The name 'Unknown' does not exist in the current context
// int x = Unknown(2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "Unknown").WithArguments("Unknown").WithLocation(6, 17));
var diffGood = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diffGood.EmitResult.Diagnostics.Verify();
diffGood.VerifyIL(@"C.G", @"
{
// Code size 9 (0x9)
.maxstack 1
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: call ""void System.Console.WriteLine(int)""
IL_0007: nop
IL_0008: ret
}
");
}
[Fact]
public void SemanticErrors_Declaration()
{
var source0 = MarkedSource(@"
class C
{
static void G()
{
System.Console.WriteLine(1);
}
}
");
var source1 = MarkedSource(@"
class C
{
static void G()
{
System.Console.WriteLine(2);
}
}
class Bad : Bad
{
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var g0 = compilation0.GetMember<MethodSymbol>("C.G");
var g1 = compilation1.GetMember<MethodSymbol>("C.G");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// All declaration errors are reported regardless of what member do we emit.
diff.EmitResult.Diagnostics.Verify(
// (10,7): error CS0146: Circular base type dependency involving 'Bad' and 'Bad'
// class Bad : Bad
Diagnostic(ErrorCode.ERR_CircularBase, "Bad").WithArguments("Bad", "Bad").WithLocation(10, 7));
}
[Fact]
public void ModifyMethod()
{
var source0 =
@"class C
{
static void Main() { }
static string F() { return null; }
}";
var source1 =
@"class C
{
static void Main() { }
static string F() { return string.Empty; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe);
var compilation1 = compilation0.WithSource(source1);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*String.*/"Empty");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(7, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
}
[CompilerTrait(CompilerFeature.Tuples)]
[Fact]
public void ModifyMethod_WithTuples()
{
var source0 =
@"class C
{
static void Main() { }
static (int, int) F() { return (1, 2); }
}";
var source1 =
@"class C
{
static void Main() { }
static (int, int) F() { return (2, 3); }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*System.ValueTuple.*/".ctor");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F
CheckEncMap(reader1,
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(6, TableIndex.MemberRef),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.TypeSpec),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyMethod_WithAttributes1()
{
var source0 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return null; }
}";
var source1 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return string.Empty; }
}";
var source2 =
@"[System.ComponentModel.Browsable(false)]
class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method""), System.ComponentModel.Category(""Methods"")]
static string F() { return string.Empty; }
}";
var source3 =
@"[System.ComponentModel.Browsable(false)]
class C
{
static void Main() { }
[System.ComponentModel.Browsable(false), System.ComponentModel.Description(""The F method""), System.ComponentModel.Category(""Methods"")]
static string F() { return string.Empty; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor");
Assert.Equal(4, reader0.CustomAttributes.Count);
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty");
Assert.Equal(1, reader1.CustomAttributes.Count);
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute
CheckEncMap(reader1,
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(9, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(6, TableIndex.MemberRef),
Handle(7, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
var method2 = compilation2.GetMember<MethodSymbol>("C.F");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember("C"), compilation2.GetMember("C")),
SemanticEdit.Create(SemanticEditKind.Update, method1, method2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, reader2.GetTypeDefNames(), "C");
CheckNames(readers, reader2.GetMethodDefNames(), "F");
CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*BrowsableAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*String.*/"Empty");
Assert.Equal(3, reader2.CustomAttributes.Count);
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(10, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(11, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(14, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 4, updating the existing custom attribute
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 5, adding a new CustomAttribute
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 6 adding a new CustomAttribute
CheckEncMap(reader2,
Handle(10, TableIndex.TypeRef),
Handle(11, TableIndex.TypeRef),
Handle(12, TableIndex.TypeRef),
Handle(13, TableIndex.TypeRef),
Handle(14, TableIndex.TypeRef),
Handle(2, TableIndex.TypeDef),
Handle(2, TableIndex.MethodDef),
Handle(8, TableIndex.MemberRef),
Handle(9, TableIndex.MemberRef),
Handle(10, TableIndex.MemberRef),
Handle(11, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute),
Handle(6, TableIndex.CustomAttribute),
Handle(3, TableIndex.StandAloneSig),
Handle(3, TableIndex.AssemblyRef));
var method3 = compilation3.GetMember<MethodSymbol>("C.F");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3)));
// Verify delta metadata contains expected rows.
using var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
readers = new[] { reader0, reader1, reader2, reader3 };
CheckNames(readers, reader3.GetTypeDefNames());
CheckNames(readers, reader3.GetMethodDefNames(), "F");
CheckNames(readers, reader3.GetMemberRefNames(), /*BrowsableAttribute*/".ctor", /*DescriptionAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*String.*/"Empty");
CheckEncLog(reader3,
Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(12, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(13, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(14, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(15, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 4, updating the existing custom attribute
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 5, updating a row that was new in Generation 2
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 7, adding a new CustomAttribute, and skipping row 6 which is not for the method being emitted
CheckEncMap(reader3,
Handle(15, TableIndex.TypeRef),
Handle(16, TableIndex.TypeRef),
Handle(17, TableIndex.TypeRef),
Handle(18, TableIndex.TypeRef),
Handle(19, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(12, TableIndex.MemberRef),
Handle(13, TableIndex.MemberRef),
Handle(14, TableIndex.MemberRef),
Handle(15, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute),
Handle(7, TableIndex.CustomAttribute),
Handle(4, TableIndex.StandAloneSig),
Handle(4, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyMethod_WithAttributes2()
{
var source0 =
@"[System.ComponentModel.Browsable(false)]
class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return null; }
}
[System.ComponentModel.Browsable(false)]
class D
{
[System.ComponentModel.Description(""A"")]
static string A() { return null; }
}
";
var source1 =
@"
[System.ComponentModel.Browsable(false)]
class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method""), System.ComponentModel.Browsable(false), System.ComponentModel.Category(""Methods"")]
static string F() { return null; }
}
[System.ComponentModel.Browsable(false)]
class D
{
[System.ComponentModel.Description(""A""), System.ComponentModel.Category(""Methods"")]
static string A() { return null; }
}
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var method0_1 = compilation0.GetMember<MethodSymbol>("C.F");
var method0_2 = compilation0.GetMember<MethodSymbol>("D.A");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "D");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor", "A", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor", /*BrowsableAttribute*/".ctor");
CheckAttributes(reader0,
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.TypeDef), Handle(4, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(3, TableIndex.TypeDef), Handle(4, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef)));
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1_1 = compilation1.GetMember<MethodSymbol>("C.F");
var method1_2 = compilation1.GetMember<MethodSymbol>("D.A");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method0_1, method1_1),
SemanticEdit.Create(SemanticEditKind.Update, method0_2, method1_2)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F", "A");
CheckNames(readers, reader1.GetMemberRefNames(), /*BrowsableAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*DescriptionAttribute*/".ctor");
CheckAttributes(reader1,
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(9, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(9, TableIndex.MemberRef)));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // update existing row
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // add new row
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // add new row
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // update existing row
Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // add new row
CheckEncMap(reader1,
Handle(8, TableIndex.TypeRef),
Handle(9, TableIndex.TypeRef),
Handle(10, TableIndex.TypeRef),
Handle(11, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(9, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(7, TableIndex.CustomAttribute),
Handle(8, TableIndex.CustomAttribute),
Handle(9, TableIndex.CustomAttribute),
Handle(10, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyMethod_DeleteAttributes1()
{
var source0 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return null; }
}";
var source1 =
@"class C
{
static void Main() { }
static string F() { return string.Empty; }
}";
var source2 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return string.Empty; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor");
CheckAttributes(reader0,
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)));
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*String.*/"Empty");
CheckAttributes(reader1,
new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // Parent row id is 0, signifying a delete
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute
CheckEncMap(reader1,
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(6, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
var method2 = compilation2.GetMember<MethodSymbol>("C.F");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
EncValidation.VerifyModuleMvid(2, reader1, reader2);
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetMethodDefNames(), "F");
CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty");
CheckAttributes(reader2,
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef)));
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, updating the original row back to a real one
CheckEncMap(reader2,
Handle(9, TableIndex.TypeRef),
Handle(10, TableIndex.TypeRef),
Handle(11, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(3, TableIndex.StandAloneSig),
Handle(3, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyMethod_DeleteAttributes2()
{
var source0 =
@"class C
{
static void Main() { }
static string F() { return null; }
}";
var source1 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return string.Empty; }
}";
var source2 = source0; // Remove the attribute we just added
var source3 = source1; // Add the attribute back again
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation1.WithSource(source3);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor");
CheckAttributes(reader0,
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)));
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty");
CheckAttributes(reader1,
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef)));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so adding a new CustomAttribute
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(6, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
var method2 = compilation2.GetMember<MethodSymbol>("C.F");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method1, method2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetMethodDefNames(), "F");
CheckNames(readers, reader2.GetMemberRefNames());
CheckAttributes(reader2,
new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // 0, delete
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute
CheckEncMap(reader2,
Handle(9, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(4, TableIndex.CustomAttribute),
Handle(3, TableIndex.StandAloneSig),
Handle(3, TableIndex.AssemblyRef));
var method3 = compilation3.GetMember<MethodSymbol>("C.F");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method2, method3)));
// Verify delta metadata contains expected rows.
using var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
readers = new[] { reader0, reader1, reader2, reader3 };
CheckNames(readers, reader3.GetTypeDefNames());
CheckNames(readers, reader3.GetMethodDefNames(), "F");
CheckNames(readers, reader3.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty");
CheckAttributes(reader3,
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef)));
CheckEncLog(reader3,
Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, update the previously deleted row
CheckEncMap(reader3,
Handle(10, TableIndex.TypeRef),
Handle(11, TableIndex.TypeRef),
Handle(12, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(4, TableIndex.StandAloneSig),
Handle(4, TableIndex.AssemblyRef));
}
[Fact]
public void AddMethod_WithAttributes()
{
var source0 =
@"class C
{
static void Main() { }
}";
var source1 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return string.Empty; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor");
Assert.Equal(3, reader0.CustomAttributes.Count);
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty");
Assert.Equal(1, reader1.CustomAttributes.Count);
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, a new attribute
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(3, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(6, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(1, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
}
[WorkItem(962219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/962219")]
[Fact]
public void PartialMethod()
{
var source =
@"partial class C
{
static partial void M1();
static partial void M2();
static partial void M3();
static partial void M1() { }
static partial void M2() { }
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetMethodDefNames(), "M1", "M2", ".ctor");
var method0 = compilation0.GetMember<MethodSymbol>("C.M2").PartialImplementationPart;
var method1 = compilation1.GetMember<MethodSymbol>("C.M2").PartialImplementationPart;
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
var methods = diff1.TestData.GetMethodsByName();
Assert.Equal(1, methods.Count);
Assert.True(methods.ContainsKey("C.M2()"));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetMethodDefNames(), "M2");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(2, TableIndex.AssemblyRef));
}
/// <summary>
/// Add a method that requires entries in the ParameterDefs table.
/// Specifically, normal parameters or return types with attributes.
/// Add the method in the first edit, then modify the method in the second.
/// </summary>
[Fact]
public void AddThenModifyMethod()
{
var source0 =
@"class A : System.Attribute { }
class C
{
static void Main() { F1(null); }
static object F1(string s1) { return s1; }
}";
var source1 =
@"class A : System.Attribute { }
class C
{
static void Main() { F2(); }
[return:A]static object F2(string s2 = ""2"") { return s2; }
}";
var source2 =
@"class A : System.Attribute { }
class C
{
static void Main() { F2(); }
[return:A]static object F2(string s2 = ""2"") { return null; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation0.WithSource(source2);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", "Main", "F1", ".ctor");
CheckNames(reader0, reader0.GetParameterDefNames(), "s1");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F2");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F2");
CheckNames(readers, reader1.GetParameterDefNames(), "", "s2");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(1, TableIndex.Constant, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(7, TableIndex.TypeRef),
Handle(5, TableIndex.MethodDef),
Handle(2, TableIndex.Param),
Handle(3, TableIndex.Param),
Handle(1, TableIndex.Constant),
Handle(4, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
var method2 = compilation2.GetMember<MethodSymbol>("C.F2");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
EncValidation.VerifyModuleMvid(2, reader1, reader2);
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetMethodDefNames(), "F2");
CheckNames(readers, reader2.GetParameterDefNames());
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F2
CheckEncMap(reader2,
Handle(8, TableIndex.TypeRef),
Handle(5, TableIndex.MethodDef),
Handle(3, TableIndex.StandAloneSig),
Handle(3, TableIndex.AssemblyRef));
}
[Fact]
public void AddThenModifyMethod_EmbeddedAttributes()
{
var source0 =
@"
namespace System.Runtime.CompilerServices { class X { } }
namespace N
{
class C
{
static void Main() { }
}
}
";
var source1 =
@"
namespace System.Runtime.CompilerServices { class X { } }
namespace N
{
struct C
{
static void Main()
{
Id(in G());
}
static ref readonly int Id(in int x) => ref x;
static ref readonly int G() => ref new int[1] { 1 }[0];
}
}";
var source2 =
@"
namespace System.Runtime.CompilerServices { class X { } }
namespace N
{
struct C
{
static void Main() { Id(in G()); }
static ref readonly int Id(in int x) => ref x;
static ref readonly int G() => ref new int[1] { 2 }[0];
static void H(string? s) {}
}
}";
var source3 =
@"
namespace System.Runtime.CompilerServices { class X { } }
namespace N
{
struct C
{
static void Main() { Id(in G()); }
static ref readonly int Id(in int x) => ref x;
static ref readonly int G() => ref new int[1] { 2 }[0];
static void H(string? s) {}
readonly ref readonly string?[]? F() => throw null;
}
}";
var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var main0 = compilation0.GetMember<MethodSymbol>("N.C.Main");
var main1 = compilation1.GetMember<MethodSymbol>("N.C.Main");
var id1 = compilation1.GetMember<MethodSymbol>("N.C.Id");
var g1 = compilation1.GetMember<MethodSymbol>("N.C.G");
var g2 = compilation2.GetMember<MethodSymbol>("N.C.G");
var h2 = compilation2.GetMember<MethodSymbol>("N.C.H");
var f3 = compilation3.GetMember<MethodSymbol>("N.C.F");
// Verify full metadata contains expected rows.
using var md0 = ModuleMetadata.CreateFromImage(compilation0.EmitToArray());
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, main0, main1),
SemanticEdit.Create(SemanticEditKind.Insert, null, id1),
SemanticEdit.Create(SemanticEditKind.Insert, null, g1)));
diff1.VerifySynthesizedMembers(
"<global namespace>: {Microsoft}",
"Microsoft: {CodeAnalysis}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"System.Runtime.CompilerServices: {IsReadOnlyAttribute}");
diff1.VerifyIL("N.C.Main", @"
{
// Code size 13 (0xd)
.maxstack 1
IL_0000: nop
IL_0001: call ""ref readonly int N.C.G()""
IL_0006: call ""ref readonly int N.C.Id(in int)""
IL_000b: pop
IL_000c: ret
}
");
diff1.VerifyIL("N.C.Id", @"
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}
");
diff1.VerifyIL("N.C.G", @"
{
// Code size 17 (0x11)
.maxstack 4
IL_0000: ldc.i4.1
IL_0001: newarr ""int""
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldc.i4.1
IL_0009: stelem.i4
IL_000a: ldc.i4.0
IL_000b: ldelema ""int""
IL_0010: ret
}
");
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader0 = md0.MetadataReader;
var reader1 = md1.Reader;
var readers = new List<MetadataReader>() { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefFullNames(), "Microsoft.CodeAnalysis.EmbeddedAttribute", "System.Runtime.CompilerServices.IsReadOnlyAttribute");
CheckNames(readers, reader1.GetMethodDefNames(), "Main", ".ctor", ".ctor", "Id", "G");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, g1, g2),
SemanticEdit.Create(SemanticEditKind.Insert, null, h2)));
// synthesized member for nullable annotations added:
diff2.VerifySynthesizedMembers(
"<global namespace>: {Microsoft}",
"Microsoft: {CodeAnalysis}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"System.Runtime.CompilerServices: {IsReadOnlyAttribute, NullableAttribute, NullableContextAttribute}");
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
// note: NullableAttribute has 2 ctors, NullableContextAttribute has one
CheckNames(readers, reader2.GetTypeDefFullNames(), "System.Runtime.CompilerServices.NullableAttribute", "System.Runtime.CompilerServices.NullableContextAttribute");
CheckNames(readers, reader2.GetMethodDefNames(), "G", ".ctor", ".ctor", ".ctor", "H");
// two new TypeDefs emitted for the attributes:
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(14, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeDef, EditAndContinueOperation.Default), // NullableAttribute
Row(7, TableIndex.TypeDef, EditAndContinueOperation.Default), // NullableContextAttribute
Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(2, TableIndex.Field, EditAndContinueOperation.Default),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(11, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMap(reader2,
Handle(11, TableIndex.TypeRef),
Handle(12, TableIndex.TypeRef),
Handle(13, TableIndex.TypeRef),
Handle(14, TableIndex.TypeRef),
Handle(15, TableIndex.TypeRef),
Handle(16, TableIndex.TypeRef),
Handle(17, TableIndex.TypeRef),
Handle(18, TableIndex.TypeRef),
Handle(6, TableIndex.TypeDef),
Handle(7, TableIndex.TypeDef),
Handle(1, TableIndex.Field),
Handle(2, TableIndex.Field),
Handle(7, TableIndex.MethodDef),
Handle(8, TableIndex.MethodDef),
Handle(9, TableIndex.MethodDef),
Handle(10, TableIndex.MethodDef),
Handle(11, TableIndex.MethodDef),
Handle(4, TableIndex.Param),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(9, TableIndex.MemberRef),
Handle(11, TableIndex.CustomAttribute),
Handle(12, TableIndex.CustomAttribute),
Handle(13, TableIndex.CustomAttribute),
Handle(14, TableIndex.CustomAttribute),
Handle(15, TableIndex.CustomAttribute),
Handle(16, TableIndex.CustomAttribute),
Handle(17, TableIndex.CustomAttribute),
Handle(3, TableIndex.AssemblyRef));
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, f3)));
// no change in synthesized members:
diff3.VerifySynthesizedMembers(
"<global namespace>: {Microsoft}",
"Microsoft: {CodeAnalysis}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"System.Runtime.CompilerServices: {IsReadOnlyAttribute, NullableAttribute, NullableContextAttribute}");
// Verify delta metadata contains expected rows.
using var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
readers.Add(reader3);
// no new type defs:
CheckNames(readers, reader3.GetTypeDefFullNames());
CheckNames(readers, reader3.GetMethodDefNames(), "F");
CheckEncLog(reader3,
Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void AddField()
{
var source0 =
@"class C
{
string F = ""F"";
}";
var source1 =
@"class C
{
string F = ""F"";
string G = ""G"";
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetFieldDefNames(), "F");
CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var method1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<FieldSymbol>("C.G")),
SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
diff1.VerifyUpdatedTypes("0x02000002");
CheckNames(readers, reader0.GetUpdatedTypeDefNames(diff1.EmitResult), "C");
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetFieldDefNames(), "G");
CheckNames(readers, reader1.GetMethodDefNames(), ".ctor");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(2, TableIndex.Field, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(2, TableIndex.Field),
Handle(1, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyProperty()
{
var source0 =
@"class C
{
object P { get { return 1; } }
}";
var source1 =
@"class C
{
object P { get { return 2; } }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var getP0 = compilation0.GetMember<MethodSymbol>("C.get_P");
var getP1 = compilation1.GetMember<MethodSymbol>("C.get_P");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetPropertyDefNames(), "P");
CheckNames(reader0, reader0.GetMethodDefNames(), "get_P", ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, getP0, getP1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetPropertyDefNames(), "P");
CheckNames(readers, reader1.GetMethodDefNames(), "get_P");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Property, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(1, TableIndex.MethodDef),
Handle(2, TableIndex.StandAloneSig),
Handle(1, TableIndex.Property),
Handle(2, TableIndex.MethodSemantics),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void AddProperty()
{
var source0 =
@"class A
{
object P { get; set; }
}
class B
{
}";
var source1 =
@"class A
{
object P { get; set; }
}
class B
{
object R { get { return null; } }
}";
var source2 =
@"class A
{
object P { get; set; }
object Q { get; set; }
}
class B
{
object R { get { return null; } }
object S { set { } }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation0.WithSource(source2);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B");
CheckNames(reader0, reader0.GetFieldDefNames(), "<P>k__BackingField");
CheckNames(reader0, reader0.GetPropertyDefNames(), "P");
CheckNames(reader0, reader0.GetMethodDefNames(), "get_P", "set_P", ".ctor", ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<PropertySymbol>("B.R"))));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetFieldDefNames());
CheckNames(readers, reader1.GetPropertyDefNames(), "R");
CheckNames(readers, reader1.GetMethodDefNames(), "get_R");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.PropertyMap, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
Row(2, TableIndex.Property, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(9, TableIndex.TypeRef),
Handle(5, TableIndex.MethodDef),
Handle(1, TableIndex.StandAloneSig),
Handle(2, TableIndex.PropertyMap),
Handle(2, TableIndex.Property),
Handle(3, TableIndex.MethodSemantics),
Handle(2, TableIndex.AssemblyRef));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation2.GetMember<PropertySymbol>("A.Q")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation2.GetMember<PropertySymbol>("B.S"))));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetFieldDefNames(), "<Q>k__BackingField");
CheckNames(readers, reader2.GetPropertyDefNames(), "Q", "S");
CheckNames(readers, reader2.GetMethodDefNames(), "get_Q", "set_Q", "set_S");
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(2, TableIndex.Field, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
Row(3, TableIndex.Property, EditAndContinueOperation.Default),
Row(2, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
Row(4, TableIndex.Property, EditAndContinueOperation.Default),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMap(reader2,
Handle(10, TableIndex.TypeRef),
Handle(11, TableIndex.TypeRef),
Handle(12, TableIndex.TypeRef),
Handle(13, TableIndex.TypeRef),
Handle(2, TableIndex.Field),
Handle(6, TableIndex.MethodDef),
Handle(7, TableIndex.MethodDef),
Handle(8, TableIndex.MethodDef),
Handle(2, TableIndex.Param),
Handle(3, TableIndex.Param),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(8, TableIndex.CustomAttribute),
Handle(9, TableIndex.CustomAttribute),
Handle(10, TableIndex.CustomAttribute),
Handle(11, TableIndex.CustomAttribute),
Handle(3, TableIndex.Property),
Handle(4, TableIndex.Property),
Handle(4, TableIndex.MethodSemantics),
Handle(5, TableIndex.MethodSemantics),
Handle(6, TableIndex.MethodSemantics),
Handle(3, TableIndex.AssemblyRef));
}
[Fact]
public void AddEvent()
{
var source0 =
@"delegate void D();
class A
{
event D E;
}
class B
{
}";
var source1 =
@"delegate void D();
class A
{
event D E;
}
class B
{
event D F;
}";
var source2 =
@"delegate void D();
class A
{
event D E;
event D G;
}
class B
{
event D F;
event D H;
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation0.WithSource(source2);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "D", "A", "B");
CheckNames(reader0, reader0.GetFieldDefNames(), "E");
CheckNames(reader0, reader0.GetEventDefNames(), "E");
CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", "Invoke", "BeginInvoke", "EndInvoke", "add_E", "remove_E", ".ctor", ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<EventSymbol>("B.F"))));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetFieldDefNames(), "F");
CheckNames(readers, reader1.GetMethodDefNames(), "add_F", "remove_F");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(10, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(11, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(12, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(13, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(14, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodSpec, EditAndContinueOperation.Default),
Row(14, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.EventMap, EditAndContinueOperation.Default),
Row(2, TableIndex.EventMap, EditAndContinueOperation.AddEvent),
Row(2, TableIndex.Event, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(2, TableIndex.Field, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(8, TableIndex.Param, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(9, TableIndex.Param, EditAndContinueOperation.Default),
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(14, TableIndex.TypeRef),
Handle(15, TableIndex.TypeRef),
Handle(16, TableIndex.TypeRef),
Handle(17, TableIndex.TypeRef),
Handle(18, TableIndex.TypeRef),
Handle(19, TableIndex.TypeRef),
Handle(2, TableIndex.Field),
Handle(9, TableIndex.MethodDef),
Handle(10, TableIndex.MethodDef),
Handle(8, TableIndex.Param),
Handle(9, TableIndex.Param),
Handle(10, TableIndex.MemberRef),
Handle(11, TableIndex.MemberRef),
Handle(12, TableIndex.MemberRef),
Handle(13, TableIndex.MemberRef),
Handle(14, TableIndex.MemberRef),
Handle(8, TableIndex.CustomAttribute),
Handle(9, TableIndex.CustomAttribute),
Handle(10, TableIndex.CustomAttribute),
Handle(11, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.EventMap),
Handle(2, TableIndex.Event),
Handle(3, TableIndex.MethodSemantics),
Handle(4, TableIndex.MethodSemantics),
Handle(2, TableIndex.AssemblyRef),
Handle(2, TableIndex.MethodSpec));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation2.GetMember<EventSymbol>("A.G")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation2.GetMember<EventSymbol>("B.H"))));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetFieldDefNames(), "G", "H");
CheckNames(readers, reader2.GetMethodDefNames(), "add_G", "remove_G", "add_H", "remove_H");
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(15, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(16, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(17, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(18, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(19, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodSpec, EditAndContinueOperation.Default),
Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(21, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(22, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(23, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(24, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(25, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent),
Row(3, TableIndex.Event, EditAndContinueOperation.Default),
Row(2, TableIndex.EventMap, EditAndContinueOperation.AddEvent),
Row(4, TableIndex.Event, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(3, TableIndex.Field, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(4, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(14, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(11, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(10, TableIndex.Param, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(11, TableIndex.Param, EditAndContinueOperation.Default),
Row(13, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(12, TableIndex.Param, EditAndContinueOperation.Default),
Row(14, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(13, TableIndex.Param, EditAndContinueOperation.Default),
Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(7, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(8, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMap(reader2,
Handle(20, TableIndex.TypeRef),
Handle(21, TableIndex.TypeRef),
Handle(22, TableIndex.TypeRef),
Handle(23, TableIndex.TypeRef),
Handle(24, TableIndex.TypeRef),
Handle(25, TableIndex.TypeRef),
Handle(3, TableIndex.Field),
Handle(4, TableIndex.Field),
Handle(11, TableIndex.MethodDef),
Handle(12, TableIndex.MethodDef),
Handle(13, TableIndex.MethodDef),
Handle(14, TableIndex.MethodDef),
Handle(10, TableIndex.Param),
Handle(11, TableIndex.Param),
Handle(12, TableIndex.Param),
Handle(13, TableIndex.Param),
Handle(15, TableIndex.MemberRef),
Handle(16, TableIndex.MemberRef),
Handle(17, TableIndex.MemberRef),
Handle(18, TableIndex.MemberRef),
Handle(19, TableIndex.MemberRef),
Handle(12, TableIndex.CustomAttribute),
Handle(13, TableIndex.CustomAttribute),
Handle(14, TableIndex.CustomAttribute),
Handle(15, TableIndex.CustomAttribute),
Handle(16, TableIndex.CustomAttribute),
Handle(17, TableIndex.CustomAttribute),
Handle(18, TableIndex.CustomAttribute),
Handle(19, TableIndex.CustomAttribute),
Handle(3, TableIndex.StandAloneSig),
Handle(3, TableIndex.Event),
Handle(4, TableIndex.Event),
Handle(5, TableIndex.MethodSemantics),
Handle(6, TableIndex.MethodSemantics),
Handle(7, TableIndex.MethodSemantics),
Handle(8, TableIndex.MethodSemantics),
Handle(3, TableIndex.AssemblyRef),
Handle(3, TableIndex.MethodSpec));
}
[WorkItem(1175704, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1175704")]
[Fact]
public void EventFields()
{
var source0 = MarkedSource(@"
using System;
class C
{
static event EventHandler handler;
static int F()
{
handler(null, null);
return 1;
}
}
");
var source1 = MarkedSource(@"
using System;
class C
{
static event EventHandler handler;
static int F()
{
handler(null, null);
return 10;
}
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
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.Update, f0, f1, preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 21 (0x15)
.maxstack 3
.locals init (int V_0)
IL_0000: nop
IL_0001: ldsfld ""System.EventHandler C.handler""
IL_0006: ldnull
IL_0007: ldnull
IL_0008: callvirt ""void System.EventHandler.Invoke(object, System.EventArgs)""
IL_000d: nop
IL_000e: ldc.i4.s 10
IL_0010: stloc.0
IL_0011: br.s IL_0013
IL_0013: ldloc.0
IL_0014: ret
}
");
}
[Fact]
public void UpdateType_AddAttributes()
{
var source0 = @"
class C
{
}";
var source1 = @"
[System.ComponentModel.Description(""C"")]
class C
{
}";
var source2 = @"
[System.ComponentModel.Description(""C"")]
[System.ObsoleteAttribute]
class C
{
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var c0 = compilation0.GetMember<NamedTypeSymbol>("C");
var c1 = compilation1.GetMember<NamedTypeSymbol>("C");
var c2 = compilation2.GetMember<NamedTypeSymbol>("C");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
Assert.Equal(3, reader0.CustomAttributes.Count);
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, c0, c1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames(), "C");
Assert.Equal(1, reader1.CustomAttributes.Count);
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(2, TableIndex.TypeDef),
Handle(4, TableIndex.CustomAttribute));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, c1, c2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, reader2.GetTypeDefNames(), "C");
Assert.Equal(2, reader2.CustomAttributes.Count);
CheckEncLogDefinitions(reader2,
Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader2,
Handle(2, TableIndex.TypeDef),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute));
}
[Fact]
public void ReplaceType()
{
var source0 = @"
class C
{
void F(int x) {}
}
";
var source1 = @"
class C
{
void F(int x, int y) { }
}";
var source2 = @"
class C
{
void F(int x, int y) { System.Console.WriteLine(1); }
}";
var source3 = @"
[System.Obsolete]
class C
{
void F(int x, int y) { System.Console.WriteLine(2); }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var c0 = compilation0.GetMember<NamedTypeSymbol>("C");
var c1 = compilation1.GetMember<NamedTypeSymbol>("C");
var c2 = compilation2.GetMember<NamedTypeSymbol>("C");
var c3 = compilation3.GetMember<NamedTypeSymbol>("C");
var f2 = c2.GetMember<MethodSymbol>("F");
var f3 = c3.GetMember<MethodSymbol>("F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
// This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one.
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Replace, null, c1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames(), "C#1");
CheckEncLogDefinitions(reader1,
Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(3, TableIndex.Param, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(3, TableIndex.TypeDef),
Handle(3, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(2, TableIndex.Param),
Handle(3, TableIndex.Param));
// This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one.
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Replace, null, c2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, reader2.GetTypeDefNames(), "C#2");
CheckEncLogDefinitions(reader2,
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(5, TableIndex.Param, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader2,
Handle(4, TableIndex.TypeDef),
Handle(5, TableIndex.MethodDef),
Handle(6, TableIndex.MethodDef),
Handle(4, TableIndex.Param),
Handle(5, TableIndex.Param));
// This update is an EnC update - even reloadable types are update in-place
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, c2, c3),
SemanticEdit.Create(SemanticEditKind.Update, f2, f3)));
// Verify delta metadata contains expected rows.
using var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
readers = new[] { reader0, reader1, reader2, reader3 };
CheckNames(readers, reader3.GetTypeDefNames(), "C#2");
CheckEncLogDefinitions(reader3,
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader3,
Handle(4, TableIndex.TypeDef),
Handle(5, TableIndex.MethodDef),
Handle(4, TableIndex.CustomAttribute));
}
[Fact]
public void AddNestedTypeAndMembers()
{
var source0 =
@"class A
{
class B { }
static object F()
{
return new B();
}
}";
var source1 =
@"class A
{
class B { }
class C
{
class D { }
static object F;
internal static object G()
{
return F;
}
}
static object F()
{
return C.G();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var c1 = compilation1.GetMember<NamedTypeSymbol>("A.C");
var f0 = compilation0.GetMember<MethodSymbol>("A.F");
var f1 = compilation1.GetMember<MethodSymbol>("A.F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B");
CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ".ctor");
Assert.Equal(1, reader0.GetTableRowCount(TableIndex.NestedClass));
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, c1),
SemanticEdit.Create(SemanticEditKind.Update, f0, f1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames(), "C", "D");
CheckNames(readers, reader1.GetMethodDefNames(), "F", "G", ".ctor", ".ctor");
Assert.Equal(2, reader1.GetTableRowCount(TableIndex.NestedClass));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default),
Row(3, TableIndex.NestedClass, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(4, TableIndex.TypeDef),
Handle(5, TableIndex.TypeDef),
Handle(1, TableIndex.Field),
Handle(1, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(5, TableIndex.MethodDef),
Handle(6, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef),
Handle(2, TableIndex.NestedClass),
Handle(3, TableIndex.NestedClass));
}
/// <summary>
/// Nested types should be emitted in the
/// same order as full emit.
/// </summary>
[Fact]
public void AddNestedTypesOrder()
{
var source0 =
@"class A
{
class B1
{
class C1 { }
}
class B2
{
class C2 { }
}
}";
var source1 =
@"class A
{
class B1
{
class C1 { }
}
class B2
{
class C2 { }
}
class B3
{
class C3 { }
}
class B4
{
class C4 { }
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B1", "B2", "C1", "C2");
Assert.Equal(4, reader0.GetTableRowCount(TableIndex.NestedClass));
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A.B3")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A.B4"))));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames(), "B3", "B4", "C3", "C4");
Assert.Equal(4, reader1.GetTableRowCount(TableIndex.NestedClass));
}
[Fact]
public void AddNestedGenericType()
{
var source0 =
@"class A
{
class B<T>
{
}
static object F()
{
return null;
}
}";
var source1 =
@"class A
{
class B<T>
{
internal class C<U>
{
internal object F<V>() where V : T, new()
{
return new C<V>();
}
}
}
static object F()
{
return new B<A>.C<B<object>>().F<A>();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var f0 = compilation0.GetMember<MethodSymbol>("A.F");
var f1 = compilation1.GetMember<MethodSymbol>("A.F");
var c1 = compilation1.GetMember<NamedTypeSymbol>("A.B.C");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B`1");
Assert.Equal(1, reader0.GetTableRowCount(TableIndex.NestedClass));
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, c1),
SemanticEdit.Create(SemanticEditKind.Update, f0, f1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
diff1.VerifyUpdatedTypes("0x02000002", "0x02000003");
CheckNames(readers, reader0.GetUpdatedTypeDefNames(diff1.EmitResult), "A", "B`1");
CheckNames(readers, reader1.GetTypeDefNames(), "C`1");
Assert.Equal(1, reader1.GetTableRowCount(TableIndex.NestedClass));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodSpec, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(1, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default),
Row(2, TableIndex.GenericParam, EditAndContinueOperation.Default),
Row(3, TableIndex.GenericParam, EditAndContinueOperation.Default),
Row(4, TableIndex.GenericParam, EditAndContinueOperation.Default),
Row(1, TableIndex.GenericParamConstraint, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(4, TableIndex.TypeDef),
Handle(1, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(5, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(6, TableIndex.MemberRef),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(2, TableIndex.StandAloneSig),
Handle(1, TableIndex.TypeSpec),
Handle(2, TableIndex.TypeSpec),
Handle(3, TableIndex.TypeSpec),
Handle(2, TableIndex.AssemblyRef),
Handle(2, TableIndex.NestedClass),
Handle(2, TableIndex.GenericParam),
Handle(3, TableIndex.GenericParam),
Handle(4, TableIndex.GenericParam),
Handle(1, TableIndex.MethodSpec),
Handle(1, TableIndex.GenericParamConstraint));
}
[Fact]
public void AddNamespace()
{
var source0 =
@"
class C
{
static void Main() { }
}";
var source1 =
@"
namespace N
{
class D { public static void F() { } }
}
class C
{
static void Main() => N.D.F();
}";
var source2 =
@"
namespace N
{
class D { public static void F() { } }
namespace M
{
class E { public static void G() { } }
}
}
class C
{
static void Main() => N.M.E.G();
}";
var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var main0 = compilation0.GetMember<MethodSymbol>("C.Main");
var main1 = compilation1.GetMember<MethodSymbol>("C.Main");
var main2 = compilation2.GetMember<MethodSymbol>("C.Main");
var d1 = compilation1.GetMember<NamedTypeSymbol>("N.D");
var e2 = compilation2.GetMember<NamedTypeSymbol>("N.M.E");
using var md0 = ModuleMetadata.CreateFromImage(compilation0.EmitToArray());
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, main0, main1),
SemanticEdit.Create(SemanticEditKind.Insert, null, d1)));
diff1.VerifyIL("C.Main", @"
{
// Code size 7 (0x7)
.maxstack 0
IL_0000: call ""void N.D.F()""
IL_0005: nop
IL_0006: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, main1, main2),
SemanticEdit.Create(SemanticEditKind.Insert, null, e2)));
diff2.VerifyIL("C.Main", @"
{
// Code size 7 (0x7)
.maxstack 0
IL_0000: call ""void N.M.E.G()""
IL_0005: nop
IL_0006: ret
}");
}
[Fact]
public void ModifyExplicitImplementation()
{
var source =
@"interface I
{
void M();
}
class C : I
{
void I.M() { }
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var method0 = compilation0.GetMember<NamedTypeSymbol>("C").GetMethod("I.M");
var method1 = compilation1.GetMember<NamedTypeSymbol>("C").GetMethod("I.M");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "I", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "M", "I.M", ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var block1 = diff1.GetMetadata();
var reader1 = block1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "I.M");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void AddThenModifyExplicitImplementation()
{
var source0 =
@"interface I
{
void M();
}
class A : I
{
void I.M() { }
}
class B : I
{
public void M() { }
}";
var source1 =
@"interface I
{
void M();
}
class A : I
{
void I.M() { }
}
class B : I
{
public void M() { }
void I.M() { }
}";
var source2 = source1;
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation0.WithSource(source2);
var method1 = compilation1.GetMember<NamedTypeSymbol>("B").GetMethod("I.M");
var method2 = compilation2.GetMember<NamedTypeSymbol>("B").GetMethod("I.M");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, method1)));
using var block1 = diff1.GetMetadata();
var reader1 = block1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetMethodDefNames(), "I.M");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(6, TableIndex.MethodDef),
Handle(2, TableIndex.MethodImpl),
Handle(2, TableIndex.AssemblyRef));
var generation1 = diff1.NextGeneration;
var diff2 = compilation2.EmitDifference(
generation1,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
EncValidation.VerifyModuleMvid(2, reader1, reader2);
CheckNames(readers, reader2.GetMethodDefNames(), "I.M");
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader2,
Handle(7, TableIndex.TypeRef),
Handle(6, TableIndex.MethodDef),
Handle(3, TableIndex.AssemblyRef));
}
[WorkItem(930065, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/930065")]
[Fact]
public void ModifyConstructorBodyInPresenceOfExplicitInterfaceImplementation()
{
var source = @"
interface I
{
void M();
}
class C : I
{
public C()
{
}
void I.M() { }
}
";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var method0 = compilation0.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single();
var method1 = compilation1.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single();
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
using var block1 = diff1.GetMetadata();
var reader1 = block1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), ".ctor");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void AddAndModifyInterfaceMembers()
{
var source0 = @"
using System;
interface I
{
}";
var source1 = @"
using System;
interface I
{
static int X = 10;
static event Action Y;
static void M() { }
void N() { }
static int P { get => 1; set { } }
int Q { get => 1; set { } }
static event Action E { add { } remove { } }
event Action F { add { } remove { } }
interface J { }
}";
var source2 = @"
using System;
interface I
{
static int X = 2;
static event Action Y;
static I() { X--; }
static void M() { X++; }
void N() { X++; }
static int P { get => 3; set { X++; } }
int Q { get => 3; set { X++; } }
static event Action E { add { X++; } remove { X++; } }
event Action F { add { X++; } remove { X++; } }
interface J { }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var x1 = compilation1.GetMember<FieldSymbol>("I.X");
var y1 = compilation1.GetMember<EventSymbol>("I.Y");
var m1 = compilation1.GetMember<MethodSymbol>("I.M");
var n1 = compilation1.GetMember<MethodSymbol>("I.N");
var p1 = compilation1.GetMember<PropertySymbol>("I.P");
var q1 = compilation1.GetMember<PropertySymbol>("I.Q");
var e1 = compilation1.GetMember<EventSymbol>("I.E");
var f1 = compilation1.GetMember<EventSymbol>("I.F");
var j1 = compilation1.GetMember<NamedTypeSymbol>("I.J");
var getP1 = compilation1.GetMember<MethodSymbol>("I.get_P");
var setP1 = compilation1.GetMember<MethodSymbol>("I.set_P");
var getQ1 = compilation1.GetMember<MethodSymbol>("I.get_Q");
var setQ1 = compilation1.GetMember<MethodSymbol>("I.set_Q");
var addE1 = compilation1.GetMember<MethodSymbol>("I.add_E");
var removeE1 = compilation1.GetMember<MethodSymbol>("I.remove_E");
var addF1 = compilation1.GetMember<MethodSymbol>("I.add_F");
var removeF1 = compilation1.GetMember<MethodSymbol>("I.remove_F");
var cctor1 = compilation1.GetMember<NamedTypeSymbol>("I").StaticConstructors.Single();
var x2 = compilation2.GetMember<FieldSymbol>("I.X");
var m2 = compilation2.GetMember<MethodSymbol>("I.M");
var n2 = compilation2.GetMember<MethodSymbol>("I.N");
var getP2 = compilation2.GetMember<MethodSymbol>("I.get_P");
var setP2 = compilation2.GetMember<MethodSymbol>("I.set_P");
var getQ2 = compilation2.GetMember<MethodSymbol>("I.get_Q");
var setQ2 = compilation2.GetMember<MethodSymbol>("I.set_Q");
var addE2 = compilation2.GetMember<MethodSymbol>("I.add_E");
var removeE2 = compilation2.GetMember<MethodSymbol>("I.remove_E");
var addF2 = compilation2.GetMember<MethodSymbol>("I.add_F");
var removeF2 = compilation2.GetMember<MethodSymbol>("I.remove_F");
var cctor2 = compilation2.GetMember<NamedTypeSymbol>("I").StaticConstructors.Single();
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, x1),
SemanticEdit.Create(SemanticEditKind.Insert, null, y1),
SemanticEdit.Create(SemanticEditKind.Insert, null, m1),
SemanticEdit.Create(SemanticEditKind.Insert, null, n1),
SemanticEdit.Create(SemanticEditKind.Insert, null, p1),
SemanticEdit.Create(SemanticEditKind.Insert, null, q1),
SemanticEdit.Create(SemanticEditKind.Insert, null, e1),
SemanticEdit.Create(SemanticEditKind.Insert, null, f1),
SemanticEdit.Create(SemanticEditKind.Insert, null, j1),
SemanticEdit.Create(SemanticEditKind.Insert, null, cctor1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
diff1.VerifyUpdatedTypes("0x02000002");
CheckNames(readers, reader0.GetUpdatedTypeDefNames(diff1.EmitResult), "I");
CheckNames(readers, reader1.GetTypeDefNames(), "J");
CheckNames(readers, reader1.GetFieldDefNames(), "X", "Y");
CheckNames(readers, reader1.GetMethodDefNames(), "add_Y", "remove_Y", "M", "N", "get_P", "set_P", "get_Q", "set_Q", "add_E", "remove_E", "add_F", "remove_F", ".cctor");
Assert.Equal(1, reader1.GetTableRowCount(TableIndex.NestedClass));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, x1, x2),
SemanticEdit.Create(SemanticEditKind.Update, m1, m2),
SemanticEdit.Create(SemanticEditKind.Update, n1, n2),
SemanticEdit.Create(SemanticEditKind.Update, getP1, getP2),
SemanticEdit.Create(SemanticEditKind.Update, setP1, setP2),
SemanticEdit.Create(SemanticEditKind.Update, getQ1, getQ2),
SemanticEdit.Create(SemanticEditKind.Update, setQ1, setQ2),
SemanticEdit.Create(SemanticEditKind.Update, addE1, addE2),
SemanticEdit.Create(SemanticEditKind.Update, removeE1, removeE2),
SemanticEdit.Create(SemanticEditKind.Update, addF1, addF2),
SemanticEdit.Create(SemanticEditKind.Update, removeF1, removeF2),
SemanticEdit.Create(SemanticEditKind.Update, cctor1, cctor2)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
diff2.VerifyUpdatedTypes("0x02000002");
CheckNames(readers, reader0.GetUpdatedTypeDefNames(diff1.EmitResult), "I");
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetFieldDefNames(), "X");
CheckNames(readers, reader2.GetMethodDefNames(), "M", "N", "get_P", "set_P", "get_Q", "set_Q", "add_E", "remove_E", "add_F", "remove_F", ".cctor");
Assert.Equal(0, reader2.GetTableRowCount(TableIndex.NestedClass));
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.Event, EditAndContinueOperation.Default),
Row(3, TableIndex.Event, EditAndContinueOperation.Default),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(7, 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(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Property, EditAndContinueOperation.Default),
Row(2, TableIndex.Property, EditAndContinueOperation.Default),
Row(11, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(13, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(14, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(15, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(16, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(17, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(18, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
diff2.VerifyIL(@"
{
// Code size 14 (0xe)
.maxstack 8
IL_0000: nop
IL_0001: ldsfld 0x04000001
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: stsfld 0x04000001
IL_000d: ret
}
{
// Code size 2 (0x2)
.maxstack 8
IL_0000: ldc.i4.3
IL_0001: ret
}
{
// Code size 20 (0x14)
.maxstack 8
IL_0000: ldc.i4.2
IL_0001: stsfld 0x04000001
IL_0006: nop
IL_0007: ldsfld 0x04000001
IL_000c: ldc.i4.1
IL_000d: sub
IL_000e: stsfld 0x04000001
IL_0013: ret
}
");
}
[Fact]
public void AddAttributeReferences()
{
var source0 =
@"class A : System.Attribute { }
class B : System.Attribute { }
class C
{
[A] static void M1<[B]T>() { }
[B] static object F1;
[A] static object P1 { get { return null; } }
[B] static event D E1;
}
delegate void D();
";
var source1 =
@"class A : System.Attribute { }
class B : System.Attribute { }
class C
{
[A] static void M1<[B]T>() { }
[B] static void M2<[A]T>() { }
[B] static object F1;
[A] static object F2;
[A] static object P1 { get { return null; } }
[B] static object P2 { get { return null; } }
[B] static event D E1;
[A] static event D E2;
}
delegate void D();
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B", "C", "D");
CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", ".ctor", "M1", "get_P1", "add_E1", "remove_E1", ".ctor", ".ctor", "Invoke", "BeginInvoke", "EndInvoke");
CheckAttributes(reader0,
new CustomAttributeRow(Handle(1, TableIndex.Field), Handle(2, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(1, TableIndex.Property), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(1, TableIndex.Event), Handle(2, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.GenericParam), Handle(2, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(2, TableIndex.Field), Handle(4, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.Field), Handle(5, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(5, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(6, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)));
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.M2")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<FieldSymbol>("C.F2")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<PropertySymbol>("C.P2")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<EventSymbol>("C.E2"))));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
diff1.VerifyUpdatedTypes("0x02000004");
CheckNames(readers, reader0.GetUpdatedTypeDefNames(diff1.EmitResult), "C");
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "M2", "get_P2", "add_E2", "remove_E2");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(11, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(12, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(13, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(14, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(15, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodSpec, EditAndContinueOperation.Default),
Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent),
Row(2, TableIndex.Event, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(3, TableIndex.Field, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(4, TableIndex.Field, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(14, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(15, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
Row(2, TableIndex.Property, EditAndContinueOperation.Default),
Row(14, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(8, TableIndex.Param, EditAndContinueOperation.Default),
Row(15, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(9, TableIndex.Param, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(20, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(2, TableIndex.GenericParam, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(15, TableIndex.TypeRef),
Handle(16, TableIndex.TypeRef),
Handle(17, TableIndex.TypeRef),
Handle(18, TableIndex.TypeRef),
Handle(19, TableIndex.TypeRef),
Handle(20, TableIndex.TypeRef),
Handle(3, TableIndex.Field),
Handle(4, TableIndex.Field),
Handle(12, TableIndex.MethodDef),
Handle(13, TableIndex.MethodDef),
Handle(14, TableIndex.MethodDef),
Handle(15, TableIndex.MethodDef),
Handle(8, TableIndex.Param),
Handle(9, TableIndex.Param),
Handle(11, TableIndex.MemberRef),
Handle(12, TableIndex.MemberRef),
Handle(13, TableIndex.MemberRef),
Handle(14, TableIndex.MemberRef),
Handle(15, TableIndex.MemberRef),
Handle(7, TableIndex.CustomAttribute),
Handle(13, TableIndex.CustomAttribute),
Handle(14, TableIndex.CustomAttribute),
Handle(15, TableIndex.CustomAttribute),
Handle(16, TableIndex.CustomAttribute),
Handle(17, TableIndex.CustomAttribute),
Handle(18, TableIndex.CustomAttribute),
Handle(19, TableIndex.CustomAttribute),
Handle(20, TableIndex.CustomAttribute),
Handle(3, TableIndex.StandAloneSig),
Handle(4, TableIndex.StandAloneSig),
Handle(2, TableIndex.Event),
Handle(2, TableIndex.Property),
Handle(4, TableIndex.MethodSemantics),
Handle(5, TableIndex.MethodSemantics),
Handle(6, TableIndex.MethodSemantics),
Handle(2, TableIndex.AssemblyRef),
Handle(2, TableIndex.GenericParam),
Handle(2, TableIndex.MethodSpec));
CheckAttributes(reader1,
new CustomAttributeRow(Handle(1, TableIndex.GenericParam), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(2, TableIndex.Property), Handle(2, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(2, TableIndex.Event), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(3, TableIndex.Field), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(4, TableIndex.Field), Handle(11, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(4, TableIndex.Field), Handle(12, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(12, TableIndex.MethodDef), Handle(2, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(14, TableIndex.MethodDef), Handle(11, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(15, TableIndex.MethodDef), Handle(11, TableIndex.MemberRef)));
}
/// <summary>
/// [assembly: ...] and [module: ...] attributes should
/// not be included in delta metadata.
/// </summary>
[Fact]
public void AssemblyAndModuleAttributeReferences()
{
var source0 =
@"[assembly: System.CLSCompliantAttribute(true)]
[module: System.CLSCompliantAttribute(true)]
class C
{
}";
var source1 =
@"[assembly: System.CLSCompliantAttribute(true)]
[module: System.CLSCompliantAttribute(true)]
class C
{
static void M()
{
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.M"))));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var readers = new[] { reader0, md1.Reader };
diff1.VerifyUpdatedTypes("0x02000002");
CheckNames(readers, reader0.GetUpdatedTypeDefNames(diff1.EmitResult), "C");
CheckNames(readers, md1.Reader.GetTypeDefNames());
CheckNames(readers, md1.Reader.GetMethodDefNames(), "M");
CheckEncLog(md1.Reader,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.M
CheckEncMap(md1.Reader,
Handle(7, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void OtherReferences()
{
var source0 =
@"delegate void D();
class C
{
object F;
object P { get { return null; } }
event D E;
void M()
{
}
}";
var source1 =
@"delegate void D();
class C
{
object F;
object P { get { return null; } }
event D E;
void M()
{
object o;
o = typeof(D);
o = F;
o = P;
E += null;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "D", "C");
CheckNames(reader0, reader0.GetEventDefNames(), "E");
CheckNames(reader0, reader0.GetFieldDefNames(), "F", "E");
CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", "Invoke", "BeginInvoke", "EndInvoke", "get_P", "add_E", "remove_E", "M", ".ctor");
CheckNames(reader0, reader0.GetPropertyDefNames(), "P");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
// Emit delta metadata.
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
diff1.VerifyUpdatedTypes("0x02000003");
CheckNames(readers, reader0.GetUpdatedTypeDefNames(diff1.EmitResult), "C");
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetEventDefNames());
CheckNames(readers, reader1.GetFieldDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "M");
CheckNames(readers, reader1.GetPropertyDefNames());
}
[Fact]
public void ArrayInitializer()
{
var source0 = WithWindowsLineBreaks(@"
class C
{
static void M()
{
int[] a = new[] { 1, 2, 3 };
}
}");
var source1 = WithWindowsLineBreaks(@"
class C
{
static void M()
{
int[] a = new[] { 1, 2, 3, 4 };
}
}");
var compilation0 = CreateCompilation(Parse(source0, "a.cs"), options: TestOptions.DebugDll);
var compilation1 = compilation0.RemoveAllSyntaxTrees().AddSyntaxTrees(Parse(source1, "a.cs"));
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(
ModuleMetadata.CreateFromImage(bytes0),
testData0.GetMethodData("C.M").EncDebugInfoProvider());
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember("C.M"), compilation1.GetMember("C.M"))));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifyUpdatedTypes("0x02000002");
CheckNames(reader0, reader0.GetUpdatedTypeDefNames(diff1.EmitResult), "C");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(12, TableIndex.TypeRef),
Handle(13, TableIndex.TypeRef),
Handle(1, TableIndex.MethodDef),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
diff1.VerifyIL(
@"{
// Code size 25 (0x19)
.maxstack 4
IL_0000: nop
IL_0001: ldc.i4.4
IL_0002: newarr 0x0100000D
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.3
IL_0012: stelem.i4
IL_0013: dup
IL_0014: ldc.i4.3
IL_0015: ldc.i4.4
IL_0016: stelem.i4
IL_0017: stloc.0
IL_0018: ret
}");
diff1.VerifyPdb(new[] { 0x06000001 },
@"<symbols>
<files>
<file id=""1"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""15-9B-5B-24-28-37-02-4F-D2-2E-40-DB-1A-89-9F-4D-54-D5-95-89"" />
</files>
<methods>
<method token=""0x6000001"">
<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=""40"" document=""1"" />
<entry offset=""0x18"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x19"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x19"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void PInvokeModuleRefAndImplMap()
{
var source0 =
@"using System.Runtime.InteropServices;
class C
{
[DllImport(""msvcrt.dll"")]
public static extern int getchar();
}";
var source1 =
@"using System.Runtime.InteropServices;
class C
{
[DllImport(""msvcrt.dll"")]
public static extern int getchar();
[DllImport(""msvcrt.dll"")]
public static extern int puts(string s);
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.puts"))));
diff1.VerifyUpdatedTypes("0x02000002");
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetUpdatedTypeDefNames(diff1.EmitResult), "C");
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(2, TableIndex.ModuleRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(2, TableIndex.ImplMap, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(3, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(2, TableIndex.ModuleRef),
Handle(2, TableIndex.ImplMap),
Handle(2, TableIndex.AssemblyRef));
}
/// <summary>
/// ClassLayout and FieldLayout tables.
/// </summary>
[Fact]
public void ClassAndFieldLayout()
{
var source0 =
@"using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit, Pack=2)]
class A
{
[FieldOffset(0)]internal byte F;
[FieldOffset(2)]internal byte G;
}";
var source1 =
@"using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit, Pack=2)]
class A
{
[FieldOffset(0)]internal byte F;
[FieldOffset(2)]internal byte G;
}
[StructLayout(LayoutKind.Explicit, Pack=4)]
class B
{
[FieldOffset(0)]internal short F;
[FieldOffset(4)]internal short G;
}";
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.Insert, null, compilation1.GetMember<NamedTypeSymbol>("B"))));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(3, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(4, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.ClassLayout, EditAndContinueOperation.Default),
Row(3, TableIndex.FieldLayout, EditAndContinueOperation.Default),
Row(4, TableIndex.FieldLayout, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(3, TableIndex.TypeDef),
Handle(3, TableIndex.Field),
Handle(4, TableIndex.Field),
Handle(2, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(2, TableIndex.ClassLayout),
Handle(3, TableIndex.FieldLayout),
Handle(4, TableIndex.FieldLayout),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void NamespacesAndOverloads()
{
var compilation0 = CreateCompilation(options: TestOptions.DebugDll, source:
@"class C { }
namespace N
{
class C { }
}
namespace M
{
class C
{
void M1(N.C o) { }
void M1(M.C o) { }
void M2(N.C a, M.C b, global::C c)
{
M1(a);
}
}
}");
var method0 = compilation0.GetMember<MethodSymbol>("M.C.M2");
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var compilation1 = compilation0.WithSource(@"
class C { }
namespace N
{
class C { }
}
namespace M
{
class C
{
void M1(N.C o) { }
void M1(M.C o) { }
void M1(global::C o) { }
void M2(N.C a, M.C b, global::C c)
{
M1(a);
M1(b);
}
}
}");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMembers("M.C.M1")[2])));
diff1.VerifyIL(
@"{
// Code size 2 (0x2)
.maxstack 8
IL_0000: nop
IL_0001: ret
}");
var compilation2 = compilation1.WithSource(@"
class C { }
namespace N
{
class C { }
}
namespace M
{
class C
{
void M1(N.C o) { }
void M1(M.C o) { }
void M1(global::C o) { }
void M2(N.C a, M.C b, global::C c)
{
M1(a);
M1(b);
M1(c);
}
}
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("M.C.M2"),
compilation2.GetMember<MethodSymbol>("M.C.M2"))));
diff2.VerifyIL(
@"{
// Code size 26 (0x1a)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldarg.1
IL_0003: call 0x06000002
IL_0008: nop
IL_0009: ldarg.0
IL_000a: ldarg.2
IL_000b: call 0x06000003
IL_0010: nop
IL_0011: ldarg.0
IL_0012: ldarg.3
IL_0013: call 0x06000007
IL_0018: nop
IL_0019: ret
}");
}
[Fact]
public void TypesAndOverloads()
{
const string source =
@"using System;
struct A<T>
{
internal class B<U> { }
}
class B { }
class C
{
static void M(A<B>.B<object> a)
{
M(a);
M((A<B>.B<B>)null);
}
static void M(A<B>.B<B> a)
{
M(a);
M((A<B>.B<object>)null);
}
static void M(A<B> a)
{
M(a);
M((A<B>?)a);
}
static void M(Nullable<A<B>> a)
{
M(a);
M(a.Value);
}
unsafe static void M(int* p)
{
M(p);
M((byte*)p);
}
unsafe static void M(byte* p)
{
M(p);
M((int*)p);
}
static void M(B[][] b)
{
M(b);
M((object[][])b);
}
static void M(object[][] b)
{
M(b);
M((B[][])b);
}
static void M(A<B[]>.B<object> b)
{
M(b);
M((A<B[, ,]>.B<object>)null);
}
static void M(A<B[, ,]>.B<object> b)
{
M(b);
M((A<B[]>.B<object>)null);
}
static void M(dynamic d)
{
M(d);
M((dynamic[])d);
}
static void M(dynamic[] d)
{
M(d);
M((dynamic)d);
}
static void M<T>(A<int>.B<T> t) where T : B
{
M(t);
M((A<double>.B<int>)null);
}
static void M<T>(A<double>.B<T> t) where T : struct
{
M(t);
M((A<int>.B<B>)null);
}
}";
var options = TestOptions.UnsafeDebugDll;
var compilation0 = CreateCompilation(source, options: options, references: new[] { CSharpRef });
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var n = compilation0.GetMembers("C.M").Length;
Assert.Equal(14, n);
//static void M(A<B>.B<object> a)
//{
// M(a);
// M((A<B>.B<B>)null);
//}
var compilation1 = compilation0.WithSource(source);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMembers("C.M")[0], compilation1.GetMembers("C.M")[0])));
diff1.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000002
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x06000003
IL_000e: nop
IL_000f: ret
}");
//static void M(A<B>.B<B> a)
//{
// M(a);
// M((A<B>.B<object>)null);
//}
var compilation2 = compilation1.WithSource(source);
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMembers("C.M")[1], compilation2.GetMembers("C.M")[1])));
diff2.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000003
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x06000002
IL_000e: nop
IL_000f: ret
}");
//static void M(A<B> a)
//{
// M(a);
// M((A<B>?)a);
//}
var compilation3 = compilation2.WithSource(source);
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation2.GetMembers("C.M")[2], compilation3.GetMembers("C.M")[2])));
diff3.VerifyIL(
@"{
// Code size 21 (0x15)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000004
IL_0007: nop
IL_0008: ldarg.0
IL_0009: newobj 0x0A000016
IL_000e: call 0x06000005
IL_0013: nop
IL_0014: ret
}");
//static void M(Nullable<A<B>> a)
//{
// M(a);
// M(a.Value);
//}
var compilation4 = compilation3.WithSource(source);
var diff4 = compilation4.EmitDifference(
diff3.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation3.GetMembers("C.M")[3], compilation4.GetMembers("C.M")[3])));
diff4.VerifyIL(
@"{
// Code size 22 (0x16)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000005
IL_0007: nop
IL_0008: ldarga.s V_0
IL_000a: call 0x0A000017
IL_000f: call 0x06000004
IL_0014: nop
IL_0015: ret
}");
//unsafe static void M(int* p)
//{
// M(p);
// M((byte*)p);
//}
var compilation5 = compilation4.WithSource(source);
var diff5 = compilation5.EmitDifference(
diff4.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation4.GetMembers("C.M")[4], compilation5.GetMembers("C.M")[4])));
diff5.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000006
IL_0007: nop
IL_0008: ldarg.0
IL_0009: call 0x06000007
IL_000e: nop
IL_000f: ret
}");
//unsafe static void M(byte* p)
//{
// M(p);
// M((int*)p);
//}
var compilation6 = compilation5.WithSource(source);
var diff6 = compilation6.EmitDifference(
diff5.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation5.GetMembers("C.M")[5], compilation6.GetMembers("C.M")[5])));
diff6.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000007
IL_0007: nop
IL_0008: ldarg.0
IL_0009: call 0x06000006
IL_000e: nop
IL_000f: ret
}");
//static void M(B[][] b)
//{
// M(b);
// M((object[][])b);
//}
var compilation7 = compilation6.WithSource(source);
var diff7 = compilation7.EmitDifference(
diff6.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation6.GetMembers("C.M")[6], compilation7.GetMembers("C.M")[6])));
diff7.VerifyIL(
@"{
// Code size 18 (0x12)
.maxstack 1
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000008
IL_0007: nop
IL_0008: ldarg.0
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: call 0x06000009
IL_0010: nop
IL_0011: ret
}");
//static void M(object[][] b)
//{
// M(b);
// M((B[][])b);
//}
var compilation8 = compilation7.WithSource(source);
var diff8 = compilation8.EmitDifference(
diff7.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation7.GetMembers("C.M")[7], compilation8.GetMembers("C.M")[7])));
diff8.VerifyIL(
@"{
// Code size 21 (0x15)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000009
IL_0007: nop
IL_0008: ldarg.0
IL_0009: castclass 0x1B00000A
IL_000e: call 0x06000008
IL_0013: nop
IL_0014: ret
}");
//static void M(A<B[]>.B<object> b)
//{
// M(b);
// M((A<B[,,]>.B<object>)null);
//}
var compilation9 = compilation8.WithSource(source);
var diff9 = compilation9.EmitDifference(
diff8.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation8.GetMembers("C.M")[8], compilation9.GetMembers("C.M")[8])));
diff9.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x0600000A
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x0600000B
IL_000e: nop
IL_000f: ret
}");
//static void M(A<B[,,]>.B<object> b)
//{
// M(b);
// M((A<B[]>.B<object>)null);
//}
var compilation10 = compilation9.WithSource(source);
var diff10 = compilation10.EmitDifference(
diff9.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation9.GetMembers("C.M")[9], compilation10.GetMembers("C.M")[9])));
diff10.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x0600000B
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x0600000A
IL_000e: nop
IL_000f: ret
}");
// TODO: dynamic
#if false
//static void M(dynamic d)
//{
// M(d);
// M((dynamic[])d);
//}
previousMethod = compilation.GetMembers("C.M")[10];
compilation = compilation0.WithSource(source);
generation = compilation.EmitDifference(
generation,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, previousMethod, compilation.GetMembers("C.M")[10])),
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000002
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x06000003
IL_000e: nop
IL_000f: ret
}");
//static void M(dynamic[] d)
//{
// M(d);
// M((dynamic)d);
//}
previousMethod = compilation.GetMembers("C.M")[11];
compilation = compilation0.WithSource(source);
generation = compilation.EmitDifference(
generation,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, previousMethod, compilation.GetMembers("C.M")[11])),
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000002
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x06000003
IL_000e: nop
IL_000f: ret
}");
#endif
//static void M<T>(A<int>.B<T> t) where T : B
//{
// M(t);
// M((A<double>.B<int>)null);
//}
var compilation11 = compilation10.WithSource(source);
var diff11 = compilation11.EmitDifference(
diff10.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation10.GetMembers("C.M")[12], compilation11.GetMembers("C.M")[12])));
diff11.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x2B000005
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x2B000006
IL_000e: nop
IL_000f: ret
}");
//static void M<T>(A<double>.B<T> t) where T : struct
//{
// M(t);
// M((A<int>.B<B>)null);
//}
var compilation12 = compilation11.WithSource(source);
var diff12 = compilation12.EmitDifference(
diff11.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation11.GetMembers("C.M")[13], compilation12.GetMembers("C.M")[13])));
diff12.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x2B000007
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x2B000008
IL_000e: nop
IL_000f: ret
}");
}
/// <summary>
/// Types should be retained in deleted locals
/// for correct alignment of remaining locals.
/// </summary>
[Fact]
public void DeletedValueTypeLocal()
{
var source0 =
@"struct S1
{
internal S1(int a, int b) { A = a; B = b; }
internal int A;
internal int B;
}
struct S2
{
internal S2(int c) { C = c; }
internal int C;
}
class C
{
static void Main()
{
var x = new S1(1, 2);
var y = new S2(3);
System.Console.WriteLine(y.C);
}
}";
var source1 =
@"struct S1
{
internal S1(int a, int b) { A = a; B = b; }
internal int A;
internal int B;
}
struct S2
{
internal S2(int c) { C = c; }
internal int C;
}
class C
{
static void Main()
{
var y = new S2(3);
System.Console.WriteLine(y.C);
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe);
var compilation1 = compilation0.WithSource(source1);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.Main");
var method0 = compilation0.GetMember<MethodSymbol>("C.Main");
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider());
testData0.GetMethodData("C.Main").VerifyIL(
@"
{
// Code size 31 (0x1f)
.maxstack 3
.locals init (S1 V_0, //x
S2 V_1) //y
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldc.i4.1
IL_0004: ldc.i4.2
IL_0005: call ""S1..ctor(int, int)""
IL_000a: ldloca.s V_1
IL_000c: ldc.i4.3
IL_000d: call ""S2..ctor(int)""
IL_0012: ldloc.1
IL_0013: ldfld ""int S2.C""
IL_0018: call ""void System.Console.WriteLine(int)""
IL_001d: nop
IL_001e: ret
}");
var method1 = compilation1.GetMember<MethodSymbol>("C.Main");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.Main",
@"{
// Code size 22 (0x16)
.maxstack 2
.locals init ([unchanged] V_0,
S2 V_1) //y
IL_0000: nop
IL_0001: ldloca.s V_1
IL_0003: ldc.i4.3
IL_0004: call ""S2..ctor(int)""
IL_0009: ldloc.1
IL_000a: ldfld ""int S2.C""
IL_000f: call ""void System.Console.WriteLine(int)""
IL_0014: nop
IL_0015: ret
}");
}
/// <summary>
/// Instance and static constructors synthesized for
/// PrivateImplementationDetails should not be
/// generated for delta.
/// </summary>
[Fact]
public void PrivateImplementationDetails()
{
var source =
@"class C
{
static int[] F = new int[] { 1, 2, 3 };
int[] G = new int[] { 4, 5, 6 };
int M(int index)
{
return F[index] + G[index];
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using (var md0 = ModuleMetadata.CreateFromImage(bytes0))
{
var reader0 = md0.MetadataReader;
var typeNames = new[] { reader0 }.GetStrings(reader0.GetTypeDefNames());
Assert.NotNull(typeNames.FirstOrDefault(n => n.StartsWith("<PrivateImplementationDetails>", StringComparison.Ordinal)));
}
var methodData0 = testData0.GetMethodData("C.M");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M", @"
{
// Code size 22 (0x16)
.maxstack 3
.locals init ([int] V_0,
int V_1)
IL_0000: nop
IL_0001: ldsfld ""int[] C.F""
IL_0006: ldarg.1
IL_0007: ldelem.i4
IL_0008: ldarg.0
IL_0009: ldfld ""int[] C.G""
IL_000e: ldarg.1
IL_000f: ldelem.i4
IL_0010: add
IL_0011: stloc.1
IL_0012: br.s IL_0014
IL_0014: ldloc.1
IL_0015: ret
}");
}
[WorkItem(780989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780989")]
[WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")]
[Fact]
public void PrivateImplementationDetails_ArrayInitializer_FromMetadata()
{
var source0 =
@"class C
{
static void M()
{
int[] a = { 1, 2, 3 };
System.Console.WriteLine(a[0]);
}
}";
var source1 =
@"class C
{
static void M()
{
int[] a = { 1, 2, 3 };
System.Console.WriteLine(a[1]);
}
}";
var source2 =
@"class C
{
static void M()
{
int[] a = { 4, 5, 6, 7, 8, 9, 10 };
System.Console.WriteLine(a[1]);
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll.WithModuleName("MODULE"));
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M");
methodData0.VerifyIL(
@" {
// Code size 29 (0x1d)
.maxstack 3
.locals init (int[] V_0) //a
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D""
IL_000d: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_0012: stloc.0
IL_0013: ldloc.0
IL_0014: ldc.i4.0
IL_0015: ldelem.i4
IL_0016: call ""void System.Console.WriteLine(int)""
IL_001b: nop
IL_001c: ret
}
");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M",
@"{
// Code size 30 (0x1e)
.maxstack 4
.locals init (int[] V_0) //a
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.3
IL_0012: stelem.i4
IL_0013: stloc.0
IL_0014: ldloc.0
IL_0015: ldc.i4.1
IL_0016: ldelem.i4
IL_0017: call ""void System.Console.WriteLine(int)""
IL_001c: nop
IL_001d: ret
}");
var method2 = compilation2.GetMember<MethodSymbol>("C.M");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true)));
diff2.VerifyIL("C.M",
@"{
// Code size 48 (0x30)
.maxstack 4
.locals init ([unchanged] V_0,
int[] V_1) //a
IL_0000: nop
IL_0001: ldc.i4.7
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.4
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.5
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.6
IL_0012: stelem.i4
IL_0013: dup
IL_0014: ldc.i4.3
IL_0015: ldc.i4.7
IL_0016: stelem.i4
IL_0017: dup
IL_0018: ldc.i4.4
IL_0019: ldc.i4.8
IL_001a: stelem.i4
IL_001b: dup
IL_001c: ldc.i4.5
IL_001d: ldc.i4.s 9
IL_001f: stelem.i4
IL_0020: dup
IL_0021: ldc.i4.6
IL_0022: ldc.i4.s 10
IL_0024: stelem.i4
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: ldc.i4.1
IL_0028: ldelem.i4
IL_0029: call ""void System.Console.WriteLine(int)""
IL_002e: nop
IL_002f: ret
}");
}
[WorkItem(780989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780989")]
[WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")]
[Fact]
public void PrivateImplementationDetails_ArrayInitializer_FromSource()
{
// PrivateImplementationDetails not needed initially.
var source0 =
@"class C
{
static object F1() { return null; }
static object F2() { return null; }
static object F3() { return null; }
static object F4() { return null; }
}";
var source1 =
@"class C
{
static object F1() { return new[] { 1, 2, 3 }; }
static object F2() { return new[] { 4, 5, 6 }; }
static object F3() { return null; }
static object F4() { return new[] { 7, 8, 9 }; }
}";
var source2 =
@"class C
{
static object F1() { return new[] { 1, 2, 3 } ?? new[] { 10, 11, 12 }; }
static object F2() { return new[] { 4, 5, 6 }; }
static object F3() { return new[] { 13, 14, 15 }; }
static object F4() { return new[] { 7, 8, 9 }; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F1"), compilation1.GetMember<MethodSymbol>("C.F1")),
SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F2"), compilation1.GetMember<MethodSymbol>("C.F2")),
SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F4"), compilation1.GetMember<MethodSymbol>("C.F4"))));
diff1.VerifyIL("C.F1",
@"{
// Code size 24 (0x18)
.maxstack 4
.locals init (object V_0)
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.3
IL_0012: stelem.i4
IL_0013: stloc.0
IL_0014: br.s IL_0016
IL_0016: ldloc.0
IL_0017: ret
}");
diff1.VerifyIL("C.F4",
@"{
// Code size 25 (0x19)
.maxstack 4
.locals init (object V_0)
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.7
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.8
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.s 9
IL_0013: stelem.i4
IL_0014: stloc.0
IL_0015: br.s IL_0017
IL_0017: ldloc.0
IL_0018: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("C.F1"), compilation2.GetMember<MethodSymbol>("C.F1")),
SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("C.F3"), compilation2.GetMember<MethodSymbol>("C.F3"))));
diff2.VerifyIL("C.F1",
@"{
// Code size 49 (0x31)
.maxstack 4
.locals init (object V_0)
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.3
IL_0012: stelem.i4
IL_0013: dup
IL_0014: brtrue.s IL_002c
IL_0016: pop
IL_0017: ldc.i4.3
IL_0018: newarr ""int""
IL_001d: dup
IL_001e: ldc.i4.0
IL_001f: ldc.i4.s 10
IL_0021: stelem.i4
IL_0022: dup
IL_0023: ldc.i4.1
IL_0024: ldc.i4.s 11
IL_0026: stelem.i4
IL_0027: dup
IL_0028: ldc.i4.2
IL_0029: ldc.i4.s 12
IL_002b: stelem.i4
IL_002c: stloc.0
IL_002d: br.s IL_002f
IL_002f: ldloc.0
IL_0030: ret
}");
diff2.VerifyIL("C.F3",
@"{
// Code size 27 (0x1b)
.maxstack 4
.locals init (object V_0)
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.s 13
IL_000b: stelem.i4
IL_000c: dup
IL_000d: ldc.i4.1
IL_000e: ldc.i4.s 14
IL_0010: stelem.i4
IL_0011: dup
IL_0012: ldc.i4.2
IL_0013: ldc.i4.s 15
IL_0015: stelem.i4
IL_0016: stloc.0
IL_0017: br.s IL_0019
IL_0019: ldloc.0
IL_001a: ret
}");
}
/// <summary>
/// Should not generate method for string switch since
/// the CLR only allows adding private members.
/// </summary>
[WorkItem(834086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834086")]
[Fact]
public void PrivateImplementationDetails_ComputeStringHash()
{
var source =
@"class C
{
static int F(string s)
{
switch (s)
{
case ""1"": return 1;
case ""2"": return 2;
case ""3"": return 3;
case ""4"": return 4;
case ""5"": return 5;
case ""6"": return 6;
case ""7"": return 7;
default: return 0;
}
}
}";
const string ComputeStringHashName = "ComputeStringHash";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.F");
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider());
// Should have generated call to ComputeStringHash and
// added the method to <PrivateImplementationDetails>.
var actualIL0 = methodData0.GetMethodIL();
Assert.True(actualIL0.Contains(ComputeStringHashName));
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ComputeStringHashName);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
// Should not have generated call to ComputeStringHash nor
// added the method to <PrivateImplementationDetails>.
var actualIL1 = diff1.GetMethodIL("C.F");
Assert.False(actualIL1.Contains(ComputeStringHashName));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetMethodDefNames(), "F");
}
/// <summary>
/// Unique ids should not conflict with ids
/// from previous generation.
/// </summary>
[WorkItem(9847, "https://github.com/dotnet/roslyn/issues/9847")]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/9847")]
public void UniqueIds()
{
var source0 =
@"class C
{
int F()
{
System.Func<int> f = () => 3;
return f();
}
static int F(bool b)
{
System.Func<int> f = () => 1;
System.Func<int> g = () => 2;
return (b ? f : g)();
}
}";
var source1 =
@"class C
{
int F()
{
System.Func<int> f = () => 3;
return f();
}
static int F(bool b)
{
System.Func<int> f = () => 1;
return f();
}
}";
var source2 =
@"class C
{
int F()
{
System.Func<int> f = () => 3;
return f();
}
static int F(bool b)
{
System.Func<int> g = () => 2;
return g();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMembers("C.F")[1], compilation1.GetMembers("C.F")[1])));
diff1.VerifyIL("C.F",
@"{
// Code size 40 (0x28)
.maxstack 2
.locals init (System.Func<int> V_0, //f
int V_1)
IL_0000: nop
IL_0001: ldsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate6""
IL_0006: dup
IL_0007: brtrue.s IL_001c
IL_0009: pop
IL_000a: ldnull
IL_000b: ldftn ""int C.<F>b__5()""
IL_0011: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_0016: dup
IL_0017: stsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate6""
IL_001c: stloc.0
IL_001d: ldloc.0
IL_001e: callvirt ""int System.Func<int>.Invoke()""
IL_0023: stloc.1
IL_0024: br.s IL_0026
IL_0026: ldloc.1
IL_0027: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMembers("C.F")[1], compilation2.GetMembers("C.F")[1])));
diff2.VerifyIL("C.F",
@"{
// Code size 40 (0x28)
.maxstack 2
.locals init (System.Func<int> V_0, //g
int V_1)
IL_0000: nop
IL_0001: ldsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate8""
IL_0006: dup
IL_0007: brtrue.s IL_001c
IL_0009: pop
IL_000a: ldnull
IL_000b: ldftn ""int C.<F>b__7()""
IL_0011: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_0016: dup
IL_0017: stsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate8""
IL_001c: stloc.0
IL_001d: ldloc.0
IL_001e: callvirt ""int System.Func<int>.Invoke()""
IL_0023: stloc.1
IL_0024: br.s IL_0026
IL_0026: ldloc.1
IL_0027: ret
}");
}
/// <summary>
/// Avoid adding references from method bodies
/// other than the changed methods.
/// </summary>
[Fact]
public void ReferencesInIL()
{
var source0 =
@"class C
{
static void F() { System.Console.WriteLine(1); }
static void G() { System.Console.WriteLine(2); }
}";
var source1 =
@"class C
{
static void F() { System.Console.WriteLine(1); }
static void G() { System.Console.Write(2); }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "F", "G", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), ".ctor", ".ctor", ".ctor", "WriteLine", ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method0 = compilation0.GetMember<MethodSymbol>("C.G");
var method1 = compilation1.GetMember<MethodSymbol>("C.G");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(
SemanticEditKind.Update,
method0,
method1,
GetEquivalentNodesMap(method1, method0),
preserveLocalVariables: true)));
// "Write" should be included in string table, but "WriteLine" should not.
Assert.True(diff1.MetadataDelta.IsIncluded("Write"));
Assert.False(diff1.MetadataDelta.IsIncluded("WriteLine"));
}
/// <summary>
/// Local slots must be preserved based on signature.
/// </summary>
[Fact]
public void PreserveLocalSlots()
{
var source0 =
@"class A<T> { }
class B : A<B>
{
static B F()
{
return null;
}
static void M(object o)
{
object x = F();
A<B> y = F();
object z = F();
M(x);
M(y);
M(z);
}
static void N()
{
object a = F();
object b = F();
M(a);
M(b);
}
}";
var methodNames0 = new[] { "A<T>..ctor", "B.F", "B.M", "B.N" };
var source1 =
@"class A<T> { }
class B : A<B>
{
static B F()
{
return null;
}
static void M(object o)
{
B z = F();
A<B> y = F();
object w = F();
M(w);
M(y);
}
static void N()
{
object a = F();
object b = F();
M(a);
M(b);
}
}";
var source2 =
@"class A<T> { }
class B : A<B>
{
static B F()
{
return null;
}
static void M(object o)
{
object x = F();
B z = F();
M(x);
M(z);
}
static void N()
{
object a = F();
object b = F();
M(a);
M(b);
}
}";
var source3 =
@"class A<T> { }
class B : A<B>
{
static B F()
{
return null;
}
static void M(object o)
{
object x = F();
B z = F();
M(x);
M(z);
}
static void N()
{
object c = F();
object b = F();
M(c);
M(b);
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var method0 = compilation0.GetMember<MethodSymbol>("B.M");
var methodN = compilation0.GetMember<MethodSymbol>("B.N");
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var generation0 = EmitBaseline.CreateInitialBaseline(
ModuleMetadata.CreateFromImage(bytes0),
m => testData0.GetMethodData(methodNames0[MetadataTokens.GetRowNumber(m) - 1]).GetEncDebugInfo());
#region Gen1
var method1 = compilation1.GetMember<MethodSymbol>("B.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL(
@"{
// Code size 36 (0x24)
.maxstack 1
IL_0000: nop
IL_0001: call 0x06000002
IL_0006: stloc.3
IL_0007: call 0x06000002
IL_000c: stloc.1
IL_000d: call 0x06000002
IL_0012: stloc.s V_4
IL_0014: ldloc.s V_4
IL_0016: call 0x06000003
IL_001b: nop
IL_001c: ldloc.1
IL_001d: call 0x06000003
IL_0022: nop
IL_0023: ret
}");
diff1.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method token=""0x6000003"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</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=""0x7"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""22"" document=""1"" />
<entry offset=""0xd"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""24"" document=""1"" />
<entry offset=""0x14"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""14"" document=""1"" />
<entry offset=""0x1c"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""14"" document=""1"" />
<entry offset=""0x23"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x24"">
<local name=""z"" il_index=""3"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" />
<local name=""y"" il_index=""1"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" />
<local name=""w"" il_index=""4"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
#endregion
#region Gen2
var method2 = compilation2.GetMember<MethodSymbol>("B.M");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true)));
diff2.VerifyIL(
@"{
// Code size 30 (0x1e)
.maxstack 1
IL_0000: nop
IL_0001: call 0x06000002
IL_0006: stloc.s V_5
IL_0008: call 0x06000002
IL_000d: stloc.3
IL_000e: ldloc.s V_5
IL_0010: call 0x06000003
IL_0015: nop
IL_0016: ldloc.3
IL_0017: call 0x06000003
IL_001c: nop
IL_001d: ret
}");
diff2.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method token=""0x6000003"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</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=""24"" document=""1"" />
<entry offset=""0x8"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""19"" document=""1"" />
<entry offset=""0xe"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""14"" document=""1"" />
<entry offset=""0x16"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""14"" document=""1"" />
<entry offset=""0x1d"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1e"">
<local name=""x"" il_index=""5"" il_start=""0x0"" il_end=""0x1e"" attributes=""0"" />
<local name=""z"" il_index=""3"" il_start=""0x0"" il_end=""0x1e"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
#endregion
#region Gen3
// Modify different method. (Previous generations
// have not referenced method.)
method2 = compilation2.GetMember<MethodSymbol>("B.N");
var method3 = compilation3.GetMember<MethodSymbol>("B.N");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables: true)));
diff3.VerifyIL(
@"{
// Code size 28 (0x1c)
.maxstack 1
IL_0000: nop
IL_0001: call 0x06000002
IL_0006: stloc.2
IL_0007: call 0x06000002
IL_000c: stloc.1
IL_000d: ldloc.2
IL_000e: call 0x06000003
IL_0013: nop
IL_0014: ldloc.1
IL_0015: call 0x06000003
IL_001a: nop
IL_001b: ret
}");
diff3.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method token=""0x6000004"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</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=""24"" document=""1"" />
<entry offset=""0x7"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""24"" document=""1"" />
<entry offset=""0xd"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""14"" document=""1"" />
<entry offset=""0x14"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""14"" document=""1"" />
<entry offset=""0x1b"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1c"">
<local name=""c"" il_index=""2"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" />
<local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
#endregion
}
/// <summary>
/// Preserve locals for method added after initial compilation.
/// </summary>
[Fact]
public void PreserveLocalSlots_NewMethod()
{
var source0 =
@"class C
{
}";
var source1 =
@"class C
{
static void M()
{
var a = new object();
var b = string.Empty;
}
}";
var source2 =
@"class C
{
static void M()
{
var a = 1;
var b = string.Empty;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var m1 = compilation1.GetMember<MethodSymbol>("C.M");
var m2 = compilation2.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, m1, null, preserveLocalVariables: true)));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetEquivalentNodesMap(m2, m1), preserveLocalVariables: true)));
diff2.VerifyIL("C.M",
@"{
// Code size 10 (0xa)
.maxstack 1
.locals init ([object] V_0,
string V_1, //b
int V_2) //a
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.2
IL_0003: ldsfld ""string string.Empty""
IL_0008: stloc.1
IL_0009: ret
}");
diff2.VerifyPdb(new[] { 0x06000002 }, @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method token=""0x6000002"">
<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=""19"" document=""1"" />
<entry offset=""0x3"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""30"" document=""1"" />
<entry offset=""0x9"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xa"">
<local name=""a"" il_index=""2"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" />
<local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
/// <summary>
/// Local types should be retained, even if the local is no longer
/// used by the method body, since there may be existing
/// references to that slot, in a Watch window for instance.
/// </summary>
[WorkItem(843320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843320")]
[Fact]
public void PreserveLocalTypes()
{
var source0 =
@"class C
{
static void Main()
{
var x = true;
var y = x;
System.Console.WriteLine(y);
}
}";
var source1 =
@"class C
{
static void Main()
{
var x = ""A"";
var y = x;
System.Console.WriteLine(y);
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var method0 = compilation0.GetMember<MethodSymbol>("C.Main");
var method1 = compilation1.GetMember<MethodSymbol>("C.Main");
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.Main").EncDebugInfoProvider());
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.Main", @"
{
// Code size 17 (0x11)
.maxstack 1
.locals init ([bool] V_0,
[bool] V_1,
string V_2, //x
string V_3) //y
IL_0000: nop
IL_0001: ldstr ""A""
IL_0006: stloc.2
IL_0007: ldloc.2
IL_0008: stloc.3
IL_0009: ldloc.3
IL_000a: call ""void System.Console.WriteLine(string)""
IL_000f: nop
IL_0010: ret
}");
}
/// <summary>
/// Preserve locals if SemanticEdit.PreserveLocalVariables is set.
/// </summary>
[Fact]
public void PreserveLocalVariablesFlag()
{
var source =
@"class C
{
static System.IDisposable F() { return null; }
static void M()
{
using (F()) { }
using (var x = F()) { }
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(
ModuleMetadata.CreateFromImage(bytes0),
testData0.GetMethodData("C.M").EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1a = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: false)));
diff1a.VerifyIL("C.M", @"
{
// Code size 44 (0x2c)
.maxstack 1
.locals init (System.IDisposable V_0,
System.IDisposable V_1) //x
IL_0000: nop
IL_0001: call ""System.IDisposable C.F()""
IL_0006: stloc.0
.try
{
IL_0007: nop
IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.0
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
IL_0015: endfinally
}
IL_0016: call ""System.IDisposable C.F()""
IL_001b: stloc.1
.try
{
IL_001c: nop
IL_001d: nop
IL_001e: leave.s IL_002b
}
finally
{
IL_0020: ldloc.1
IL_0021: brfalse.s IL_002a
IL_0023: ldloc.1
IL_0024: callvirt ""void System.IDisposable.Dispose()""
IL_0029: nop
IL_002a: endfinally
}
IL_002b: ret
}
");
var diff1b = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: true)));
diff1b.VerifyIL("C.M",
@"{
// Code size 44 (0x2c)
.maxstack 1
.locals init (System.IDisposable V_0,
System.IDisposable V_1) //x
IL_0000: nop
IL_0001: call ""System.IDisposable C.F()""
IL_0006: stloc.0
.try
{
IL_0007: nop
IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.0
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
IL_0015: endfinally
}
IL_0016: call ""System.IDisposable C.F()""
IL_001b: stloc.1
.try
{
IL_001c: nop
IL_001d: nop
IL_001e: leave.s IL_002b
}
finally
{
IL_0020: ldloc.1
IL_0021: brfalse.s IL_002a
IL_0023: ldloc.1
IL_0024: callvirt ""void System.IDisposable.Dispose()""
IL_0029: nop
IL_002a: endfinally
}
IL_002b: ret
}");
}
[WorkItem(779531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/779531")]
[Fact]
public void ChangeLocalType()
{
var source0 =
@"enum E { }
class C
{
static void M1()
{
var x = default(E);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
static void M2()
{
var x = default(E);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
}";
// Change locals in one method to type added.
var source1 =
@"enum E { }
class A { }
class C
{
static void M1()
{
var x = default(A);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
static void M2()
{
var x = default(E);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
}";
// Change locals in another method.
var source2 =
@"enum E { }
class A { }
class C
{
static void M1()
{
var x = default(A);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
static void M2()
{
var x = default(A);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
}";
// Change locals in same method.
var source3 =
@"enum E { }
class A { }
class C
{
static void M1()
{
var x = default(A);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
static void M2()
{
var x = default(A);
var y = x;
var z = default(A);
System.Console.WriteLine(y);
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M1");
var method0 = compilation0.GetMember<MethodSymbol>("C.M1");
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M1");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A")),
SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M1",
@"{
// Code size 17 (0x11)
.maxstack 1
.locals init ([unchanged] V_0,
[unchanged] V_1,
E V_2, //z
A V_3, //x
A V_4) //y
IL_0000: nop
IL_0001: ldnull
IL_0002: stloc.3
IL_0003: ldloc.3
IL_0004: stloc.s V_4
IL_0006: ldc.i4.0
IL_0007: stloc.2
IL_0008: ldloc.s V_4
IL_000a: call ""void System.Console.WriteLine(object)""
IL_000f: nop
IL_0010: ret
}");
var method2 = compilation2.GetMember<MethodSymbol>("C.M2");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true)));
diff2.VerifyIL("C.M2",
@"{
// Code size 17 (0x11)
.maxstack 1
.locals init ([unchanged] V_0,
[unchanged] V_1,
E V_2, //z
A V_3, //x
A V_4) //y
IL_0000: nop
IL_0001: ldnull
IL_0002: stloc.3
IL_0003: ldloc.3
IL_0004: stloc.s V_4
IL_0006: ldc.i4.0
IL_0007: stloc.2
IL_0008: ldloc.s V_4
IL_000a: call ""void System.Console.WriteLine(object)""
IL_000f: nop
IL_0010: ret
}");
var method3 = compilation3.GetMember<MethodSymbol>("C.M2");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables: true)));
diff3.VerifyIL("C.M2",
@"{
// Code size 18 (0x12)
.maxstack 1
.locals init ([unchanged] V_0,
[unchanged] V_1,
[unchanged] V_2,
A V_3, //x
A V_4, //y
A V_5) //z
IL_0000: nop
IL_0001: ldnull
IL_0002: stloc.3
IL_0003: ldloc.3
IL_0004: stloc.s V_4
IL_0006: ldnull
IL_0007: stloc.s V_5
IL_0009: ldloc.s V_4
IL_000b: call ""void System.Console.WriteLine(object)""
IL_0010: nop
IL_0011: ret
}");
}
[Fact]
public void AnonymousTypes_Update()
{
var source0 = MarkedSource(@"
class C
{
static void F()
{
var <N:0>x = new { A = 1 }</N:0>;
}
}
");
var source1 = MarkedSource(@"
class C
{
static void F()
{
var <N:0>x = new { A = 2 }</N:0>;
}
}
");
var source2 = MarkedSource(@"
class C
{
static void F()
{
var <N:0>x = new { A = 3 }</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);
v0.VerifyIL("C.F", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (<>f__AnonymousType0<int> V_0) //x
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0007: stloc.0
IL_0008: ret
}
");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.F", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (<>f__AnonymousType0<int> V_0) //x
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0007: stloc.0
IL_0008: ret
}
");
// expect a single TypeRef for System.Object
var md1 = diff1.GetMetadata();
AssertEx.Equal(new[] { "[0x23000002] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader }));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (<>f__AnonymousType0<int> V_0) //x
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0007: stloc.0
IL_0008: ret
}
");
// expect a single TypeRef for System.Object
var md2 = diff2.GetMetadata();
AssertEx.Equal(new[] { "[0x23000003] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader, md2.Reader }));
}
[Fact]
public void AnonymousTypes_UpdateAfterAdd()
{
var source0 = MarkedSource(@"
class C
{
static void F()
{
}
}
");
var source1 = MarkedSource(@"
class C
{
static void F()
{
var <N:0>x = new { A = 2 }</N:0>;
}
}
");
var source2 = MarkedSource(@"
class C
{
static void F()
{
var <N:0>x = new { A = 3 }</N:0>;
}
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), targetFramework: TargetFramework.NetStandard20);
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();
diff1.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.F", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (<>f__AnonymousType0<int> V_0) //x
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0007: stloc.0
IL_0008: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (<>f__AnonymousType0<int> V_0) //x
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0007: stloc.0
IL_0008: ret
}
");
// expect a single TypeRef for System.Object
var md2 = diff2.GetMetadata();
AssertEx.Equal(new[] { "[0x23000003] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader, md2.Reader }));
}
/// <summary>
/// Reuse existing anonymous types.
/// </summary>
[WorkItem(825903, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825903")]
[Fact]
public void AnonymousTypes()
{
var source0 =
@"namespace N
{
class A
{
static object F = new { A = 1, B = 2 };
}
}
namespace M
{
class B
{
static void M()
{
var x = new { B = 3, A = 4 };
var y = x.A;
var z = new { };
}
}
}";
var source1 =
@"namespace N
{
class A
{
static object F = new { A = 1, B = 2 };
}
}
namespace M
{
class B
{
static void M()
{
var x = new { B = 3, A = 4 };
var y = new { A = x.A };
var z = new { };
}
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var m0 = compilation0.GetMember<MethodSymbol>("M.B.M");
var m1 = compilation1.GetMember<MethodSymbol>("M.B.M");
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, testData0.GetMethodData("M.B.M").EncDebugInfoProvider());
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`2", "<>f__AnonymousType1`2", "<>f__AnonymousType2", "B", "A");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetEquivalentNodesMap(m1, m0), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType3`1"); // one additional type
diff1.VerifyIL("M.B.M", @"
{
// Code size 28 (0x1c)
.maxstack 2
.locals init (<>f__AnonymousType1<int, int> V_0, //x
[int] V_1,
<>f__AnonymousType2 V_2, //z
<>f__AnonymousType3<int> V_3) //y
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: ldc.i4.4
IL_0003: newobj ""<>f__AnonymousType1<int, int>..ctor(int, int)""
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: callvirt ""int <>f__AnonymousType1<int, int>.A.get""
IL_000f: newobj ""<>f__AnonymousType3<int>..ctor(int)""
IL_0014: stloc.3
IL_0015: newobj ""<>f__AnonymousType2..ctor()""
IL_001a: stloc.2
IL_001b: ret
}");
}
/// <summary>
/// Anonymous type names with module ids
/// and gaps in indices.
/// </summary>
[ConditionalFact(typeof(WindowsOnly), Reason = "ILASM doesn't support Portable PDBs")]
[WorkItem(2982, "https://github.com/dotnet/coreclr/issues/2982")]
public void AnonymousTypes_OtherTypeNames()
{
var ilSource =
@".assembly extern netstandard { .ver 2:0:0:0 .publickeytoken = (cc 7b 13 ff cd 2d dd 51) }
// Valid signature, although not sequential index
.class '<>f__AnonymousType2'<'<A>j__TPar', '<B>j__TPar'> extends object
{
.field public !'<A>j__TPar' A
.field public !'<B>j__TPar' B
}
// Invalid signature, unexpected type parameter names
.class '<>f__AnonymousType1'<A, B> extends object
{
.field public !A A
.field public !B B
}
// Module id, duplicate index
.class '<m>f__AnonymousType2`1'<'<A>j__TPar'> extends object
{
.field public !'<A>j__TPar' A
}
// Module id
.class '<m>f__AnonymousType3`1'<'<B>j__TPar'> extends object
{
.field public !'<B>j__TPar' B
}
.class public C extends object
{
.method public specialname rtspecialname instance void .ctor()
{
ret
}
.method public static object F()
{
ldnull
ret
}
}";
var source0 =
@"class C
{
static object F()
{
return 0;
}
}";
var source1 =
@"class C
{
static object F()
{
var x = new { A = new object(), B = 1 };
var y = new { A = x.A };
return y;
}
}";
var metadata0 = (MetadataImageReference)CompileIL(ilSource, prependDefaultHeader: false);
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var moduleMetadata0 = ((AssemblyMetadata)metadata0.GetMetadataNoCopy()).GetModules()[0];
var generation0 = EmitBaseline.CreateInitialBaseline(moduleMetadata0, m => default);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
diff1.VerifyIL("C.F",
@"{
// Code size 31 (0x1f)
.maxstack 2
.locals init (<>f__AnonymousType2<object, int> V_0, //x
<>f__AnonymousType3<object> V_1, //y
object V_2)
IL_0000: nop
IL_0001: newobj ""object..ctor()""
IL_0006: ldc.i4.1
IL_0007: newobj ""<>f__AnonymousType2<object, int>..ctor(object, int)""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: callvirt ""object <>f__AnonymousType2<object, int>.A.get""
IL_0013: newobj ""<>f__AnonymousType3<object>..ctor(object)""
IL_0018: stloc.1
IL_0019: ldloc.1
IL_001a: stloc.2
IL_001b: br.s IL_001d
IL_001d: ldloc.2
IL_001e: ret
}");
}
/// <summary>
/// Update method with anonymous type that was
/// not directly referenced in previous generation.
/// </summary>
[Fact]
public void AnonymousTypes_SkipGeneration()
{
var source0 = MarkedSource(
@"class A { }
class B
{
static object F()
{
var <N:0>x = new { A = 1 }</N:0>;
return x.A;
}
static object G()
{
var <N:1>x = 1</N:1>;
return x;
}
}");
var source1 = MarkedSource(
@"class A { }
class B
{
static object F()
{
var <N:0>x = new { A = 1 }</N:0>;
return x.A;
}
static object G()
{
var <N:1>x = 1</N:1>;
return x + 1;
}
}");
var source2 = MarkedSource(
@"class A { }
class B
{
static object F()
{
var <N:0>x = new { A = 1 }</N:0>;
return x.A;
}
static object G()
{
var <N:1>x = new { A = new A() }</N:1>;
var <N:2>y = new { B = 2 }</N:2>;
return x.A;
}
}");
var source3 = MarkedSource(
@"class A { }
class B
{
static object F()
{
var <N:0>x = new { A = 1 }</N:0>;
return x.A;
}
static object G()
{
var <N:1>x = new { A = new A() }</N:1>;
var <N:2>y = new { B = 3 }</N:2>;
return y.B;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
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 generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var method0 = compilation0.GetMember<MethodSymbol>("B.G");
var method1 = compilation1.GetMember<MethodSymbol>("B.G");
var method2 = compilation2.GetMember<MethodSymbol>("B.G");
var method3 = compilation3.GetMember<MethodSymbol>("B.G");
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`1", "A", "B");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames()); // no additional types
diff1.VerifyIL("B.G", @"
{
// Code size 16 (0x10)
.maxstack 2
.locals init (int V_0, //x
[object] V_1,
object V_2)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldc.i4.1
IL_0005: add
IL_0006: box ""int""
IL_000b: stloc.2
IL_000c: br.s IL_000e
IL_000e: ldloc.2
IL_000f: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>f__AnonymousType1`1"); // one additional type
diff2.VerifyIL("B.G", @"
{
// Code size 33 (0x21)
.maxstack 1
.locals init ([int] V_0,
[object] V_1,
[object] V_2,
<>f__AnonymousType0<A> V_3, //x
<>f__AnonymousType1<int> V_4, //y
object V_5)
IL_0000: nop
IL_0001: newobj ""A..ctor()""
IL_0006: newobj ""<>f__AnonymousType0<A>..ctor(A)""
IL_000b: stloc.3
IL_000c: ldc.i4.2
IL_000d: newobj ""<>f__AnonymousType1<int>..ctor(int)""
IL_0012: stloc.s V_4
IL_0014: ldloc.3
IL_0015: callvirt ""A <>f__AnonymousType0<A>.A.get""
IL_001a: stloc.s V_5
IL_001c: br.s IL_001e
IL_001e: ldloc.s V_5
IL_0020: ret
}");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables: true)));
var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
CheckNames(new[] { reader0, reader1, reader2, reader3 }, reader3.GetTypeDefNames()); // no additional types
diff3.VerifyIL("B.G", @"
{
// Code size 39 (0x27)
.maxstack 1
.locals init ([int] V_0,
[object] V_1,
[object] V_2,
<>f__AnonymousType0<A> V_3, //x
<>f__AnonymousType1<int> V_4, //y
[object] V_5,
object V_6)
IL_0000: nop
IL_0001: newobj ""A..ctor()""
IL_0006: newobj ""<>f__AnonymousType0<A>..ctor(A)""
IL_000b: stloc.3
IL_000c: ldc.i4.3
IL_000d: newobj ""<>f__AnonymousType1<int>..ctor(int)""
IL_0012: stloc.s V_4
IL_0014: ldloc.s V_4
IL_0016: callvirt ""int <>f__AnonymousType1<int>.B.get""
IL_001b: box ""int""
IL_0020: stloc.s V_6
IL_0022: br.s IL_0024
IL_0024: ldloc.s V_6
IL_0026: ret
}");
}
/// <summary>
/// Update another method (without directly referencing
/// anonymous type) after updating method with anonymous type.
/// </summary>
[Fact]
public void AnonymousTypes_SkipGeneration_2()
{
var source0 =
@"class C
{
static object F()
{
var x = new { A = 1 };
return x.A;
}
static object G()
{
var x = 1;
return x;
}
}";
var source1 =
@"class C
{
static object F()
{
var x = new { A = 2, B = 3 };
return x.A;
}
static object G()
{
var x = 1;
return x;
}
}";
var source2 =
@"class C
{
static object F()
{
var x = new { A = 2, B = 3 };
return x.A;
}
static object G()
{
var x = 1;
return x + 1;
}
}";
var source3 =
@"class C
{
static object F()
{
var x = new { A = 2, B = 3 };
return x.A;
}
static object G()
{
var x = new { A = (object)null };
var y = new { A = 'a', B = 'b' };
return x;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var g1 = compilation1.GetMember<MethodSymbol>("C.G");
var g2 = compilation2.GetMember<MethodSymbol>("C.G");
var g3 = compilation3.GetMember<MethodSymbol>("C.G");
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
m => md0.MetadataReader.GetString(md0.MetadataReader.GetMethodDefinition(m).Name) switch
{
"F" => testData0.GetMethodData("C.F").GetEncDebugInfo(),
"G" => testData0.GetMethodData("C.G").GetEncDebugInfo(),
_ => default,
});
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`1", "C");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames(), "<>f__AnonymousType1`2"); // one additional type
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g1, g2, GetEquivalentNodesMap(g2, g1), preserveLocalVariables: true)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
CheckNames(readers, reader2.GetTypeDefNames()); // no additional types
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g2, g3, GetEquivalentNodesMap(g3, g2), preserveLocalVariables: true)));
using var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
readers.Add(reader3);
CheckNames(readers, reader3.GetTypeDefNames()); // no additional types
}
/// <summary>
/// Local from previous generation is of an anonymous
/// type not available in next generation.
/// </summary>
[Fact]
public void AnonymousTypes_AddThenDelete()
{
var source0 =
@"class C
{
object A;
static object F()
{
var x = new C();
var y = x.A;
return y;
}
}";
var source1 =
@"class C
{
static object F()
{
var x = new { A = new object() };
var y = x.A;
return y;
}
}";
var source2 =
@"class C
{
static object F()
{
var x = new { A = new object(), B = 2 };
var y = x.A;
y = new { B = new object() }.B;
return y;
}
}";
var source3 =
@"class C
{
static object F()
{
var x = new { A = new object(), B = 3 };
var y = x.A;
return y;
}
}";
var source4 =
@"class C
{
static object F()
{
var x = new { B = 4, A = new object() };
var y = x.A;
return y;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var compilation4 = compilation3.WithSource(source4);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, testData0.GetMethodData("C.F").EncDebugInfoProvider());
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType0`1"); // one additional type
diff1.VerifyIL("C.F", @"
{
// Code size 27 (0x1b)
.maxstack 1
.locals init ([unchanged] V_0,
object V_1, //y
[object] V_2,
<>f__AnonymousType0<object> V_3, //x
object V_4)
IL_0000: nop
IL_0001: newobj ""object..ctor()""
IL_0006: newobj ""<>f__AnonymousType0<object>..ctor(object)""
IL_000b: stloc.3
IL_000c: ldloc.3
IL_000d: callvirt ""object <>f__AnonymousType0<object>.A.get""
IL_0012: stloc.1
IL_0013: ldloc.1
IL_0014: stloc.s V_4
IL_0016: br.s IL_0018
IL_0018: ldloc.s V_4
IL_001a: ret
}");
var method2 = compilation2.GetMember<MethodSymbol>("C.F");
}
[Fact]
public void AnonymousTypes_DifferentCase()
{
var source0 = MarkedSource(@"
class C
{
static void M()
{
var <N:0>x = new { A = 1, B = 2 }</N:0>;
var <N:1>y = new { a = 3, b = 4 }</N:1>;
}
}");
var source1 = MarkedSource(@"
class C
{
static void M()
{
var <N:0>x = new { a = 1, B = 2 }</N:0>;
var <N:1>y = new { AB = 3 }</N:1>;
}
}");
var source2 = MarkedSource(@"
class C
{
static void M()
{
var <N:0>x = new { a = 1, B = 2 }</N:0>;
var <N:1>y = new { Ab = 5 }</N:1>;
}
}");
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 reader0 = md0.MetadataReader;
var m0 = compilation0.GetMember<MethodSymbol>("C.M");
var m1 = compilation1.GetMember<MethodSymbol>("C.M");
var m2 = compilation2.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`2", "<>f__AnonymousType1`2", "C");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var reader1 = diff1.GetMetadata().Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType2`2", "<>f__AnonymousType3`1");
// the first two slots can't be reused since the type changed
diff1.VerifyIL("C.M",
@"{
// Code size 17 (0x11)
.maxstack 2
.locals init ([unchanged] V_0,
[unchanged] V_1,
<>f__AnonymousType2<int, int> V_2, //x
<>f__AnonymousType3<int> V_3) //y
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: ldc.i4.2
IL_0003: newobj ""<>f__AnonymousType2<int, int>..ctor(int, int)""
IL_0008: stloc.2
IL_0009: ldc.i4.3
IL_000a: newobj ""<>f__AnonymousType3<int>..ctor(int)""
IL_000f: stloc.3
IL_0010: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
var reader2 = diff2.GetMetadata().Reader;
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>f__AnonymousType4`1");
// we can reuse slot for "x", it's type haven't changed
diff2.VerifyIL("C.M",
@"{
// Code size 18 (0x12)
.maxstack 2
.locals init ([unchanged] V_0,
[unchanged] V_1,
<>f__AnonymousType2<int, int> V_2, //x
[unchanged] V_3,
<>f__AnonymousType4<int> V_4) //y
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: ldc.i4.2
IL_0003: newobj ""<>f__AnonymousType2<int, int>..ctor(int, int)""
IL_0008: stloc.2
IL_0009: ldc.i4.5
IL_000a: newobj ""<>f__AnonymousType4<int>..ctor(int)""
IL_000f: stloc.s V_4
IL_0011: ret
}");
}
[Fact]
public void AnonymousTypes_Nested1()
{
var template = @"
using System;
using System.Linq;
class C
{
static void F(string[] args)
{
var <N:0>result =
from a in args
<N:1>let x = a.Reverse()</N:1>
<N:2>let y = x.Reverse()</N:2>
<N:3>where x.SequenceEqual(y)</N:3>
<N:4>select new { Value = a, Length = a.Length }</N:4></N:0>;
Console.WriteLine(<<VALUE>>);
}
}";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation0.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 expectedIL = @"
{
// Code size 155 (0x9b)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0""
IL_0007: dup
IL_0008: brtrue.s IL_0021
IL_000a: pop
IL_000b: ldsfld ""C.<>c C.<>c.<>9""
IL_0010: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> C.<>c.<F>b__0_0(string)""
IL_0016: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)""
IL_001b: dup
IL_001c: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0""
IL_0021: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)""
IL_0026: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> 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 ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> C.<>c.<F>b__0_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)""
IL_003a: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)""
IL_003f: dup
IL_0040: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1""
IL_0045: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)""
IL_004a: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2""
IL_004f: dup
IL_0050: brtrue.s IL_0069
IL_0052: pop
IL_0053: ldsfld ""C.<>c C.<>c.<>9""
IL_0058: ldftn ""bool C.<>c.<F>b__0_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_005e: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)""
IL_0063: dup
IL_0064: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2""
IL_0069: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)""
IL_006e: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3""
IL_0073: dup
IL_0074: brtrue.s IL_008d
IL_0076: pop
IL_0077: ldsfld ""C.<>c C.<>c.<>9""
IL_007c: ldftn ""<anonymous type: string Value, int Length> C.<>c.<F>b__0_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_0082: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)""
IL_0087: dup
IL_0088: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3""
IL_008d: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)""
IL_0092: stloc.0
IL_0093: ldc.i4.<<VALUE>>
IL_0094: call ""void System.Console.WriteLine(int)""
IL_0099: nop
IL_009a: 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}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}",
"<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <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}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}",
"<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2"));
}
[Fact]
public void AnonymousTypes_Nested2()
{
var template = @"
using System;
using System.Linq;
class C
{
static void F(string[] args)
{
var <N:0>result =
from a in args
<N:1>let x = a.Reverse()</N:1>
<N:2>let y = x.Reverse()</N:2>
<N:3>where x.SequenceEqual(y)</N:3>
<N:4>select new { Value = a, Length = a.Length }</N:4></N:0>;
Console.WriteLine(<<VALUE>>);
}
}";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation0.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 expectedIL = @"
{
// Code size 155 (0x9b)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0""
IL_0007: dup
IL_0008: brtrue.s IL_0021
IL_000a: pop
IL_000b: ldsfld ""C.<>c C.<>c.<>9""
IL_0010: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> C.<>c.<F>b__0_0(string)""
IL_0016: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)""
IL_001b: dup
IL_001c: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0""
IL_0021: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)""
IL_0026: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> 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 ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> C.<>c.<F>b__0_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)""
IL_003a: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)""
IL_003f: dup
IL_0040: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1""
IL_0045: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)""
IL_004a: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2""
IL_004f: dup
IL_0050: brtrue.s IL_0069
IL_0052: pop
IL_0053: ldsfld ""C.<>c C.<>c.<>9""
IL_0058: ldftn ""bool C.<>c.<F>b__0_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_005e: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)""
IL_0063: dup
IL_0064: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2""
IL_0069: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)""
IL_006e: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3""
IL_0073: dup
IL_0074: brtrue.s IL_008d
IL_0076: pop
IL_0077: ldsfld ""C.<>c C.<>c.<>9""
IL_007c: ldftn ""<anonymous type: string Value, int Length> C.<>c.<F>b__0_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_0082: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)""
IL_0087: dup
IL_0088: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3""
IL_008d: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)""
IL_0092: stloc.0
IL_0093: ldc.i4.<<VALUE>>
IL_0094: call ""void System.Console.WriteLine(int)""
IL_0099: nop
IL_009a: 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}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}",
"<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <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}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}",
"<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2"));
}
[Fact]
public void AnonymousTypes_Query1()
{
var source0 = MarkedSource(@"
using System.Linq;
class C
{
static void F(string[] args)
{
args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" };
var <N:4>result =
from a in args
<N:0>let x = a.Reverse()</N:0>
<N:1>let y = x.Reverse()</N:1>
<N:2>where x.SequenceEqual(y)</N:2>
<N:3>select new { Value = a, Length = a.Length }</N:3></N:4>;
var <N:8>newArgs =
from a in result
<N:5>let value = a.Value</N:5>
<N:6>let length = a.Length</N:6>
<N:7>where value.Length == length</N:7>
select value</N:8>;
args = args.Concat(newArgs).ToArray();
System.Diagnostics.Debugger.Break();
result.ToString();
}
}
");
var source1 = MarkedSource(@"
using System.Linq;
class C
{
static void F(string[] args)
{
args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" };
var list = false ? null : new { Head = (dynamic)null, Tail = (dynamic)null };
for (int i = 0; i < 10; i++)
{
var <N:4>result =
from a in args
<N:0>let x = a.Reverse()</N:0>
<N:1>let y = x.Reverse()</N:1>
<N:2>where x.SequenceEqual(y)</N:2>
orderby a.Length ascending, a descending
<N:3>select new { Value = a, Length = x.Count() }</N:3></N:4>;
var linked = result.Aggregate(
false ? new { Head = (string)null, Tail = (dynamic)null } : null,
(total, curr) => new { Head = curr.Value, Tail = (dynamic)total });
var str = linked?.Tail?.Head;
var <N:8>newArgs =
from a in result
<N:5>let value = a.Value</N:5>
<N:6>let length = a.Length</N:6>
<N:7>where value.Length == length</N:7>
select value + value</N:8>;
args = args.Concat(newArgs).ToArray();
list = new { Head = (dynamic)i, Tail = (dynamic)list };
System.Diagnostics.Debugger.Break();
}
System.Diagnostics.Debugger.Break();
}
}
");
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
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);
v0.VerifyLocalSignature("C.F", @"
.locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0, //result
System.Collections.Generic.IEnumerable<string> V_1) //newArgs
");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C.<>o__0#1: {<>p__0}",
"C: {<>o__0#1, <>c}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3#1, <>9__0_4#1, <>9__0_3, <>9__0_6#1, <>9__0_4, <>9__0_5, <>9__0_6, <>9__0_10#1, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3#1, <F>b__0_4#1, <F>b__0_3, <F>b__0_6#1, <F>b__0_4, <F>b__0_5, <F>b__0_6, <F>b__0_10#1}",
"<>f__AnonymousType4<<<>h__TransparentIdentifier0>j__TPar, <length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType5<<Head>j__TPar, <Tail>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType3<<a>j__TPar, <value>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyLocalSignature("C.F", @"
.locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0, //result
System.Collections.Generic.IEnumerable<string> V_1, //newArgs
<>f__AnonymousType5<dynamic, dynamic> V_2, //list
int V_3, //i
<>f__AnonymousType5<string, dynamic> V_4, //linked
object V_5, //str
<>f__AnonymousType5<string, dynamic> V_6,
object V_7,
bool V_8)
");
}
[Fact]
public void AnonymousTypes_Dynamic1()
{
var template = @"
using System;
class C
{
public void F()
{
var <N:0>x = new { A = (dynamic)null, B = 1 }</N:0>;
Console.WriteLine(x.B + <<VALUE>>);
}
}
";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
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 baselineIL0 = @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (<>f__AnonymousType0<dynamic, int> V_0) //x
IL_0000: nop
IL_0001: ldnull
IL_0002: ldc.i4.1
IL_0003: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)""
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get""
IL_000f: call ""void System.Console.WriteLine(int)""
IL_0014: nop
IL_0015: ret
}
";
v0.VerifyIL("C.F", baselineIL0);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}");
var baselineIL = @"
{
// Code size 24 (0x18)
.maxstack 2
.locals init (<>f__AnonymousType0<dynamic, int> V_0) //x
IL_0000: nop
IL_0001: ldnull
IL_0002: ldc.i4.1
IL_0003: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)""
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get""
IL_000f: ldc.i4.<<VALUE>>
IL_0010: add
IL_0011: call ""void System.Console.WriteLine(int)""
IL_0016: nop
IL_0017: ret
}
";
diff1.VerifyIL("C.F", baselineIL.Replace("<<VALUE>>", "1"));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", baselineIL.Replace("<<VALUE>>", "2"));
}
/// <summary>
/// Should not re-use locals if the method metadata
/// signature is unsupported.
/// </summary>
[WorkItem(9849, "https://github.com/dotnet/roslyn/issues/9849")]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/9849")]
public void LocalType_UnsupportedSignatureContent()
{
// Equivalent to C#, but with extra local and required modifier on
// expected local. Used to generate initial (unsupported) metadata.
var ilSource =
@".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly '<<GeneratedFileName>>' { }
.class C
{
.method public specialname rtspecialname instance void .ctor()
{
ret
}
.method private static object F()
{
ldnull
ret
}
.method private static void M1()
{
.locals init ([0] object other, [1] object modreq(int32) o)
call object C::F()
stloc.1
ldloc.1
call void C::M2(object)
ret
}
.method private static void M2(object o)
{
ret
}
}";
var source =
@"class C
{
static object F()
{
return null;
}
static void M1()
{
object o = F();
M2(o);
}
static void M2(object o)
{
}
}";
ImmutableArray<byte> assemblyBytes;
ImmutableArray<byte> pdbBytes;
EmitILToArray(ilSource, appendDefaultHeader: false, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
var md0 = ModuleMetadata.CreateFromImage(assemblyBytes);
// Still need a compilation with source for the initial
// generation - to get a MethodSymbol and syntax map.
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var method0 = compilation0.GetMember<MethodSymbol>("C.M1");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, m => default);
var method1 = compilation1.GetMember<MethodSymbol>("C.M1");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M1",
@"{
// Code size 15 (0xf)
.maxstack 1
.locals init (object V_0) //o
IL_0000: nop
IL_0001: call ""object C.F()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: call ""void C.M2(object)""
IL_000d: nop
IL_000e: ret
}");
}
/// <summary>
/// Should not re-use locals with custom modifiers.
/// </summary>
[WorkItem(9848, "https://github.com/dotnet/roslyn/issues/9848")]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/9848")]
public void LocalType_CustomModifiers()
{
// Equivalent method signature to C#, but
// with optional modifier on locals.
var ilSource =
@".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly '<<GeneratedFileName>>' { }
.class public C
{
.method public specialname rtspecialname instance void .ctor()
{
ret
}
.method public static object F(class [mscorlib]System.IDisposable d)
{
.locals init ([0] class C modopt(int32) c,
[1] class [mscorlib]System.IDisposable modopt(object),
[2] bool V_2,
[3] object V_3)
ldnull
ret
}
}";
var source =
@"class C
{
static object F(System.IDisposable d)
{
C c;
using (d)
{
c = (C)d;
}
return c;
}
}";
var metadata0 = (MetadataImageReference)CompileIL(ilSource, prependDefaultHeader: false);
// Still need a compilation with source for the initial
// generation - to get a MethodSymbol and syntax map.
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var moduleMetadata0 = ((AssemblyMetadata)metadata0.GetMetadataNoCopy()).GetModules()[0];
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(
moduleMetadata0,
m => default);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 38 (0x26)
.maxstack 1
.locals init ([unchanged] V_0,
[unchanged] V_1,
[bool] V_2,
[object] V_3,
C V_4, //c
System.IDisposable V_5,
object V_6)
-IL_0000: nop
-IL_0001: ldarg.0
IL_0002: stloc.s V_5
.try
{
-IL_0004: nop
-IL_0005: ldarg.0
IL_0006: castclass ""C""
IL_000b: stloc.s V_4
-IL_000d: nop
IL_000e: leave.s IL_001d
}
finally
{
~IL_0010: ldloc.s V_5
IL_0012: brfalse.s IL_001c
IL_0014: ldloc.s V_5
IL_0016: callvirt ""void System.IDisposable.Dispose()""
IL_001b: nop
IL_001c: endfinally
}
-IL_001d: ldloc.s V_4
IL_001f: stloc.s V_6
IL_0021: br.s IL_0023
-IL_0023: ldloc.s V_6
IL_0025: ret
}", methodToken: diff1.EmitResult.UpdatedMethods.Single());
}
/// <summary>
/// Temporaries for locals used within a single
/// statement should not be preserved.
/// </summary>
[Fact]
public void TemporaryLocals_Other()
{
// Use increment as an example of a compiler generated
// temporary that does not span multiple statements.
var source =
@"class C
{
int P { get; set; }
static int M()
{
var c = new C();
return c.P++;
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(
ModuleMetadata.CreateFromImage(bytes0),
methodData0.EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M", @"
{
// Code size 32 (0x20)
.maxstack 3
.locals init (C V_0, //c
[int] V_1,
[int] V_2,
int V_3,
int V_4)
IL_0000: nop
IL_0001: newobj ""C..ctor()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: dup
IL_0009: callvirt ""int C.P.get""
IL_000e: stloc.3
IL_000f: ldloc.3
IL_0010: ldc.i4.1
IL_0011: add
IL_0012: callvirt ""void C.P.set""
IL_0017: nop
IL_0018: ldloc.3
IL_0019: stloc.s V_4
IL_001b: br.s IL_001d
IL_001d: ldloc.s V_4
IL_001f: ret
}");
}
/// <summary>
/// Local names array (from PDB) may have fewer slots than method
/// signature (from metadata) when the trailing slots are unnamed.
/// </summary>
[WorkItem(782270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782270")]
[Fact]
public void Bug782270()
{
var source =
@"class C
{
static System.IDisposable F()
{
return null;
}
static void M()
{
using (var o = F())
{
}
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(
ModuleMetadata.CreateFromImage(bytes0),
testData0.GetMethodData("C.M").EncDebugInfoProvider());
testData0.GetMethodData("C.M").VerifyIL(@"
{
// Code size 23 (0x17)
.maxstack 1
.locals init (System.IDisposable V_0) //o
IL_0000: nop
IL_0001: call ""System.IDisposable C.F()""
IL_0006: stloc.0
.try
{
IL_0007: nop
IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.0
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
IL_0015: endfinally
}
IL_0016: ret
}");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M", @"
{
// Code size 23 (0x17)
.maxstack 1
.locals init (System.IDisposable V_0) //o
IL_0000: nop
IL_0001: call ""System.IDisposable C.F()""
IL_0006: stloc.0
.try
{
IL_0007: nop
IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.0
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
IL_0015: endfinally
}
IL_0016: ret
}");
}
/// <summary>
/// Similar to above test but with no named locals in original.
/// </summary>
[WorkItem(782270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782270")]
[Fact]
public void Bug782270_NoNamedLocals()
{
// Equivalent to C#, but with unnamed locals.
// Used to generate initial metadata.
var ilSource =
@".assembly extern netstandard { .ver 2:0:0:0 .publickeytoken = (cc 7b 13 ff cd 2d dd 51) }
.assembly '<<GeneratedFileName>>' { }
.class C extends object
{
.method private static class [netstandard]System.IDisposable F()
{
ldnull
ret
}
.method private static void M()
{
.locals init ([0] object, [1] object)
ret
}
}";
var source0 =
@"class C
{
static System.IDisposable F()
{
return null;
}
static void M()
{
}
}";
var source1 =
@"class C
{
static System.IDisposable F()
{
return null;
}
static void M()
{
using (var o = F())
{
}
}
}";
EmitILToArray(ilSource, appendDefaultHeader: false, includePdb: false, assemblyBytes: out var assemblyBytes, pdbBytes: out var pdbBytes);
var md0 = ModuleMetadata.CreateFromImage(assemblyBytes);
// Still need a compilation with source for the initial
// generation - to get a MethodSymbol and syntax map.
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M", @"
{
// Code size 23 (0x17)
.maxstack 1
.locals init ([object] V_0,
[object] V_1,
System.IDisposable V_2) //o
IL_0000: nop
IL_0001: call ""System.IDisposable C.F()""
IL_0006: stloc.2
.try
{
IL_0007: nop
IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
IL_000b: ldloc.2
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.2
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
IL_0015: endfinally
}
IL_0016: ret
}
");
}
[Fact]
public void TemporaryLocals_ReferencedType()
{
var source =
@"class C
{
static object F()
{
return null;
}
static void M()
{
var x = new System.Collections.Generic.HashSet<int>();
x.Add(1);
}
}";
var compilation0 = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var modMeta = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(
modMeta,
methodData0.EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M",
@"
{
// Code size 16 (0x10)
.maxstack 2
.locals init (System.Collections.Generic.HashSet<int> V_0) //x
IL_0000: nop
IL_0001: newobj ""System.Collections.Generic.HashSet<int>..ctor()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4.1
IL_0009: callvirt ""bool System.Collections.Generic.HashSet<int>.Add(int)""
IL_000e: pop
IL_000f: ret
}
");
}
[WorkItem(770502, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770502")]
[WorkItem(839565, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/839565")]
[Fact]
public void DynamicOperations()
{
var source =
@"class A
{
static object F = null;
object x = ((dynamic)F) + 1;
static A()
{
((dynamic)F).F();
}
A() { }
static void M(object o)
{
((dynamic)o).x = 1;
}
static void N(A o)
{
o.x = 1;
}
}
class B
{
static object F = null;
static object G = ((dynamic)F).F();
object x = ((dynamic)F) + 1;
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new[] { CSharpRef });
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
// Source method with dynamic operations.
var methodData0 = testData0.GetMethodData("A.M");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
var method0 = compilation0.GetMember<MethodSymbol>("A.M");
var method1 = compilation1.GetMember<MethodSymbol>("A.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
// Source method with no dynamic operations.
methodData0 = testData0.GetMethodData("A.N");
generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
method0 = compilation0.GetMember<MethodSymbol>("A.N");
method1 = compilation1.GetMember<MethodSymbol>("A.N");
diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
// Explicit .ctor with dynamic operations.
methodData0 = testData0.GetMethodData("A..ctor");
generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
method0 = compilation0.GetMember<MethodSymbol>("A..ctor");
method1 = compilation1.GetMember<MethodSymbol>("A..ctor");
diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
// Explicit .cctor with dynamic operations.
methodData0 = testData0.GetMethodData("A..cctor");
generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
method0 = compilation0.GetMember<MethodSymbol>("A..cctor");
method1 = compilation1.GetMember<MethodSymbol>("A..cctor");
diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
// Implicit .ctor with dynamic operations.
methodData0 = testData0.GetMethodData("B..ctor");
generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
method0 = compilation0.GetMember<MethodSymbol>("B..ctor");
method1 = compilation1.GetMember<MethodSymbol>("B..ctor");
diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
// Implicit .cctor with dynamic operations.
methodData0 = testData0.GetMethodData("B..cctor");
generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
method0 = compilation0.GetMember<MethodSymbol>("B..cctor");
method1 = compilation1.GetMember<MethodSymbol>("B..cctor");
diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
}
[Fact]
public void DynamicLocals()
{
var template = @"
using System;
class C
{
public void F()
{
dynamic <N:0>x = 1</N:0>;
Console.WriteLine((int)x + <<VALUE>>);
}
}
";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
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 82 (0x52)
.maxstack 3
.locals init (object V_0) //x
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: box ""int""
IL_0007: stloc.0
IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_000d: brfalse.s IL_0011
IL_000f: br.s IL_0036
IL_0011: ldc.i4.s 16
IL_0013: ldtoken ""int""
IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001d: ldtoken ""C""
IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target""
IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_0045: ldloc.0
IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_004b: call ""void System.Console.WriteLine(int)""
IL_0050: nop
IL_0051: ret
}
");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<>o__0#1}",
"C.<>o__0#1: {<>p__0}");
diff1.VerifyIL("C.F", @"
{
// Code size 84 (0x54)
.maxstack 3
.locals init (object V_0) //x
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: box ""int""
IL_0007: stloc.0
IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0""
IL_000d: brfalse.s IL_0011
IL_000f: br.s IL_0036
IL_0011: ldc.i4.s 16
IL_0013: ldtoken ""int""
IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001d: ldtoken ""C""
IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0""
IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0""
IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target""
IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0""
IL_0045: ldloc.0
IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_004b: ldc.i4.1
IL_004c: add
IL_004d: call ""void System.Console.WriteLine(int)""
IL_0052: nop
IL_0053: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<>o__0#2, <>o__0#1}",
"C.<>o__0#1: {<>p__0}",
"C.<>o__0#2: {<>p__0}");
diff2.VerifyIL("C.F", @"
{
// Code size 84 (0x54)
.maxstack 3
.locals init (object V_0) //x
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: box ""int""
IL_0007: stloc.0
IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0""
IL_000d: brfalse.s IL_0011
IL_000f: br.s IL_0036
IL_0011: ldc.i4.s 16
IL_0013: ldtoken ""int""
IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001d: ldtoken ""C""
IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0""
IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0""
IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target""
IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0""
IL_0045: ldloc.0
IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_004b: ldc.i4.2
IL_004c: add
IL_004d: call ""void System.Console.WriteLine(int)""
IL_0052: nop
IL_0053: ret
}
");
}
[Fact]
public void ExceptionFilters()
{
var source0 = MarkedSource(@"
using System;
using System.IO;
class C
{
static bool G(Exception e) => true;
static void F()
{
try
{
throw new InvalidOperationException();
}
catch <N:0>(IOException e)</N:0> <N:1>when (G(e))</N:1>
{
Console.WriteLine();
}
catch <N:2>(Exception e)</N:2> <N:3>when (G(e))</N:3>
{
Console.WriteLine();
}
}
}
");
var source1 = MarkedSource(@"
using System;
using System.IO;
class C
{
static bool G(Exception e) => true;
static void F()
{
try
{
throw new InvalidOperationException();
}
catch <N:0>(IOException e)</N:0> <N:1>when (G(e))</N:1>
{
Console.WriteLine();
}
catch <N:2>(Exception e)</N:2> <N:3>when (G(e))</N:3>
{
Console.WriteLine();
}
Console.WriteLine(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 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.VerifyIL("C.F", @"
{
// Code size 90 (0x5a)
.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_0020
IL_0014: stloc.0
IL_0015: ldloc.0
IL_0016: call ""bool C.G(System.Exception)""
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: ldc.i4.0
IL_001e: cgt.un
IL_0020: endfilter
} // end filter
{ // handler
IL_0022: pop
IL_0023: nop
IL_0024: call ""void System.Console.WriteLine()""
IL_0029: nop
IL_002a: nop
IL_002b: leave.s IL_0052
}
filter
{
IL_002d: isinst ""System.Exception""
IL_0032: dup
IL_0033: brtrue.s IL_0039
IL_0035: pop
IL_0036: ldc.i4.0
IL_0037: br.s IL_0045
IL_0039: stloc.2
IL_003a: ldloc.2
IL_003b: call ""bool C.G(System.Exception)""
IL_0040: stloc.3
IL_0041: ldloc.3
IL_0042: ldc.i4.0
IL_0043: cgt.un
IL_0045: endfilter
} // end filter
{ // handler
IL_0047: pop
IL_0048: nop
IL_0049: call ""void System.Console.WriteLine()""
IL_004e: nop
IL_004f: nop
IL_0050: leave.s IL_0052
}
IL_0052: ldc.i4.1
IL_0053: call ""void System.Console.WriteLine(int)""
IL_0058: nop
IL_0059: ret
}
");
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)]
public void MethodSignatureWithNoPIAType()
{
var sourcePIA = @"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""_.dll"")]
[assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A3"")]
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42920E2A4"")]
public interface I
{
}";
var source0 = MarkedSource(@"
class C
{
static void M(I x)
{
System.Console.WriteLine(1);
}
}");
var source1 = MarkedSource(@"
class C
{
static void M(I x)
{
System.Console.WriteLine(2);
}
}");
var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll);
var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true);
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll, references: new MetadataReference[] { referencePIA });
var compilation1 = compilation0.WithSource(source1.Tree);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
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.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify(
// error CS7096: Cannot continue since the edit includes a reference to an embedded type: 'I'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("I"));
}
[WorkItem(844472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844472")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)]
public void LocalSignatureWithNoPIAType()
{
var sourcePIA = @"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""_.dll"")]
[assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A3"")]
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42920E2A4"")]
public interface I
{
}";
var source0 = MarkedSource(@"
class C
{
static void M(I x)
{
I <N:0>y = null</N:0>;
M(null);
}
}");
var source1 = MarkedSource(@"
class C
{
static void M(I x)
{
I <N:0>y = null</N:0>;
M(x);
}
}");
var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll);
var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true);
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll, references: new MetadataReference[] { referencePIA });
var compilation1 = compilation0.WithSource(source1.Tree);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
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.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify(
// (6,16): warning CS0219: The variable 'y' is assigned but its value is never used
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y"),
// error CS7096: Cannot continue since the edit includes a reference to an embedded type: 'I'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("I"));
}
/// <summary>
/// Disallow edits that require NoPIA references.
/// </summary>
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)]
public void NoPIAReferences()
{
var sourcePIA =
@"using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""_.dll"")]
[assembly: Guid(""35DB1A6B-D635-4320-A062-28D42921E2B3"")]
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42921E2B4"")]
public interface IA
{
void M();
int P { get; }
event Action E;
}
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42921E2B5"")]
public interface IB
{
}
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42921E2B6"")]
public interface IC
{
}
public struct S
{
public object F;
}";
var source0 =
@"class C<T>
{
static object F = typeof(IC);
static void M1()
{
var o = default(IA);
o.M();
M2(o.P);
o.E += M1;
M2(C<IA>.F);
M2(new S());
}
static void M2(object o)
{
}
}";
var source1A = source0;
var source1B =
@"class C<T>
{
static object F = typeof(IC);
static void M1()
{
M2(null);
}
static void M2(object o)
{
}
}";
var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll);
var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true);
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, references: new MetadataReference[] { referencePIA, CSharpRef });
var compilation1A = compilation0.WithSource(source1A);
var compilation1B = compilation0.WithSource(source1B);
var method0 = compilation0.GetMember<MethodSymbol>("C.M1");
var method1B = compilation1B.GetMember<MethodSymbol>("C.M1");
var method1A = compilation1A.GetMember<MethodSymbol>("C.M1");
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C<T>.M1");
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C`1", "IA", "IC", "S");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
// Disallow edits that require NoPIA references.
var diff1A = compilation1A.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1A, GetEquivalentNodesMap(method1A, method0), preserveLocalVariables: true)));
diff1A.EmitResult.Diagnostics.Verify(
// error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'S'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("S"),
// error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'IA'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("IA"));
// Allow edits that do not require NoPIA references,
// even if the previous code included references.
var diff1B = compilation1B.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1B, GetEquivalentNodesMap(method1B, method0), preserveLocalVariables: true)));
diff1B.VerifyIL("C<T>.M1",
@"{
// Code size 9 (0x9)
.maxstack 1
.locals init ([unchanged] V_0,
[unchanged] V_1)
IL_0000: nop
IL_0001: ldnull
IL_0002: call ""void C<T>.M2(object)""
IL_0007: nop
IL_0008: ret
}");
using var md1 = diff1B.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames());
}
[WorkItem(844536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844536")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)]
public void NoPIATypeInNamespace()
{
var sourcePIA =
@"using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""_.dll"")]
[assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A5"")]
namespace N
{
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42920E2A6"")]
public interface IA
{
}
}
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42920E2A7"")]
public interface IB
{
}";
var source =
@"class C<T>
{
static void M(object o)
{
M(C<N.IA>.E.X);
M(C<IB>.E.X);
}
enum E { X }
}";
var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll);
var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true);
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new MetadataReference[] { referencePIA, CSharpRef });
var compilation1 = compilation0.WithSource(source);
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, m => default);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
diff1.EmitResult.Diagnostics.Verify(
// error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'N.IA'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("N.IA"),
// error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'IB'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("IB"));
diff1.VerifyIL("C<T>.M",
@"{
// Code size 26 (0x1a)
.maxstack 1
IL_0000: nop
IL_0001: ldc.i4.0
IL_0002: box ""C<N.IA>.E""
IL_0007: call ""void C<T>.M(object)""
IL_000c: nop
IL_000d: ldc.i4.0
IL_000e: box ""C<IB>.E""
IL_0013: call ""void C<T>.M(object)""
IL_0018: nop
IL_0019: ret
}");
}
/// <summary>
/// Should use TypeDef rather than TypeRef for unrecognized
/// local of a type defined in the original assembly.
/// </summary>
[WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")]
[Fact]
public void UnrecognizedLocalOfTypeFromAssembly()
{
var source =
@"class E : System.Exception
{
}
class C
{
static void M()
{
try
{
}
catch (E e)
{
}
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M");
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetAssemblyRefNames(), "netstandard");
CheckNames(readers, reader1.GetTypeRefNames(), "Object");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(7, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
diff1.VerifyIL("C.M", @"
{
// Code size 11 (0xb)
.maxstack 1
.locals init (E V_0) //e
IL_0000: nop
.try
{
IL_0001: nop
IL_0002: nop
IL_0003: leave.s IL_000a
}
catch E
{
IL_0005: stloc.0
IL_0006: nop
IL_0007: nop
IL_0008: leave.s IL_000a
}
IL_000a: ret
}");
}
/// <summary>
/// Similar to above test but with anonymous type
/// added in subsequent generation.
/// </summary>
[WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")]
[Fact]
public void UnrecognizedLocalOfAnonymousTypeFromAssembly()
{
var source0 =
@"class C
{
static string F()
{
return null;
}
static string G()
{
var o = new { Y = 1 };
return o.ToString();
}
}";
var source1 =
@"class C
{
static string F()
{
var o = new { X = 1 };
return o.ToString();
}
static string G()
{
var o = new { Y = 1 };
return o.ToString();
}
}";
var source2 =
@"class C
{
static string F()
{
return null;
}
static string G()
{
return null;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var method0F = compilation0.GetMember<MethodSymbol>("C.F");
var method1F = compilation1.GetMember<MethodSymbol>("C.F");
var method1G = compilation1.GetMember<MethodSymbol>("C.G");
var method2F = compilation2.GetMember<MethodSymbol>("C.F");
var method2G = compilation2.GetMember<MethodSymbol>("C.G");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard");
// Use empty LocalVariableNameProvider for original locals and
// use preserveLocalVariables: true for the edit so that existing
// locals are retained even though all are unrecognized.
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
CheckNames(readers, reader1.GetAssemblyRefNames(), "netstandard");
CheckNames(readers, reader1.GetTypeDefNames(), "<>f__AnonymousType1`1");
CheckNames(readers, reader1.GetTypeRefNames(), "CompilerGeneratedAttribute", "DebuggerDisplayAttribute", "Object", "DebuggerBrowsableState", "DebuggerBrowsableAttribute", "DebuggerHiddenAttribute", "EqualityComparer`1", "String", "IFormatProvider");
// Change method updated in generation 1.
var diff2F = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1F, method2F, syntaxMap: s => null, preserveLocalVariables: true)));
using var md2 = diff2F.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
CheckNames(readers, reader2.GetAssemblyRefNames(), "netstandard");
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetTypeRefNames(), "Object");
// Change method unchanged since generation 0.
var diff2G = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1G, method2G, syntaxMap: s => null, preserveLocalVariables: true)));
}
[Fact]
public void BrokenOutputStreams()
{
var source0 =
@"class C
{
static string F()
{
return null;
}
}";
var source1 =
@"class C
{
static string F()
{
var o = new { X = 1 };
return o.ToString();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray();
using (new EnsureEnglishUICulture())
using (var md0 = ModuleMetadata.CreateFromImage(bytes0))
{
var method0F = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1F = compilation1.GetMember<MethodSymbol>("C.F");
using MemoryStream mdStream = new MemoryStream(), ilStream = new MemoryStream(), pdbStream = new MemoryStream();
var isAddedSymbol = new Func<ISymbol, bool>(s => false);
var badStream = new BrokenStream();
badStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite;
var result = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)),
isAddedSymbol,
badStream,
ilStream,
pdbStream,
new CompilationTestData(),
default);
Assert.False(result.Success);
result.Diagnostics.Verify(
// error CS8104: An error occurred while writing the output file: System.IO.IOException: I/O error occurred.
Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(badStream.ThrownException.ToString()).WithLocation(1, 1)
);
result = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)),
isAddedSymbol,
mdStream,
badStream,
pdbStream,
new CompilationTestData(),
default);
Assert.False(result.Success);
result.Diagnostics.Verify(
// error CS8104: An error occurred while writing the output file: System.IO.IOException: I/O error occurred.
Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(badStream.ThrownException.ToString()).WithLocation(1, 1)
);
result = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)),
isAddedSymbol,
mdStream,
ilStream,
badStream,
new CompilationTestData(),
default);
Assert.False(result.Success);
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'I/O error occurred.'
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1)
);
}
}
[Fact]
public void BrokenPortablePdbStream()
{
var source0 =
@"class C
{
static string F()
{
return null;
}
}";
var source1 =
@"class C
{
static string F()
{
var o = new { X = 1 };
return o.ToString();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb));
using (new EnsureEnglishUICulture())
using (var md0 = ModuleMetadata.CreateFromImage(bytes0))
{
var method0F = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1F = compilation1.GetMember<MethodSymbol>("C.F");
using MemoryStream mdStream = new MemoryStream(), ilStream = new MemoryStream(), pdbStream = new MemoryStream();
var isAddedSymbol = new Func<ISymbol, bool>(s => false);
var badStream = new BrokenStream();
badStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite;
var result = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)),
isAddedSymbol,
mdStream,
ilStream,
badStream,
new CompilationTestData(),
default);
Assert.False(result.Success);
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'I/O error occurred.'
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1)
);
}
}
[WorkItem(923492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/923492")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SymWriterErrors()
{
var source0 =
@"class C
{
}";
var source1 =
@"class C
{
static void Main() { }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var diff1 = compilation1.EmitDifference(
EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider),
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.Main"))),
testData: new CompilationTestData { SymWriterFactory = _ => new MockSymUnmanagedWriter() });
diff1.EmitResult.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'MockSymUnmanagedWriter error message'
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("MockSymUnmanagedWriter error message"));
Assert.False(diff1.EmitResult.Success);
}
[WorkItem(1058058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1058058")]
[Fact]
public void BlobContainsInvalidValues()
{
var source0 =
@"class C
{
static void F()
{
string goo = ""abc"";
}
}";
var source1 =
@"class C
{
static void F()
{
float goo = 10;
}
}";
var source2 =
@"class C
{
static void F()
{
bool goo = true;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard");
var method0F = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method1F = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)));
var handle = MetadataTokens.BlobHandle(1);
byte[] value0 = reader0.GetBlobBytes(handle);
Assert.Equal("20-01-01-08", BitConverter.ToString(value0));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var method2F = compilation2.GetMember<MethodSymbol>("C.F");
var diff2F = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1F, method2F, syntaxMap: s => null, preserveLocalVariables: true)));
byte[] value1 = reader1.GetBlobBytes(handle);
Assert.Equal("07-02-0E-0C", BitConverter.ToString(value1));
using var md2 = diff2F.GetMetadata();
var reader2 = md2.Reader;
byte[] value2 = reader2.GetBlobBytes(handle);
Assert.Equal("07-03-0E-0C-02", BitConverter.ToString(value2));
}
[Fact]
public void ReferenceToMemberAddedToAnotherAssembly1()
{
var sourceA0 = @"
public class A
{
}
";
var sourceA1 = @"
public class A
{
public void M() { System.Console.WriteLine(1);}
}
public class X {}
";
var sourceB0 = @"
public class B
{
public static void F() { }
}";
var sourceB1 = @"
public class B
{
public static void F() { new A().M(); }
}
public class Y : X { }
";
var compilationA0 = CreateCompilation(sourceA0, options: TestOptions.DebugDll, assemblyName: "LibA");
var compilationA1 = compilationA0.WithSource(sourceA1);
var compilationB0 = CreateCompilation(sourceB0, new[] { compilationA0.ToMetadataReference() }, options: TestOptions.DebugDll, assemblyName: "LibB");
var compilationB1 = CreateCompilation(sourceB1, new[] { compilationA1.ToMetadataReference() }, options: TestOptions.DebugDll, assemblyName: "LibB");
var bytesA0 = compilationA0.EmitToArray();
var bytesB0 = compilationB0.EmitToArray();
var mdA0 = ModuleMetadata.CreateFromImage(bytesA0);
var mdB0 = ModuleMetadata.CreateFromImage(bytesB0);
var generationA0 = EmitBaseline.CreateInitialBaseline(mdA0, EmptyLocalsProvider);
var generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, EmptyLocalsProvider);
var mA1 = compilationA1.GetMember<MethodSymbol>("A.M");
var mX1 = compilationA1.GetMember<TypeSymbol>("X");
var allAddedSymbols = new ISymbol[] { mA1.GetPublicSymbol(), mX1.GetPublicSymbol() };
var diffA1 = compilationA1.EmitDifference(
generationA0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, mA1),
SemanticEdit.Create(SemanticEditKind.Insert, null, mX1)),
allAddedSymbols);
diffA1.EmitResult.Diagnostics.Verify();
var diffB1 = compilationB1.EmitDifference(
generationB0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, compilationB0.GetMember<MethodSymbol>("B.F"), compilationB1.GetMember<MethodSymbol>("B.F")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilationB1.GetMember<TypeSymbol>("Y"))),
allAddedSymbols);
diffB1.EmitResult.Diagnostics.Verify(
// (7,14): error CS7101: Member 'X' added during the current debug session can only be accessed from within its declaring assembly 'LibA'.
// public class X {}
Diagnostic(ErrorCode.ERR_EncReferenceToAddedMember, "X").WithArguments("X", "LibA").WithLocation(7, 14),
// (4,17): error CS7101: Member 'M' added during the current debug session can only be accessed from within its declaring assembly 'LibA'.
// public void M() { System.Console.WriteLine(1);}
Diagnostic(ErrorCode.ERR_EncReferenceToAddedMember, "M").WithArguments("M", "LibA").WithLocation(4, 17));
}
[Fact]
public void ReferenceToMemberAddedToAnotherAssembly2()
{
var sourceA = @"
public class A
{
public void M() { }
}";
var sourceB0 = @"
public class B
{
public static void F() { var a = new A(); }
}";
var sourceB1 = @"
public class B
{
public static void F() { var a = new A(); a.M(); }
}";
var sourceB2 = @"
public class B
{
public static void F() { var a = new A(); }
}";
var compilationA = CreateCompilation(sourceA, options: TestOptions.DebugDll, assemblyName: "AssemblyA");
var aRef = compilationA.ToMetadataReference();
var compilationB0 = CreateCompilation(sourceB0, new[] { aRef }, options: TestOptions.DebugDll, assemblyName: "AssemblyB");
var compilationB1 = compilationB0.WithSource(sourceB1);
var compilationB2 = compilationB1.WithSource(sourceB2);
var testDataB0 = new CompilationTestData();
var bytesB0 = compilationB0.EmitToArray(testData: testDataB0);
var mdB0 = ModuleMetadata.CreateFromImage(bytesB0);
var generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, testDataB0.GetMethodData("B.F").EncDebugInfoProvider());
var f0 = compilationB0.GetMember<MethodSymbol>("B.F");
var f1 = compilationB1.GetMember<MethodSymbol>("B.F");
var f2 = compilationB2.GetMember<MethodSymbol>("B.F");
var diffB1 = compilationB1.EmitDifference(
generationB0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true)));
diffB1.VerifyIL("B.F", @"
{
// Code size 15 (0xf)
.maxstack 1
.locals init (A V_0) //a
IL_0000: nop
IL_0001: newobj ""A..ctor()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: callvirt ""void A.M()""
IL_000d: nop
IL_000e: ret
}
");
var diffB2 = compilationB2.EmitDifference(
diffB1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetEquivalentNodesMap(f2, f1), preserveLocalVariables: true)));
diffB2.VerifyIL("B.F", @"
{
// Code size 8 (0x8)
.maxstack 1
.locals init (A V_0) //a
IL_0000: nop
IL_0001: newobj ""A..ctor()""
IL_0006: stloc.0
IL_0007: ret
}
");
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)]
public void UniqueSynthesizedNames_DynamicSiteContainer()
{
var source0 = @"
public class C
{
public static void F(dynamic d) { d.Goo(); }
}";
var source1 = @"
public class C
{
public static void F(dynamic d) { d.Bar(); }
}";
var source2 = @"
public class C
{
public static void F(dynamic d, byte b) { d.Bar(); }
public static void F(dynamic d) { d.Bar(); }
}";
var compilation0 = CreateCompilation(source0, targetFramework: TargetFramework.StandardAndCSharp,
options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A");
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f_byte2 = compilation2.GetMembers("C.F").Single(m => m.ToString() == "C.F(dynamic, byte)");
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.Update, f0, f1, preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f_byte2)));
diff2.EmitResult.Diagnostics.Verify();
var reader0 = md0.MetadataReader;
var reader1 = diff1.GetMetadata().Reader;
var reader2 = diff2.GetMetadata().Reader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>o__0");
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>o__0#1");
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>o__0#2");
}
[WorkItem(918650, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/918650")]
[Fact]
public void ManyGenerations()
{
var source =
@"class C
{{
static int F() {{ return {0}; }}
}}";
var compilation0 = CreateCompilation(String.Format(source, 1), options: TestOptions.DebugDll);
var bytes0 = compilation0.EmitToArray();
var md0 = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
for (int i = 2; i <= 50; i++)
{
var compilation1 = compilation0.WithSource(String.Format(source, i));
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
compilation0 = compilation1;
method0 = method1;
generation0 = diff1.NextGeneration;
}
}
[WorkItem(187868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/187868")]
[Fact]
public void PdbReadingErrors()
{
var source0 = MarkedSource(@"
using System;
class C
{
static void F()
{
<N:0>Console.WriteLine(1);</N:0>
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static void F()
{
<N:0>Console.WriteLine(2);</N:0>
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll, assemblyName: "PdbReadingErrorsAssembly");
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, methodHandle =>
{
throw new InvalidDataException("Bad PDB!");
});
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify(
// (6,14): error CS7038: Failed to emit module 'Unable to read debug information of method 'C.F()' (token 0x06000001) from assembly 'PdbReadingErrorsAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null''.
Diagnostic(ErrorCode.ERR_InvalidDebugInfo, "F").WithArguments("C.F()", "100663297", "PdbReadingErrorsAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 14));
}
[Fact]
public void PdbReadingErrors_PassThruExceptions()
{
var source0 = MarkedSource(@"
using System;
class C
{
static void F()
{
<N:0>Console.WriteLine(1);</N:0>
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static void F()
{
<N:0>Console.WriteLine(2);</N:0>
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll, assemblyName: "PdbReadingErrorsAssembly");
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, methodHandle =>
{
throw new ArgumentOutOfRangeException();
});
// the compiler should't swallow any exceptions but InvalidDataException
Assert.Throws<ArgumentOutOfRangeException>(() =>
compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))));
}
[Fact]
public void PatternVariable_TypeChange()
{
var source0 = MarkedSource(@"
class C
{
static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; }
}");
var source1 = MarkedSource(@"
class C
{
static int F(object o) { if (o is bool <N:0>i</N:0>) { return i ? 1 : 0; } return 0; }
}");
var source2 = MarkedSource(@"
class C
{
static int F(object o) { if (o is int <N:0>j</N:0>) { return j; } return 0; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.F", @"
{
// Code size 35 (0x23)
.maxstack 1
.locals init (int V_0, //i
bool V_1,
int V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""int""
IL_0007: brfalse.s IL_0013
IL_0009: ldarg.0
IL_000a: unbox.any ""int""
IL_000f: stloc.0
IL_0010: ldc.i4.1
IL_0011: br.s IL_0014
IL_0013: ldc.i4.0
IL_0014: stloc.1
IL_0015: ldloc.1
IL_0016: brfalse.s IL_001d
IL_0018: nop
IL_0019: ldloc.0
IL_001a: stloc.2
IL_001b: br.s IL_0021
IL_001d: ldc.i4.0
IL_001e: stloc.2
IL_001f: br.s IL_0021
IL_0021: ldloc.2
IL_0022: ret
}");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
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.VerifyIL("C.F", @"
{
// Code size 46 (0x2e)
.maxstack 1
.locals init ([int] V_0,
[bool] V_1,
[int] V_2,
bool V_3, //i
bool V_4,
int V_5)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""bool""
IL_0007: brfalse.s IL_0013
IL_0009: ldarg.0
IL_000a: unbox.any ""bool""
IL_000f: stloc.3
IL_0010: ldc.i4.1
IL_0011: br.s IL_0014
IL_0013: ldc.i4.0
IL_0014: stloc.s V_4
IL_0016: ldloc.s V_4
IL_0018: brfalse.s IL_0026
IL_001a: nop
IL_001b: ldloc.3
IL_001c: brtrue.s IL_0021
IL_001e: ldc.i4.0
IL_001f: br.s IL_0022
IL_0021: ldc.i4.1
IL_0022: stloc.s V_5
IL_0024: br.s IL_002b
IL_0026: ldc.i4.0
IL_0027: stloc.s V_5
IL_0029: br.s IL_002b
IL_002b: ldloc.s V_5
IL_002d: 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 42 (0x2a)
.maxstack 1
.locals init ([int] V_0,
[bool] V_1,
[int] V_2,
[bool] V_3,
[bool] V_4,
[int] V_5,
int V_6, //j
bool V_7,
int V_8)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""int""
IL_0007: brfalse.s IL_0014
IL_0009: ldarg.0
IL_000a: unbox.any ""int""
IL_000f: stloc.s V_6
IL_0011: ldc.i4.1
IL_0012: br.s IL_0015
IL_0014: ldc.i4.0
IL_0015: stloc.s V_7
IL_0017: ldloc.s V_7
IL_0019: brfalse.s IL_0022
IL_001b: nop
IL_001c: ldloc.s V_6
IL_001e: stloc.s V_8
IL_0020: br.s IL_0027
IL_0022: ldc.i4.0
IL_0023: stloc.s V_8
IL_0025: br.s IL_0027
IL_0027: ldloc.s V_8
IL_0029: ret
}");
}
[Fact]
public void PatternVariable_DeleteInsert()
{
var source0 = MarkedSource(@"
class C
{
static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; }
}");
var source1 = MarkedSource(@"
class C
{
static int F(object o) { if (o is int) { return 1; } return 0; }
}");
var source2 = MarkedSource(@"
class C
{
static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.F", @"
{
// Code size 35 (0x23)
.maxstack 1
.locals init (int V_0, //i
bool V_1,
int V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""int""
IL_0007: brfalse.s IL_0013
IL_0009: ldarg.0
IL_000a: unbox.any ""int""
IL_000f: stloc.0
IL_0010: ldc.i4.1
IL_0011: br.s IL_0014
IL_0013: ldc.i4.0
IL_0014: stloc.1
IL_0015: ldloc.1
IL_0016: brfalse.s IL_001d
IL_0018: nop
IL_0019: ldloc.0
IL_001a: stloc.2
IL_001b: br.s IL_0021
IL_001d: ldc.i4.0
IL_001e: stloc.2
IL_001f: br.s IL_0021
IL_0021: ldloc.2
IL_0022: ret
}");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
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.VerifyIL("C.F", @"
{
// Code size 28 (0x1c)
.maxstack 2
.locals init ([int] V_0,
[bool] V_1,
[int] V_2,
bool V_3,
int V_4)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""int""
IL_0007: ldnull
IL_0008: cgt.un
IL_000a: stloc.3
IL_000b: ldloc.3
IL_000c: brfalse.s IL_0014
IL_000e: nop
IL_000f: ldc.i4.1
IL_0010: stloc.s V_4
IL_0012: br.s IL_0019
IL_0014: ldc.i4.0
IL_0015: stloc.s V_4
IL_0017: br.s IL_0019
IL_0019: ldloc.s V_4
IL_001b: 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 42 (0x2a)
.maxstack 1
.locals init ([int] V_0,
[bool] V_1,
[int] V_2,
[bool] V_3,
[int] V_4,
int V_5, //i
bool V_6,
int V_7)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""int""
IL_0007: brfalse.s IL_0014
IL_0009: ldarg.0
IL_000a: unbox.any ""int""
IL_000f: stloc.s V_5
IL_0011: ldc.i4.1
IL_0012: br.s IL_0015
IL_0014: ldc.i4.0
IL_0015: stloc.s V_6
IL_0017: ldloc.s V_6
IL_0019: brfalse.s IL_0022
IL_001b: nop
IL_001c: ldloc.s V_5
IL_001e: stloc.s V_7
IL_0020: br.s IL_0027
IL_0022: ldc.i4.0
IL_0023: stloc.s V_7
IL_0025: br.s IL_0027
IL_0027: ldloc.s V_7
IL_0029: ret
}");
}
[Fact]
public void PatternVariable_InConstructorInitializer()
{
var baseClass = "public class Base { public Base(bool x) { } }";
var source0 = MarkedSource(@"
public class C : Base
{
public C(int a) : base(a is int <N:0>x</N:0> && x == 0 && a is int <N:1>y</N:1>) { y = 1; }
}" + baseClass);
var source1 = MarkedSource(@"
public class C : Base
{
public C(int a) : base(a is int <N:0>x</N:0> && x == 0) { }
}" + baseClass);
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: brtrue.s IL_000b
IL_0006: ldarg.1
IL_0007: stloc.1
IL_0008: ldc.i4.1
IL_0009: br.s IL_000c
IL_000b: ldc.i4.0
IL_000c: call ""Base..ctor(bool)""
IL_0011: nop
IL_0012: nop
IL_0013: ldc.i4.1
IL_0014: stloc.1
IL_0015: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
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)));
diff1.VerifyIL("C..ctor", @"
{
// Code size 15 (0xf)
.maxstack 3
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldc.i4.0
IL_0005: ceq
IL_0007: call ""Base..ctor(bool)""
IL_000c: nop
IL_000d: nop
IL_000e: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifyIL("C..ctor", @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: brtrue.s IL_000b
IL_0006: ldarg.1
IL_0007: stloc.2
IL_0008: ldc.i4.1
IL_0009: br.s IL_000c
IL_000b: ldc.i4.0
IL_000c: call ""Base..ctor(bool)""
IL_0011: nop
IL_0012: nop
IL_0013: ldc.i4.1
IL_0014: stloc.2
IL_0015: ret
}
");
}
[Fact]
public void PatternVariable_InFieldInitializer()
{
var source0 = MarkedSource(@"
public class C
{
public static int a = 0;
public bool field = a is int <N:0>x</N:0> && x == 0 && a is int <N:1>y</N:1>;
}");
var source1 = MarkedSource(@"
public class C
{
public static int a = 0;
public bool field = a is int <N:0>x</N:0> && x == 0;
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.0
IL_0001: ldsfld ""int C.a""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brtrue.s IL_0013
IL_000a: ldsfld ""int C.a""
IL_000f: stloc.1
IL_0010: ldc.i4.1
IL_0011: br.s IL_0014
IL_0013: ldc.i4.0
IL_0014: stfld ""bool C.field""
IL_0019: ldarg.0
IL_001a: call ""object..ctor()""
IL_001f: nop
IL_0020: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
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)));
diff1.VerifyIL("C..ctor", @"
{
// Code size 24 (0x18)
.maxstack 3
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.0
IL_0001: ldsfld ""int C.a""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4.0
IL_0009: ceq
IL_000b: stfld ""bool C.field""
IL_0010: ldarg.0
IL_0011: call ""object..ctor()""
IL_0016: nop
IL_0017: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifyIL("C..ctor", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.0
IL_0001: ldsfld ""int C.a""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brtrue.s IL_0013
IL_000a: ldsfld ""int C.a""
IL_000f: stloc.2
IL_0010: ldc.i4.1
IL_0011: br.s IL_0014
IL_0013: ldc.i4.0
IL_0014: stfld ""bool C.field""
IL_0019: ldarg.0
IL_001a: call ""object..ctor()""
IL_001f: nop
IL_0020: ret
}
");
}
[Fact]
public void PatternVariable_InQuery()
{
var source0 = MarkedSource(@"
using System.Linq;
public class Program
{
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select a is int <N:2>x</N:2> && x == 0 && a is int <N:3>y</N:3></N:1></N:0>;
}
}");
var source1 = MarkedSource(@"
using System.Linq;
public class Program
{
static int M(int x, out int y) { y = 42; return 43; }
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select a is int <N:2>x</N:2> && x == 0</N:1></N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var n0 = compilation0.GetMember<MethodSymbol>("Program.N");
var n1 = compilation1.GetMember<MethodSymbol>("Program.N");
var n2 = compilation2.GetMember<MethodSymbol>("Program.N");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)""
IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_0033: stloc.0
IL_0034: ret
}
");
v0.VerifyIL("Program.<>c.<N>b__0_0(int)", @"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: brtrue.s IL_000a
IL_0005: ldarg.1
IL_0006: stloc.1
IL_0007: ldc.i4.1
IL_0008: br.s IL_000b
IL_000a: ldc.i4.0
IL_000b: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers("Program: {<>c}", "Program.<>c: {<>9__0_0, <N>b__0_0}");
diff1.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)""
IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff1.VerifyIL("Program.<>c.<N>b__0_0(int)", @"
{
// Code size 7 (0x7)
.maxstack 2
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ceq
IL_0006: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers("Program: {<>c}", "Program.<>c: {<>9__0_0, <N>b__0_0}");
diff2.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)""
IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff2.VerifyIL("Program.<>c.<N>b__0_0(int)", @"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: brtrue.s IL_000a
IL_0005: ldarg.1
IL_0006: stloc.2
IL_0007: ldc.i4.1
IL_0008: br.s IL_000b
IL_000a: ldc.i4.0
IL_000b: ret
}
");
}
[Fact]
public void Tuple_Parenthesized()
{
var source0 = MarkedSource(@"
class C
{
static int F() { (int, (int, int)) <N:0>x</N:0> = (1, (2, 3)); return x.Item1 + x.Item2.Item1 + x.Item2.Item2; }
}");
var source1 = MarkedSource(@"
class C
{
static int F() { (int, int, int) <N:0>x</N:0> = (1, 2, 3); return x.Item1 + x.Item2 + x.Item3; }
}");
var source2 = MarkedSource(@"
class C
{
static int F() { (int, int) <N:0>x</N:0> = (1, 3); return x.Item1 + x.Item2; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.F", @"
{
// Code size 51 (0x33)
.maxstack 4
.locals init (System.ValueTuple<int, System.ValueTuple<int, int>> V_0, //x
int V_1)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldc.i4.1
IL_0004: ldc.i4.2
IL_0005: ldc.i4.3
IL_0006: newobj ""System.ValueTuple<int, int>..ctor(int, int)""
IL_000b: call ""System.ValueTuple<int, System.ValueTuple<int, int>>..ctor(int, System.ValueTuple<int, int>)""
IL_0010: ldloc.0
IL_0011: ldfld ""int System.ValueTuple<int, System.ValueTuple<int, int>>.Item1""
IL_0016: ldloc.0
IL_0017: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2""
IL_001c: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_0021: add
IL_0022: ldloc.0
IL_0023: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2""
IL_0028: ldfld ""int System.ValueTuple<int, int>.Item2""
IL_002d: add
IL_002e: stloc.1
IL_002f: br.s IL_0031
IL_0031: ldloc.1
IL_0032: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
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.VerifyIL("C.F", @"
{
// Code size 36 (0x24)
.maxstack 4
.locals init ([unchanged] V_0,
[int] V_1,
System.ValueTuple<int, int, int> V_2, //x
int V_3)
IL_0000: nop
IL_0001: ldloca.s V_2
IL_0003: ldc.i4.1
IL_0004: ldc.i4.2
IL_0005: ldc.i4.3
IL_0006: call ""System.ValueTuple<int, int, int>..ctor(int, int, int)""
IL_000b: ldloc.2
IL_000c: ldfld ""int System.ValueTuple<int, int, int>.Item1""
IL_0011: ldloc.2
IL_0012: ldfld ""int System.ValueTuple<int, int, int>.Item2""
IL_0017: add
IL_0018: ldloc.2
IL_0019: ldfld ""int System.ValueTuple<int, int, int>.Item3""
IL_001e: add
IL_001f: stloc.3
IL_0020: br.s IL_0022
IL_0022: ldloc.3
IL_0023: 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 32 (0x20)
.maxstack 3
.locals init ([unchanged] V_0,
[int] V_1,
[unchanged] V_2,
[int] V_3,
System.ValueTuple<int, int> V_4, //x
int V_5)
IL_0000: nop
IL_0001: ldloca.s V_4
IL_0003: ldc.i4.1
IL_0004: ldc.i4.3
IL_0005: call ""System.ValueTuple<int, int>..ctor(int, int)""
IL_000a: ldloc.s V_4
IL_000c: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_0011: ldloc.s V_4
IL_0013: ldfld ""int System.ValueTuple<int, int>.Item2""
IL_0018: add
IL_0019: stloc.s V_5
IL_001b: br.s IL_001d
IL_001d: ldloc.s V_5
IL_001f: ret
}
");
}
[Fact]
public void Tuple_Decomposition()
{
var source0 = MarkedSource(@"
class C
{
static int F() { (int <N:0>x</N:0>, int <N:1>y</N:1>, int <N:2>z</N:2>) = (1, 2, 3); return x + y + z; }
}");
var source1 = MarkedSource(@"
class C
{
static int F() { (int <N:0>x</N:0>, int <N:2>z</N:2>) = (1, 3); return x + z; }
}");
var source2 = MarkedSource(@"
class C
{
static int F() { (int <N:0>x</N:0>, int <N:1>y</N:1>, int <N:2>z</N:2>) = (1, 2, 3); return x + y + z; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.F", @"
{
// Code size 17 (0x11)
.maxstack 2
.locals init (int V_0, //x
int V_1, //y
int V_2, //z
int V_3)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldc.i4.2
IL_0004: stloc.1
IL_0005: ldc.i4.3
IL_0006: stloc.2
IL_0007: ldloc.0
IL_0008: ldloc.1
IL_0009: add
IL_000a: ldloc.2
IL_000b: add
IL_000c: stloc.3
IL_000d: br.s IL_000f
IL_000f: ldloc.3
IL_0010: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
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.VerifyIL("C.F", @"
{
// Code size 15 (0xf)
.maxstack 2
.locals init (int V_0, //x
[int] V_1,
int V_2, //z
[int] V_3,
int V_4)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldc.i4.3
IL_0004: stloc.2
IL_0005: ldloc.0
IL_0006: ldloc.2
IL_0007: add
IL_0008: stloc.s V_4
IL_000a: br.s IL_000c
IL_000c: ldloc.s V_4
IL_000e: 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 21 (0x15)
.maxstack 2
.locals init (int V_0, //x
[int] V_1,
int V_2, //z
[int] V_3,
[int] V_4,
int V_5, //y
int V_6)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldc.i4.2
IL_0004: stloc.s V_5
IL_0006: ldc.i4.3
IL_0007: stloc.2
IL_0008: ldloc.0
IL_0009: ldloc.s V_5
IL_000b: add
IL_000c: ldloc.2
IL_000d: add
IL_000e: stloc.s V_6
IL_0010: br.s IL_0012
IL_0012: ldloc.s V_6
IL_0014: ret
}
");
}
[Fact]
public void ForeachStatement()
{
var source0 = MarkedSource(@"
class C
{
public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) };
public static void G()
{
foreach (var (<N:0>x</N:0>, (<N:1>y</N:1>, <N:2>z</N:2>)) in F())
{
System.Console.WriteLine(x);
}
}
}");
var source1 = MarkedSource(@"
class C
{
public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) };
public static void G()
{
foreach (var (<N:0>x1</N:0>, (<N:1>y</N:1>, <N:2>z</N:2>)) in F())
{
System.Console.WriteLine(x1);
}
}
}");
var source2 = MarkedSource(@"
class C
{
public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) };
public static void G()
{
foreach (var (<N:0>x1</N:0>, <N:1>yz</N:1>) in F())
{
System.Console.WriteLine(x1);
}
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.G");
var f1 = compilation1.GetMember<MethodSymbol>("C.G");
var f2 = compilation2.GetMember<MethodSymbol>("C.G");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.G", @"
{
// Code size 70 (0x46)
.maxstack 2
.locals init (System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_0,
int V_1,
int V_2, //x
bool V_3, //y
double V_4, //z
System.ValueTuple<bool, double> V_5)
IL_0000: nop
IL_0001: nop
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
IL_000a: br.s IL_003f
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
IL_0032: nop
IL_0033: ldloc.2
IL_0034: call ""void System.Console.WriteLine(int)""
IL_0039: nop
IL_003a: nop
IL_003b: ldloc.1
IL_003c: ldc.i4.1
IL_003d: add
IL_003e: stloc.1
IL_003f: ldloc.1
IL_0040: ldloc.0
IL_0041: ldlen
IL_0042: conv.i4
IL_0043: blt.s IL_000c
IL_0045: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
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.VerifyIL("C.G", @"
{
// Code size 78 (0x4e)
.maxstack 2
.locals init ([unchanged] V_0,
[int] V_1,
int V_2, //x1
bool V_3, //y
double V_4, //z
[unchanged] V_5,
System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_6,
int V_7,
System.ValueTuple<bool, double> V_8)
IL_0000: nop
IL_0001: nop
IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()""
IL_0007: stloc.s V_6
IL_0009: ldc.i4.0
IL_000a: stloc.s V_7
IL_000c: br.s IL_0045
IL_000e: ldloc.s V_6
IL_0010: ldloc.s V_7
IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>""
IL_0017: dup
IL_0018: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2""
IL_001d: stloc.s V_8
IL_001f: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1""
IL_0024: stloc.2
IL_0025: ldloc.s V_8
IL_0027: ldfld ""bool System.ValueTuple<bool, double>.Item1""
IL_002c: stloc.3
IL_002d: ldloc.s V_8
IL_002f: ldfld ""double System.ValueTuple<bool, double>.Item2""
IL_0034: stloc.s V_4
IL_0036: nop
IL_0037: ldloc.2
IL_0038: call ""void System.Console.WriteLine(int)""
IL_003d: nop
IL_003e: nop
IL_003f: ldloc.s V_7
IL_0041: ldc.i4.1
IL_0042: add
IL_0043: stloc.s V_7
IL_0045: ldloc.s V_7
IL_0047: ldloc.s V_6
IL_0049: ldlen
IL_004a: conv.i4
IL_004b: blt.s IL_000e
IL_004d: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifyIL("C.G", @"
{
// Code size 61 (0x3d)
.maxstack 2
.locals init ([unchanged] V_0,
[int] V_1,
int V_2, //x1
[bool] V_3,
[unchanged] V_4,
[unchanged] V_5,
[unchanged] V_6,
[int] V_7,
[unchanged] V_8,
System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_9,
int V_10,
System.ValueTuple<bool, double> V_11) //yz
IL_0000: nop
IL_0001: nop
IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()""
IL_0007: stloc.s V_9
IL_0009: ldc.i4.0
IL_000a: stloc.s V_10
IL_000c: br.s IL_0034
IL_000e: ldloc.s V_9
IL_0010: ldloc.s V_10
IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>""
IL_0017: dup
IL_0018: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1""
IL_001d: stloc.2
IL_001e: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2""
IL_0023: stloc.s V_11
IL_0025: nop
IL_0026: ldloc.2
IL_0027: call ""void System.Console.WriteLine(int)""
IL_002c: nop
IL_002d: nop
IL_002e: ldloc.s V_10
IL_0030: ldc.i4.1
IL_0031: add
IL_0032: stloc.s V_10
IL_0034: ldloc.s V_10
IL_0036: ldloc.s V_9
IL_0038: ldlen
IL_0039: conv.i4
IL_003a: blt.s IL_000e
IL_003c: ret
}
");
}
[Fact]
public void OutVar()
{
var source0 = MarkedSource(@"
class C
{
static void F(out int x, out int y) { x = 1; y = 2; }
static int G() { F(out int <N:0>x</N:0>, out var <N:1>y</N:1>); return x + y; }
}");
var source1 = MarkedSource(@"
class C
{
static void F(out int x, out int y) { x = 1; y = 2; }
static int G() { F(out int <N:0>x</N:0>, out var <N:1>z</N:1>); return x + z; }
}");
var source2 = MarkedSource(@"
class C
{
static void F(out int x, out int y) { x = 1; y = 2; }
static int G() { F(out int <N:0>x</N:0>, out int <N:1>y</N:1>); return x + y; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.G");
var f1 = compilation1.GetMember<MethodSymbol>("C.G");
var f2 = compilation2.GetMember<MethodSymbol>("C.G");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.G", @"
{
// Code size 19 (0x13)
.maxstack 2
.locals init (int V_0, //x
int V_1, //y
int V_2)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldloca.s V_1
IL_0005: call ""void C.F(out int, out int)""
IL_000a: nop
IL_000b: ldloc.0
IL_000c: ldloc.1
IL_000d: add
IL_000e: stloc.2
IL_000f: br.s IL_0011
IL_0011: ldloc.2
IL_0012: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
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.VerifyIL("C.G", @"
{
// Code size 19 (0x13)
.maxstack 2
.locals init (int V_0, //x
int V_1, //z
[int] V_2,
int V_3)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldloca.s V_1
IL_0005: call ""void C.F(out int, out int)""
IL_000a: nop
IL_000b: ldloc.0
IL_000c: ldloc.1
IL_000d: add
IL_000e: stloc.3
IL_000f: br.s IL_0011
IL_0011: ldloc.3
IL_0012: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifyIL("C.G", @"
{
// Code size 21 (0x15)
.maxstack 2
.locals init (int V_0, //x
int V_1, //y
[int] V_2,
[int] V_3,
int V_4)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldloca.s V_1
IL_0005: call ""void C.F(out int, out int)""
IL_000a: nop
IL_000b: ldloc.0
IL_000c: ldloc.1
IL_000d: add
IL_000e: stloc.s V_4
IL_0010: br.s IL_0012
IL_0012: ldloc.s V_4
IL_0014: ret
}
");
}
[Fact]
public void OutVar_InConstructorInitializer()
{
var baseClass = "public class Base { public Base(int x) { } }";
var source0 = MarkedSource(@"
public class C : Base
{
public C() : base(M(out int <N:0>x</N:0>) + x + M(out int <N:1>y</N:1>)) { System.Console.Write(y); }
static int M(out int x) => throw null;
}" + baseClass);
var source1 = MarkedSource(@"
public class C : Base
{
public C() : base(M(out int <N:0>x</N:0>) + x) { }
static int M(out int x) => throw null;
}" + baseClass);
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 33 (0x21)
.maxstack 3
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldloca.s V_1
IL_000c: call ""int C.M(out int)""
IL_0011: add
IL_0012: call ""Base..ctor(int)""
IL_0017: nop
IL_0018: nop
IL_0019: ldloc.1
IL_001a: call ""void System.Console.Write(int)""
IL_001f: nop
IL_0020: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
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)));
diff1.VerifyIL("C..ctor", @"
{
// Code size 18 (0x12)
.maxstack 3
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: call ""Base..ctor(int)""
IL_000f: nop
IL_0010: nop
IL_0011: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifyIL("C..ctor", @"
{
// Code size 33 (0x21)
.maxstack 3
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldloca.s V_2
IL_000c: call ""int C.M(out int)""
IL_0011: add
IL_0012: call ""Base..ctor(int)""
IL_0017: nop
IL_0018: nop
IL_0019: ldloc.2
IL_001a: call ""void System.Console.Write(int)""
IL_001f: nop
IL_0020: ret
}
");
}
[Fact]
public void OutVar_InConstructorInitializer_WithLambda()
{
var baseClass = "public class Base { public Base(int x) { } }";
var source0 = MarkedSource(@"
public class C : Base
{
<N:0>public C() : base(M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>)) { }</N:0>
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}" + baseClass);
var source1 = MarkedSource(@"
public class C : Base
{
<N:0>public C() : base(M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>)) { }</N:0>
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}" + baseClass);
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 44 (0x2c)
.maxstack 4
.locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: call ""Base..ctor(int)""
IL_0029: nop
IL_002a: nop
IL_002b: ret
}
");
v0.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @"
{
// 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
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
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)));
diff1.VerifyUpdatedTypes("0x02000002", "0x02000004");
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetUpdatedTypeDefNames(diff1.EmitResult), "C", "<>c__DisplayClass0_0");
diff1.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {x, <.ctor>b__0}");
diff1.VerifyIL("C..ctor", @"
{
// Code size 44 (0x2c)
.maxstack 4
.locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: call ""Base..ctor(int)""
IL_0029: nop
IL_002a: nop
IL_002b: ret
}
");
diff1.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @"
{
// 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: sub
IL_0008: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifyUpdatedTypes("0x02000002", "0x02000004");
CheckNames(reader0, reader0.GetUpdatedTypeDefNames(diff2.EmitResult), "C", "<>c__DisplayClass0_0");
diff2.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {x, <.ctor>b__0}");
diff2.VerifyIL("C..ctor", @"
{
// Code size 44 (0x2c)
.maxstack 4
.locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: call ""Base..ctor(int)""
IL_0029: nop
IL_002a: nop
IL_002b: ret
}
");
diff2.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @"
{
// 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
}
");
}
[Fact]
public void OutVar_InMethodBody_WithLambda()
{
var source0 = MarkedSource(@"
public class C
{
public void Method() <N:0>{ int _ = M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>); }</N:0>
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}");
var source1 = MarkedSource(@"
public class C
{
public void Method() <N:0>{ int _ = M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>); }</N:0>
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C.Method");
var ctor1 = compilation1.GetMember<MethodSymbol>("C.Method");
var ctor2 = compilation2.GetMember<MethodSymbol>("C.Method");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.Method", @"
{
// Code size 38 (0x26)
.maxstack 3
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
int V_1) //_
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stloc.1
IL_0025: ret
}
");
v0.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @"
{
// 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
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
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)));
diff1.VerifySynthesizedMembers("C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <Method>b__0}");
diff1.VerifyIL("C.Method", @"
{
// Code size 38 (0x26)
.maxstack 3
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
[int] V_1,
int V_2) //_
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stloc.2
IL_0025: ret
}
");
diff1.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @"
{
// 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: sub
IL_0008: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers("C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <Method>b__0}");
diff2.VerifyIL("C.Method", @"
{
// Code size 38 (0x26)
.maxstack 3
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
[int] V_1,
[int] V_2,
int V_3) //_
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stloc.3
IL_0025: ret
}
");
diff2.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @"
{
// 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
}
");
}
[Fact]
public void OutVar_InFieldInitializer()
{
var source0 = MarkedSource(@"
public class C
{
public int field = M(out int <N:0>x</N:0>) + x + M(out int <N:1>y</N:1>);
static int M(out int x) => throw null;
}");
var source1 = MarkedSource(@"
public class C
{
public int field = M(out int <N:0>x</N:0>) + x;
static int M(out int x) => throw null;
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 31 (0x1f)
.maxstack 3
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldloca.s V_1
IL_000c: call ""int C.M(out int)""
IL_0011: add
IL_0012: stfld ""int C.field""
IL_0017: ldarg.0
IL_0018: call ""object..ctor()""
IL_001d: nop
IL_001e: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
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)));
diff1.VerifyIL("C..ctor", @"
{
// Code size 23 (0x17)
.maxstack 3
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: stfld ""int C.field""
IL_000f: ldarg.0
IL_0010: call ""object..ctor()""
IL_0015: nop
IL_0016: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifyIL("C..ctor", @"
{
// Code size 31 (0x1f)
.maxstack 3
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldloca.s V_2
IL_000c: call ""int C.M(out int)""
IL_0011: add
IL_0012: stfld ""int C.field""
IL_0017: ldarg.0
IL_0018: call ""object..ctor()""
IL_001d: nop
IL_001e: ret
}
");
}
[Fact]
public void OutVar_InFieldInitializer_WithLambda()
{
var source0 = MarkedSource(@"
public class C
{
int field = <N:0>M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>)</N:0>;
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}");
var source1 = MarkedSource(@"
public class C
{
int field = <N:0>M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>)</N:0>;
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 49 (0x31)
.maxstack 4
.locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stfld ""int C.field""
IL_0029: ldarg.0
IL_002a: call ""object..ctor()""
IL_002f: nop
IL_0030: ret
}
");
v0.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
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)));
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass3_0: {x, <.ctor>b__0}",
"C: {<>c__DisplayClass3_0}");
diff1.VerifyIL("C..ctor", @"
{
// Code size 49 (0x31)
.maxstack 4
.locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stfld ""int C.field""
IL_0029: ldarg.0
IL_002a: call ""object..ctor()""
IL_002f: nop
IL_0030: ret
}
");
diff1.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x""
IL_0006: ldc.i4.1
IL_0007: sub
IL_0008: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C.<>c__DisplayClass3_0: {x, <.ctor>b__0}",
"C: {<>c__DisplayClass3_0}");
diff2.VerifyIL("C..ctor", @"
{
// Code size 49 (0x31)
.maxstack 4
.locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stfld ""int C.field""
IL_0029: ldarg.0
IL_002a: call ""object..ctor()""
IL_002f: nop
IL_0030: ret
}
");
diff2.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
}
[Fact]
public void OutVar_InQuery()
{
var source0 = MarkedSource(@"
using System.Linq;
public class Program
{
static int M(int x, out int y) { y = 42; return 43; }
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select M(a, out int <N:2>x</N:2>) + x + M(a, out int <N:3>y</N:3></N:1>)</N:0>;
}
}");
var source1 = MarkedSource(@"
using System.Linq;
public class Program
{
static int M(int x, out int y) { y = 42; return 43; }
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select M(a, out int <N:2>x</N:2>) + x</N:1></N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var n0 = compilation0.GetMember<MethodSymbol>("Program.N");
var n1 = compilation1.GetMember<MethodSymbol>("Program.N");
var n2 = compilation2.GetMember<MethodSymbol>("Program.N");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
v0.VerifyIL("Program.<>c.<N>b__1_0(int)", @"
{
// Code size 20 (0x14)
.maxstack 3
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.1
IL_0001: ldloca.s V_0
IL_0003: call ""int Program.M(int, out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldarg.1
IL_000b: ldloca.s V_1
IL_000d: call ""int Program.M(int, out int)""
IL_0012: add
IL_0013: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"Program: {<>c}",
"Program.<>c: {<>9__1_0, <N>b__1_0}");
diff1.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff1.VerifyIL("Program.<>c.<N>b__1_0(int)", @"
{
// Code size 11 (0xb)
.maxstack 2
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.1
IL_0001: ldloca.s V_0
IL_0003: call ""int Program.M(int, out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"Program: {<>c}",
"Program.<>c: {<>9__1_0, <N>b__1_0}");
diff2.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff2.VerifyIL("Program.<>c.<N>b__1_0(int)", @"
{
// Code size 20 (0x14)
.maxstack 3
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.1
IL_0001: ldloca.s V_0
IL_0003: call ""int Program.M(int, out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldarg.1
IL_000b: ldloca.s V_2
IL_000d: call ""int Program.M(int, out int)""
IL_0012: add
IL_0013: ret
}
");
}
[Fact]
public void OutVar_InQuery_WithLambda()
{
var source0 = MarkedSource(@"
using System.Linq;
public class Program
{
static int M(int x, out int y) { y = 42; return 43; }
static int M2(System.Func<int> x) => throw null;
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select <N:2>M(a, out int <N:3>x</N:3>) + M2(<N:4>() => x + 1</N:4>)</N:2></N:1></N:0>;
}
}");
var source1 = MarkedSource(@"
using System.Linq;
public class Program
{
static int M(int x, out int y) { y = 42; return 43; }
static int M2(System.Func<int> x) => throw null;
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select <N:2>M(a, out int <N:3>x</N:3>) + M2(<N:4>() => x - 1</N:4>)</N:2></N:1></N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var n0 = compilation0.GetMember<MethodSymbol>("Program.N");
var n1 = compilation1.GetMember<MethodSymbol>("Program.N");
var n2 = compilation2.GetMember<MethodSymbol>("Program.N");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
v0.VerifyIL("Program.<>c.<N>b__2_0(int)", @"
{
// Code size 37 (0x25)
.maxstack 3
.locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.1
IL_0007: ldloc.0
IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x""
IL_000d: call ""int Program.M(int, out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int Program.M2(System.Func<int>)""
IL_0023: add
IL_0024: ret
}
");
v0.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"Program: {<>c__DisplayClass2_0, <>c}",
"Program.<>c__DisplayClass2_0: {x, <N>b__1}",
"Program.<>c: {<>9__2_0, <N>b__2_0}");
diff1.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff1.VerifyIL("Program.<>c.<N>b__2_0(int)", @"
{
// Code size 37 (0x25)
.maxstack 3
.locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.1
IL_0007: ldloc.0
IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x""
IL_000d: call ""int Program.M(int, out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int Program.M2(System.Func<int>)""
IL_0023: add
IL_0024: ret
}
");
diff1.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x""
IL_0006: ldc.i4.1
IL_0007: sub
IL_0008: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"Program.<>c__DisplayClass2_0: {x, <N>b__1}",
"Program: {<>c__DisplayClass2_0, <>c}",
"Program.<>c: {<>9__2_0, <N>b__2_0}");
diff2.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff2.VerifyIL("Program.<>c.<N>b__2_0(int)", @"
{
// Code size 37 (0x25)
.maxstack 3
.locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.1
IL_0007: ldloc.0
IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x""
IL_000d: call ""int Program.M(int, out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int Program.M2(System.Func<int>)""
IL_0023: add
IL_0024: ret
}
");
diff2.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
}
[Fact]
public void OutVar_InSwitchExpression()
{
var source0 = MarkedSource(@"
public class Program
{
static object G(int i)
{
return i switch
{
0 => 0,
_ => 1
};
}
static object N(out int x) { x = 1; return null; }
}");
var source1 = MarkedSource(@"
public class Program
{
static object G(int i)
{
return i + N(out var x) switch
{
0 => 0,
_ => 1
};
}
static int N(out int x) { x = 1; return 0; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var n0 = compilation0.GetMember<MethodSymbol>("Program.G");
var n1 = compilation1.GetMember<MethodSymbol>("Program.G");
var n2 = compilation2.GetMember<MethodSymbol>("Program.G");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("Program.G(int)", @"
{
// Code size 33 (0x21)
.maxstack 1
.locals init (int V_0,
object V_1)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: brtrue.s IL_0005
IL_0004: nop
IL_0005: ldarg.0
IL_0006: brfalse.s IL_000a
IL_0008: br.s IL_000e
IL_000a: ldc.i4.0
IL_000b: stloc.0
IL_000c: br.s IL_0012
IL_000e: ldc.i4.1
IL_000f: stloc.0
IL_0010: br.s IL_0012
IL_0012: ldc.i4.1
IL_0013: brtrue.s IL_0016
IL_0015: nop
IL_0016: ldloc.0
IL_0017: box ""int""
IL_001c: stloc.1
IL_001d: br.s IL_001f
IL_001f: ldloc.1
IL_0020: ret
}
");
v0.VerifyIL("Program.N(out int)", @"
{
// Code size 10 (0xa)
.maxstack 2
.locals init (object V_0)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldc.i4.1
IL_0003: stind.i4
IL_0004: ldnull
IL_0005: stloc.0
IL_0006: br.s IL_0008
IL_0008: ldloc.0
IL_0009: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers();
diff1.VerifyIL("Program.G(int)", @"
{
// Code size 52 (0x34)
.maxstack 2
.locals init ([int] V_0,
[object] V_1,
int V_2, //x
int V_3,
int V_4,
int V_5,
object V_6)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.3
IL_0003: ldloca.s V_2
IL_0005: call ""int Program.N(out int)""
IL_000a: stloc.s V_5
IL_000c: ldc.i4.1
IL_000d: brtrue.s IL_0010
IL_000f: nop
IL_0010: ldloc.s V_5
IL_0012: brfalse.s IL_0016
IL_0014: br.s IL_001b
IL_0016: ldc.i4.0
IL_0017: stloc.s V_4
IL_0019: br.s IL_0020
IL_001b: ldc.i4.1
IL_001c: stloc.s V_4
IL_001e: br.s IL_0020
IL_0020: ldc.i4.1
IL_0021: brtrue.s IL_0024
IL_0023: nop
IL_0024: ldloc.3
IL_0025: ldloc.s V_4
IL_0027: add
IL_0028: box ""int""
IL_002d: stloc.s V_6
IL_002f: br.s IL_0031
IL_0031: ldloc.s V_6
IL_0033: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers();
diff2.VerifyIL("Program.G(int)", @"
{
// Code size 38 (0x26)
.maxstack 1
.locals init ([int] V_0,
[object] V_1,
[int] V_2,
[int] V_3,
[int] V_4,
[int] V_5,
[object] V_6,
int V_7,
object V_8)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: brtrue.s IL_0005
IL_0004: nop
IL_0005: ldarg.0
IL_0006: brfalse.s IL_000a
IL_0008: br.s IL_000f
IL_000a: ldc.i4.0
IL_000b: stloc.s V_7
IL_000d: br.s IL_0014
IL_000f: ldc.i4.1
IL_0010: stloc.s V_7
IL_0012: br.s IL_0014
IL_0014: ldc.i4.1
IL_0015: brtrue.s IL_0018
IL_0017: nop
IL_0018: ldloc.s V_7
IL_001a: box ""int""
IL_001f: stloc.s V_8
IL_0021: br.s IL_0023
IL_0023: ldloc.s V_8
IL_0025: ret
}
");
}
[Fact]
public void AddUsing_AmbiguousCode()
{
var source0 = MarkedSource(@"
using System.Threading;
class C
{
static void E()
{
var t = new Timer(s => System.Console.WriteLine(s));
}
}");
var source1 = MarkedSource(@"
using System.Threading;
using System.Timers;
class C
{
static void E()
{
var t = new Timer(s => System.Console.WriteLine(s));
}
static void G()
{
System.Console.WriteLine(new TimersDescriptionAttribute(""""));
}
}");
var compilation0 = CreateCompilation(source0.Tree, targetFramework: TargetFramework.NetStandard20, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var e0 = compilation0.GetMember<MethodSymbol>("C.E");
var e1 = compilation1.GetMember<MethodSymbol>("C.E");
var g1 = compilation1.GetMember<MethodSymbol>("C.G");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
// Pretend there was an update to C.E to ensure we haven't invalidated the test
var diffError = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diffError.EmitResult.Diagnostics.Verify(
// (9,21): error CS0104: 'Timer' is an ambiguous reference between 'System.Threading.Timer' and 'System.Timers.Timer'
// var t = new Timer(s => System.Console.WriteLine(s));
Diagnostic(ErrorCode.ERR_AmbigContext, "Timer").WithArguments("Timer", "System.Threading.Timer", "System.Timers.Timer").WithLocation(9, 21));
// Semantic errors are reported only for the bodies of members being emitted so we shouldn't see any
var diff = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, g1)));
diff.EmitResult.Diagnostics.Verify();
diff.VerifyIL(@"C.G", @"
{
// Code size 18 (0x12)
.maxstack 1
IL_0000: nop
IL_0001: ldstr """"
IL_0006: newobj ""System.Timers.TimersDescriptionAttribute..ctor(string)""
IL_000b: call ""void System.Console.WriteLine(object)""
IL_0010: nop
IL_0011: ret
}
");
}
[Fact]
public void Records_AddWellKnownMember()
{
var source0 =
@"
#nullable enable
namespace N
{
record R(int X)
{
}
}
";
var source1 =
@"
#nullable enable
namespace N
{
record R(int X)
{
protected virtual bool PrintMembers(System.Text.StringBuilder builder)
{
return true;
}
}
}
";
var compilation0 = CreateCompilation(new[] { source0, IsExternalInitTypeDefinition }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(new[] { source1, IsExternalInitTypeDefinition });
var printMembers0 = compilation0.GetMember<MethodSymbol>("N.R.PrintMembers");
var printMembers1 = compilation1.GetMember<MethodSymbol>("N.R.PrintMembers");
var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped);
using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
// Verify full metadata contains expected rows.
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "EmbeddedAttribute", "NullableAttribute", "NullableContextAttribute", "IsExternalInit", "R");
CheckNames(reader0, reader0.GetMethodDefNames(),
/* EmbeddedAttribute */".ctor",
/* NullableAttribute */ ".ctor",
/* NullableContextAttribute */".ctor",
/* IsExternalInit */".ctor",
/* R: */
".ctor",
"get_EqualityContract",
"get_X",
"set_X",
"ToString",
"PrintMembers",
"op_Inequality",
"op_Equality",
"GetHashCode",
"Equals",
"Equals",
"<Clone>$",
".ctor",
"Deconstruct");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, printMembers0, printMembers1)));
diff1.VerifySynthesizedMembers(
"<global namespace>: {Microsoft}",
"Microsoft: {CodeAnalysis}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}");
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "PrintMembers");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(21, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(22, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default)); // R.PrintMembers
CheckEncMap(reader1,
Handle(20, TableIndex.TypeRef),
Handle(21, TableIndex.TypeRef),
Handle(22, TableIndex.TypeRef),
Handle(10, TableIndex.MethodDef),
Handle(3, TableIndex.StandAloneSig),
Handle(4, TableIndex.TypeSpec),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void Records_RemoveWellKnownMember()
{
var source0 =
@"
namespace N
{
record R(int X)
{
protected virtual bool PrintMembers(System.Text.StringBuilder builder)
{
return true;
}
}
}
";
var source1 =
@"
namespace N
{
record R(int X)
{
}
}
";
var compilation0 = CreateCompilation(new[] { source0, IsExternalInitTypeDefinition }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(new[] { source1, IsExternalInitTypeDefinition });
var method0 = compilation0.GetMember<MethodSymbol>("N.R.PrintMembers");
var method1 = compilation1.GetMember<MethodSymbol>("N.R.PrintMembers");
var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped);
using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
diff1.VerifySynthesizedMembers(
"<global namespace>: {Microsoft}",
"Microsoft: {CodeAnalysis}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}");
}
[Fact]
public void TopLevelStatement_Update()
{
var source0 = @"
using System;
Console.WriteLine(""Hello"");
";
var source1 = @"
using System;
Console.WriteLine(""Hello World"");
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe);
var compilation1 = compilation0.WithSource(source1);
var method0 = compilation0.GetMember<MethodSymbol>("<Program>$.<Main>$");
var method1 = compilation1.GetMember<MethodSymbol>("<Program>$.<Main>$");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<Program>$");
CheckNames(reader0, reader0.GetMethodDefNames(), "<Main>$");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*Console.*/"WriteLine");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "<Main>$");
CheckNames(readers, reader1.GetMemberRefNames(), /*CompilerGenerated*/".ctor", /*Console.*/"WriteLine");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default)); // Synthesized Main method
CheckEncMap(reader1,
Handle(8, TableIndex.TypeRef),
Handle(9, TableIndex.TypeRef),
Handle(10, TableIndex.TypeRef),
Handle(1, TableIndex.MethodDef),
Handle(6, TableIndex.MemberRef),
Handle(7, TableIndex.MemberRef),
Handle(2, TableIndex.AssemblyRef));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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 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
{
/// <summary>
/// Tip: debug EncVariableSlotAllocator.TryGetPreviousClosure or other TryGet methods to figure out missing markers in your test.
/// </summary>
public class EditAndContinueTests : EditAndContinueTestBase
{
private static IEnumerable<string> DumpTypeRefs(MetadataReader[] readers)
{
var currentGenerationReader = readers.Last();
foreach (var typeRefHandle in currentGenerationReader.TypeReferences)
{
var typeRef = currentGenerationReader.GetTypeReference(typeRefHandle);
yield return $"[0x{MetadataTokens.GetToken(typeRef.ResolutionScope):x8}] {readers.GetString(typeRef.Namespace)}.{readers.GetString(typeRef.Name)}";
}
}
[Fact]
public void DeltaHeapsStartWithEmptyItem()
{
var source0 =
@"class C
{
static string F() { return null; }
}";
var source1 =
@"class C
{
static string F() { return ""a""; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var diff1 = compilation1.EmitDifference(
EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider),
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var s = MetadataTokens.StringHandle(0);
Assert.Equal("", reader1.GetString(s));
var b = MetadataTokens.BlobHandle(0);
Assert.Equal(0, reader1.GetBlobBytes(b).Length);
var us = MetadataTokens.UserStringHandle(0);
Assert.Equal("", reader1.GetUserString(us));
}
[Fact]
public void Delta_AssemblyDefTable()
{
var source0 = @"public class C { public static void F() { System.Console.WriteLine(1); } }";
var source1 = @"public class C { public static void F() { System.Console.WriteLine(2); } }";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
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.Update, f0, f1, preserveLocalVariables: true)));
// AssemblyDef record is not emitted to delta since changes in assembly identity are not allowed:
Assert.True(md0.MetadataReader.IsAssembly);
Assert.False(diff1.GetMetadata().Reader.IsAssembly);
}
[Fact]
public void SemanticErrors_MethodBody()
{
var source0 = MarkedSource(@"
class C
{
static void E()
{
int x = 1;
System.Console.WriteLine(x);
}
static void G()
{
System.Console.WriteLine(1);
}
}");
var source1 = MarkedSource(@"
class C
{
static void E()
{
int x = Unknown(2);
System.Console.WriteLine(x);
}
static void G()
{
System.Console.WriteLine(2);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var e0 = compilation0.GetMember<MethodSymbol>("C.E");
var e1 = compilation1.GetMember<MethodSymbol>("C.E");
var g0 = compilation0.GetMember<MethodSymbol>("C.G");
var g1 = compilation1.GetMember<MethodSymbol>("C.G");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
// Semantic errors are reported only for the bodies of members being emitted.
var diffError = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diffError.EmitResult.Diagnostics.Verify(
// (6,17): error CS0103: The name 'Unknown' does not exist in the current context
// int x = Unknown(2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "Unknown").WithArguments("Unknown").WithLocation(6, 17));
var diffGood = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diffGood.EmitResult.Diagnostics.Verify();
diffGood.VerifyIL(@"C.G", @"
{
// Code size 9 (0x9)
.maxstack 1
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: call ""void System.Console.WriteLine(int)""
IL_0007: nop
IL_0008: ret
}
");
}
[Fact]
public void SemanticErrors_Declaration()
{
var source0 = MarkedSource(@"
class C
{
static void G()
{
System.Console.WriteLine(1);
}
}
");
var source1 = MarkedSource(@"
class C
{
static void G()
{
System.Console.WriteLine(2);
}
}
class Bad : Bad
{
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var g0 = compilation0.GetMember<MethodSymbol>("C.G");
var g1 = compilation1.GetMember<MethodSymbol>("C.G");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// All declaration errors are reported regardless of what member do we emit.
diff.EmitResult.Diagnostics.Verify(
// (10,7): error CS0146: Circular base type dependency involving 'Bad' and 'Bad'
// class Bad : Bad
Diagnostic(ErrorCode.ERR_CircularBase, "Bad").WithArguments("Bad", "Bad").WithLocation(10, 7));
}
[Fact]
public void ModifyMethod()
{
var source0 =
@"class C
{
static void Main() { }
static string F() { return null; }
}";
var source1 =
@"class C
{
static void Main() { }
static string F() { return string.Empty; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe);
var compilation1 = compilation0.WithSource(source1);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*String.*/"Empty");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(7, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
}
[CompilerTrait(CompilerFeature.Tuples)]
[Fact]
public void ModifyMethod_WithTuples()
{
var source0 =
@"class C
{
static void Main() { }
static (int, int) F() { return (1, 2); }
}";
var source1 =
@"class C
{
static void Main() { }
static (int, int) F() { return (2, 3); }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*System.ValueTuple.*/".ctor");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F
CheckEncMap(reader1,
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(6, TableIndex.MemberRef),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.TypeSpec),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyMethod_WithAttributes1()
{
var source0 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return null; }
}";
var source1 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return string.Empty; }
}";
var source2 =
@"[System.ComponentModel.Browsable(false)]
class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method""), System.ComponentModel.Category(""Methods"")]
static string F() { return string.Empty; }
}";
var source3 =
@"[System.ComponentModel.Browsable(false)]
class C
{
static void Main() { }
[System.ComponentModel.Browsable(false), System.ComponentModel.Description(""The F method""), System.ComponentModel.Category(""Methods"")]
static string F() { return string.Empty; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor");
Assert.Equal(4, reader0.CustomAttributes.Count);
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty");
Assert.Equal(1, reader1.CustomAttributes.Count);
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute
CheckEncMap(reader1,
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(9, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(6, TableIndex.MemberRef),
Handle(7, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
var method2 = compilation2.GetMember<MethodSymbol>("C.F");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember("C"), compilation2.GetMember("C")),
SemanticEdit.Create(SemanticEditKind.Update, method1, method2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, reader2.GetTypeDefNames(), "C");
CheckNames(readers, reader2.GetMethodDefNames(), "F");
CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*BrowsableAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*String.*/"Empty");
Assert.Equal(3, reader2.CustomAttributes.Count);
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(10, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(11, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(14, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 4, updating the existing custom attribute
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 5, adding a new CustomAttribute
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 6 adding a new CustomAttribute
CheckEncMap(reader2,
Handle(10, TableIndex.TypeRef),
Handle(11, TableIndex.TypeRef),
Handle(12, TableIndex.TypeRef),
Handle(13, TableIndex.TypeRef),
Handle(14, TableIndex.TypeRef),
Handle(2, TableIndex.TypeDef),
Handle(2, TableIndex.MethodDef),
Handle(8, TableIndex.MemberRef),
Handle(9, TableIndex.MemberRef),
Handle(10, TableIndex.MemberRef),
Handle(11, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute),
Handle(6, TableIndex.CustomAttribute),
Handle(3, TableIndex.StandAloneSig),
Handle(3, TableIndex.AssemblyRef));
var method3 = compilation3.GetMember<MethodSymbol>("C.F");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3)));
// Verify delta metadata contains expected rows.
using var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
readers = new[] { reader0, reader1, reader2, reader3 };
CheckNames(readers, reader3.GetTypeDefNames());
CheckNames(readers, reader3.GetMethodDefNames(), "F");
CheckNames(readers, reader3.GetMemberRefNames(), /*BrowsableAttribute*/".ctor", /*DescriptionAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*String.*/"Empty");
CheckEncLog(reader3,
Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(12, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(13, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(14, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(15, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 4, updating the existing custom attribute
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 5, updating a row that was new in Generation 2
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 7, adding a new CustomAttribute, and skipping row 6 which is not for the method being emitted
CheckEncMap(reader3,
Handle(15, TableIndex.TypeRef),
Handle(16, TableIndex.TypeRef),
Handle(17, TableIndex.TypeRef),
Handle(18, TableIndex.TypeRef),
Handle(19, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(12, TableIndex.MemberRef),
Handle(13, TableIndex.MemberRef),
Handle(14, TableIndex.MemberRef),
Handle(15, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute),
Handle(7, TableIndex.CustomAttribute),
Handle(4, TableIndex.StandAloneSig),
Handle(4, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyMethod_WithAttributes2()
{
var source0 =
@"[System.ComponentModel.Browsable(false)]
class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return null; }
}
[System.ComponentModel.Browsable(false)]
class D
{
[System.ComponentModel.Description(""A"")]
static string A() { return null; }
}
";
var source1 =
@"
[System.ComponentModel.Browsable(false)]
class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method""), System.ComponentModel.Browsable(false), System.ComponentModel.Category(""Methods"")]
static string F() { return null; }
}
[System.ComponentModel.Browsable(false)]
class D
{
[System.ComponentModel.Description(""A""), System.ComponentModel.Category(""Methods"")]
static string A() { return null; }
}
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var method0_1 = compilation0.GetMember<MethodSymbol>("C.F");
var method0_2 = compilation0.GetMember<MethodSymbol>("D.A");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "D");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor", "A", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor", /*BrowsableAttribute*/".ctor");
CheckAttributes(reader0,
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.TypeDef), Handle(4, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(3, TableIndex.TypeDef), Handle(4, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef)));
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1_1 = compilation1.GetMember<MethodSymbol>("C.F");
var method1_2 = compilation1.GetMember<MethodSymbol>("D.A");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method0_1, method1_1),
SemanticEdit.Create(SemanticEditKind.Update, method0_2, method1_2)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F", "A");
CheckNames(readers, reader1.GetMemberRefNames(), /*BrowsableAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*DescriptionAttribute*/".ctor");
CheckAttributes(reader1,
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(9, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(9, TableIndex.MemberRef)));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // update existing row
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // add new row
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // add new row
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // update existing row
Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // add new row
CheckEncMap(reader1,
Handle(8, TableIndex.TypeRef),
Handle(9, TableIndex.TypeRef),
Handle(10, TableIndex.TypeRef),
Handle(11, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(9, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(7, TableIndex.CustomAttribute),
Handle(8, TableIndex.CustomAttribute),
Handle(9, TableIndex.CustomAttribute),
Handle(10, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyMethod_DeleteAttributes1()
{
var source0 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return null; }
}";
var source1 =
@"class C
{
static void Main() { }
static string F() { return string.Empty; }
}";
var source2 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return string.Empty; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor");
CheckAttributes(reader0,
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)));
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*String.*/"Empty");
CheckAttributes(reader1,
new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // Parent row id is 0, signifying a delete
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute
CheckEncMap(reader1,
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(6, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
var method2 = compilation2.GetMember<MethodSymbol>("C.F");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
EncValidation.VerifyModuleMvid(2, reader1, reader2);
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetMethodDefNames(), "F");
CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty");
CheckAttributes(reader2,
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef)));
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, updating the original row back to a real one
CheckEncMap(reader2,
Handle(9, TableIndex.TypeRef),
Handle(10, TableIndex.TypeRef),
Handle(11, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(3, TableIndex.StandAloneSig),
Handle(3, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyMethod_DeleteAttributes2()
{
var source0 =
@"class C
{
static void Main() { }
static string F() { return null; }
}";
var source1 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return string.Empty; }
}";
var source2 = source0; // Remove the attribute we just added
var source3 = source1; // Add the attribute back again
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation1.WithSource(source3);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor");
CheckAttributes(reader0,
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)));
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty");
CheckAttributes(reader1,
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef)));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so adding a new CustomAttribute
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(6, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
var method2 = compilation2.GetMember<MethodSymbol>("C.F");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method1, method2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetMethodDefNames(), "F");
CheckNames(readers, reader2.GetMemberRefNames());
CheckAttributes(reader2,
new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // 0, delete
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute
CheckEncMap(reader2,
Handle(9, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(4, TableIndex.CustomAttribute),
Handle(3, TableIndex.StandAloneSig),
Handle(3, TableIndex.AssemblyRef));
var method3 = compilation3.GetMember<MethodSymbol>("C.F");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method2, method3)));
// Verify delta metadata contains expected rows.
using var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
readers = new[] { reader0, reader1, reader2, reader3 };
CheckNames(readers, reader3.GetTypeDefNames());
CheckNames(readers, reader3.GetMethodDefNames(), "F");
CheckNames(readers, reader3.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty");
CheckAttributes(reader3,
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef)));
CheckEncLog(reader3,
Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, update the previously deleted row
CheckEncMap(reader3,
Handle(10, TableIndex.TypeRef),
Handle(11, TableIndex.TypeRef),
Handle(12, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(4, TableIndex.StandAloneSig),
Handle(4, TableIndex.AssemblyRef));
}
[WorkItem(962219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/962219")]
[Fact]
public void PartialMethod()
{
var source =
@"partial class C
{
static partial void M1();
static partial void M2();
static partial void M3();
static partial void M1() { }
static partial void M2() { }
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetMethodDefNames(), "M1", "M2", ".ctor");
var method0 = compilation0.GetMember<MethodSymbol>("C.M2").PartialImplementationPart;
var method1 = compilation1.GetMember<MethodSymbol>("C.M2").PartialImplementationPart;
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
var methods = diff1.TestData.GetMethodsByName();
Assert.Equal(1, methods.Count);
Assert.True(methods.ContainsKey("C.M2()"));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetMethodDefNames(), "M2");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void Method_WithAttributes_Add()
{
var source0 =
@"class C
{
static void Main() { }
}";
var source1 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return string.Empty; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor");
Assert.Equal(3, reader0.CustomAttributes.Count);
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty");
Assert.Equal(1, reader1.CustomAttributes.Count);
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, a new attribute
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(3, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(6, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(1, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
}
/// <summary>
/// Add a method that requires entries in the ParameterDefs table.
/// Specifically, normal parameters or return types with attributes.
/// Add the method in the first edit, then modify the method in the second.
/// </summary>
[Fact]
public void Method_WithParameterAttributes_AddThenUpdate()
{
var source0 =
@"class A : System.Attribute { }
class C
{
}";
var source1 =
@"class A : System.Attribute { }
class C
{
[return:A]static object F(int arg = 1) => arg;
}";
var source2 =
@"class A : System.Attribute { }
class C
{
[return:A]static object F(int arg = 1) => null;
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation0.WithSource(source2);
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
// gen 1
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, f1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetParameterDefNames(), "", "arg");
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckNames(readers, diff1.EmitResult.UpdatedMethods);
CheckEncLogDefinitions(reader1,
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(1, TableIndex.Constant, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(3, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(2, TableIndex.Param),
Handle(1, TableIndex.Constant),
Handle(4, TableIndex.CustomAttribute));
// gen 2
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
EncValidation.VerifyModuleMvid(2, reader1, reader2);
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetMethodDefNames(), "F");
CheckNames(readers, reader2.GetParameterDefNames());
CheckNames(readers, diff2.EmitResult.ChangedTypes, "C");
CheckNames(readers, diff2.EmitResult.UpdatedMethods, "F");
CheckEncLogDefinitions(reader2,
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F
CheckEncMapDefinitions(reader2,
Handle(3, TableIndex.MethodDef));
}
[Fact]
public void Method_WithEmbeddedAttributes_AndThenUpdate()
{
var source0 =
@"
namespace System.Runtime.CompilerServices { class X { } }
namespace N
{
class C
{
static void Main() { }
}
}
";
var source1 =
@"
namespace System.Runtime.CompilerServices { class X { } }
namespace N
{
struct C
{
static void Main()
{
Id(in G());
}
static ref readonly int Id(in int x) => ref x;
static ref readonly int G() => ref new int[1] { 1 }[0];
}
}";
var source2 =
@"
namespace System.Runtime.CompilerServices { class X { } }
namespace N
{
struct C
{
static void Main() { Id(in G()); }
static ref readonly int Id(in int x) => ref x;
static ref readonly int G() => ref new int[1] { 2 }[0];
static void H(string? s) {}
}
}";
var source3 =
@"
namespace System.Runtime.CompilerServices { class X { } }
namespace N
{
struct C
{
static void Main() { Id(in G()); }
static ref readonly int Id(in int x) => ref x;
static ref readonly int G() => ref new int[1] { 2 }[0];
static void H(string? s) {}
readonly ref readonly string?[]? F() => throw null;
}
}";
var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var main0 = compilation0.GetMember<MethodSymbol>("N.C.Main");
var main1 = compilation1.GetMember<MethodSymbol>("N.C.Main");
var id1 = compilation1.GetMember<MethodSymbol>("N.C.Id");
var g1 = compilation1.GetMember<MethodSymbol>("N.C.G");
var g2 = compilation2.GetMember<MethodSymbol>("N.C.G");
var h2 = compilation2.GetMember<MethodSymbol>("N.C.H");
var f3 = compilation3.GetMember<MethodSymbol>("N.C.F");
// Verify full metadata contains expected rows.
using var md0 = ModuleMetadata.CreateFromImage(compilation0.EmitToArray());
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, main0, main1),
SemanticEdit.Create(SemanticEditKind.Insert, null, id1),
SemanticEdit.Create(SemanticEditKind.Insert, null, g1)));
diff1.VerifySynthesizedMembers(
"<global namespace>: {Microsoft}",
"Microsoft: {CodeAnalysis}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"System.Runtime.CompilerServices: {IsReadOnlyAttribute}");
diff1.VerifyIL("N.C.Main", @"
{
// Code size 13 (0xd)
.maxstack 1
IL_0000: nop
IL_0001: call ""ref readonly int N.C.G()""
IL_0006: call ""ref readonly int N.C.Id(in int)""
IL_000b: pop
IL_000c: ret
}
");
diff1.VerifyIL("N.C.Id", @"
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}
");
diff1.VerifyIL("N.C.G", @"
{
// Code size 17 (0x11)
.maxstack 4
IL_0000: ldc.i4.1
IL_0001: newarr ""int""
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldc.i4.1
IL_0009: stelem.i4
IL_000a: ldc.i4.0
IL_000b: ldelema ""int""
IL_0010: ret
}
");
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader0 = md0.MetadataReader;
var reader1 = md1.Reader;
var readers = new List<MetadataReader>() { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefFullNames(), "Microsoft.CodeAnalysis.EmbeddedAttribute", "System.Runtime.CompilerServices.IsReadOnlyAttribute");
CheckNames(readers, reader1.GetMethodDefNames(), "Main", ".ctor", ".ctor", "Id", "G");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, g1, g2),
SemanticEdit.Create(SemanticEditKind.Insert, null, h2)));
// synthesized member for nullable annotations added:
diff2.VerifySynthesizedMembers(
"<global namespace>: {Microsoft}",
"Microsoft: {CodeAnalysis}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"System.Runtime.CompilerServices: {IsReadOnlyAttribute, NullableAttribute, NullableContextAttribute}");
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
// note: NullableAttribute has 2 ctors, NullableContextAttribute has one
CheckNames(readers, reader2.GetTypeDefFullNames(), "System.Runtime.CompilerServices.NullableAttribute", "System.Runtime.CompilerServices.NullableContextAttribute");
CheckNames(readers, reader2.GetMethodDefNames(), "G", ".ctor", ".ctor", ".ctor", "H");
// two new TypeDefs emitted for the attributes:
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(14, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeDef, EditAndContinueOperation.Default), // NullableAttribute
Row(7, TableIndex.TypeDef, EditAndContinueOperation.Default), // NullableContextAttribute
Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(2, TableIndex.Field, EditAndContinueOperation.Default),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(11, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMap(reader2,
Handle(11, TableIndex.TypeRef),
Handle(12, TableIndex.TypeRef),
Handle(13, TableIndex.TypeRef),
Handle(14, TableIndex.TypeRef),
Handle(15, TableIndex.TypeRef),
Handle(16, TableIndex.TypeRef),
Handle(17, TableIndex.TypeRef),
Handle(18, TableIndex.TypeRef),
Handle(6, TableIndex.TypeDef),
Handle(7, TableIndex.TypeDef),
Handle(1, TableIndex.Field),
Handle(2, TableIndex.Field),
Handle(7, TableIndex.MethodDef),
Handle(8, TableIndex.MethodDef),
Handle(9, TableIndex.MethodDef),
Handle(10, TableIndex.MethodDef),
Handle(11, TableIndex.MethodDef),
Handle(4, TableIndex.Param),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(9, TableIndex.MemberRef),
Handle(11, TableIndex.CustomAttribute),
Handle(12, TableIndex.CustomAttribute),
Handle(13, TableIndex.CustomAttribute),
Handle(14, TableIndex.CustomAttribute),
Handle(15, TableIndex.CustomAttribute),
Handle(16, TableIndex.CustomAttribute),
Handle(17, TableIndex.CustomAttribute),
Handle(3, TableIndex.AssemblyRef));
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, f3)));
// no change in synthesized members:
diff3.VerifySynthesizedMembers(
"<global namespace>: {Microsoft}",
"Microsoft: {CodeAnalysis}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"System.Runtime.CompilerServices: {IsReadOnlyAttribute, NullableAttribute, NullableContextAttribute}");
// Verify delta metadata contains expected rows.
using var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
readers.Add(reader3);
// no new type defs:
CheckNames(readers, reader3.GetTypeDefFullNames());
CheckNames(readers, reader3.GetMethodDefNames(), "F");
CheckEncLog(reader3,
Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void Field_Add()
{
var source0 =
@"class C
{
string F = ""F"";
}";
var source1 =
@"class C
{
string F = ""F"";
string G = ""G"";
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetFieldDefNames(), "F");
CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var method1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<FieldSymbol>("C.G")),
SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetFieldDefNames(), "G");
CheckNames(readers, reader1.GetMethodDefNames(), ".ctor");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(2, TableIndex.Field, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(2, TableIndex.Field),
Handle(1, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void Property_Accessor_Update()
{
var source0 =
@"class C
{
object P { get { return 1; } }
}";
var source1 =
@"class C
{
object P { get { return 2; } }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var getP0 = compilation0.GetMember<MethodSymbol>("C.get_P");
var getP1 = compilation1.GetMember<MethodSymbol>("C.get_P");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetPropertyDefNames(), "P");
CheckNames(reader0, reader0.GetMethodDefNames(), "get_P", ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, getP0, getP1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetPropertyDefNames(), "P");
CheckNames(readers, reader1.GetMethodDefNames(), "get_P");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Property, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(1, TableIndex.MethodDef),
Handle(2, TableIndex.StandAloneSig),
Handle(1, TableIndex.Property),
Handle(2, TableIndex.MethodSemantics),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void Property_Add()
{
var source0 = @"
class C
{
}
";
var source1 = @"
class C
{
object R { get { return null; } }
}
";
var source2 = @"
class C
{
object R { get { return null; } }
object Q { get; set; }
}
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation0.WithSource(source2);
var r1 = compilation1.GetMember<PropertySymbol>("C.R");
var q2 = compilation2.GetMember<PropertySymbol>("C.Q");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
// gen 1
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, r1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetFieldDefNames());
CheckNames(readers, reader1.GetPropertyDefNames(), "R");
CheckNames(readers, reader1.GetMethodDefNames(), "get_R");
CheckNames(readers, diff1.EmitResult.UpdatedMethods);
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
Row(1, TableIndex.Property, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(2, TableIndex.MethodDef),
Handle(1, TableIndex.StandAloneSig),
Handle(1, TableIndex.PropertyMap),
Handle(1, TableIndex.Property),
Handle(1, TableIndex.MethodSemantics));
// gen 2
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, q2)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetFieldDefNames(), "<Q>k__BackingField");
CheckNames(readers, reader2.GetPropertyDefNames(), "Q");
CheckNames(readers, reader2.GetMethodDefNames(), "get_Q", "set_Q");
CheckNames(readers, diff1.EmitResult.UpdatedMethods);
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckEncLogDefinitions(reader2,
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
Row(2, TableIndex.Property, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader2,
Handle(1, TableIndex.Field),
Handle(3, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute),
Handle(6, TableIndex.CustomAttribute),
Handle(7, TableIndex.CustomAttribute),
Handle(2, TableIndex.Property),
Handle(2, TableIndex.MethodSemantics),
Handle(3, TableIndex.MethodSemantics));
}
[Fact]
public void Event_Add()
{
var source0 = @"
class C
{
}";
var source1 = @"
class C
{
event System.Action E;
}";
var source2 = @"
class C
{
event System.Action E;
event System.Action G;
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation0.WithSource(source2);
var e1 = compilation1.GetMember<EventSymbol>("C.E");
var g2 = compilation2.GetMember<EventSymbol>("C.G");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
// gen 1
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, e1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetFieldDefNames(), "E");
CheckNames(readers, reader1.GetMethodDefNames(), "add_E", "remove_E");
CheckNames(readers, diff1.EmitResult.UpdatedMethods);
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.EventMap, EditAndContinueOperation.Default),
Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent),
Row(1, TableIndex.Event, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(1, TableIndex.Field),
Handle(2, TableIndex.MethodDef),
Handle(3, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(2, TableIndex.Param),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute),
Handle(6, TableIndex.CustomAttribute),
Handle(7, TableIndex.CustomAttribute),
Handle(1, TableIndex.StandAloneSig),
Handle(1, TableIndex.EventMap),
Handle(1, TableIndex.Event),
Handle(1, TableIndex.MethodSemantics),
Handle(2, TableIndex.MethodSemantics));
// gen 2
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, g2)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetFieldDefNames(), "G");
CheckNames(readers, reader2.GetMethodDefNames(), "add_G", "remove_G");
CheckNames(readers, diff1.EmitResult.UpdatedMethods);
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckEncLogDefinitions(reader2,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent),
Row(2, TableIndex.Event, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(2, TableIndex.Field, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader2,
Handle(2, TableIndex.Field),
Handle(4, TableIndex.MethodDef),
Handle(5, TableIndex.MethodDef),
Handle(3, TableIndex.Param),
Handle(4, TableIndex.Param),
Handle(8, TableIndex.CustomAttribute),
Handle(9, TableIndex.CustomAttribute),
Handle(10, TableIndex.CustomAttribute),
Handle(11, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.Event),
Handle(3, TableIndex.MethodSemantics),
Handle(4, TableIndex.MethodSemantics));
}
[WorkItem(1175704, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1175704")]
[Fact]
public void EventFields()
{
var source0 = MarkedSource(@"
using System;
class C
{
static event EventHandler handler;
static int F()
{
handler(null, null);
return 1;
}
}
");
var source1 = MarkedSource(@"
using System;
class C
{
static event EventHandler handler;
static int F()
{
handler(null, null);
return 10;
}
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
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.Update, f0, f1, preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 21 (0x15)
.maxstack 3
.locals init (int V_0)
IL_0000: nop
IL_0001: ldsfld ""System.EventHandler C.handler""
IL_0006: ldnull
IL_0007: ldnull
IL_0008: callvirt ""void System.EventHandler.Invoke(object, System.EventArgs)""
IL_000d: nop
IL_000e: ldc.i4.s 10
IL_0010: stloc.0
IL_0011: br.s IL_0013
IL_0013: ldloc.0
IL_0014: ret
}
");
}
[Fact]
public void UpdateType_AddAttributes()
{
var source0 = @"
class C
{
}";
var source1 = @"
[System.ComponentModel.Description(""C"")]
class C
{
}";
var source2 = @"
[System.ComponentModel.Description(""C"")]
[System.ObsoleteAttribute]
class C
{
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var c0 = compilation0.GetMember<NamedTypeSymbol>("C");
var c1 = compilation1.GetMember<NamedTypeSymbol>("C");
var c2 = compilation2.GetMember<NamedTypeSymbol>("C");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
Assert.Equal(3, reader0.CustomAttributes.Count);
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, c0, c1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames(), "C");
Assert.Equal(1, reader1.CustomAttributes.Count);
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(2, TableIndex.TypeDef),
Handle(4, TableIndex.CustomAttribute));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, c1, c2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, reader2.GetTypeDefNames(), "C");
Assert.Equal(2, reader2.CustomAttributes.Count);
CheckEncLogDefinitions(reader2,
Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader2,
Handle(2, TableIndex.TypeDef),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute));
}
[Fact]
public void ReplaceType()
{
var source0 = @"
class C
{
void F(int x) {}
}
";
var source1 = @"
class C
{
void F(int x, int y) { }
}";
var source2 = @"
class C
{
void F(int x, int y) { System.Console.WriteLine(1); }
}";
var source3 = @"
[System.Obsolete]
class C
{
void F(int x, int y) { System.Console.WriteLine(2); }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var c0 = compilation0.GetMember<NamedTypeSymbol>("C");
var c1 = compilation1.GetMember<NamedTypeSymbol>("C");
var c2 = compilation2.GetMember<NamedTypeSymbol>("C");
var c3 = compilation3.GetMember<NamedTypeSymbol>("C");
var f2 = c2.GetMember<MethodSymbol>("F");
var f3 = c3.GetMember<MethodSymbol>("F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
// This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one.
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Replace, null, c1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames(), "C#1");
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C#1");
CheckEncLogDefinitions(reader1,
Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(3, TableIndex.Param, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(3, TableIndex.TypeDef),
Handle(3, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(2, TableIndex.Param),
Handle(3, TableIndex.Param));
// This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one.
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Replace, null, c2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, reader2.GetTypeDefNames(), "C#2");
CheckNames(readers, diff2.EmitResult.ChangedTypes, "C#2");
CheckEncLogDefinitions(reader2,
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(5, TableIndex.Param, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader2,
Handle(4, TableIndex.TypeDef),
Handle(5, TableIndex.MethodDef),
Handle(6, TableIndex.MethodDef),
Handle(4, TableIndex.Param),
Handle(5, TableIndex.Param));
// This update is an EnC update - even reloadable types are update in-place
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, c2, c3),
SemanticEdit.Create(SemanticEditKind.Update, f2, f3)));
// Verify delta metadata contains expected rows.
using var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
readers = new[] { reader0, reader1, reader2, reader3 };
CheckNames(readers, reader3.GetTypeDefNames(), "C#2");
CheckNames(readers, diff3.EmitResult.ChangedTypes, "C#2");
CheckEncLogDefinitions(reader3,
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader3,
Handle(4, TableIndex.TypeDef),
Handle(5, TableIndex.MethodDef),
Handle(4, TableIndex.CustomAttribute));
}
[Fact]
public void AddNestedTypeAndMembers()
{
var source0 =
@"class A
{
class B { }
static object F()
{
return new B();
}
}";
var source1 =
@"class A
{
class B { }
class C
{
class D { }
static object F;
internal static object G()
{
return F;
}
}
static object F()
{
return C.G();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var c1 = compilation1.GetMember<NamedTypeSymbol>("A.C");
var f0 = compilation0.GetMember<MethodSymbol>("A.F");
var f1 = compilation1.GetMember<MethodSymbol>("A.F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B");
CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ".ctor");
Assert.Equal(1, reader0.GetTableRowCount(TableIndex.NestedClass));
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, c1),
SemanticEdit.Create(SemanticEditKind.Update, f0, f1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames(), "C", "D");
CheckNames(readers, reader1.GetMethodDefNames(), "F", "G", ".ctor", ".ctor");
CheckNames(readers, diff1.EmitResult.UpdatedMethods, "F");
CheckNames(readers, diff1.EmitResult.ChangedTypes, "A", "C", "D");
Assert.Equal(2, reader1.GetTableRowCount(TableIndex.NestedClass));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default),
Row(3, TableIndex.NestedClass, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(4, TableIndex.TypeDef),
Handle(5, TableIndex.TypeDef),
Handle(1, TableIndex.Field),
Handle(1, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(5, TableIndex.MethodDef),
Handle(6, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef),
Handle(2, TableIndex.NestedClass),
Handle(3, TableIndex.NestedClass));
}
/// <summary>
/// Nested types should be emitted in the
/// same order as full emit.
/// </summary>
[Fact]
public void AddNestedTypesOrder()
{
var source0 =
@"class A
{
class B1
{
class C1 { }
}
class B2
{
class C2 { }
}
}";
var source1 =
@"class A
{
class B1
{
class C1 { }
}
class B2
{
class C2 { }
}
class B3
{
class C3 { }
}
class B4
{
class C4 { }
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B1", "B2", "C1", "C2");
Assert.Equal(4, reader0.GetTableRowCount(TableIndex.NestedClass));
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A.B3")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A.B4"))));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames(), "B3", "B4", "C3", "C4");
Assert.Equal(4, reader1.GetTableRowCount(TableIndex.NestedClass));
}
[Fact]
public void AddNestedGenericType()
{
var source0 =
@"class A
{
class B<T>
{
}
static object F()
{
return null;
}
}";
var source1 =
@"class A
{
class B<T>
{
internal class C<U>
{
internal object F<V>() where V : T, new()
{
return new C<V>();
}
}
}
static object F()
{
return new B<A>.C<B<object>>().F<A>();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var f0 = compilation0.GetMember<MethodSymbol>("A.F");
var f1 = compilation1.GetMember<MethodSymbol>("A.F");
var c1 = compilation1.GetMember<NamedTypeSymbol>("A.B.C");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B`1");
Assert.Equal(1, reader0.GetTableRowCount(TableIndex.NestedClass));
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, c1),
SemanticEdit.Create(SemanticEditKind.Update, f0, f1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "A", "B`1", "C`1");
CheckNames(readers, reader1.GetTypeDefNames(), "C`1");
Assert.Equal(1, reader1.GetTableRowCount(TableIndex.NestedClass));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodSpec, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(1, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default),
Row(2, TableIndex.GenericParam, EditAndContinueOperation.Default),
Row(3, TableIndex.GenericParam, EditAndContinueOperation.Default),
Row(4, TableIndex.GenericParam, EditAndContinueOperation.Default),
Row(1, TableIndex.GenericParamConstraint, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(4, TableIndex.TypeDef),
Handle(1, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(5, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(6, TableIndex.MemberRef),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(2, TableIndex.StandAloneSig),
Handle(1, TableIndex.TypeSpec),
Handle(2, TableIndex.TypeSpec),
Handle(3, TableIndex.TypeSpec),
Handle(2, TableIndex.AssemblyRef),
Handle(2, TableIndex.NestedClass),
Handle(2, TableIndex.GenericParam),
Handle(3, TableIndex.GenericParam),
Handle(4, TableIndex.GenericParam),
Handle(1, TableIndex.MethodSpec),
Handle(1, TableIndex.GenericParamConstraint));
}
[Fact]
public void AddNamespace()
{
var source0 =
@"
class C
{
static void Main() { }
}";
var source1 =
@"
namespace N
{
class D { public static void F() { } }
}
class C
{
static void Main() => N.D.F();
}";
var source2 =
@"
namespace N
{
class D { public static void F() { } }
namespace M
{
class E { public static void G() { } }
}
}
class C
{
static void Main() => N.M.E.G();
}";
var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var main0 = compilation0.GetMember<MethodSymbol>("C.Main");
var main1 = compilation1.GetMember<MethodSymbol>("C.Main");
var main2 = compilation2.GetMember<MethodSymbol>("C.Main");
var d1 = compilation1.GetMember<NamedTypeSymbol>("N.D");
var e2 = compilation2.GetMember<NamedTypeSymbol>("N.M.E");
using var md0 = ModuleMetadata.CreateFromImage(compilation0.EmitToArray());
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, main0, main1),
SemanticEdit.Create(SemanticEditKind.Insert, null, d1)));
diff1.VerifyIL("C.Main", @"
{
// Code size 7 (0x7)
.maxstack 0
IL_0000: call ""void N.D.F()""
IL_0005: nop
IL_0006: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, main1, main2),
SemanticEdit.Create(SemanticEditKind.Insert, null, e2)));
diff2.VerifyIL("C.Main", @"
{
// Code size 7 (0x7)
.maxstack 0
IL_0000: call ""void N.M.E.G()""
IL_0005: nop
IL_0006: ret
}");
}
[Fact]
public void ModifyExplicitImplementation()
{
var source =
@"interface I
{
void M();
}
class C : I
{
void I.M() { }
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var method0 = compilation0.GetMember<NamedTypeSymbol>("C").GetMethod("I.M");
var method1 = compilation1.GetMember<NamedTypeSymbol>("C").GetMethod("I.M");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "I", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "M", "I.M", ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var block1 = diff1.GetMetadata();
var reader1 = block1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "I.M");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void AddThenModifyExplicitImplementation()
{
var source0 =
@"interface I
{
void M();
}
class A : I
{
void I.M() { }
}
class B : I
{
public void M() { }
}";
var source1 =
@"interface I
{
void M();
}
class A : I
{
void I.M() { }
}
class B : I
{
public void M() { }
void I.M() { }
}";
var source2 = source1;
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation0.WithSource(source2);
var method1 = compilation1.GetMember<NamedTypeSymbol>("B").GetMethod("I.M");
var method2 = compilation2.GetMember<NamedTypeSymbol>("B").GetMethod("I.M");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, method1)));
using var block1 = diff1.GetMetadata();
var reader1 = block1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetMethodDefNames(), "I.M");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(6, TableIndex.MethodDef),
Handle(2, TableIndex.MethodImpl),
Handle(2, TableIndex.AssemblyRef));
var generation1 = diff1.NextGeneration;
var diff2 = compilation2.EmitDifference(
generation1,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
EncValidation.VerifyModuleMvid(2, reader1, reader2);
CheckNames(readers, reader2.GetMethodDefNames(), "I.M");
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader2,
Handle(7, TableIndex.TypeRef),
Handle(6, TableIndex.MethodDef),
Handle(3, TableIndex.AssemblyRef));
}
[WorkItem(930065, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/930065")]
[Fact]
public void ModifyConstructorBodyInPresenceOfExplicitInterfaceImplementation()
{
var source = @"
interface I
{
void M();
}
class C : I
{
public C()
{
}
void I.M() { }
}
";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var method0 = compilation0.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single();
var method1 = compilation1.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single();
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
using var block1 = diff1.GetMetadata();
var reader1 = block1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), ".ctor");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void AddAndModifyInterfaceMembers()
{
var source0 = @"
using System;
interface I
{
}";
var source1 = @"
using System;
interface I
{
static int X = 10;
static event Action Y;
static void M() { }
void N() { }
static int P { get => 1; set { } }
int Q { get => 1; set { } }
static event Action E { add { } remove { } }
event Action F { add { } remove { } }
interface J { }
}";
var source2 = @"
using System;
interface I
{
static int X = 2;
static event Action Y;
static I() { X--; }
static void M() { X++; }
void N() { X++; }
static int P { get => 3; set { X++; } }
int Q { get => 3; set { X++; } }
static event Action E { add { X++; } remove { X++; } }
event Action F { add { X++; } remove { X++; } }
interface J { }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var x1 = compilation1.GetMember<FieldSymbol>("I.X");
var y1 = compilation1.GetMember<EventSymbol>("I.Y");
var m1 = compilation1.GetMember<MethodSymbol>("I.M");
var n1 = compilation1.GetMember<MethodSymbol>("I.N");
var p1 = compilation1.GetMember<PropertySymbol>("I.P");
var q1 = compilation1.GetMember<PropertySymbol>("I.Q");
var e1 = compilation1.GetMember<EventSymbol>("I.E");
var f1 = compilation1.GetMember<EventSymbol>("I.F");
var j1 = compilation1.GetMember<NamedTypeSymbol>("I.J");
var getP1 = compilation1.GetMember<MethodSymbol>("I.get_P");
var setP1 = compilation1.GetMember<MethodSymbol>("I.set_P");
var getQ1 = compilation1.GetMember<MethodSymbol>("I.get_Q");
var setQ1 = compilation1.GetMember<MethodSymbol>("I.set_Q");
var addE1 = compilation1.GetMember<MethodSymbol>("I.add_E");
var removeE1 = compilation1.GetMember<MethodSymbol>("I.remove_E");
var addF1 = compilation1.GetMember<MethodSymbol>("I.add_F");
var removeF1 = compilation1.GetMember<MethodSymbol>("I.remove_F");
var cctor1 = compilation1.GetMember<NamedTypeSymbol>("I").StaticConstructors.Single();
var x2 = compilation2.GetMember<FieldSymbol>("I.X");
var m2 = compilation2.GetMember<MethodSymbol>("I.M");
var n2 = compilation2.GetMember<MethodSymbol>("I.N");
var getP2 = compilation2.GetMember<MethodSymbol>("I.get_P");
var setP2 = compilation2.GetMember<MethodSymbol>("I.set_P");
var getQ2 = compilation2.GetMember<MethodSymbol>("I.get_Q");
var setQ2 = compilation2.GetMember<MethodSymbol>("I.set_Q");
var addE2 = compilation2.GetMember<MethodSymbol>("I.add_E");
var removeE2 = compilation2.GetMember<MethodSymbol>("I.remove_E");
var addF2 = compilation2.GetMember<MethodSymbol>("I.add_F");
var removeF2 = compilation2.GetMember<MethodSymbol>("I.remove_F");
var cctor2 = compilation2.GetMember<NamedTypeSymbol>("I").StaticConstructors.Single();
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, x1),
SemanticEdit.Create(SemanticEditKind.Insert, null, y1),
SemanticEdit.Create(SemanticEditKind.Insert, null, m1),
SemanticEdit.Create(SemanticEditKind.Insert, null, n1),
SemanticEdit.Create(SemanticEditKind.Insert, null, p1),
SemanticEdit.Create(SemanticEditKind.Insert, null, q1),
SemanticEdit.Create(SemanticEditKind.Insert, null, e1),
SemanticEdit.Create(SemanticEditKind.Insert, null, f1),
SemanticEdit.Create(SemanticEditKind.Insert, null, j1),
SemanticEdit.Create(SemanticEditKind.Insert, null, cctor1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "I", "J");
CheckNames(readers, reader1.GetTypeDefNames(), "J");
CheckNames(readers, reader1.GetFieldDefNames(), "X", "Y");
CheckNames(readers, reader1.GetMethodDefNames(), "add_Y", "remove_Y", "M", "N", "get_P", "set_P", "get_Q", "set_Q", "add_E", "remove_E", "add_F", "remove_F", ".cctor");
Assert.Equal(1, reader1.GetTableRowCount(TableIndex.NestedClass));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, x1, x2),
SemanticEdit.Create(SemanticEditKind.Update, m1, m2),
SemanticEdit.Create(SemanticEditKind.Update, n1, n2),
SemanticEdit.Create(SemanticEditKind.Update, getP1, getP2),
SemanticEdit.Create(SemanticEditKind.Update, setP1, setP2),
SemanticEdit.Create(SemanticEditKind.Update, getQ1, getQ2),
SemanticEdit.Create(SemanticEditKind.Update, setQ1, setQ2),
SemanticEdit.Create(SemanticEditKind.Update, addE1, addE2),
SemanticEdit.Create(SemanticEditKind.Update, removeE1, removeE2),
SemanticEdit.Create(SemanticEditKind.Update, addF1, addF2),
SemanticEdit.Create(SemanticEditKind.Update, removeF1, removeF2),
SemanticEdit.Create(SemanticEditKind.Update, cctor1, cctor2)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "I", "J");
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetFieldDefNames(), "X");
CheckNames(readers, reader2.GetMethodDefNames(), "M", "N", "get_P", "set_P", "get_Q", "set_Q", "add_E", "remove_E", "add_F", "remove_F", ".cctor");
Assert.Equal(0, reader2.GetTableRowCount(TableIndex.NestedClass));
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.Event, EditAndContinueOperation.Default),
Row(3, TableIndex.Event, EditAndContinueOperation.Default),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(7, 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(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Property, EditAndContinueOperation.Default),
Row(2, TableIndex.Property, EditAndContinueOperation.Default),
Row(11, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(13, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(14, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(15, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(16, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(17, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(18, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
diff2.VerifyIL(@"
{
// Code size 14 (0xe)
.maxstack 8
IL_0000: nop
IL_0001: ldsfld 0x04000001
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: stsfld 0x04000001
IL_000d: ret
}
{
// Code size 2 (0x2)
.maxstack 8
IL_0000: ldc.i4.3
IL_0001: ret
}
{
// Code size 20 (0x14)
.maxstack 8
IL_0000: ldc.i4.2
IL_0001: stsfld 0x04000001
IL_0006: nop
IL_0007: ldsfld 0x04000001
IL_000c: ldc.i4.1
IL_000d: sub
IL_000e: stsfld 0x04000001
IL_0013: ret
}
");
}
[Fact]
public void AddAttributeReferences()
{
var source0 =
@"class A : System.Attribute { }
class B : System.Attribute { }
class C
{
[A] static void M1<[B]T>() { }
[B] static object F1;
[A] static object P1 { get { return null; } }
[B] static event D E1;
}
delegate void D();
";
var source1 =
@"class A : System.Attribute { }
class B : System.Attribute { }
class C
{
[A] static void M1<[B]T>() { }
[B] static void M2<[A]T>() { }
[B] static object F1;
[A] static object F2;
[A] static object P1 { get { return null; } }
[B] static object P2 { get { return null; } }
[B] static event D E1;
[A] static event D E2;
}
delegate void D();
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B", "C", "D");
CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", ".ctor", "M1", "get_P1", "add_E1", "remove_E1", ".ctor", ".ctor", "Invoke", "BeginInvoke", "EndInvoke");
CheckAttributes(reader0,
new CustomAttributeRow(Handle(1, TableIndex.Field), Handle(2, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(1, TableIndex.Property), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(1, TableIndex.Event), Handle(2, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.GenericParam), Handle(2, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(2, TableIndex.Field), Handle(4, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.Field), Handle(5, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(5, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(6, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)));
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.M2")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<FieldSymbol>("C.F2")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<PropertySymbol>("C.P2")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<EventSymbol>("C.E2"))));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "M2", "get_P2", "add_E2", "remove_E2");
CheckEncLogDefinitions(reader1,
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent),
Row(2, TableIndex.Event, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(3, TableIndex.Field, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(4, TableIndex.Field, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(14, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(15, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
Row(2, TableIndex.Property, EditAndContinueOperation.Default),
Row(14, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(8, TableIndex.Param, EditAndContinueOperation.Default),
Row(15, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(9, TableIndex.Param, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(20, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(2, TableIndex.GenericParam, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(3, TableIndex.Field),
Handle(4, TableIndex.Field),
Handle(12, TableIndex.MethodDef),
Handle(13, TableIndex.MethodDef),
Handle(14, TableIndex.MethodDef),
Handle(15, TableIndex.MethodDef),
Handle(8, TableIndex.Param),
Handle(9, TableIndex.Param),
Handle(7, TableIndex.CustomAttribute),
Handle(13, TableIndex.CustomAttribute),
Handle(14, TableIndex.CustomAttribute),
Handle(15, TableIndex.CustomAttribute),
Handle(16, TableIndex.CustomAttribute),
Handle(17, TableIndex.CustomAttribute),
Handle(18, TableIndex.CustomAttribute),
Handle(19, TableIndex.CustomAttribute),
Handle(20, TableIndex.CustomAttribute),
Handle(3, TableIndex.StandAloneSig),
Handle(4, TableIndex.StandAloneSig),
Handle(2, TableIndex.Event),
Handle(2, TableIndex.Property),
Handle(4, TableIndex.MethodSemantics),
Handle(5, TableIndex.MethodSemantics),
Handle(6, TableIndex.MethodSemantics),
Handle(2, TableIndex.GenericParam));
CheckAttributes(reader1,
new CustomAttributeRow(Handle(1, TableIndex.GenericParam), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(2, TableIndex.Property), Handle(2, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(2, TableIndex.Event), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(3, TableIndex.Field), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(4, TableIndex.Field), Handle(11, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(4, TableIndex.Field), Handle(12, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(12, TableIndex.MethodDef), Handle(2, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(14, TableIndex.MethodDef), Handle(11, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(15, TableIndex.MethodDef), Handle(11, TableIndex.MemberRef)));
}
/// <summary>
/// [assembly: ...] and [module: ...] attributes should
/// not be included in delta metadata.
/// </summary>
[Fact]
public void AssemblyAndModuleAttributeReferences()
{
var source0 =
@"[assembly: System.CLSCompliantAttribute(true)]
[module: System.CLSCompliantAttribute(true)]
class C
{
}";
var source1 =
@"[assembly: System.CLSCompliantAttribute(true)]
[module: System.CLSCompliantAttribute(true)]
class C
{
static void M()
{
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.M"))));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var readers = new[] { reader0, md1.Reader };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckNames(readers, md1.Reader.GetTypeDefNames());
CheckNames(readers, md1.Reader.GetMethodDefNames(), "M");
CheckEncLog(md1.Reader,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.M
CheckEncMap(md1.Reader,
Handle(7, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void OtherReferences()
{
var source0 =
@"delegate void D();
class C
{
object F;
object P { get { return null; } }
event D E;
void M()
{
}
}";
var source1 =
@"delegate void D();
class C
{
object F;
object P { get { return null; } }
event D E;
void M()
{
object o;
o = typeof(D);
o = F;
o = P;
E += null;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "D", "C");
CheckNames(reader0, reader0.GetEventDefNames(), "E");
CheckNames(reader0, reader0.GetFieldDefNames(), "F", "E");
CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", "Invoke", "BeginInvoke", "EndInvoke", "get_P", "add_E", "remove_E", "M", ".ctor");
CheckNames(reader0, reader0.GetPropertyDefNames(), "P");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
// Emit delta metadata.
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetEventDefNames());
CheckNames(readers, reader1.GetFieldDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "M");
CheckNames(readers, reader1.GetPropertyDefNames());
}
[Fact]
public void ArrayInitializer()
{
var source0 = WithWindowsLineBreaks(@"
class C
{
static void M()
{
int[] a = new[] { 1, 2, 3 };
}
}");
var source1 = WithWindowsLineBreaks(@"
class C
{
static void M()
{
int[] a = new[] { 1, 2, 3, 4 };
}
}");
var compilation0 = CreateCompilation(Parse(source0, "a.cs"), options: TestOptions.DebugDll);
var compilation1 = compilation0.RemoveAllSyntaxTrees().AddSyntaxTrees(Parse(source1, "a.cs"));
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(
ModuleMetadata.CreateFromImage(bytes0),
testData0.GetMethodData("C.M").EncDebugInfoProvider());
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember("C.M"), compilation1.GetMember("C.M"))));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(12, TableIndex.TypeRef),
Handle(13, TableIndex.TypeRef),
Handle(1, TableIndex.MethodDef),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
diff1.VerifyIL(
@"{
// Code size 25 (0x19)
.maxstack 4
IL_0000: nop
IL_0001: ldc.i4.4
IL_0002: newarr 0x0100000D
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.3
IL_0012: stelem.i4
IL_0013: dup
IL_0014: ldc.i4.3
IL_0015: ldc.i4.4
IL_0016: stelem.i4
IL_0017: stloc.0
IL_0018: ret
}");
diff1.VerifyPdb(new[] { 0x06000001 },
@"<symbols>
<files>
<file id=""1"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""15-9B-5B-24-28-37-02-4F-D2-2E-40-DB-1A-89-9F-4D-54-D5-95-89"" />
</files>
<methods>
<method token=""0x6000001"">
<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=""40"" document=""1"" />
<entry offset=""0x18"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x19"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x19"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void PInvokeModuleRefAndImplMap()
{
var source0 =
@"using System.Runtime.InteropServices;
class C
{
[DllImport(""msvcrt.dll"")]
public static extern int getchar();
}";
var source1 =
@"using System.Runtime.InteropServices;
class C
{
[DllImport(""msvcrt.dll"")]
public static extern int getchar();
[DllImport(""msvcrt.dll"")]
public static extern int puts(string s);
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.puts"))));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(2, TableIndex.ImplMap, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(3, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(2, TableIndex.ImplMap));
}
/// <summary>
/// ClassLayout and FieldLayout tables.
/// </summary>
[Fact]
public void ClassAndFieldLayout()
{
var source0 =
@"using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit, Pack=2)]
class A
{
[FieldOffset(0)]internal byte F;
[FieldOffset(2)]internal byte G;
}";
var source1 =
@"using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit, Pack=2)]
class A
{
[FieldOffset(0)]internal byte F;
[FieldOffset(2)]internal byte G;
}
[StructLayout(LayoutKind.Explicit, Pack=4)]
class B
{
[FieldOffset(0)]internal short F;
[FieldOffset(4)]internal short G;
}";
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.Insert, null, compilation1.GetMember<NamedTypeSymbol>("B"))));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(3, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(4, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.ClassLayout, EditAndContinueOperation.Default),
Row(3, TableIndex.FieldLayout, EditAndContinueOperation.Default),
Row(4, TableIndex.FieldLayout, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(3, TableIndex.TypeDef),
Handle(3, TableIndex.Field),
Handle(4, TableIndex.Field),
Handle(2, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(2, TableIndex.ClassLayout),
Handle(3, TableIndex.FieldLayout),
Handle(4, TableIndex.FieldLayout),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void NamespacesAndOverloads()
{
var compilation0 = CreateCompilation(options: TestOptions.DebugDll, source:
@"class C { }
namespace N
{
class C { }
}
namespace M
{
class C
{
void M1(N.C o) { }
void M1(M.C o) { }
void M2(N.C a, M.C b, global::C c)
{
M1(a);
}
}
}");
var method0 = compilation0.GetMember<MethodSymbol>("M.C.M2");
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var compilation1 = compilation0.WithSource(@"
class C { }
namespace N
{
class C { }
}
namespace M
{
class C
{
void M1(N.C o) { }
void M1(M.C o) { }
void M1(global::C o) { }
void M2(N.C a, M.C b, global::C c)
{
M1(a);
M1(b);
}
}
}");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMembers("M.C.M1")[2])));
diff1.VerifyIL(
@"{
// Code size 2 (0x2)
.maxstack 8
IL_0000: nop
IL_0001: ret
}");
var compilation2 = compilation1.WithSource(@"
class C { }
namespace N
{
class C { }
}
namespace M
{
class C
{
void M1(N.C o) { }
void M1(M.C o) { }
void M1(global::C o) { }
void M2(N.C a, M.C b, global::C c)
{
M1(a);
M1(b);
M1(c);
}
}
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("M.C.M2"),
compilation2.GetMember<MethodSymbol>("M.C.M2"))));
diff2.VerifyIL(
@"{
// Code size 26 (0x1a)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldarg.1
IL_0003: call 0x06000002
IL_0008: nop
IL_0009: ldarg.0
IL_000a: ldarg.2
IL_000b: call 0x06000003
IL_0010: nop
IL_0011: ldarg.0
IL_0012: ldarg.3
IL_0013: call 0x06000007
IL_0018: nop
IL_0019: ret
}");
}
[Fact]
public void TypesAndOverloads()
{
const string source =
@"using System;
struct A<T>
{
internal class B<U> { }
}
class B { }
class C
{
static void M(A<B>.B<object> a)
{
M(a);
M((A<B>.B<B>)null);
}
static void M(A<B>.B<B> a)
{
M(a);
M((A<B>.B<object>)null);
}
static void M(A<B> a)
{
M(a);
M((A<B>?)a);
}
static void M(Nullable<A<B>> a)
{
M(a);
M(a.Value);
}
unsafe static void M(int* p)
{
M(p);
M((byte*)p);
}
unsafe static void M(byte* p)
{
M(p);
M((int*)p);
}
static void M(B[][] b)
{
M(b);
M((object[][])b);
}
static void M(object[][] b)
{
M(b);
M((B[][])b);
}
static void M(A<B[]>.B<object> b)
{
M(b);
M((A<B[, ,]>.B<object>)null);
}
static void M(A<B[, ,]>.B<object> b)
{
M(b);
M((A<B[]>.B<object>)null);
}
static void M(dynamic d)
{
M(d);
M((dynamic[])d);
}
static void M(dynamic[] d)
{
M(d);
M((dynamic)d);
}
static void M<T>(A<int>.B<T> t) where T : B
{
M(t);
M((A<double>.B<int>)null);
}
static void M<T>(A<double>.B<T> t) where T : struct
{
M(t);
M((A<int>.B<B>)null);
}
}";
var options = TestOptions.UnsafeDebugDll;
var compilation0 = CreateCompilation(source, options: options, references: new[] { CSharpRef });
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var n = compilation0.GetMembers("C.M").Length;
Assert.Equal(14, n);
//static void M(A<B>.B<object> a)
//{
// M(a);
// M((A<B>.B<B>)null);
//}
var compilation1 = compilation0.WithSource(source);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMembers("C.M")[0], compilation1.GetMembers("C.M")[0])));
diff1.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000002
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x06000003
IL_000e: nop
IL_000f: ret
}");
//static void M(A<B>.B<B> a)
//{
// M(a);
// M((A<B>.B<object>)null);
//}
var compilation2 = compilation1.WithSource(source);
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMembers("C.M")[1], compilation2.GetMembers("C.M")[1])));
diff2.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000003
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x06000002
IL_000e: nop
IL_000f: ret
}");
//static void M(A<B> a)
//{
// M(a);
// M((A<B>?)a);
//}
var compilation3 = compilation2.WithSource(source);
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation2.GetMembers("C.M")[2], compilation3.GetMembers("C.M")[2])));
diff3.VerifyIL(
@"{
// Code size 21 (0x15)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000004
IL_0007: nop
IL_0008: ldarg.0
IL_0009: newobj 0x0A000016
IL_000e: call 0x06000005
IL_0013: nop
IL_0014: ret
}");
//static void M(Nullable<A<B>> a)
//{
// M(a);
// M(a.Value);
//}
var compilation4 = compilation3.WithSource(source);
var diff4 = compilation4.EmitDifference(
diff3.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation3.GetMembers("C.M")[3], compilation4.GetMembers("C.M")[3])));
diff4.VerifyIL(
@"{
// Code size 22 (0x16)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000005
IL_0007: nop
IL_0008: ldarga.s V_0
IL_000a: call 0x0A000017
IL_000f: call 0x06000004
IL_0014: nop
IL_0015: ret
}");
//unsafe static void M(int* p)
//{
// M(p);
// M((byte*)p);
//}
var compilation5 = compilation4.WithSource(source);
var diff5 = compilation5.EmitDifference(
diff4.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation4.GetMembers("C.M")[4], compilation5.GetMembers("C.M")[4])));
diff5.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000006
IL_0007: nop
IL_0008: ldarg.0
IL_0009: call 0x06000007
IL_000e: nop
IL_000f: ret
}");
//unsafe static void M(byte* p)
//{
// M(p);
// M((int*)p);
//}
var compilation6 = compilation5.WithSource(source);
var diff6 = compilation6.EmitDifference(
diff5.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation5.GetMembers("C.M")[5], compilation6.GetMembers("C.M")[5])));
diff6.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000007
IL_0007: nop
IL_0008: ldarg.0
IL_0009: call 0x06000006
IL_000e: nop
IL_000f: ret
}");
//static void M(B[][] b)
//{
// M(b);
// M((object[][])b);
//}
var compilation7 = compilation6.WithSource(source);
var diff7 = compilation7.EmitDifference(
diff6.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation6.GetMembers("C.M")[6], compilation7.GetMembers("C.M")[6])));
diff7.VerifyIL(
@"{
// Code size 18 (0x12)
.maxstack 1
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000008
IL_0007: nop
IL_0008: ldarg.0
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: call 0x06000009
IL_0010: nop
IL_0011: ret
}");
//static void M(object[][] b)
//{
// M(b);
// M((B[][])b);
//}
var compilation8 = compilation7.WithSource(source);
var diff8 = compilation8.EmitDifference(
diff7.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation7.GetMembers("C.M")[7], compilation8.GetMembers("C.M")[7])));
diff8.VerifyIL(
@"{
// Code size 21 (0x15)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000009
IL_0007: nop
IL_0008: ldarg.0
IL_0009: castclass 0x1B00000A
IL_000e: call 0x06000008
IL_0013: nop
IL_0014: ret
}");
//static void M(A<B[]>.B<object> b)
//{
// M(b);
// M((A<B[,,]>.B<object>)null);
//}
var compilation9 = compilation8.WithSource(source);
var diff9 = compilation9.EmitDifference(
diff8.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation8.GetMembers("C.M")[8], compilation9.GetMembers("C.M")[8])));
diff9.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x0600000A
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x0600000B
IL_000e: nop
IL_000f: ret
}");
//static void M(A<B[,,]>.B<object> b)
//{
// M(b);
// M((A<B[]>.B<object>)null);
//}
var compilation10 = compilation9.WithSource(source);
var diff10 = compilation10.EmitDifference(
diff9.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation9.GetMembers("C.M")[9], compilation10.GetMembers("C.M")[9])));
diff10.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x0600000B
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x0600000A
IL_000e: nop
IL_000f: ret
}");
// TODO: dynamic
#if false
//static void M(dynamic d)
//{
// M(d);
// M((dynamic[])d);
//}
previousMethod = compilation.GetMembers("C.M")[10];
compilation = compilation0.WithSource(source);
generation = compilation.EmitDifference(
generation,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, previousMethod, compilation.GetMembers("C.M")[10])),
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000002
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x06000003
IL_000e: nop
IL_000f: ret
}");
//static void M(dynamic[] d)
//{
// M(d);
// M((dynamic)d);
//}
previousMethod = compilation.GetMembers("C.M")[11];
compilation = compilation0.WithSource(source);
generation = compilation.EmitDifference(
generation,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, previousMethod, compilation.GetMembers("C.M")[11])),
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000002
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x06000003
IL_000e: nop
IL_000f: ret
}");
#endif
//static void M<T>(A<int>.B<T> t) where T : B
//{
// M(t);
// M((A<double>.B<int>)null);
//}
var compilation11 = compilation10.WithSource(source);
var diff11 = compilation11.EmitDifference(
diff10.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation10.GetMembers("C.M")[12], compilation11.GetMembers("C.M")[12])));
diff11.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x2B000005
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x2B000006
IL_000e: nop
IL_000f: ret
}");
//static void M<T>(A<double>.B<T> t) where T : struct
//{
// M(t);
// M((A<int>.B<B>)null);
//}
var compilation12 = compilation11.WithSource(source);
var diff12 = compilation12.EmitDifference(
diff11.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation11.GetMembers("C.M")[13], compilation12.GetMembers("C.M")[13])));
diff12.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x2B000007
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x2B000008
IL_000e: nop
IL_000f: ret
}");
}
/// <summary>
/// Types should be retained in deleted locals
/// for correct alignment of remaining locals.
/// </summary>
[Fact]
public void DeletedValueTypeLocal()
{
var source0 =
@"struct S1
{
internal S1(int a, int b) { A = a; B = b; }
internal int A;
internal int B;
}
struct S2
{
internal S2(int c) { C = c; }
internal int C;
}
class C
{
static void Main()
{
var x = new S1(1, 2);
var y = new S2(3);
System.Console.WriteLine(y.C);
}
}";
var source1 =
@"struct S1
{
internal S1(int a, int b) { A = a; B = b; }
internal int A;
internal int B;
}
struct S2
{
internal S2(int c) { C = c; }
internal int C;
}
class C
{
static void Main()
{
var y = new S2(3);
System.Console.WriteLine(y.C);
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe);
var compilation1 = compilation0.WithSource(source1);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.Main");
var method0 = compilation0.GetMember<MethodSymbol>("C.Main");
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider());
testData0.GetMethodData("C.Main").VerifyIL(
@"
{
// Code size 31 (0x1f)
.maxstack 3
.locals init (S1 V_0, //x
S2 V_1) //y
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldc.i4.1
IL_0004: ldc.i4.2
IL_0005: call ""S1..ctor(int, int)""
IL_000a: ldloca.s V_1
IL_000c: ldc.i4.3
IL_000d: call ""S2..ctor(int)""
IL_0012: ldloc.1
IL_0013: ldfld ""int S2.C""
IL_0018: call ""void System.Console.WriteLine(int)""
IL_001d: nop
IL_001e: ret
}");
var method1 = compilation1.GetMember<MethodSymbol>("C.Main");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.Main",
@"{
// Code size 22 (0x16)
.maxstack 2
.locals init ([unchanged] V_0,
S2 V_1) //y
IL_0000: nop
IL_0001: ldloca.s V_1
IL_0003: ldc.i4.3
IL_0004: call ""S2..ctor(int)""
IL_0009: ldloc.1
IL_000a: ldfld ""int S2.C""
IL_000f: call ""void System.Console.WriteLine(int)""
IL_0014: nop
IL_0015: ret
}");
}
/// <summary>
/// Instance and static constructors synthesized for
/// PrivateImplementationDetails should not be
/// generated for delta.
/// </summary>
[Fact]
public void PrivateImplementationDetails()
{
var source =
@"class C
{
static int[] F = new int[] { 1, 2, 3 };
int[] G = new int[] { 4, 5, 6 };
int M(int index)
{
return F[index] + G[index];
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using (var md0 = ModuleMetadata.CreateFromImage(bytes0))
{
var reader0 = md0.MetadataReader;
var typeNames = new[] { reader0 }.GetStrings(reader0.GetTypeDefNames());
Assert.NotNull(typeNames.FirstOrDefault(n => n.StartsWith("<PrivateImplementationDetails>", StringComparison.Ordinal)));
}
var methodData0 = testData0.GetMethodData("C.M");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M", @"
{
// Code size 22 (0x16)
.maxstack 3
.locals init ([int] V_0,
int V_1)
IL_0000: nop
IL_0001: ldsfld ""int[] C.F""
IL_0006: ldarg.1
IL_0007: ldelem.i4
IL_0008: ldarg.0
IL_0009: ldfld ""int[] C.G""
IL_000e: ldarg.1
IL_000f: ldelem.i4
IL_0010: add
IL_0011: stloc.1
IL_0012: br.s IL_0014
IL_0014: ldloc.1
IL_0015: ret
}");
}
[WorkItem(780989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780989")]
[WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")]
[Fact]
public void PrivateImplementationDetails_ArrayInitializer_FromMetadata()
{
var source0 =
@"class C
{
static void M()
{
int[] a = { 1, 2, 3 };
System.Console.WriteLine(a[0]);
}
}";
var source1 =
@"class C
{
static void M()
{
int[] a = { 1, 2, 3 };
System.Console.WriteLine(a[1]);
}
}";
var source2 =
@"class C
{
static void M()
{
int[] a = { 4, 5, 6, 7, 8, 9, 10 };
System.Console.WriteLine(a[1]);
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll.WithModuleName("MODULE"));
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M");
methodData0.VerifyIL(
@" {
// Code size 29 (0x1d)
.maxstack 3
.locals init (int[] V_0) //a
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D""
IL_000d: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_0012: stloc.0
IL_0013: ldloc.0
IL_0014: ldc.i4.0
IL_0015: ldelem.i4
IL_0016: call ""void System.Console.WriteLine(int)""
IL_001b: nop
IL_001c: ret
}
");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M",
@"{
// Code size 30 (0x1e)
.maxstack 4
.locals init (int[] V_0) //a
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.3
IL_0012: stelem.i4
IL_0013: stloc.0
IL_0014: ldloc.0
IL_0015: ldc.i4.1
IL_0016: ldelem.i4
IL_0017: call ""void System.Console.WriteLine(int)""
IL_001c: nop
IL_001d: ret
}");
var method2 = compilation2.GetMember<MethodSymbol>("C.M");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true)));
diff2.VerifyIL("C.M",
@"{
// Code size 48 (0x30)
.maxstack 4
.locals init ([unchanged] V_0,
int[] V_1) //a
IL_0000: nop
IL_0001: ldc.i4.7
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.4
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.5
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.6
IL_0012: stelem.i4
IL_0013: dup
IL_0014: ldc.i4.3
IL_0015: ldc.i4.7
IL_0016: stelem.i4
IL_0017: dup
IL_0018: ldc.i4.4
IL_0019: ldc.i4.8
IL_001a: stelem.i4
IL_001b: dup
IL_001c: ldc.i4.5
IL_001d: ldc.i4.s 9
IL_001f: stelem.i4
IL_0020: dup
IL_0021: ldc.i4.6
IL_0022: ldc.i4.s 10
IL_0024: stelem.i4
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: ldc.i4.1
IL_0028: ldelem.i4
IL_0029: call ""void System.Console.WriteLine(int)""
IL_002e: nop
IL_002f: ret
}");
}
[WorkItem(780989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780989")]
[WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")]
[Fact]
public void PrivateImplementationDetails_ArrayInitializer_FromSource()
{
// PrivateImplementationDetails not needed initially.
var source0 =
@"class C
{
static object F1() { return null; }
static object F2() { return null; }
static object F3() { return null; }
static object F4() { return null; }
}";
var source1 =
@"class C
{
static object F1() { return new[] { 1, 2, 3 }; }
static object F2() { return new[] { 4, 5, 6 }; }
static object F3() { return null; }
static object F4() { return new[] { 7, 8, 9 }; }
}";
var source2 =
@"class C
{
static object F1() { return new[] { 1, 2, 3 } ?? new[] { 10, 11, 12 }; }
static object F2() { return new[] { 4, 5, 6 }; }
static object F3() { return new[] { 13, 14, 15 }; }
static object F4() { return new[] { 7, 8, 9 }; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F1"), compilation1.GetMember<MethodSymbol>("C.F1")),
SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F2"), compilation1.GetMember<MethodSymbol>("C.F2")),
SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F4"), compilation1.GetMember<MethodSymbol>("C.F4"))));
diff1.VerifyIL("C.F1",
@"{
// Code size 24 (0x18)
.maxstack 4
.locals init (object V_0)
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.3
IL_0012: stelem.i4
IL_0013: stloc.0
IL_0014: br.s IL_0016
IL_0016: ldloc.0
IL_0017: ret
}");
diff1.VerifyIL("C.F4",
@"{
// Code size 25 (0x19)
.maxstack 4
.locals init (object V_0)
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.7
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.8
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.s 9
IL_0013: stelem.i4
IL_0014: stloc.0
IL_0015: br.s IL_0017
IL_0017: ldloc.0
IL_0018: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("C.F1"), compilation2.GetMember<MethodSymbol>("C.F1")),
SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("C.F3"), compilation2.GetMember<MethodSymbol>("C.F3"))));
diff2.VerifyIL("C.F1",
@"{
// Code size 49 (0x31)
.maxstack 4
.locals init (object V_0)
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.3
IL_0012: stelem.i4
IL_0013: dup
IL_0014: brtrue.s IL_002c
IL_0016: pop
IL_0017: ldc.i4.3
IL_0018: newarr ""int""
IL_001d: dup
IL_001e: ldc.i4.0
IL_001f: ldc.i4.s 10
IL_0021: stelem.i4
IL_0022: dup
IL_0023: ldc.i4.1
IL_0024: ldc.i4.s 11
IL_0026: stelem.i4
IL_0027: dup
IL_0028: ldc.i4.2
IL_0029: ldc.i4.s 12
IL_002b: stelem.i4
IL_002c: stloc.0
IL_002d: br.s IL_002f
IL_002f: ldloc.0
IL_0030: ret
}");
diff2.VerifyIL("C.F3",
@"{
// Code size 27 (0x1b)
.maxstack 4
.locals init (object V_0)
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.s 13
IL_000b: stelem.i4
IL_000c: dup
IL_000d: ldc.i4.1
IL_000e: ldc.i4.s 14
IL_0010: stelem.i4
IL_0011: dup
IL_0012: ldc.i4.2
IL_0013: ldc.i4.s 15
IL_0015: stelem.i4
IL_0016: stloc.0
IL_0017: br.s IL_0019
IL_0019: ldloc.0
IL_001a: ret
}");
}
/// <summary>
/// Should not generate method for string switch since
/// the CLR only allows adding private members.
/// </summary>
[WorkItem(834086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834086")]
[Fact]
public void PrivateImplementationDetails_ComputeStringHash()
{
var source =
@"class C
{
static int F(string s)
{
switch (s)
{
case ""1"": return 1;
case ""2"": return 2;
case ""3"": return 3;
case ""4"": return 4;
case ""5"": return 5;
case ""6"": return 6;
case ""7"": return 7;
default: return 0;
}
}
}";
const string ComputeStringHashName = "ComputeStringHash";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.F");
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider());
// Should have generated call to ComputeStringHash and
// added the method to <PrivateImplementationDetails>.
var actualIL0 = methodData0.GetMethodIL();
Assert.True(actualIL0.Contains(ComputeStringHashName));
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ComputeStringHashName);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
// Should not have generated call to ComputeStringHash nor
// added the method to <PrivateImplementationDetails>.
var actualIL1 = diff1.GetMethodIL("C.F");
Assert.False(actualIL1.Contains(ComputeStringHashName));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetMethodDefNames(), "F");
}
/// <summary>
/// Unique ids should not conflict with ids
/// from previous generation.
/// </summary>
[WorkItem(9847, "https://github.com/dotnet/roslyn/issues/9847")]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/9847")]
public void UniqueIds()
{
var source0 =
@"class C
{
int F()
{
System.Func<int> f = () => 3;
return f();
}
static int F(bool b)
{
System.Func<int> f = () => 1;
System.Func<int> g = () => 2;
return (b ? f : g)();
}
}";
var source1 =
@"class C
{
int F()
{
System.Func<int> f = () => 3;
return f();
}
static int F(bool b)
{
System.Func<int> f = () => 1;
return f();
}
}";
var source2 =
@"class C
{
int F()
{
System.Func<int> f = () => 3;
return f();
}
static int F(bool b)
{
System.Func<int> g = () => 2;
return g();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMembers("C.F")[1], compilation1.GetMembers("C.F")[1])));
diff1.VerifyIL("C.F",
@"{
// Code size 40 (0x28)
.maxstack 2
.locals init (System.Func<int> V_0, //f
int V_1)
IL_0000: nop
IL_0001: ldsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate6""
IL_0006: dup
IL_0007: brtrue.s IL_001c
IL_0009: pop
IL_000a: ldnull
IL_000b: ldftn ""int C.<F>b__5()""
IL_0011: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_0016: dup
IL_0017: stsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate6""
IL_001c: stloc.0
IL_001d: ldloc.0
IL_001e: callvirt ""int System.Func<int>.Invoke()""
IL_0023: stloc.1
IL_0024: br.s IL_0026
IL_0026: ldloc.1
IL_0027: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMembers("C.F")[1], compilation2.GetMembers("C.F")[1])));
diff2.VerifyIL("C.F",
@"{
// Code size 40 (0x28)
.maxstack 2
.locals init (System.Func<int> V_0, //g
int V_1)
IL_0000: nop
IL_0001: ldsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate8""
IL_0006: dup
IL_0007: brtrue.s IL_001c
IL_0009: pop
IL_000a: ldnull
IL_000b: ldftn ""int C.<F>b__7()""
IL_0011: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_0016: dup
IL_0017: stsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate8""
IL_001c: stloc.0
IL_001d: ldloc.0
IL_001e: callvirt ""int System.Func<int>.Invoke()""
IL_0023: stloc.1
IL_0024: br.s IL_0026
IL_0026: ldloc.1
IL_0027: ret
}");
}
/// <summary>
/// Avoid adding references from method bodies
/// other than the changed methods.
/// </summary>
[Fact]
public void ReferencesInIL()
{
var source0 =
@"class C
{
static void F() { System.Console.WriteLine(1); }
static void G() { System.Console.WriteLine(2); }
}";
var source1 =
@"class C
{
static void F() { System.Console.WriteLine(1); }
static void G() { System.Console.Write(2); }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "F", "G", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), ".ctor", ".ctor", ".ctor", "WriteLine", ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method0 = compilation0.GetMember<MethodSymbol>("C.G");
var method1 = compilation1.GetMember<MethodSymbol>("C.G");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(
SemanticEditKind.Update,
method0,
method1,
GetEquivalentNodesMap(method1, method0),
preserveLocalVariables: true)));
// "Write" should be included in string table, but "WriteLine" should not.
Assert.True(diff1.MetadataDelta.IsIncluded("Write"));
Assert.False(diff1.MetadataDelta.IsIncluded("WriteLine"));
}
/// <summary>
/// Local slots must be preserved based on signature.
/// </summary>
[Fact]
public void PreserveLocalSlots()
{
var source0 =
@"class A<T> { }
class B : A<B>
{
static B F()
{
return null;
}
static void M(object o)
{
object x = F();
A<B> y = F();
object z = F();
M(x);
M(y);
M(z);
}
static void N()
{
object a = F();
object b = F();
M(a);
M(b);
}
}";
var methodNames0 = new[] { "A<T>..ctor", "B.F", "B.M", "B.N" };
var source1 =
@"class A<T> { }
class B : A<B>
{
static B F()
{
return null;
}
static void M(object o)
{
B z = F();
A<B> y = F();
object w = F();
M(w);
M(y);
}
static void N()
{
object a = F();
object b = F();
M(a);
M(b);
}
}";
var source2 =
@"class A<T> { }
class B : A<B>
{
static B F()
{
return null;
}
static void M(object o)
{
object x = F();
B z = F();
M(x);
M(z);
}
static void N()
{
object a = F();
object b = F();
M(a);
M(b);
}
}";
var source3 =
@"class A<T> { }
class B : A<B>
{
static B F()
{
return null;
}
static void M(object o)
{
object x = F();
B z = F();
M(x);
M(z);
}
static void N()
{
object c = F();
object b = F();
M(c);
M(b);
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var method0 = compilation0.GetMember<MethodSymbol>("B.M");
var methodN = compilation0.GetMember<MethodSymbol>("B.N");
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var generation0 = EmitBaseline.CreateInitialBaseline(
ModuleMetadata.CreateFromImage(bytes0),
m => testData0.GetMethodData(methodNames0[MetadataTokens.GetRowNumber(m) - 1]).GetEncDebugInfo());
#region Gen1
var method1 = compilation1.GetMember<MethodSymbol>("B.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL(
@"{
// Code size 36 (0x24)
.maxstack 1
IL_0000: nop
IL_0001: call 0x06000002
IL_0006: stloc.3
IL_0007: call 0x06000002
IL_000c: stloc.1
IL_000d: call 0x06000002
IL_0012: stloc.s V_4
IL_0014: ldloc.s V_4
IL_0016: call 0x06000003
IL_001b: nop
IL_001c: ldloc.1
IL_001d: call 0x06000003
IL_0022: nop
IL_0023: ret
}");
diff1.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method token=""0x6000003"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</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=""0x7"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""22"" document=""1"" />
<entry offset=""0xd"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""24"" document=""1"" />
<entry offset=""0x14"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""14"" document=""1"" />
<entry offset=""0x1c"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""14"" document=""1"" />
<entry offset=""0x23"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x24"">
<local name=""z"" il_index=""3"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" />
<local name=""y"" il_index=""1"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" />
<local name=""w"" il_index=""4"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
#endregion
#region Gen2
var method2 = compilation2.GetMember<MethodSymbol>("B.M");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true)));
diff2.VerifyIL(
@"{
// Code size 30 (0x1e)
.maxstack 1
IL_0000: nop
IL_0001: call 0x06000002
IL_0006: stloc.s V_5
IL_0008: call 0x06000002
IL_000d: stloc.3
IL_000e: ldloc.s V_5
IL_0010: call 0x06000003
IL_0015: nop
IL_0016: ldloc.3
IL_0017: call 0x06000003
IL_001c: nop
IL_001d: ret
}");
diff2.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method token=""0x6000003"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</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=""24"" document=""1"" />
<entry offset=""0x8"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""19"" document=""1"" />
<entry offset=""0xe"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""14"" document=""1"" />
<entry offset=""0x16"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""14"" document=""1"" />
<entry offset=""0x1d"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1e"">
<local name=""x"" il_index=""5"" il_start=""0x0"" il_end=""0x1e"" attributes=""0"" />
<local name=""z"" il_index=""3"" il_start=""0x0"" il_end=""0x1e"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
#endregion
#region Gen3
// Modify different method. (Previous generations
// have not referenced method.)
method2 = compilation2.GetMember<MethodSymbol>("B.N");
var method3 = compilation3.GetMember<MethodSymbol>("B.N");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables: true)));
diff3.VerifyIL(
@"{
// Code size 28 (0x1c)
.maxstack 1
IL_0000: nop
IL_0001: call 0x06000002
IL_0006: stloc.2
IL_0007: call 0x06000002
IL_000c: stloc.1
IL_000d: ldloc.2
IL_000e: call 0x06000003
IL_0013: nop
IL_0014: ldloc.1
IL_0015: call 0x06000003
IL_001a: nop
IL_001b: ret
}");
diff3.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method token=""0x6000004"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</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=""24"" document=""1"" />
<entry offset=""0x7"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""24"" document=""1"" />
<entry offset=""0xd"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""14"" document=""1"" />
<entry offset=""0x14"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""14"" document=""1"" />
<entry offset=""0x1b"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1c"">
<local name=""c"" il_index=""2"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" />
<local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
#endregion
}
/// <summary>
/// Preserve locals for method added after initial compilation.
/// </summary>
[Fact]
public void PreserveLocalSlots_NewMethod()
{
var source0 =
@"class C
{
}";
var source1 =
@"class C
{
static void M()
{
var a = new object();
var b = string.Empty;
}
}";
var source2 =
@"class C
{
static void M()
{
var a = 1;
var b = string.Empty;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var m1 = compilation1.GetMember<MethodSymbol>("C.M");
var m2 = compilation2.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, m1, null, preserveLocalVariables: true)));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetEquivalentNodesMap(m2, m1), preserveLocalVariables: true)));
diff2.VerifyIL("C.M",
@"{
// Code size 10 (0xa)
.maxstack 1
.locals init ([object] V_0,
string V_1, //b
int V_2) //a
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.2
IL_0003: ldsfld ""string string.Empty""
IL_0008: stloc.1
IL_0009: ret
}");
diff2.VerifyPdb(new[] { 0x06000002 }, @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method token=""0x6000002"">
<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=""19"" document=""1"" />
<entry offset=""0x3"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""30"" document=""1"" />
<entry offset=""0x9"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xa"">
<local name=""a"" il_index=""2"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" />
<local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
/// <summary>
/// Local types should be retained, even if the local is no longer
/// used by the method body, since there may be existing
/// references to that slot, in a Watch window for instance.
/// </summary>
[WorkItem(843320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843320")]
[Fact]
public void PreserveLocalTypes()
{
var source0 =
@"class C
{
static void Main()
{
var x = true;
var y = x;
System.Console.WriteLine(y);
}
}";
var source1 =
@"class C
{
static void Main()
{
var x = ""A"";
var y = x;
System.Console.WriteLine(y);
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var method0 = compilation0.GetMember<MethodSymbol>("C.Main");
var method1 = compilation1.GetMember<MethodSymbol>("C.Main");
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.Main").EncDebugInfoProvider());
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.Main", @"
{
// Code size 17 (0x11)
.maxstack 1
.locals init ([bool] V_0,
[bool] V_1,
string V_2, //x
string V_3) //y
IL_0000: nop
IL_0001: ldstr ""A""
IL_0006: stloc.2
IL_0007: ldloc.2
IL_0008: stloc.3
IL_0009: ldloc.3
IL_000a: call ""void System.Console.WriteLine(string)""
IL_000f: nop
IL_0010: ret
}");
}
/// <summary>
/// Preserve locals if SemanticEdit.PreserveLocalVariables is set.
/// </summary>
[Fact]
public void PreserveLocalVariablesFlag()
{
var source =
@"class C
{
static System.IDisposable F() { return null; }
static void M()
{
using (F()) { }
using (var x = F()) { }
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(
ModuleMetadata.CreateFromImage(bytes0),
testData0.GetMethodData("C.M").EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1a = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: false)));
diff1a.VerifyIL("C.M", @"
{
// Code size 44 (0x2c)
.maxstack 1
.locals init (System.IDisposable V_0,
System.IDisposable V_1) //x
IL_0000: nop
IL_0001: call ""System.IDisposable C.F()""
IL_0006: stloc.0
.try
{
IL_0007: nop
IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.0
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
IL_0015: endfinally
}
IL_0016: call ""System.IDisposable C.F()""
IL_001b: stloc.1
.try
{
IL_001c: nop
IL_001d: nop
IL_001e: leave.s IL_002b
}
finally
{
IL_0020: ldloc.1
IL_0021: brfalse.s IL_002a
IL_0023: ldloc.1
IL_0024: callvirt ""void System.IDisposable.Dispose()""
IL_0029: nop
IL_002a: endfinally
}
IL_002b: ret
}
");
var diff1b = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: true)));
diff1b.VerifyIL("C.M",
@"{
// Code size 44 (0x2c)
.maxstack 1
.locals init (System.IDisposable V_0,
System.IDisposable V_1) //x
IL_0000: nop
IL_0001: call ""System.IDisposable C.F()""
IL_0006: stloc.0
.try
{
IL_0007: nop
IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.0
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
IL_0015: endfinally
}
IL_0016: call ""System.IDisposable C.F()""
IL_001b: stloc.1
.try
{
IL_001c: nop
IL_001d: nop
IL_001e: leave.s IL_002b
}
finally
{
IL_0020: ldloc.1
IL_0021: brfalse.s IL_002a
IL_0023: ldloc.1
IL_0024: callvirt ""void System.IDisposable.Dispose()""
IL_0029: nop
IL_002a: endfinally
}
IL_002b: ret
}");
}
[WorkItem(779531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/779531")]
[Fact]
public void ChangeLocalType()
{
var source0 =
@"enum E { }
class C
{
static void M1()
{
var x = default(E);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
static void M2()
{
var x = default(E);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
}";
// Change locals in one method to type added.
var source1 =
@"enum E { }
class A { }
class C
{
static void M1()
{
var x = default(A);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
static void M2()
{
var x = default(E);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
}";
// Change locals in another method.
var source2 =
@"enum E { }
class A { }
class C
{
static void M1()
{
var x = default(A);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
static void M2()
{
var x = default(A);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
}";
// Change locals in same method.
var source3 =
@"enum E { }
class A { }
class C
{
static void M1()
{
var x = default(A);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
static void M2()
{
var x = default(A);
var y = x;
var z = default(A);
System.Console.WriteLine(y);
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M1");
var method0 = compilation0.GetMember<MethodSymbol>("C.M1");
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M1");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A")),
SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M1",
@"{
// Code size 17 (0x11)
.maxstack 1
.locals init ([unchanged] V_0,
[unchanged] V_1,
E V_2, //z
A V_3, //x
A V_4) //y
IL_0000: nop
IL_0001: ldnull
IL_0002: stloc.3
IL_0003: ldloc.3
IL_0004: stloc.s V_4
IL_0006: ldc.i4.0
IL_0007: stloc.2
IL_0008: ldloc.s V_4
IL_000a: call ""void System.Console.WriteLine(object)""
IL_000f: nop
IL_0010: ret
}");
var method2 = compilation2.GetMember<MethodSymbol>("C.M2");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true)));
diff2.VerifyIL("C.M2",
@"{
// Code size 17 (0x11)
.maxstack 1
.locals init ([unchanged] V_0,
[unchanged] V_1,
E V_2, //z
A V_3, //x
A V_4) //y
IL_0000: nop
IL_0001: ldnull
IL_0002: stloc.3
IL_0003: ldloc.3
IL_0004: stloc.s V_4
IL_0006: ldc.i4.0
IL_0007: stloc.2
IL_0008: ldloc.s V_4
IL_000a: call ""void System.Console.WriteLine(object)""
IL_000f: nop
IL_0010: ret
}");
var method3 = compilation3.GetMember<MethodSymbol>("C.M2");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables: true)));
diff3.VerifyIL("C.M2",
@"{
// Code size 18 (0x12)
.maxstack 1
.locals init ([unchanged] V_0,
[unchanged] V_1,
[unchanged] V_2,
A V_3, //x
A V_4, //y
A V_5) //z
IL_0000: nop
IL_0001: ldnull
IL_0002: stloc.3
IL_0003: ldloc.3
IL_0004: stloc.s V_4
IL_0006: ldnull
IL_0007: stloc.s V_5
IL_0009: ldloc.s V_4
IL_000b: call ""void System.Console.WriteLine(object)""
IL_0010: nop
IL_0011: ret
}");
}
[Fact]
public void AnonymousTypes_Update()
{
var source0 = MarkedSource(@"
class C
{
static void F()
{
var <N:0>x = new { A = 1 }</N:0>;
}
}
");
var source1 = MarkedSource(@"
class C
{
static void F()
{
var <N:0>x = new { A = 2 }</N:0>;
}
}
");
var source2 = MarkedSource(@"
class C
{
static void F()
{
var <N:0>x = new { A = 3 }</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);
v0.VerifyIL("C.F", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (<>f__AnonymousType0<int> V_0) //x
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0007: stloc.0
IL_0008: ret
}
");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.F", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (<>f__AnonymousType0<int> V_0) //x
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0007: stloc.0
IL_0008: ret
}
");
// expect a single TypeRef for System.Object
var md1 = diff1.GetMetadata();
AssertEx.Equal(new[] { "[0x23000002] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader }));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (<>f__AnonymousType0<int> V_0) //x
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0007: stloc.0
IL_0008: ret
}
");
// expect a single TypeRef for System.Object
var md2 = diff2.GetMetadata();
AssertEx.Equal(new[] { "[0x23000003] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader, md2.Reader }));
}
[Fact]
public void AnonymousTypes_UpdateAfterAdd()
{
var source0 = MarkedSource(@"
class C
{
static void F()
{
}
}
");
var source1 = MarkedSource(@"
class C
{
static void F()
{
var <N:0>x = new { A = 2 }</N:0>;
}
}
");
var source2 = MarkedSource(@"
class C
{
static void F()
{
var <N:0>x = new { A = 3 }</N:0>;
}
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), targetFramework: TargetFramework.NetStandard20);
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();
diff1.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.F", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (<>f__AnonymousType0<int> V_0) //x
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0007: stloc.0
IL_0008: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (<>f__AnonymousType0<int> V_0) //x
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0007: stloc.0
IL_0008: ret
}
");
// expect a single TypeRef for System.Object
var md2 = diff2.GetMetadata();
AssertEx.Equal(new[] { "[0x23000003] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader, md2.Reader }));
}
/// <summary>
/// Reuse existing anonymous types.
/// </summary>
[WorkItem(825903, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825903")]
[Fact]
public void AnonymousTypes()
{
var source0 =
@"namespace N
{
class A
{
static object F = new { A = 1, B = 2 };
}
}
namespace M
{
class B
{
static void M()
{
var x = new { B = 3, A = 4 };
var y = x.A;
var z = new { };
}
}
}";
var source1 =
@"namespace N
{
class A
{
static object F = new { A = 1, B = 2 };
}
}
namespace M
{
class B
{
static void M()
{
var x = new { B = 3, A = 4 };
var y = new { A = x.A };
var z = new { };
}
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var m0 = compilation0.GetMember<MethodSymbol>("M.B.M");
var m1 = compilation1.GetMember<MethodSymbol>("M.B.M");
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, testData0.GetMethodData("M.B.M").EncDebugInfoProvider());
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`2", "<>f__AnonymousType1`2", "<>f__AnonymousType2", "B", "A");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetEquivalentNodesMap(m1, m0), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType3`1"); // one additional type
diff1.VerifyIL("M.B.M", @"
{
// Code size 28 (0x1c)
.maxstack 2
.locals init (<>f__AnonymousType1<int, int> V_0, //x
[int] V_1,
<>f__AnonymousType2 V_2, //z
<>f__AnonymousType3<int> V_3) //y
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: ldc.i4.4
IL_0003: newobj ""<>f__AnonymousType1<int, int>..ctor(int, int)""
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: callvirt ""int <>f__AnonymousType1<int, int>.A.get""
IL_000f: newobj ""<>f__AnonymousType3<int>..ctor(int)""
IL_0014: stloc.3
IL_0015: newobj ""<>f__AnonymousType2..ctor()""
IL_001a: stloc.2
IL_001b: ret
}");
}
/// <summary>
/// Anonymous type names with module ids
/// and gaps in indices.
/// </summary>
[ConditionalFact(typeof(WindowsOnly), Reason = "ILASM doesn't support Portable PDBs")]
[WorkItem(2982, "https://github.com/dotnet/coreclr/issues/2982")]
public void AnonymousTypes_OtherTypeNames()
{
var ilSource =
@".assembly extern netstandard { .ver 2:0:0:0 .publickeytoken = (cc 7b 13 ff cd 2d dd 51) }
// Valid signature, although not sequential index
.class '<>f__AnonymousType2'<'<A>j__TPar', '<B>j__TPar'> extends object
{
.field public !'<A>j__TPar' A
.field public !'<B>j__TPar' B
}
// Invalid signature, unexpected type parameter names
.class '<>f__AnonymousType1'<A, B> extends object
{
.field public !A A
.field public !B B
}
// Module id, duplicate index
.class '<m>f__AnonymousType2`1'<'<A>j__TPar'> extends object
{
.field public !'<A>j__TPar' A
}
// Module id
.class '<m>f__AnonymousType3`1'<'<B>j__TPar'> extends object
{
.field public !'<B>j__TPar' B
}
.class public C extends object
{
.method public specialname rtspecialname instance void .ctor()
{
ret
}
.method public static object F()
{
ldnull
ret
}
}";
var source0 =
@"class C
{
static object F()
{
return 0;
}
}";
var source1 =
@"class C
{
static object F()
{
var x = new { A = new object(), B = 1 };
var y = new { A = x.A };
return y;
}
}";
var metadata0 = (MetadataImageReference)CompileIL(ilSource, prependDefaultHeader: false);
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var moduleMetadata0 = ((AssemblyMetadata)metadata0.GetMetadataNoCopy()).GetModules()[0];
var generation0 = EmitBaseline.CreateInitialBaseline(moduleMetadata0, m => default);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
diff1.VerifyIL("C.F",
@"{
// Code size 31 (0x1f)
.maxstack 2
.locals init (<>f__AnonymousType2<object, int> V_0, //x
<>f__AnonymousType3<object> V_1, //y
object V_2)
IL_0000: nop
IL_0001: newobj ""object..ctor()""
IL_0006: ldc.i4.1
IL_0007: newobj ""<>f__AnonymousType2<object, int>..ctor(object, int)""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: callvirt ""object <>f__AnonymousType2<object, int>.A.get""
IL_0013: newobj ""<>f__AnonymousType3<object>..ctor(object)""
IL_0018: stloc.1
IL_0019: ldloc.1
IL_001a: stloc.2
IL_001b: br.s IL_001d
IL_001d: ldloc.2
IL_001e: ret
}");
}
/// <summary>
/// Update method with anonymous type that was
/// not directly referenced in previous generation.
/// </summary>
[Fact]
public void AnonymousTypes_SkipGeneration()
{
var source0 = MarkedSource(
@"class A { }
class B
{
static object F()
{
var <N:0>x = new { A = 1 }</N:0>;
return x.A;
}
static object G()
{
var <N:1>x = 1</N:1>;
return x;
}
}");
var source1 = MarkedSource(
@"class A { }
class B
{
static object F()
{
var <N:0>x = new { A = 1 }</N:0>;
return x.A;
}
static object G()
{
var <N:1>x = 1</N:1>;
return x + 1;
}
}");
var source2 = MarkedSource(
@"class A { }
class B
{
static object F()
{
var <N:0>x = new { A = 1 }</N:0>;
return x.A;
}
static object G()
{
var <N:1>x = new { A = new A() }</N:1>;
var <N:2>y = new { B = 2 }</N:2>;
return x.A;
}
}");
var source3 = MarkedSource(
@"class A { }
class B
{
static object F()
{
var <N:0>x = new { A = 1 }</N:0>;
return x.A;
}
static object G()
{
var <N:1>x = new { A = new A() }</N:1>;
var <N:2>y = new { B = 3 }</N:2>;
return y.B;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
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 generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var method0 = compilation0.GetMember<MethodSymbol>("B.G");
var method1 = compilation1.GetMember<MethodSymbol>("B.G");
var method2 = compilation2.GetMember<MethodSymbol>("B.G");
var method3 = compilation3.GetMember<MethodSymbol>("B.G");
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`1", "A", "B");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames()); // no additional types
diff1.VerifyIL("B.G", @"
{
// Code size 16 (0x10)
.maxstack 2
.locals init (int V_0, //x
[object] V_1,
object V_2)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldc.i4.1
IL_0005: add
IL_0006: box ""int""
IL_000b: stloc.2
IL_000c: br.s IL_000e
IL_000e: ldloc.2
IL_000f: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>f__AnonymousType1`1"); // one additional type
diff2.VerifyIL("B.G", @"
{
// Code size 33 (0x21)
.maxstack 1
.locals init ([int] V_0,
[object] V_1,
[object] V_2,
<>f__AnonymousType0<A> V_3, //x
<>f__AnonymousType1<int> V_4, //y
object V_5)
IL_0000: nop
IL_0001: newobj ""A..ctor()""
IL_0006: newobj ""<>f__AnonymousType0<A>..ctor(A)""
IL_000b: stloc.3
IL_000c: ldc.i4.2
IL_000d: newobj ""<>f__AnonymousType1<int>..ctor(int)""
IL_0012: stloc.s V_4
IL_0014: ldloc.3
IL_0015: callvirt ""A <>f__AnonymousType0<A>.A.get""
IL_001a: stloc.s V_5
IL_001c: br.s IL_001e
IL_001e: ldloc.s V_5
IL_0020: ret
}");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables: true)));
var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
CheckNames(new[] { reader0, reader1, reader2, reader3 }, reader3.GetTypeDefNames()); // no additional types
diff3.VerifyIL("B.G", @"
{
// Code size 39 (0x27)
.maxstack 1
.locals init ([int] V_0,
[object] V_1,
[object] V_2,
<>f__AnonymousType0<A> V_3, //x
<>f__AnonymousType1<int> V_4, //y
[object] V_5,
object V_6)
IL_0000: nop
IL_0001: newobj ""A..ctor()""
IL_0006: newobj ""<>f__AnonymousType0<A>..ctor(A)""
IL_000b: stloc.3
IL_000c: ldc.i4.3
IL_000d: newobj ""<>f__AnonymousType1<int>..ctor(int)""
IL_0012: stloc.s V_4
IL_0014: ldloc.s V_4
IL_0016: callvirt ""int <>f__AnonymousType1<int>.B.get""
IL_001b: box ""int""
IL_0020: stloc.s V_6
IL_0022: br.s IL_0024
IL_0024: ldloc.s V_6
IL_0026: ret
}");
}
/// <summary>
/// Update another method (without directly referencing
/// anonymous type) after updating method with anonymous type.
/// </summary>
[Fact]
public void AnonymousTypes_SkipGeneration_2()
{
var source0 =
@"class C
{
static object F()
{
var x = new { A = 1 };
return x.A;
}
static object G()
{
var x = 1;
return x;
}
}";
var source1 =
@"class C
{
static object F()
{
var x = new { A = 2, B = 3 };
return x.A;
}
static object G()
{
var x = 1;
return x;
}
}";
var source2 =
@"class C
{
static object F()
{
var x = new { A = 2, B = 3 };
return x.A;
}
static object G()
{
var x = 1;
return x + 1;
}
}";
var source3 =
@"class C
{
static object F()
{
var x = new { A = 2, B = 3 };
return x.A;
}
static object G()
{
var x = new { A = (object)null };
var y = new { A = 'a', B = 'b' };
return x;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var g1 = compilation1.GetMember<MethodSymbol>("C.G");
var g2 = compilation2.GetMember<MethodSymbol>("C.G");
var g3 = compilation3.GetMember<MethodSymbol>("C.G");
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
m => md0.MetadataReader.GetString(md0.MetadataReader.GetMethodDefinition(m).Name) switch
{
"F" => testData0.GetMethodData("C.F").GetEncDebugInfo(),
"G" => testData0.GetMethodData("C.G").GetEncDebugInfo(),
_ => default,
});
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`1", "C");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames(), "<>f__AnonymousType1`2"); // one additional type
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g1, g2, GetEquivalentNodesMap(g2, g1), preserveLocalVariables: true)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
CheckNames(readers, reader2.GetTypeDefNames()); // no additional types
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g2, g3, GetEquivalentNodesMap(g3, g2), preserveLocalVariables: true)));
using var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
readers.Add(reader3);
CheckNames(readers, reader3.GetTypeDefNames()); // no additional types
}
/// <summary>
/// Local from previous generation is of an anonymous
/// type not available in next generation.
/// </summary>
[Fact]
public void AnonymousTypes_AddThenDelete()
{
var source0 =
@"class C
{
object A;
static object F()
{
var x = new C();
var y = x.A;
return y;
}
}";
var source1 =
@"class C
{
static object F()
{
var x = new { A = new object() };
var y = x.A;
return y;
}
}";
var source2 =
@"class C
{
static object F()
{
var x = new { A = new object(), B = 2 };
var y = x.A;
y = new { B = new object() }.B;
return y;
}
}";
var source3 =
@"class C
{
static object F()
{
var x = new { A = new object(), B = 3 };
var y = x.A;
return y;
}
}";
var source4 =
@"class C
{
static object F()
{
var x = new { B = 4, A = new object() };
var y = x.A;
return y;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var compilation4 = compilation3.WithSource(source4);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, testData0.GetMethodData("C.F").EncDebugInfoProvider());
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType0`1"); // one additional type
diff1.VerifyIL("C.F", @"
{
// Code size 27 (0x1b)
.maxstack 1
.locals init ([unchanged] V_0,
object V_1, //y
[object] V_2,
<>f__AnonymousType0<object> V_3, //x
object V_4)
IL_0000: nop
IL_0001: newobj ""object..ctor()""
IL_0006: newobj ""<>f__AnonymousType0<object>..ctor(object)""
IL_000b: stloc.3
IL_000c: ldloc.3
IL_000d: callvirt ""object <>f__AnonymousType0<object>.A.get""
IL_0012: stloc.1
IL_0013: ldloc.1
IL_0014: stloc.s V_4
IL_0016: br.s IL_0018
IL_0018: ldloc.s V_4
IL_001a: ret
}");
var method2 = compilation2.GetMember<MethodSymbol>("C.F");
}
[Fact]
public void AnonymousTypes_DifferentCase()
{
var source0 = MarkedSource(@"
class C
{
static void M()
{
var <N:0>x = new { A = 1, B = 2 }</N:0>;
var <N:1>y = new { a = 3, b = 4 }</N:1>;
}
}");
var source1 = MarkedSource(@"
class C
{
static void M()
{
var <N:0>x = new { a = 1, B = 2 }</N:0>;
var <N:1>y = new { AB = 3 }</N:1>;
}
}");
var source2 = MarkedSource(@"
class C
{
static void M()
{
var <N:0>x = new { a = 1, B = 2 }</N:0>;
var <N:1>y = new { Ab = 5 }</N:1>;
}
}");
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 reader0 = md0.MetadataReader;
var m0 = compilation0.GetMember<MethodSymbol>("C.M");
var m1 = compilation1.GetMember<MethodSymbol>("C.M");
var m2 = compilation2.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`2", "<>f__AnonymousType1`2", "C");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var reader1 = diff1.GetMetadata().Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType2`2", "<>f__AnonymousType3`1");
// the first two slots can't be reused since the type changed
diff1.VerifyIL("C.M",
@"{
// Code size 17 (0x11)
.maxstack 2
.locals init ([unchanged] V_0,
[unchanged] V_1,
<>f__AnonymousType2<int, int> V_2, //x
<>f__AnonymousType3<int> V_3) //y
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: ldc.i4.2
IL_0003: newobj ""<>f__AnonymousType2<int, int>..ctor(int, int)""
IL_0008: stloc.2
IL_0009: ldc.i4.3
IL_000a: newobj ""<>f__AnonymousType3<int>..ctor(int)""
IL_000f: stloc.3
IL_0010: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
var reader2 = diff2.GetMetadata().Reader;
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>f__AnonymousType4`1");
// we can reuse slot for "x", it's type haven't changed
diff2.VerifyIL("C.M",
@"{
// Code size 18 (0x12)
.maxstack 2
.locals init ([unchanged] V_0,
[unchanged] V_1,
<>f__AnonymousType2<int, int> V_2, //x
[unchanged] V_3,
<>f__AnonymousType4<int> V_4) //y
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: ldc.i4.2
IL_0003: newobj ""<>f__AnonymousType2<int, int>..ctor(int, int)""
IL_0008: stloc.2
IL_0009: ldc.i4.5
IL_000a: newobj ""<>f__AnonymousType4<int>..ctor(int)""
IL_000f: stloc.s V_4
IL_0011: ret
}");
}
[Fact]
public void AnonymousTypes_Nested1()
{
var template = @"
using System;
using System.Linq;
class C
{
static void F(string[] args)
{
var <N:0>result =
from a in args
<N:1>let x = a.Reverse()</N:1>
<N:2>let y = x.Reverse()</N:2>
<N:3>where x.SequenceEqual(y)</N:3>
<N:4>select new { Value = a, Length = a.Length }</N:4></N:0>;
Console.WriteLine(<<VALUE>>);
}
}";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation0.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 expectedIL = @"
{
// Code size 155 (0x9b)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0""
IL_0007: dup
IL_0008: brtrue.s IL_0021
IL_000a: pop
IL_000b: ldsfld ""C.<>c C.<>c.<>9""
IL_0010: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> C.<>c.<F>b__0_0(string)""
IL_0016: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)""
IL_001b: dup
IL_001c: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0""
IL_0021: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)""
IL_0026: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> 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 ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> C.<>c.<F>b__0_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)""
IL_003a: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)""
IL_003f: dup
IL_0040: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1""
IL_0045: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)""
IL_004a: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2""
IL_004f: dup
IL_0050: brtrue.s IL_0069
IL_0052: pop
IL_0053: ldsfld ""C.<>c C.<>c.<>9""
IL_0058: ldftn ""bool C.<>c.<F>b__0_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_005e: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)""
IL_0063: dup
IL_0064: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2""
IL_0069: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)""
IL_006e: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3""
IL_0073: dup
IL_0074: brtrue.s IL_008d
IL_0076: pop
IL_0077: ldsfld ""C.<>c C.<>c.<>9""
IL_007c: ldftn ""<anonymous type: string Value, int Length> C.<>c.<F>b__0_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_0082: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)""
IL_0087: dup
IL_0088: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3""
IL_008d: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)""
IL_0092: stloc.0
IL_0093: ldc.i4.<<VALUE>>
IL_0094: call ""void System.Console.WriteLine(int)""
IL_0099: nop
IL_009a: 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}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}",
"<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <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}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}",
"<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2"));
}
[Fact]
public void AnonymousTypes_Nested2()
{
var template = @"
using System;
using System.Linq;
class C
{
static void F(string[] args)
{
var <N:0>result =
from a in args
<N:1>let x = a.Reverse()</N:1>
<N:2>let y = x.Reverse()</N:2>
<N:3>where x.SequenceEqual(y)</N:3>
<N:4>select new { Value = a, Length = a.Length }</N:4></N:0>;
Console.WriteLine(<<VALUE>>);
}
}";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation0.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 expectedIL = @"
{
// Code size 155 (0x9b)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0""
IL_0007: dup
IL_0008: brtrue.s IL_0021
IL_000a: pop
IL_000b: ldsfld ""C.<>c C.<>c.<>9""
IL_0010: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> C.<>c.<F>b__0_0(string)""
IL_0016: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)""
IL_001b: dup
IL_001c: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0""
IL_0021: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)""
IL_0026: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> 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 ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> C.<>c.<F>b__0_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)""
IL_003a: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)""
IL_003f: dup
IL_0040: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1""
IL_0045: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)""
IL_004a: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2""
IL_004f: dup
IL_0050: brtrue.s IL_0069
IL_0052: pop
IL_0053: ldsfld ""C.<>c C.<>c.<>9""
IL_0058: ldftn ""bool C.<>c.<F>b__0_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_005e: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)""
IL_0063: dup
IL_0064: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2""
IL_0069: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)""
IL_006e: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3""
IL_0073: dup
IL_0074: brtrue.s IL_008d
IL_0076: pop
IL_0077: ldsfld ""C.<>c C.<>c.<>9""
IL_007c: ldftn ""<anonymous type: string Value, int Length> C.<>c.<F>b__0_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_0082: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)""
IL_0087: dup
IL_0088: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3""
IL_008d: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)""
IL_0092: stloc.0
IL_0093: ldc.i4.<<VALUE>>
IL_0094: call ""void System.Console.WriteLine(int)""
IL_0099: nop
IL_009a: 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}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}",
"<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <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}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}",
"<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2"));
}
[Fact]
public void AnonymousTypes_Query1()
{
var source0 = MarkedSource(@"
using System.Linq;
class C
{
static void F(string[] args)
{
args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" };
var <N:4>result =
from a in args
<N:0>let x = a.Reverse()</N:0>
<N:1>let y = x.Reverse()</N:1>
<N:2>where x.SequenceEqual(y)</N:2>
<N:3>select new { Value = a, Length = a.Length }</N:3></N:4>;
var <N:8>newArgs =
from a in result
<N:5>let value = a.Value</N:5>
<N:6>let length = a.Length</N:6>
<N:7>where value.Length == length</N:7>
select value</N:8>;
args = args.Concat(newArgs).ToArray();
System.Diagnostics.Debugger.Break();
result.ToString();
}
}
");
var source1 = MarkedSource(@"
using System.Linq;
class C
{
static void F(string[] args)
{
args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" };
var list = false ? null : new { Head = (dynamic)null, Tail = (dynamic)null };
for (int i = 0; i < 10; i++)
{
var <N:4>result =
from a in args
<N:0>let x = a.Reverse()</N:0>
<N:1>let y = x.Reverse()</N:1>
<N:2>where x.SequenceEqual(y)</N:2>
orderby a.Length ascending, a descending
<N:3>select new { Value = a, Length = x.Count() }</N:3></N:4>;
var linked = result.Aggregate(
false ? new { Head = (string)null, Tail = (dynamic)null } : null,
(total, curr) => new { Head = curr.Value, Tail = (dynamic)total });
var str = linked?.Tail?.Head;
var <N:8>newArgs =
from a in result
<N:5>let value = a.Value</N:5>
<N:6>let length = a.Length</N:6>
<N:7>where value.Length == length</N:7>
select value + value</N:8>;
args = args.Concat(newArgs).ToArray();
list = new { Head = (dynamic)i, Tail = (dynamic)list };
System.Diagnostics.Debugger.Break();
}
System.Diagnostics.Debugger.Break();
}
}
");
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
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);
v0.VerifyLocalSignature("C.F", @"
.locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0, //result
System.Collections.Generic.IEnumerable<string> V_1) //newArgs
");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C.<>o__0#1: {<>p__0}",
"C: {<>o__0#1, <>c}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3#1, <>9__0_4#1, <>9__0_3, <>9__0_6#1, <>9__0_4, <>9__0_5, <>9__0_6, <>9__0_10#1, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3#1, <F>b__0_4#1, <F>b__0_3, <F>b__0_6#1, <F>b__0_4, <F>b__0_5, <F>b__0_6, <F>b__0_10#1}",
"<>f__AnonymousType4<<<>h__TransparentIdentifier0>j__TPar, <length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType5<<Head>j__TPar, <Tail>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType3<<a>j__TPar, <value>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyLocalSignature("C.F", @"
.locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0, //result
System.Collections.Generic.IEnumerable<string> V_1, //newArgs
<>f__AnonymousType5<dynamic, dynamic> V_2, //list
int V_3, //i
<>f__AnonymousType5<string, dynamic> V_4, //linked
object V_5, //str
<>f__AnonymousType5<string, dynamic> V_6,
object V_7,
bool V_8)
");
}
[Fact]
public void AnonymousTypes_Dynamic1()
{
var template = @"
using System;
class C
{
public void F()
{
var <N:0>x = new { A = (dynamic)null, B = 1 }</N:0>;
Console.WriteLine(x.B + <<VALUE>>);
}
}
";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
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 baselineIL0 = @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (<>f__AnonymousType0<dynamic, int> V_0) //x
IL_0000: nop
IL_0001: ldnull
IL_0002: ldc.i4.1
IL_0003: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)""
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get""
IL_000f: call ""void System.Console.WriteLine(int)""
IL_0014: nop
IL_0015: ret
}
";
v0.VerifyIL("C.F", baselineIL0);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}");
var baselineIL = @"
{
// Code size 24 (0x18)
.maxstack 2
.locals init (<>f__AnonymousType0<dynamic, int> V_0) //x
IL_0000: nop
IL_0001: ldnull
IL_0002: ldc.i4.1
IL_0003: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)""
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get""
IL_000f: ldc.i4.<<VALUE>>
IL_0010: add
IL_0011: call ""void System.Console.WriteLine(int)""
IL_0016: nop
IL_0017: ret
}
";
diff1.VerifyIL("C.F", baselineIL.Replace("<<VALUE>>", "1"));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", baselineIL.Replace("<<VALUE>>", "2"));
}
/// <summary>
/// Should not re-use locals if the method metadata
/// signature is unsupported.
/// </summary>
[WorkItem(9849, "https://github.com/dotnet/roslyn/issues/9849")]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/9849")]
public void LocalType_UnsupportedSignatureContent()
{
// Equivalent to C#, but with extra local and required modifier on
// expected local. Used to generate initial (unsupported) metadata.
var ilSource =
@".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly '<<GeneratedFileName>>' { }
.class C
{
.method public specialname rtspecialname instance void .ctor()
{
ret
}
.method private static object F()
{
ldnull
ret
}
.method private static void M1()
{
.locals init ([0] object other, [1] object modreq(int32) o)
call object C::F()
stloc.1
ldloc.1
call void C::M2(object)
ret
}
.method private static void M2(object o)
{
ret
}
}";
var source =
@"class C
{
static object F()
{
return null;
}
static void M1()
{
object o = F();
M2(o);
}
static void M2(object o)
{
}
}";
ImmutableArray<byte> assemblyBytes;
ImmutableArray<byte> pdbBytes;
EmitILToArray(ilSource, appendDefaultHeader: false, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
var md0 = ModuleMetadata.CreateFromImage(assemblyBytes);
// Still need a compilation with source for the initial
// generation - to get a MethodSymbol and syntax map.
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var method0 = compilation0.GetMember<MethodSymbol>("C.M1");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, m => default);
var method1 = compilation1.GetMember<MethodSymbol>("C.M1");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M1",
@"{
// Code size 15 (0xf)
.maxstack 1
.locals init (object V_0) //o
IL_0000: nop
IL_0001: call ""object C.F()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: call ""void C.M2(object)""
IL_000d: nop
IL_000e: ret
}");
}
/// <summary>
/// Should not re-use locals with custom modifiers.
/// </summary>
[WorkItem(9848, "https://github.com/dotnet/roslyn/issues/9848")]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/9848")]
public void LocalType_CustomModifiers()
{
// Equivalent method signature to C#, but
// with optional modifier on locals.
var ilSource =
@".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly '<<GeneratedFileName>>' { }
.class public C
{
.method public specialname rtspecialname instance void .ctor()
{
ret
}
.method public static object F(class [mscorlib]System.IDisposable d)
{
.locals init ([0] class C modopt(int32) c,
[1] class [mscorlib]System.IDisposable modopt(object),
[2] bool V_2,
[3] object V_3)
ldnull
ret
}
}";
var source =
@"class C
{
static object F(System.IDisposable d)
{
C c;
using (d)
{
c = (C)d;
}
return c;
}
}";
var metadata0 = (MetadataImageReference)CompileIL(ilSource, prependDefaultHeader: false);
// Still need a compilation with source for the initial
// generation - to get a MethodSymbol and syntax map.
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var moduleMetadata0 = ((AssemblyMetadata)metadata0.GetMetadataNoCopy()).GetModules()[0];
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(
moduleMetadata0,
m => default);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 38 (0x26)
.maxstack 1
.locals init ([unchanged] V_0,
[unchanged] V_1,
[bool] V_2,
[object] V_3,
C V_4, //c
System.IDisposable V_5,
object V_6)
-IL_0000: nop
-IL_0001: ldarg.0
IL_0002: stloc.s V_5
.try
{
-IL_0004: nop
-IL_0005: ldarg.0
IL_0006: castclass ""C""
IL_000b: stloc.s V_4
-IL_000d: nop
IL_000e: leave.s IL_001d
}
finally
{
~IL_0010: ldloc.s V_5
IL_0012: brfalse.s IL_001c
IL_0014: ldloc.s V_5
IL_0016: callvirt ""void System.IDisposable.Dispose()""
IL_001b: nop
IL_001c: endfinally
}
-IL_001d: ldloc.s V_4
IL_001f: stloc.s V_6
IL_0021: br.s IL_0023
-IL_0023: ldloc.s V_6
IL_0025: ret
}", methodToken: diff1.EmitResult.UpdatedMethods.Single());
}
/// <summary>
/// Temporaries for locals used within a single
/// statement should not be preserved.
/// </summary>
[Fact]
public void TemporaryLocals_Other()
{
// Use increment as an example of a compiler generated
// temporary that does not span multiple statements.
var source =
@"class C
{
int P { get; set; }
static int M()
{
var c = new C();
return c.P++;
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(
ModuleMetadata.CreateFromImage(bytes0),
methodData0.EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M", @"
{
// Code size 32 (0x20)
.maxstack 3
.locals init (C V_0, //c
[int] V_1,
[int] V_2,
int V_3,
int V_4)
IL_0000: nop
IL_0001: newobj ""C..ctor()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: dup
IL_0009: callvirt ""int C.P.get""
IL_000e: stloc.3
IL_000f: ldloc.3
IL_0010: ldc.i4.1
IL_0011: add
IL_0012: callvirt ""void C.P.set""
IL_0017: nop
IL_0018: ldloc.3
IL_0019: stloc.s V_4
IL_001b: br.s IL_001d
IL_001d: ldloc.s V_4
IL_001f: ret
}");
}
/// <summary>
/// Local names array (from PDB) may have fewer slots than method
/// signature (from metadata) when the trailing slots are unnamed.
/// </summary>
[WorkItem(782270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782270")]
[Fact]
public void Bug782270()
{
var source =
@"class C
{
static System.IDisposable F()
{
return null;
}
static void M()
{
using (var o = F())
{
}
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(
ModuleMetadata.CreateFromImage(bytes0),
testData0.GetMethodData("C.M").EncDebugInfoProvider());
testData0.GetMethodData("C.M").VerifyIL(@"
{
// Code size 23 (0x17)
.maxstack 1
.locals init (System.IDisposable V_0) //o
IL_0000: nop
IL_0001: call ""System.IDisposable C.F()""
IL_0006: stloc.0
.try
{
IL_0007: nop
IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.0
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
IL_0015: endfinally
}
IL_0016: ret
}");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M", @"
{
// Code size 23 (0x17)
.maxstack 1
.locals init (System.IDisposable V_0) //o
IL_0000: nop
IL_0001: call ""System.IDisposable C.F()""
IL_0006: stloc.0
.try
{
IL_0007: nop
IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.0
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
IL_0015: endfinally
}
IL_0016: ret
}");
}
/// <summary>
/// Similar to above test but with no named locals in original.
/// </summary>
[WorkItem(782270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782270")]
[Fact]
public void Bug782270_NoNamedLocals()
{
// Equivalent to C#, but with unnamed locals.
// Used to generate initial metadata.
var ilSource =
@".assembly extern netstandard { .ver 2:0:0:0 .publickeytoken = (cc 7b 13 ff cd 2d dd 51) }
.assembly '<<GeneratedFileName>>' { }
.class C extends object
{
.method private static class [netstandard]System.IDisposable F()
{
ldnull
ret
}
.method private static void M()
{
.locals init ([0] object, [1] object)
ret
}
}";
var source0 =
@"class C
{
static System.IDisposable F()
{
return null;
}
static void M()
{
}
}";
var source1 =
@"class C
{
static System.IDisposable F()
{
return null;
}
static void M()
{
using (var o = F())
{
}
}
}";
EmitILToArray(ilSource, appendDefaultHeader: false, includePdb: false, assemblyBytes: out var assemblyBytes, pdbBytes: out var pdbBytes);
var md0 = ModuleMetadata.CreateFromImage(assemblyBytes);
// Still need a compilation with source for the initial
// generation - to get a MethodSymbol and syntax map.
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M", @"
{
// Code size 23 (0x17)
.maxstack 1
.locals init ([object] V_0,
[object] V_1,
System.IDisposable V_2) //o
IL_0000: nop
IL_0001: call ""System.IDisposable C.F()""
IL_0006: stloc.2
.try
{
IL_0007: nop
IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
IL_000b: ldloc.2
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.2
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
IL_0015: endfinally
}
IL_0016: ret
}
");
}
[Fact]
public void TemporaryLocals_ReferencedType()
{
var source =
@"class C
{
static object F()
{
return null;
}
static void M()
{
var x = new System.Collections.Generic.HashSet<int>();
x.Add(1);
}
}";
var compilation0 = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var modMeta = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(
modMeta,
methodData0.EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M",
@"
{
// Code size 16 (0x10)
.maxstack 2
.locals init (System.Collections.Generic.HashSet<int> V_0) //x
IL_0000: nop
IL_0001: newobj ""System.Collections.Generic.HashSet<int>..ctor()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4.1
IL_0009: callvirt ""bool System.Collections.Generic.HashSet<int>.Add(int)""
IL_000e: pop
IL_000f: ret
}
");
}
[WorkItem(770502, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770502")]
[WorkItem(839565, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/839565")]
[Fact]
public void DynamicOperations()
{
var source =
@"class A
{
static object F = null;
object x = ((dynamic)F) + 1;
static A()
{
((dynamic)F).F();
}
A() { }
static void M(object o)
{
((dynamic)o).x = 1;
}
static void N(A o)
{
o.x = 1;
}
}
class B
{
static object F = null;
static object G = ((dynamic)F).F();
object x = ((dynamic)F) + 1;
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new[] { CSharpRef });
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
// Source method with dynamic operations.
var methodData0 = testData0.GetMethodData("A.M");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
var method0 = compilation0.GetMember<MethodSymbol>("A.M");
var method1 = compilation1.GetMember<MethodSymbol>("A.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
// Source method with no dynamic operations.
methodData0 = testData0.GetMethodData("A.N");
generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
method0 = compilation0.GetMember<MethodSymbol>("A.N");
method1 = compilation1.GetMember<MethodSymbol>("A.N");
diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
// Explicit .ctor with dynamic operations.
methodData0 = testData0.GetMethodData("A..ctor");
generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
method0 = compilation0.GetMember<MethodSymbol>("A..ctor");
method1 = compilation1.GetMember<MethodSymbol>("A..ctor");
diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
// Explicit .cctor with dynamic operations.
methodData0 = testData0.GetMethodData("A..cctor");
generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
method0 = compilation0.GetMember<MethodSymbol>("A..cctor");
method1 = compilation1.GetMember<MethodSymbol>("A..cctor");
diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
// Implicit .ctor with dynamic operations.
methodData0 = testData0.GetMethodData("B..ctor");
generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
method0 = compilation0.GetMember<MethodSymbol>("B..ctor");
method1 = compilation1.GetMember<MethodSymbol>("B..ctor");
diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
// Implicit .cctor with dynamic operations.
methodData0 = testData0.GetMethodData("B..cctor");
generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
method0 = compilation0.GetMember<MethodSymbol>("B..cctor");
method1 = compilation1.GetMember<MethodSymbol>("B..cctor");
diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
}
[Fact]
public void DynamicLocals()
{
var template = @"
using System;
class C
{
public void F()
{
dynamic <N:0>x = 1</N:0>;
Console.WriteLine((int)x + <<VALUE>>);
}
}
";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
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 82 (0x52)
.maxstack 3
.locals init (object V_0) //x
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: box ""int""
IL_0007: stloc.0
IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_000d: brfalse.s IL_0011
IL_000f: br.s IL_0036
IL_0011: ldc.i4.s 16
IL_0013: ldtoken ""int""
IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001d: ldtoken ""C""
IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target""
IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_0045: ldloc.0
IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_004b: call ""void System.Console.WriteLine(int)""
IL_0050: nop
IL_0051: ret
}
");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<>o__0#1}",
"C.<>o__0#1: {<>p__0}");
diff1.VerifyIL("C.F", @"
{
// Code size 84 (0x54)
.maxstack 3
.locals init (object V_0) //x
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: box ""int""
IL_0007: stloc.0
IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0""
IL_000d: brfalse.s IL_0011
IL_000f: br.s IL_0036
IL_0011: ldc.i4.s 16
IL_0013: ldtoken ""int""
IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001d: ldtoken ""C""
IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0""
IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0""
IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target""
IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0""
IL_0045: ldloc.0
IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_004b: ldc.i4.1
IL_004c: add
IL_004d: call ""void System.Console.WriteLine(int)""
IL_0052: nop
IL_0053: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<>o__0#2, <>o__0#1}",
"C.<>o__0#1: {<>p__0}",
"C.<>o__0#2: {<>p__0}");
diff2.VerifyIL("C.F", @"
{
// Code size 84 (0x54)
.maxstack 3
.locals init (object V_0) //x
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: box ""int""
IL_0007: stloc.0
IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0""
IL_000d: brfalse.s IL_0011
IL_000f: br.s IL_0036
IL_0011: ldc.i4.s 16
IL_0013: ldtoken ""int""
IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001d: ldtoken ""C""
IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0""
IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0""
IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target""
IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0""
IL_0045: ldloc.0
IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_004b: ldc.i4.2
IL_004c: add
IL_004d: call ""void System.Console.WriteLine(int)""
IL_0052: nop
IL_0053: ret
}
");
}
[Fact]
public void ExceptionFilters()
{
var source0 = MarkedSource(@"
using System;
using System.IO;
class C
{
static bool G(Exception e) => true;
static void F()
{
try
{
throw new InvalidOperationException();
}
catch <N:0>(IOException e)</N:0> <N:1>when (G(e))</N:1>
{
Console.WriteLine();
}
catch <N:2>(Exception e)</N:2> <N:3>when (G(e))</N:3>
{
Console.WriteLine();
}
}
}
");
var source1 = MarkedSource(@"
using System;
using System.IO;
class C
{
static bool G(Exception e) => true;
static void F()
{
try
{
throw new InvalidOperationException();
}
catch <N:0>(IOException e)</N:0> <N:1>when (G(e))</N:1>
{
Console.WriteLine();
}
catch <N:2>(Exception e)</N:2> <N:3>when (G(e))</N:3>
{
Console.WriteLine();
}
Console.WriteLine(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 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.VerifyIL("C.F", @"
{
// Code size 90 (0x5a)
.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_0020
IL_0014: stloc.0
IL_0015: ldloc.0
IL_0016: call ""bool C.G(System.Exception)""
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: ldc.i4.0
IL_001e: cgt.un
IL_0020: endfilter
} // end filter
{ // handler
IL_0022: pop
IL_0023: nop
IL_0024: call ""void System.Console.WriteLine()""
IL_0029: nop
IL_002a: nop
IL_002b: leave.s IL_0052
}
filter
{
IL_002d: isinst ""System.Exception""
IL_0032: dup
IL_0033: brtrue.s IL_0039
IL_0035: pop
IL_0036: ldc.i4.0
IL_0037: br.s IL_0045
IL_0039: stloc.2
IL_003a: ldloc.2
IL_003b: call ""bool C.G(System.Exception)""
IL_0040: stloc.3
IL_0041: ldloc.3
IL_0042: ldc.i4.0
IL_0043: cgt.un
IL_0045: endfilter
} // end filter
{ // handler
IL_0047: pop
IL_0048: nop
IL_0049: call ""void System.Console.WriteLine()""
IL_004e: nop
IL_004f: nop
IL_0050: leave.s IL_0052
}
IL_0052: ldc.i4.1
IL_0053: call ""void System.Console.WriteLine(int)""
IL_0058: nop
IL_0059: ret
}
");
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)]
public void MethodSignatureWithNoPIAType()
{
var sourcePIA = @"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""_.dll"")]
[assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A3"")]
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42920E2A4"")]
public interface I
{
}";
var source0 = MarkedSource(@"
class C
{
static void M(I x)
{
System.Console.WriteLine(1);
}
}");
var source1 = MarkedSource(@"
class C
{
static void M(I x)
{
System.Console.WriteLine(2);
}
}");
var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll);
var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true);
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll, references: new MetadataReference[] { referencePIA });
var compilation1 = compilation0.WithSource(source1.Tree);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
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.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify(
// error CS7096: Cannot continue since the edit includes a reference to an embedded type: 'I'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("I"));
}
[WorkItem(844472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844472")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)]
public void LocalSignatureWithNoPIAType()
{
var sourcePIA = @"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""_.dll"")]
[assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A3"")]
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42920E2A4"")]
public interface I
{
}";
var source0 = MarkedSource(@"
class C
{
static void M(I x)
{
I <N:0>y = null</N:0>;
M(null);
}
}");
var source1 = MarkedSource(@"
class C
{
static void M(I x)
{
I <N:0>y = null</N:0>;
M(x);
}
}");
var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll);
var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true);
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll, references: new MetadataReference[] { referencePIA });
var compilation1 = compilation0.WithSource(source1.Tree);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
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.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify(
// (6,16): warning CS0219: The variable 'y' is assigned but its value is never used
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y"),
// error CS7096: Cannot continue since the edit includes a reference to an embedded type: 'I'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("I"));
}
/// <summary>
/// Disallow edits that require NoPIA references.
/// </summary>
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)]
public void NoPIAReferences()
{
var sourcePIA =
@"using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""_.dll"")]
[assembly: Guid(""35DB1A6B-D635-4320-A062-28D42921E2B3"")]
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42921E2B4"")]
public interface IA
{
void M();
int P { get; }
event Action E;
}
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42921E2B5"")]
public interface IB
{
}
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42921E2B6"")]
public interface IC
{
}
public struct S
{
public object F;
}";
var source0 =
@"class C<T>
{
static object F = typeof(IC);
static void M1()
{
var o = default(IA);
o.M();
M2(o.P);
o.E += M1;
M2(C<IA>.F);
M2(new S());
}
static void M2(object o)
{
}
}";
var source1A = source0;
var source1B =
@"class C<T>
{
static object F = typeof(IC);
static void M1()
{
M2(null);
}
static void M2(object o)
{
}
}";
var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll);
var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true);
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, references: new MetadataReference[] { referencePIA, CSharpRef });
var compilation1A = compilation0.WithSource(source1A);
var compilation1B = compilation0.WithSource(source1B);
var method0 = compilation0.GetMember<MethodSymbol>("C.M1");
var method1B = compilation1B.GetMember<MethodSymbol>("C.M1");
var method1A = compilation1A.GetMember<MethodSymbol>("C.M1");
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C<T>.M1");
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C`1", "IA", "IC", "S");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
// Disallow edits that require NoPIA references.
var diff1A = compilation1A.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1A, GetEquivalentNodesMap(method1A, method0), preserveLocalVariables: true)));
diff1A.EmitResult.Diagnostics.Verify(
// error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'S'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("S"),
// error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'IA'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("IA"));
// Allow edits that do not require NoPIA references,
// even if the previous code included references.
var diff1B = compilation1B.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1B, GetEquivalentNodesMap(method1B, method0), preserveLocalVariables: true)));
diff1B.VerifyIL("C<T>.M1",
@"{
// Code size 9 (0x9)
.maxstack 1
.locals init ([unchanged] V_0,
[unchanged] V_1)
IL_0000: nop
IL_0001: ldnull
IL_0002: call ""void C<T>.M2(object)""
IL_0007: nop
IL_0008: ret
}");
using var md1 = diff1B.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames());
}
[WorkItem(844536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844536")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)]
public void NoPIATypeInNamespace()
{
var sourcePIA =
@"using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""_.dll"")]
[assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A5"")]
namespace N
{
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42920E2A6"")]
public interface IA
{
}
}
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42920E2A7"")]
public interface IB
{
}";
var source =
@"class C<T>
{
static void M(object o)
{
M(C<N.IA>.E.X);
M(C<IB>.E.X);
}
enum E { X }
}";
var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll);
var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true);
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new MetadataReference[] { referencePIA, CSharpRef });
var compilation1 = compilation0.WithSource(source);
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, m => default);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
diff1.EmitResult.Diagnostics.Verify(
// error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'N.IA'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("N.IA"),
// error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'IB'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("IB"));
diff1.VerifyIL("C<T>.M",
@"{
// Code size 26 (0x1a)
.maxstack 1
IL_0000: nop
IL_0001: ldc.i4.0
IL_0002: box ""C<N.IA>.E""
IL_0007: call ""void C<T>.M(object)""
IL_000c: nop
IL_000d: ldc.i4.0
IL_000e: box ""C<IB>.E""
IL_0013: call ""void C<T>.M(object)""
IL_0018: nop
IL_0019: ret
}");
}
/// <summary>
/// Should use TypeDef rather than TypeRef for unrecognized
/// local of a type defined in the original assembly.
/// </summary>
[WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")]
[Fact]
public void UnrecognizedLocalOfTypeFromAssembly()
{
var source =
@"class E : System.Exception
{
}
class C
{
static void M()
{
try
{
}
catch (E e)
{
}
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M");
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetAssemblyRefNames(), "netstandard");
CheckNames(readers, reader1.GetTypeRefNames(), "Object");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(7, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
diff1.VerifyIL("C.M", @"
{
// Code size 11 (0xb)
.maxstack 1
.locals init (E V_0) //e
IL_0000: nop
.try
{
IL_0001: nop
IL_0002: nop
IL_0003: leave.s IL_000a
}
catch E
{
IL_0005: stloc.0
IL_0006: nop
IL_0007: nop
IL_0008: leave.s IL_000a
}
IL_000a: ret
}");
}
/// <summary>
/// Similar to above test but with anonymous type
/// added in subsequent generation.
/// </summary>
[WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")]
[Fact]
public void UnrecognizedLocalOfAnonymousTypeFromAssembly()
{
var source0 =
@"class C
{
static string F()
{
return null;
}
static string G()
{
var o = new { Y = 1 };
return o.ToString();
}
}";
var source1 =
@"class C
{
static string F()
{
var o = new { X = 1 };
return o.ToString();
}
static string G()
{
var o = new { Y = 1 };
return o.ToString();
}
}";
var source2 =
@"class C
{
static string F()
{
return null;
}
static string G()
{
return null;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var method0F = compilation0.GetMember<MethodSymbol>("C.F");
var method1F = compilation1.GetMember<MethodSymbol>("C.F");
var method1G = compilation1.GetMember<MethodSymbol>("C.G");
var method2F = compilation2.GetMember<MethodSymbol>("C.F");
var method2G = compilation2.GetMember<MethodSymbol>("C.G");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard");
// Use empty LocalVariableNameProvider for original locals and
// use preserveLocalVariables: true for the edit so that existing
// locals are retained even though all are unrecognized.
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
CheckNames(readers, reader1.GetAssemblyRefNames(), "netstandard");
CheckNames(readers, reader1.GetTypeDefNames(), "<>f__AnonymousType1`1");
CheckNames(readers, reader1.GetTypeRefNames(), "CompilerGeneratedAttribute", "DebuggerDisplayAttribute", "Object", "DebuggerBrowsableState", "DebuggerBrowsableAttribute", "DebuggerHiddenAttribute", "EqualityComparer`1", "String", "IFormatProvider");
// Change method updated in generation 1.
var diff2F = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1F, method2F, syntaxMap: s => null, preserveLocalVariables: true)));
using var md2 = diff2F.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
CheckNames(readers, reader2.GetAssemblyRefNames(), "netstandard");
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetTypeRefNames(), "Object");
// Change method unchanged since generation 0.
var diff2G = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1G, method2G, syntaxMap: s => null, preserveLocalVariables: true)));
}
[Fact]
public void BrokenOutputStreams()
{
var source0 =
@"class C
{
static string F()
{
return null;
}
}";
var source1 =
@"class C
{
static string F()
{
var o = new { X = 1 };
return o.ToString();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray();
using (new EnsureEnglishUICulture())
using (var md0 = ModuleMetadata.CreateFromImage(bytes0))
{
var method0F = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1F = compilation1.GetMember<MethodSymbol>("C.F");
using MemoryStream mdStream = new MemoryStream(), ilStream = new MemoryStream(), pdbStream = new MemoryStream();
var isAddedSymbol = new Func<ISymbol, bool>(s => false);
var badStream = new BrokenStream();
badStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite;
var result = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)),
isAddedSymbol,
badStream,
ilStream,
pdbStream,
new CompilationTestData(),
default);
Assert.False(result.Success);
result.Diagnostics.Verify(
// error CS8104: An error occurred while writing the output file: System.IO.IOException: I/O error occurred.
Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(badStream.ThrownException.ToString()).WithLocation(1, 1)
);
result = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)),
isAddedSymbol,
mdStream,
badStream,
pdbStream,
new CompilationTestData(),
default);
Assert.False(result.Success);
result.Diagnostics.Verify(
// error CS8104: An error occurred while writing the output file: System.IO.IOException: I/O error occurred.
Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(badStream.ThrownException.ToString()).WithLocation(1, 1)
);
result = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)),
isAddedSymbol,
mdStream,
ilStream,
badStream,
new CompilationTestData(),
default);
Assert.False(result.Success);
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'I/O error occurred.'
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1)
);
}
}
[Fact]
public void BrokenPortablePdbStream()
{
var source0 =
@"class C
{
static string F()
{
return null;
}
}";
var source1 =
@"class C
{
static string F()
{
var o = new { X = 1 };
return o.ToString();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb));
using (new EnsureEnglishUICulture())
using (var md0 = ModuleMetadata.CreateFromImage(bytes0))
{
var method0F = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1F = compilation1.GetMember<MethodSymbol>("C.F");
using MemoryStream mdStream = new MemoryStream(), ilStream = new MemoryStream(), pdbStream = new MemoryStream();
var isAddedSymbol = new Func<ISymbol, bool>(s => false);
var badStream = new BrokenStream();
badStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite;
var result = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)),
isAddedSymbol,
mdStream,
ilStream,
badStream,
new CompilationTestData(),
default);
Assert.False(result.Success);
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'I/O error occurred.'
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1)
);
}
}
[WorkItem(923492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/923492")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SymWriterErrors()
{
var source0 =
@"class C
{
}";
var source1 =
@"class C
{
static void Main() { }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var diff1 = compilation1.EmitDifference(
EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider),
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.Main"))),
testData: new CompilationTestData { SymWriterFactory = _ => new MockSymUnmanagedWriter() });
diff1.EmitResult.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'MockSymUnmanagedWriter error message'
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("MockSymUnmanagedWriter error message"));
Assert.False(diff1.EmitResult.Success);
}
[WorkItem(1058058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1058058")]
[Fact]
public void BlobContainsInvalidValues()
{
var source0 =
@"class C
{
static void F()
{
string goo = ""abc"";
}
}";
var source1 =
@"class C
{
static void F()
{
float goo = 10;
}
}";
var source2 =
@"class C
{
static void F()
{
bool goo = true;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard");
var method0F = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method1F = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)));
var handle = MetadataTokens.BlobHandle(1);
byte[] value0 = reader0.GetBlobBytes(handle);
Assert.Equal("20-01-01-08", BitConverter.ToString(value0));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var method2F = compilation2.GetMember<MethodSymbol>("C.F");
var diff2F = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1F, method2F, syntaxMap: s => null, preserveLocalVariables: true)));
byte[] value1 = reader1.GetBlobBytes(handle);
Assert.Equal("07-02-0E-0C", BitConverter.ToString(value1));
using var md2 = diff2F.GetMetadata();
var reader2 = md2.Reader;
byte[] value2 = reader2.GetBlobBytes(handle);
Assert.Equal("07-03-0E-0C-02", BitConverter.ToString(value2));
}
[Fact]
public void ReferenceToMemberAddedToAnotherAssembly1()
{
var sourceA0 = @"
public class A
{
}
";
var sourceA1 = @"
public class A
{
public void M() { System.Console.WriteLine(1);}
}
public class X {}
";
var sourceB0 = @"
public class B
{
public static void F() { }
}";
var sourceB1 = @"
public class B
{
public static void F() { new A().M(); }
}
public class Y : X { }
";
var compilationA0 = CreateCompilation(sourceA0, options: TestOptions.DebugDll, assemblyName: "LibA");
var compilationA1 = compilationA0.WithSource(sourceA1);
var compilationB0 = CreateCompilation(sourceB0, new[] { compilationA0.ToMetadataReference() }, options: TestOptions.DebugDll, assemblyName: "LibB");
var compilationB1 = CreateCompilation(sourceB1, new[] { compilationA1.ToMetadataReference() }, options: TestOptions.DebugDll, assemblyName: "LibB");
var bytesA0 = compilationA0.EmitToArray();
var bytesB0 = compilationB0.EmitToArray();
var mdA0 = ModuleMetadata.CreateFromImage(bytesA0);
var mdB0 = ModuleMetadata.CreateFromImage(bytesB0);
var generationA0 = EmitBaseline.CreateInitialBaseline(mdA0, EmptyLocalsProvider);
var generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, EmptyLocalsProvider);
var mA1 = compilationA1.GetMember<MethodSymbol>("A.M");
var mX1 = compilationA1.GetMember<TypeSymbol>("X");
var allAddedSymbols = new ISymbol[] { mA1.GetPublicSymbol(), mX1.GetPublicSymbol() };
var diffA1 = compilationA1.EmitDifference(
generationA0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, mA1),
SemanticEdit.Create(SemanticEditKind.Insert, null, mX1)),
allAddedSymbols);
diffA1.EmitResult.Diagnostics.Verify();
var diffB1 = compilationB1.EmitDifference(
generationB0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, compilationB0.GetMember<MethodSymbol>("B.F"), compilationB1.GetMember<MethodSymbol>("B.F")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilationB1.GetMember<TypeSymbol>("Y"))),
allAddedSymbols);
diffB1.EmitResult.Diagnostics.Verify(
// (7,14): error CS7101: Member 'X' added during the current debug session can only be accessed from within its declaring assembly 'LibA'.
// public class X {}
Diagnostic(ErrorCode.ERR_EncReferenceToAddedMember, "X").WithArguments("X", "LibA").WithLocation(7, 14),
// (4,17): error CS7101: Member 'M' added during the current debug session can only be accessed from within its declaring assembly 'LibA'.
// public void M() { System.Console.WriteLine(1);}
Diagnostic(ErrorCode.ERR_EncReferenceToAddedMember, "M").WithArguments("M", "LibA").WithLocation(4, 17));
}
[Fact]
public void ReferenceToMemberAddedToAnotherAssembly2()
{
var sourceA = @"
public class A
{
public void M() { }
}";
var sourceB0 = @"
public class B
{
public static void F() { var a = new A(); }
}";
var sourceB1 = @"
public class B
{
public static void F() { var a = new A(); a.M(); }
}";
var sourceB2 = @"
public class B
{
public static void F() { var a = new A(); }
}";
var compilationA = CreateCompilation(sourceA, options: TestOptions.DebugDll, assemblyName: "AssemblyA");
var aRef = compilationA.ToMetadataReference();
var compilationB0 = CreateCompilation(sourceB0, new[] { aRef }, options: TestOptions.DebugDll, assemblyName: "AssemblyB");
var compilationB1 = compilationB0.WithSource(sourceB1);
var compilationB2 = compilationB1.WithSource(sourceB2);
var testDataB0 = new CompilationTestData();
var bytesB0 = compilationB0.EmitToArray(testData: testDataB0);
var mdB0 = ModuleMetadata.CreateFromImage(bytesB0);
var generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, testDataB0.GetMethodData("B.F").EncDebugInfoProvider());
var f0 = compilationB0.GetMember<MethodSymbol>("B.F");
var f1 = compilationB1.GetMember<MethodSymbol>("B.F");
var f2 = compilationB2.GetMember<MethodSymbol>("B.F");
var diffB1 = compilationB1.EmitDifference(
generationB0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true)));
diffB1.VerifyIL("B.F", @"
{
// Code size 15 (0xf)
.maxstack 1
.locals init (A V_0) //a
IL_0000: nop
IL_0001: newobj ""A..ctor()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: callvirt ""void A.M()""
IL_000d: nop
IL_000e: ret
}
");
var diffB2 = compilationB2.EmitDifference(
diffB1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetEquivalentNodesMap(f2, f1), preserveLocalVariables: true)));
diffB2.VerifyIL("B.F", @"
{
// Code size 8 (0x8)
.maxstack 1
.locals init (A V_0) //a
IL_0000: nop
IL_0001: newobj ""A..ctor()""
IL_0006: stloc.0
IL_0007: ret
}
");
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)]
public void UniqueSynthesizedNames_DynamicSiteContainer()
{
var source0 = @"
public class C
{
public static void F(dynamic d) { d.Goo(); }
}";
var source1 = @"
public class C
{
public static void F(dynamic d) { d.Bar(); }
}";
var source2 = @"
public class C
{
public static void F(dynamic d, byte b) { d.Bar(); }
public static void F(dynamic d) { d.Bar(); }
}";
var compilation0 = CreateCompilation(source0, targetFramework: TargetFramework.StandardAndCSharp,
options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A");
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f_byte2 = compilation2.GetMembers("C.F").Single(m => m.ToString() == "C.F(dynamic, byte)");
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.Update, f0, f1, preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f_byte2)));
diff2.EmitResult.Diagnostics.Verify();
var reader0 = md0.MetadataReader;
var reader1 = diff1.GetMetadata().Reader;
var reader2 = diff2.GetMetadata().Reader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>o__0");
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>o__0#1");
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>o__0#2");
}
[WorkItem(918650, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/918650")]
[Fact]
public void ManyGenerations()
{
var source =
@"class C
{{
static int F() {{ return {0}; }}
}}";
var compilation0 = CreateCompilation(String.Format(source, 1), options: TestOptions.DebugDll);
var bytes0 = compilation0.EmitToArray();
var md0 = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
for (int i = 2; i <= 50; i++)
{
var compilation1 = compilation0.WithSource(String.Format(source, i));
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
compilation0 = compilation1;
method0 = method1;
generation0 = diff1.NextGeneration;
}
}
[WorkItem(187868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/187868")]
[Fact]
public void PdbReadingErrors()
{
var source0 = MarkedSource(@"
using System;
class C
{
static void F()
{
<N:0>Console.WriteLine(1);</N:0>
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static void F()
{
<N:0>Console.WriteLine(2);</N:0>
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll, assemblyName: "PdbReadingErrorsAssembly");
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, methodHandle =>
{
throw new InvalidDataException("Bad PDB!");
});
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify(
// (6,14): error CS7038: Failed to emit module 'Unable to read debug information of method 'C.F()' (token 0x06000001) from assembly 'PdbReadingErrorsAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null''.
Diagnostic(ErrorCode.ERR_InvalidDebugInfo, "F").WithArguments("C.F()", "100663297", "PdbReadingErrorsAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 14));
}
[Fact]
public void PdbReadingErrors_PassThruExceptions()
{
var source0 = MarkedSource(@"
using System;
class C
{
static void F()
{
<N:0>Console.WriteLine(1);</N:0>
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static void F()
{
<N:0>Console.WriteLine(2);</N:0>
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll, assemblyName: "PdbReadingErrorsAssembly");
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, methodHandle =>
{
throw new ArgumentOutOfRangeException();
});
// the compiler should't swallow any exceptions but InvalidDataException
Assert.Throws<ArgumentOutOfRangeException>(() =>
compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))));
}
[Fact]
public void PatternVariable_TypeChange()
{
var source0 = MarkedSource(@"
class C
{
static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; }
}");
var source1 = MarkedSource(@"
class C
{
static int F(object o) { if (o is bool <N:0>i</N:0>) { return i ? 1 : 0; } return 0; }
}");
var source2 = MarkedSource(@"
class C
{
static int F(object o) { if (o is int <N:0>j</N:0>) { return j; } return 0; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.F", @"
{
// Code size 35 (0x23)
.maxstack 1
.locals init (int V_0, //i
bool V_1,
int V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""int""
IL_0007: brfalse.s IL_0013
IL_0009: ldarg.0
IL_000a: unbox.any ""int""
IL_000f: stloc.0
IL_0010: ldc.i4.1
IL_0011: br.s IL_0014
IL_0013: ldc.i4.0
IL_0014: stloc.1
IL_0015: ldloc.1
IL_0016: brfalse.s IL_001d
IL_0018: nop
IL_0019: ldloc.0
IL_001a: stloc.2
IL_001b: br.s IL_0021
IL_001d: ldc.i4.0
IL_001e: stloc.2
IL_001f: br.s IL_0021
IL_0021: ldloc.2
IL_0022: ret
}");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
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.VerifyIL("C.F", @"
{
// Code size 46 (0x2e)
.maxstack 1
.locals init ([int] V_0,
[bool] V_1,
[int] V_2,
bool V_3, //i
bool V_4,
int V_5)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""bool""
IL_0007: brfalse.s IL_0013
IL_0009: ldarg.0
IL_000a: unbox.any ""bool""
IL_000f: stloc.3
IL_0010: ldc.i4.1
IL_0011: br.s IL_0014
IL_0013: ldc.i4.0
IL_0014: stloc.s V_4
IL_0016: ldloc.s V_4
IL_0018: brfalse.s IL_0026
IL_001a: nop
IL_001b: ldloc.3
IL_001c: brtrue.s IL_0021
IL_001e: ldc.i4.0
IL_001f: br.s IL_0022
IL_0021: ldc.i4.1
IL_0022: stloc.s V_5
IL_0024: br.s IL_002b
IL_0026: ldc.i4.0
IL_0027: stloc.s V_5
IL_0029: br.s IL_002b
IL_002b: ldloc.s V_5
IL_002d: 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 42 (0x2a)
.maxstack 1
.locals init ([int] V_0,
[bool] V_1,
[int] V_2,
[bool] V_3,
[bool] V_4,
[int] V_5,
int V_6, //j
bool V_7,
int V_8)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""int""
IL_0007: brfalse.s IL_0014
IL_0009: ldarg.0
IL_000a: unbox.any ""int""
IL_000f: stloc.s V_6
IL_0011: ldc.i4.1
IL_0012: br.s IL_0015
IL_0014: ldc.i4.0
IL_0015: stloc.s V_7
IL_0017: ldloc.s V_7
IL_0019: brfalse.s IL_0022
IL_001b: nop
IL_001c: ldloc.s V_6
IL_001e: stloc.s V_8
IL_0020: br.s IL_0027
IL_0022: ldc.i4.0
IL_0023: stloc.s V_8
IL_0025: br.s IL_0027
IL_0027: ldloc.s V_8
IL_0029: ret
}");
}
[Fact]
public void PatternVariable_DeleteInsert()
{
var source0 = MarkedSource(@"
class C
{
static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; }
}");
var source1 = MarkedSource(@"
class C
{
static int F(object o) { if (o is int) { return 1; } return 0; }
}");
var source2 = MarkedSource(@"
class C
{
static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.F", @"
{
// Code size 35 (0x23)
.maxstack 1
.locals init (int V_0, //i
bool V_1,
int V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""int""
IL_0007: brfalse.s IL_0013
IL_0009: ldarg.0
IL_000a: unbox.any ""int""
IL_000f: stloc.0
IL_0010: ldc.i4.1
IL_0011: br.s IL_0014
IL_0013: ldc.i4.0
IL_0014: stloc.1
IL_0015: ldloc.1
IL_0016: brfalse.s IL_001d
IL_0018: nop
IL_0019: ldloc.0
IL_001a: stloc.2
IL_001b: br.s IL_0021
IL_001d: ldc.i4.0
IL_001e: stloc.2
IL_001f: br.s IL_0021
IL_0021: ldloc.2
IL_0022: ret
}");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
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.VerifyIL("C.F", @"
{
// Code size 28 (0x1c)
.maxstack 2
.locals init ([int] V_0,
[bool] V_1,
[int] V_2,
bool V_3,
int V_4)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""int""
IL_0007: ldnull
IL_0008: cgt.un
IL_000a: stloc.3
IL_000b: ldloc.3
IL_000c: brfalse.s IL_0014
IL_000e: nop
IL_000f: ldc.i4.1
IL_0010: stloc.s V_4
IL_0012: br.s IL_0019
IL_0014: ldc.i4.0
IL_0015: stloc.s V_4
IL_0017: br.s IL_0019
IL_0019: ldloc.s V_4
IL_001b: 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 42 (0x2a)
.maxstack 1
.locals init ([int] V_0,
[bool] V_1,
[int] V_2,
[bool] V_3,
[int] V_4,
int V_5, //i
bool V_6,
int V_7)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""int""
IL_0007: brfalse.s IL_0014
IL_0009: ldarg.0
IL_000a: unbox.any ""int""
IL_000f: stloc.s V_5
IL_0011: ldc.i4.1
IL_0012: br.s IL_0015
IL_0014: ldc.i4.0
IL_0015: stloc.s V_6
IL_0017: ldloc.s V_6
IL_0019: brfalse.s IL_0022
IL_001b: nop
IL_001c: ldloc.s V_5
IL_001e: stloc.s V_7
IL_0020: br.s IL_0027
IL_0022: ldc.i4.0
IL_0023: stloc.s V_7
IL_0025: br.s IL_0027
IL_0027: ldloc.s V_7
IL_0029: ret
}");
}
[Fact]
public void PatternVariable_InConstructorInitializer()
{
var baseClass = "public class Base { public Base(bool x) { } }";
var source0 = MarkedSource(@"
public class C : Base
{
public C(int a) : base(a is int <N:0>x</N:0> && x == 0 && a is int <N:1>y</N:1>) { y = 1; }
}" + baseClass);
var source1 = MarkedSource(@"
public class C : Base
{
public C(int a) : base(a is int <N:0>x</N:0> && x == 0) { }
}" + baseClass);
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: brtrue.s IL_000b
IL_0006: ldarg.1
IL_0007: stloc.1
IL_0008: ldc.i4.1
IL_0009: br.s IL_000c
IL_000b: ldc.i4.0
IL_000c: call ""Base..ctor(bool)""
IL_0011: nop
IL_0012: nop
IL_0013: ldc.i4.1
IL_0014: stloc.1
IL_0015: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
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)));
diff1.VerifyIL("C..ctor", @"
{
// Code size 15 (0xf)
.maxstack 3
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldc.i4.0
IL_0005: ceq
IL_0007: call ""Base..ctor(bool)""
IL_000c: nop
IL_000d: nop
IL_000e: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifyIL("C..ctor", @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: brtrue.s IL_000b
IL_0006: ldarg.1
IL_0007: stloc.2
IL_0008: ldc.i4.1
IL_0009: br.s IL_000c
IL_000b: ldc.i4.0
IL_000c: call ""Base..ctor(bool)""
IL_0011: nop
IL_0012: nop
IL_0013: ldc.i4.1
IL_0014: stloc.2
IL_0015: ret
}
");
}
[Fact]
public void PatternVariable_InFieldInitializer()
{
var source0 = MarkedSource(@"
public class C
{
public static int a = 0;
public bool field = a is int <N:0>x</N:0> && x == 0 && a is int <N:1>y</N:1>;
}");
var source1 = MarkedSource(@"
public class C
{
public static int a = 0;
public bool field = a is int <N:0>x</N:0> && x == 0;
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.0
IL_0001: ldsfld ""int C.a""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brtrue.s IL_0013
IL_000a: ldsfld ""int C.a""
IL_000f: stloc.1
IL_0010: ldc.i4.1
IL_0011: br.s IL_0014
IL_0013: ldc.i4.0
IL_0014: stfld ""bool C.field""
IL_0019: ldarg.0
IL_001a: call ""object..ctor()""
IL_001f: nop
IL_0020: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
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)));
diff1.VerifyIL("C..ctor", @"
{
// Code size 24 (0x18)
.maxstack 3
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.0
IL_0001: ldsfld ""int C.a""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4.0
IL_0009: ceq
IL_000b: stfld ""bool C.field""
IL_0010: ldarg.0
IL_0011: call ""object..ctor()""
IL_0016: nop
IL_0017: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifyIL("C..ctor", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.0
IL_0001: ldsfld ""int C.a""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brtrue.s IL_0013
IL_000a: ldsfld ""int C.a""
IL_000f: stloc.2
IL_0010: ldc.i4.1
IL_0011: br.s IL_0014
IL_0013: ldc.i4.0
IL_0014: stfld ""bool C.field""
IL_0019: ldarg.0
IL_001a: call ""object..ctor()""
IL_001f: nop
IL_0020: ret
}
");
}
[Fact]
public void PatternVariable_InQuery()
{
var source0 = MarkedSource(@"
using System.Linq;
public class Program
{
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select a is int <N:2>x</N:2> && x == 0 && a is int <N:3>y</N:3></N:1></N:0>;
}
}");
var source1 = MarkedSource(@"
using System.Linq;
public class Program
{
static int M(int x, out int y) { y = 42; return 43; }
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select a is int <N:2>x</N:2> && x == 0</N:1></N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var n0 = compilation0.GetMember<MethodSymbol>("Program.N");
var n1 = compilation1.GetMember<MethodSymbol>("Program.N");
var n2 = compilation2.GetMember<MethodSymbol>("Program.N");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)""
IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_0033: stloc.0
IL_0034: ret
}
");
v0.VerifyIL("Program.<>c.<N>b__0_0(int)", @"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: brtrue.s IL_000a
IL_0005: ldarg.1
IL_0006: stloc.1
IL_0007: ldc.i4.1
IL_0008: br.s IL_000b
IL_000a: ldc.i4.0
IL_000b: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers("Program: {<>c}", "Program.<>c: {<>9__0_0, <N>b__0_0}");
diff1.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)""
IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff1.VerifyIL("Program.<>c.<N>b__0_0(int)", @"
{
// Code size 7 (0x7)
.maxstack 2
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ceq
IL_0006: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers("Program: {<>c}", "Program.<>c: {<>9__0_0, <N>b__0_0}");
diff2.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)""
IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff2.VerifyIL("Program.<>c.<N>b__0_0(int)", @"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: brtrue.s IL_000a
IL_0005: ldarg.1
IL_0006: stloc.2
IL_0007: ldc.i4.1
IL_0008: br.s IL_000b
IL_000a: ldc.i4.0
IL_000b: ret
}
");
}
[Fact]
public void Tuple_Parenthesized()
{
var source0 = MarkedSource(@"
class C
{
static int F() { (int, (int, int)) <N:0>x</N:0> = (1, (2, 3)); return x.Item1 + x.Item2.Item1 + x.Item2.Item2; }
}");
var source1 = MarkedSource(@"
class C
{
static int F() { (int, int, int) <N:0>x</N:0> = (1, 2, 3); return x.Item1 + x.Item2 + x.Item3; }
}");
var source2 = MarkedSource(@"
class C
{
static int F() { (int, int) <N:0>x</N:0> = (1, 3); return x.Item1 + x.Item2; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.F", @"
{
// Code size 51 (0x33)
.maxstack 4
.locals init (System.ValueTuple<int, System.ValueTuple<int, int>> V_0, //x
int V_1)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldc.i4.1
IL_0004: ldc.i4.2
IL_0005: ldc.i4.3
IL_0006: newobj ""System.ValueTuple<int, int>..ctor(int, int)""
IL_000b: call ""System.ValueTuple<int, System.ValueTuple<int, int>>..ctor(int, System.ValueTuple<int, int>)""
IL_0010: ldloc.0
IL_0011: ldfld ""int System.ValueTuple<int, System.ValueTuple<int, int>>.Item1""
IL_0016: ldloc.0
IL_0017: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2""
IL_001c: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_0021: add
IL_0022: ldloc.0
IL_0023: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2""
IL_0028: ldfld ""int System.ValueTuple<int, int>.Item2""
IL_002d: add
IL_002e: stloc.1
IL_002f: br.s IL_0031
IL_0031: ldloc.1
IL_0032: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
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.VerifyIL("C.F", @"
{
// Code size 36 (0x24)
.maxstack 4
.locals init ([unchanged] V_0,
[int] V_1,
System.ValueTuple<int, int, int> V_2, //x
int V_3)
IL_0000: nop
IL_0001: ldloca.s V_2
IL_0003: ldc.i4.1
IL_0004: ldc.i4.2
IL_0005: ldc.i4.3
IL_0006: call ""System.ValueTuple<int, int, int>..ctor(int, int, int)""
IL_000b: ldloc.2
IL_000c: ldfld ""int System.ValueTuple<int, int, int>.Item1""
IL_0011: ldloc.2
IL_0012: ldfld ""int System.ValueTuple<int, int, int>.Item2""
IL_0017: add
IL_0018: ldloc.2
IL_0019: ldfld ""int System.ValueTuple<int, int, int>.Item3""
IL_001e: add
IL_001f: stloc.3
IL_0020: br.s IL_0022
IL_0022: ldloc.3
IL_0023: 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 32 (0x20)
.maxstack 3
.locals init ([unchanged] V_0,
[int] V_1,
[unchanged] V_2,
[int] V_3,
System.ValueTuple<int, int> V_4, //x
int V_5)
IL_0000: nop
IL_0001: ldloca.s V_4
IL_0003: ldc.i4.1
IL_0004: ldc.i4.3
IL_0005: call ""System.ValueTuple<int, int>..ctor(int, int)""
IL_000a: ldloc.s V_4
IL_000c: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_0011: ldloc.s V_4
IL_0013: ldfld ""int System.ValueTuple<int, int>.Item2""
IL_0018: add
IL_0019: stloc.s V_5
IL_001b: br.s IL_001d
IL_001d: ldloc.s V_5
IL_001f: ret
}
");
}
[Fact]
public void Tuple_Decomposition()
{
var source0 = MarkedSource(@"
class C
{
static int F() { (int <N:0>x</N:0>, int <N:1>y</N:1>, int <N:2>z</N:2>) = (1, 2, 3); return x + y + z; }
}");
var source1 = MarkedSource(@"
class C
{
static int F() { (int <N:0>x</N:0>, int <N:2>z</N:2>) = (1, 3); return x + z; }
}");
var source2 = MarkedSource(@"
class C
{
static int F() { (int <N:0>x</N:0>, int <N:1>y</N:1>, int <N:2>z</N:2>) = (1, 2, 3); return x + y + z; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.F", @"
{
// Code size 17 (0x11)
.maxstack 2
.locals init (int V_0, //x
int V_1, //y
int V_2, //z
int V_3)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldc.i4.2
IL_0004: stloc.1
IL_0005: ldc.i4.3
IL_0006: stloc.2
IL_0007: ldloc.0
IL_0008: ldloc.1
IL_0009: add
IL_000a: ldloc.2
IL_000b: add
IL_000c: stloc.3
IL_000d: br.s IL_000f
IL_000f: ldloc.3
IL_0010: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
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.VerifyIL("C.F", @"
{
// Code size 15 (0xf)
.maxstack 2
.locals init (int V_0, //x
[int] V_1,
int V_2, //z
[int] V_3,
int V_4)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldc.i4.3
IL_0004: stloc.2
IL_0005: ldloc.0
IL_0006: ldloc.2
IL_0007: add
IL_0008: stloc.s V_4
IL_000a: br.s IL_000c
IL_000c: ldloc.s V_4
IL_000e: 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 21 (0x15)
.maxstack 2
.locals init (int V_0, //x
[int] V_1,
int V_2, //z
[int] V_3,
[int] V_4,
int V_5, //y
int V_6)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldc.i4.2
IL_0004: stloc.s V_5
IL_0006: ldc.i4.3
IL_0007: stloc.2
IL_0008: ldloc.0
IL_0009: ldloc.s V_5
IL_000b: add
IL_000c: ldloc.2
IL_000d: add
IL_000e: stloc.s V_6
IL_0010: br.s IL_0012
IL_0012: ldloc.s V_6
IL_0014: ret
}
");
}
[Fact]
public void ForeachStatement()
{
var source0 = MarkedSource(@"
class C
{
public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) };
public static void G()
{
foreach (var (<N:0>x</N:0>, (<N:1>y</N:1>, <N:2>z</N:2>)) in F())
{
System.Console.WriteLine(x);
}
}
}");
var source1 = MarkedSource(@"
class C
{
public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) };
public static void G()
{
foreach (var (<N:0>x1</N:0>, (<N:1>y</N:1>, <N:2>z</N:2>)) in F())
{
System.Console.WriteLine(x1);
}
}
}");
var source2 = MarkedSource(@"
class C
{
public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) };
public static void G()
{
foreach (var (<N:0>x1</N:0>, <N:1>yz</N:1>) in F())
{
System.Console.WriteLine(x1);
}
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.G");
var f1 = compilation1.GetMember<MethodSymbol>("C.G");
var f2 = compilation2.GetMember<MethodSymbol>("C.G");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.G", @"
{
// Code size 70 (0x46)
.maxstack 2
.locals init (System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_0,
int V_1,
int V_2, //x
bool V_3, //y
double V_4, //z
System.ValueTuple<bool, double> V_5)
IL_0000: nop
IL_0001: nop
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
IL_000a: br.s IL_003f
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
IL_0032: nop
IL_0033: ldloc.2
IL_0034: call ""void System.Console.WriteLine(int)""
IL_0039: nop
IL_003a: nop
IL_003b: ldloc.1
IL_003c: ldc.i4.1
IL_003d: add
IL_003e: stloc.1
IL_003f: ldloc.1
IL_0040: ldloc.0
IL_0041: ldlen
IL_0042: conv.i4
IL_0043: blt.s IL_000c
IL_0045: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
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.VerifyIL("C.G", @"
{
// Code size 78 (0x4e)
.maxstack 2
.locals init ([unchanged] V_0,
[int] V_1,
int V_2, //x1
bool V_3, //y
double V_4, //z
[unchanged] V_5,
System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_6,
int V_7,
System.ValueTuple<bool, double> V_8)
IL_0000: nop
IL_0001: nop
IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()""
IL_0007: stloc.s V_6
IL_0009: ldc.i4.0
IL_000a: stloc.s V_7
IL_000c: br.s IL_0045
IL_000e: ldloc.s V_6
IL_0010: ldloc.s V_7
IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>""
IL_0017: dup
IL_0018: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2""
IL_001d: stloc.s V_8
IL_001f: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1""
IL_0024: stloc.2
IL_0025: ldloc.s V_8
IL_0027: ldfld ""bool System.ValueTuple<bool, double>.Item1""
IL_002c: stloc.3
IL_002d: ldloc.s V_8
IL_002f: ldfld ""double System.ValueTuple<bool, double>.Item2""
IL_0034: stloc.s V_4
IL_0036: nop
IL_0037: ldloc.2
IL_0038: call ""void System.Console.WriteLine(int)""
IL_003d: nop
IL_003e: nop
IL_003f: ldloc.s V_7
IL_0041: ldc.i4.1
IL_0042: add
IL_0043: stloc.s V_7
IL_0045: ldloc.s V_7
IL_0047: ldloc.s V_6
IL_0049: ldlen
IL_004a: conv.i4
IL_004b: blt.s IL_000e
IL_004d: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifyIL("C.G", @"
{
// Code size 61 (0x3d)
.maxstack 2
.locals init ([unchanged] V_0,
[int] V_1,
int V_2, //x1
[bool] V_3,
[unchanged] V_4,
[unchanged] V_5,
[unchanged] V_6,
[int] V_7,
[unchanged] V_8,
System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_9,
int V_10,
System.ValueTuple<bool, double> V_11) //yz
IL_0000: nop
IL_0001: nop
IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()""
IL_0007: stloc.s V_9
IL_0009: ldc.i4.0
IL_000a: stloc.s V_10
IL_000c: br.s IL_0034
IL_000e: ldloc.s V_9
IL_0010: ldloc.s V_10
IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>""
IL_0017: dup
IL_0018: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1""
IL_001d: stloc.2
IL_001e: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2""
IL_0023: stloc.s V_11
IL_0025: nop
IL_0026: ldloc.2
IL_0027: call ""void System.Console.WriteLine(int)""
IL_002c: nop
IL_002d: nop
IL_002e: ldloc.s V_10
IL_0030: ldc.i4.1
IL_0031: add
IL_0032: stloc.s V_10
IL_0034: ldloc.s V_10
IL_0036: ldloc.s V_9
IL_0038: ldlen
IL_0039: conv.i4
IL_003a: blt.s IL_000e
IL_003c: ret
}
");
}
[Fact]
public void OutVar()
{
var source0 = MarkedSource(@"
class C
{
static void F(out int x, out int y) { x = 1; y = 2; }
static int G() { F(out int <N:0>x</N:0>, out var <N:1>y</N:1>); return x + y; }
}");
var source1 = MarkedSource(@"
class C
{
static void F(out int x, out int y) { x = 1; y = 2; }
static int G() { F(out int <N:0>x</N:0>, out var <N:1>z</N:1>); return x + z; }
}");
var source2 = MarkedSource(@"
class C
{
static void F(out int x, out int y) { x = 1; y = 2; }
static int G() { F(out int <N:0>x</N:0>, out int <N:1>y</N:1>); return x + y; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.G");
var f1 = compilation1.GetMember<MethodSymbol>("C.G");
var f2 = compilation2.GetMember<MethodSymbol>("C.G");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.G", @"
{
// Code size 19 (0x13)
.maxstack 2
.locals init (int V_0, //x
int V_1, //y
int V_2)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldloca.s V_1
IL_0005: call ""void C.F(out int, out int)""
IL_000a: nop
IL_000b: ldloc.0
IL_000c: ldloc.1
IL_000d: add
IL_000e: stloc.2
IL_000f: br.s IL_0011
IL_0011: ldloc.2
IL_0012: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
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.VerifyIL("C.G", @"
{
// Code size 19 (0x13)
.maxstack 2
.locals init (int V_0, //x
int V_1, //z
[int] V_2,
int V_3)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldloca.s V_1
IL_0005: call ""void C.F(out int, out int)""
IL_000a: nop
IL_000b: ldloc.0
IL_000c: ldloc.1
IL_000d: add
IL_000e: stloc.3
IL_000f: br.s IL_0011
IL_0011: ldloc.3
IL_0012: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifyIL("C.G", @"
{
// Code size 21 (0x15)
.maxstack 2
.locals init (int V_0, //x
int V_1, //y
[int] V_2,
[int] V_3,
int V_4)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldloca.s V_1
IL_0005: call ""void C.F(out int, out int)""
IL_000a: nop
IL_000b: ldloc.0
IL_000c: ldloc.1
IL_000d: add
IL_000e: stloc.s V_4
IL_0010: br.s IL_0012
IL_0012: ldloc.s V_4
IL_0014: ret
}
");
}
[Fact]
public void OutVar_InConstructorInitializer()
{
var baseClass = "public class Base { public Base(int x) { } }";
var source0 = MarkedSource(@"
public class C : Base
{
public C() : base(M(out int <N:0>x</N:0>) + x + M(out int <N:1>y</N:1>)) { System.Console.Write(y); }
static int M(out int x) => throw null;
}" + baseClass);
var source1 = MarkedSource(@"
public class C : Base
{
public C() : base(M(out int <N:0>x</N:0>) + x) { }
static int M(out int x) => throw null;
}" + baseClass);
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 33 (0x21)
.maxstack 3
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldloca.s V_1
IL_000c: call ""int C.M(out int)""
IL_0011: add
IL_0012: call ""Base..ctor(int)""
IL_0017: nop
IL_0018: nop
IL_0019: ldloc.1
IL_001a: call ""void System.Console.Write(int)""
IL_001f: nop
IL_0020: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
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)));
diff1.VerifyIL("C..ctor", @"
{
// Code size 18 (0x12)
.maxstack 3
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: call ""Base..ctor(int)""
IL_000f: nop
IL_0010: nop
IL_0011: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifyIL("C..ctor", @"
{
// Code size 33 (0x21)
.maxstack 3
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldloca.s V_2
IL_000c: call ""int C.M(out int)""
IL_0011: add
IL_0012: call ""Base..ctor(int)""
IL_0017: nop
IL_0018: nop
IL_0019: ldloc.2
IL_001a: call ""void System.Console.Write(int)""
IL_001f: nop
IL_0020: ret
}
");
}
[Fact]
public void OutVar_InConstructorInitializer_WithLambda()
{
var baseClass = "public class Base { public Base(int x) { } }";
var source0 = MarkedSource(@"
public class C : Base
{
<N:0>public C() : base(M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>)) { }</N:0>
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}" + baseClass);
var source1 = MarkedSource(@"
public class C : Base
{
<N:0>public C() : base(M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>)) { }</N:0>
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}" + baseClass);
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 44 (0x2c)
.maxstack 4
.locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: call ""Base..ctor(int)""
IL_0029: nop
IL_002a: nop
IL_002b: ret
}
");
v0.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @"
{
// 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
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var reader0 = md0.MetadataReader;
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)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C", "<>c__DisplayClass0_0");
diff1.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {x, <.ctor>b__0}");
diff1.VerifyIL("C..ctor", @"
{
// Code size 44 (0x2c)
.maxstack 4
.locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: call ""Base..ctor(int)""
IL_0029: nop
IL_002a: nop
IL_002b: ret
}
");
diff1.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @"
{
// 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: sub
IL_0008: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, diff2.EmitResult.ChangedTypes, "C", "<>c__DisplayClass0_0");
diff2.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {x, <.ctor>b__0}");
diff2.VerifyIL("C..ctor", @"
{
// Code size 44 (0x2c)
.maxstack 4
.locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: call ""Base..ctor(int)""
IL_0029: nop
IL_002a: nop
IL_002b: ret
}
");
diff2.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @"
{
// 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
}
");
}
[Fact]
public void OutVar_InMethodBody_WithLambda()
{
var source0 = MarkedSource(@"
public class C
{
public void Method() <N:0>{ int _ = M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>); }</N:0>
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}");
var source1 = MarkedSource(@"
public class C
{
public void Method() <N:0>{ int _ = M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>); }</N:0>
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C.Method");
var ctor1 = compilation1.GetMember<MethodSymbol>("C.Method");
var ctor2 = compilation2.GetMember<MethodSymbol>("C.Method");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.Method", @"
{
// Code size 38 (0x26)
.maxstack 3
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
int V_1) //_
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stloc.1
IL_0025: ret
}
");
v0.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @"
{
// 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
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
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)));
diff1.VerifySynthesizedMembers("C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <Method>b__0}");
diff1.VerifyIL("C.Method", @"
{
// Code size 38 (0x26)
.maxstack 3
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
[int] V_1,
int V_2) //_
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stloc.2
IL_0025: ret
}
");
diff1.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @"
{
// 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: sub
IL_0008: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers("C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <Method>b__0}");
diff2.VerifyIL("C.Method", @"
{
// Code size 38 (0x26)
.maxstack 3
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
[int] V_1,
[int] V_2,
int V_3) //_
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stloc.3
IL_0025: ret
}
");
diff2.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @"
{
// 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
}
");
}
[Fact]
public void OutVar_InFieldInitializer()
{
var source0 = MarkedSource(@"
public class C
{
public int field = M(out int <N:0>x</N:0>) + x + M(out int <N:1>y</N:1>);
static int M(out int x) => throw null;
}");
var source1 = MarkedSource(@"
public class C
{
public int field = M(out int <N:0>x</N:0>) + x;
static int M(out int x) => throw null;
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 31 (0x1f)
.maxstack 3
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldloca.s V_1
IL_000c: call ""int C.M(out int)""
IL_0011: add
IL_0012: stfld ""int C.field""
IL_0017: ldarg.0
IL_0018: call ""object..ctor()""
IL_001d: nop
IL_001e: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
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)));
diff1.VerifyIL("C..ctor", @"
{
// Code size 23 (0x17)
.maxstack 3
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: stfld ""int C.field""
IL_000f: ldarg.0
IL_0010: call ""object..ctor()""
IL_0015: nop
IL_0016: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifyIL("C..ctor", @"
{
// Code size 31 (0x1f)
.maxstack 3
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldloca.s V_2
IL_000c: call ""int C.M(out int)""
IL_0011: add
IL_0012: stfld ""int C.field""
IL_0017: ldarg.0
IL_0018: call ""object..ctor()""
IL_001d: nop
IL_001e: ret
}
");
}
[Fact]
public void OutVar_InFieldInitializer_WithLambda()
{
var source0 = MarkedSource(@"
public class C
{
int field = <N:0>M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>)</N:0>;
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}");
var source1 = MarkedSource(@"
public class C
{
int field = <N:0>M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>)</N:0>;
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 49 (0x31)
.maxstack 4
.locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stfld ""int C.field""
IL_0029: ldarg.0
IL_002a: call ""object..ctor()""
IL_002f: nop
IL_0030: ret
}
");
v0.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
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)));
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass3_0: {x, <.ctor>b__0}",
"C: {<>c__DisplayClass3_0}");
diff1.VerifyIL("C..ctor", @"
{
// Code size 49 (0x31)
.maxstack 4
.locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stfld ""int C.field""
IL_0029: ldarg.0
IL_002a: call ""object..ctor()""
IL_002f: nop
IL_0030: ret
}
");
diff1.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x""
IL_0006: ldc.i4.1
IL_0007: sub
IL_0008: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C.<>c__DisplayClass3_0: {x, <.ctor>b__0}",
"C: {<>c__DisplayClass3_0}");
diff2.VerifyIL("C..ctor", @"
{
// Code size 49 (0x31)
.maxstack 4
.locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stfld ""int C.field""
IL_0029: ldarg.0
IL_002a: call ""object..ctor()""
IL_002f: nop
IL_0030: ret
}
");
diff2.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
}
[Fact]
public void OutVar_InQuery()
{
var source0 = MarkedSource(@"
using System.Linq;
public class Program
{
static int M(int x, out int y) { y = 42; return 43; }
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select M(a, out int <N:2>x</N:2>) + x + M(a, out int <N:3>y</N:3></N:1>)</N:0>;
}
}");
var source1 = MarkedSource(@"
using System.Linq;
public class Program
{
static int M(int x, out int y) { y = 42; return 43; }
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select M(a, out int <N:2>x</N:2>) + x</N:1></N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var n0 = compilation0.GetMember<MethodSymbol>("Program.N");
var n1 = compilation1.GetMember<MethodSymbol>("Program.N");
var n2 = compilation2.GetMember<MethodSymbol>("Program.N");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
v0.VerifyIL("Program.<>c.<N>b__1_0(int)", @"
{
// Code size 20 (0x14)
.maxstack 3
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.1
IL_0001: ldloca.s V_0
IL_0003: call ""int Program.M(int, out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldarg.1
IL_000b: ldloca.s V_1
IL_000d: call ""int Program.M(int, out int)""
IL_0012: add
IL_0013: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"Program: {<>c}",
"Program.<>c: {<>9__1_0, <N>b__1_0}");
diff1.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff1.VerifyIL("Program.<>c.<N>b__1_0(int)", @"
{
// Code size 11 (0xb)
.maxstack 2
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.1
IL_0001: ldloca.s V_0
IL_0003: call ""int Program.M(int, out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"Program: {<>c}",
"Program.<>c: {<>9__1_0, <N>b__1_0}");
diff2.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff2.VerifyIL("Program.<>c.<N>b__1_0(int)", @"
{
// Code size 20 (0x14)
.maxstack 3
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.1
IL_0001: ldloca.s V_0
IL_0003: call ""int Program.M(int, out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldarg.1
IL_000b: ldloca.s V_2
IL_000d: call ""int Program.M(int, out int)""
IL_0012: add
IL_0013: ret
}
");
}
[Fact]
public void OutVar_InQuery_WithLambda()
{
var source0 = MarkedSource(@"
using System.Linq;
public class Program
{
static int M(int x, out int y) { y = 42; return 43; }
static int M2(System.Func<int> x) => throw null;
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select <N:2>M(a, out int <N:3>x</N:3>) + M2(<N:4>() => x + 1</N:4>)</N:2></N:1></N:0>;
}
}");
var source1 = MarkedSource(@"
using System.Linq;
public class Program
{
static int M(int x, out int y) { y = 42; return 43; }
static int M2(System.Func<int> x) => throw null;
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select <N:2>M(a, out int <N:3>x</N:3>) + M2(<N:4>() => x - 1</N:4>)</N:2></N:1></N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var n0 = compilation0.GetMember<MethodSymbol>("Program.N");
var n1 = compilation1.GetMember<MethodSymbol>("Program.N");
var n2 = compilation2.GetMember<MethodSymbol>("Program.N");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
v0.VerifyIL("Program.<>c.<N>b__2_0(int)", @"
{
// Code size 37 (0x25)
.maxstack 3
.locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.1
IL_0007: ldloc.0
IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x""
IL_000d: call ""int Program.M(int, out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int Program.M2(System.Func<int>)""
IL_0023: add
IL_0024: ret
}
");
v0.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"Program: {<>c__DisplayClass2_0, <>c}",
"Program.<>c__DisplayClass2_0: {x, <N>b__1}",
"Program.<>c: {<>9__2_0, <N>b__2_0}");
diff1.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff1.VerifyIL("Program.<>c.<N>b__2_0(int)", @"
{
// Code size 37 (0x25)
.maxstack 3
.locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.1
IL_0007: ldloc.0
IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x""
IL_000d: call ""int Program.M(int, out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int Program.M2(System.Func<int>)""
IL_0023: add
IL_0024: ret
}
");
diff1.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x""
IL_0006: ldc.i4.1
IL_0007: sub
IL_0008: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"Program.<>c__DisplayClass2_0: {x, <N>b__1}",
"Program: {<>c__DisplayClass2_0, <>c}",
"Program.<>c: {<>9__2_0, <N>b__2_0}");
diff2.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff2.VerifyIL("Program.<>c.<N>b__2_0(int)", @"
{
// Code size 37 (0x25)
.maxstack 3
.locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.1
IL_0007: ldloc.0
IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x""
IL_000d: call ""int Program.M(int, out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int Program.M2(System.Func<int>)""
IL_0023: add
IL_0024: ret
}
");
diff2.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
}
[Fact]
public void OutVar_InSwitchExpression()
{
var source0 = MarkedSource(@"
public class Program
{
static object G(int i)
{
return i switch
{
0 => 0,
_ => 1
};
}
static object N(out int x) { x = 1; return null; }
}");
var source1 = MarkedSource(@"
public class Program
{
static object G(int i)
{
return i + N(out var x) switch
{
0 => 0,
_ => 1
};
}
static int N(out int x) { x = 1; return 0; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var n0 = compilation0.GetMember<MethodSymbol>("Program.G");
var n1 = compilation1.GetMember<MethodSymbol>("Program.G");
var n2 = compilation2.GetMember<MethodSymbol>("Program.G");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("Program.G(int)", @"
{
// Code size 33 (0x21)
.maxstack 1
.locals init (int V_0,
object V_1)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: brtrue.s IL_0005
IL_0004: nop
IL_0005: ldarg.0
IL_0006: brfalse.s IL_000a
IL_0008: br.s IL_000e
IL_000a: ldc.i4.0
IL_000b: stloc.0
IL_000c: br.s IL_0012
IL_000e: ldc.i4.1
IL_000f: stloc.0
IL_0010: br.s IL_0012
IL_0012: ldc.i4.1
IL_0013: brtrue.s IL_0016
IL_0015: nop
IL_0016: ldloc.0
IL_0017: box ""int""
IL_001c: stloc.1
IL_001d: br.s IL_001f
IL_001f: ldloc.1
IL_0020: ret
}
");
v0.VerifyIL("Program.N(out int)", @"
{
// Code size 10 (0xa)
.maxstack 2
.locals init (object V_0)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldc.i4.1
IL_0003: stind.i4
IL_0004: ldnull
IL_0005: stloc.0
IL_0006: br.s IL_0008
IL_0008: ldloc.0
IL_0009: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers();
diff1.VerifyIL("Program.G(int)", @"
{
// Code size 52 (0x34)
.maxstack 2
.locals init ([int] V_0,
[object] V_1,
int V_2, //x
int V_3,
int V_4,
int V_5,
object V_6)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.3
IL_0003: ldloca.s V_2
IL_0005: call ""int Program.N(out int)""
IL_000a: stloc.s V_5
IL_000c: ldc.i4.1
IL_000d: brtrue.s IL_0010
IL_000f: nop
IL_0010: ldloc.s V_5
IL_0012: brfalse.s IL_0016
IL_0014: br.s IL_001b
IL_0016: ldc.i4.0
IL_0017: stloc.s V_4
IL_0019: br.s IL_0020
IL_001b: ldc.i4.1
IL_001c: stloc.s V_4
IL_001e: br.s IL_0020
IL_0020: ldc.i4.1
IL_0021: brtrue.s IL_0024
IL_0023: nop
IL_0024: ldloc.3
IL_0025: ldloc.s V_4
IL_0027: add
IL_0028: box ""int""
IL_002d: stloc.s V_6
IL_002f: br.s IL_0031
IL_0031: ldloc.s V_6
IL_0033: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers();
diff2.VerifyIL("Program.G(int)", @"
{
// Code size 38 (0x26)
.maxstack 1
.locals init ([int] V_0,
[object] V_1,
[int] V_2,
[int] V_3,
[int] V_4,
[int] V_5,
[object] V_6,
int V_7,
object V_8)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: brtrue.s IL_0005
IL_0004: nop
IL_0005: ldarg.0
IL_0006: brfalse.s IL_000a
IL_0008: br.s IL_000f
IL_000a: ldc.i4.0
IL_000b: stloc.s V_7
IL_000d: br.s IL_0014
IL_000f: ldc.i4.1
IL_0010: stloc.s V_7
IL_0012: br.s IL_0014
IL_0014: ldc.i4.1
IL_0015: brtrue.s IL_0018
IL_0017: nop
IL_0018: ldloc.s V_7
IL_001a: box ""int""
IL_001f: stloc.s V_8
IL_0021: br.s IL_0023
IL_0023: ldloc.s V_8
IL_0025: ret
}
");
}
[Fact]
public void AddUsing_AmbiguousCode()
{
var source0 = MarkedSource(@"
using System.Threading;
class C
{
static void E()
{
var t = new Timer(s => System.Console.WriteLine(s));
}
}");
var source1 = MarkedSource(@"
using System.Threading;
using System.Timers;
class C
{
static void E()
{
var t = new Timer(s => System.Console.WriteLine(s));
}
static void G()
{
System.Console.WriteLine(new TimersDescriptionAttribute(""""));
}
}");
var compilation0 = CreateCompilation(source0.Tree, targetFramework: TargetFramework.NetStandard20, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var e0 = compilation0.GetMember<MethodSymbol>("C.E");
var e1 = compilation1.GetMember<MethodSymbol>("C.E");
var g1 = compilation1.GetMember<MethodSymbol>("C.G");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
// Pretend there was an update to C.E to ensure we haven't invalidated the test
var diffError = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diffError.EmitResult.Diagnostics.Verify(
// (9,21): error CS0104: 'Timer' is an ambiguous reference between 'System.Threading.Timer' and 'System.Timers.Timer'
// var t = new Timer(s => System.Console.WriteLine(s));
Diagnostic(ErrorCode.ERR_AmbigContext, "Timer").WithArguments("Timer", "System.Threading.Timer", "System.Timers.Timer").WithLocation(9, 21));
// Semantic errors are reported only for the bodies of members being emitted so we shouldn't see any
var diff = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, g1)));
diff.EmitResult.Diagnostics.Verify();
diff.VerifyIL(@"C.G", @"
{
// Code size 18 (0x12)
.maxstack 1
IL_0000: nop
IL_0001: ldstr """"
IL_0006: newobj ""System.Timers.TimersDescriptionAttribute..ctor(string)""
IL_000b: call ""void System.Console.WriteLine(object)""
IL_0010: nop
IL_0011: ret
}
");
}
[Fact]
public void Records_AddWellKnownMember()
{
var source0 =
@"
#nullable enable
namespace N
{
record R(int X)
{
}
}
";
var source1 =
@"
#nullable enable
namespace N
{
record R(int X)
{
protected virtual bool PrintMembers(System.Text.StringBuilder builder)
{
return true;
}
}
}
";
var compilation0 = CreateCompilation(new[] { source0, IsExternalInitTypeDefinition }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(new[] { source1, IsExternalInitTypeDefinition });
var printMembers0 = compilation0.GetMember<MethodSymbol>("N.R.PrintMembers");
var printMembers1 = compilation1.GetMember<MethodSymbol>("N.R.PrintMembers");
var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped);
using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
// Verify full metadata contains expected rows.
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "EmbeddedAttribute", "NullableAttribute", "NullableContextAttribute", "IsExternalInit", "R");
CheckNames(reader0, reader0.GetMethodDefNames(),
/* EmbeddedAttribute */".ctor",
/* NullableAttribute */ ".ctor",
/* NullableContextAttribute */".ctor",
/* IsExternalInit */".ctor",
/* R: */
".ctor",
"get_EqualityContract",
"get_X",
"set_X",
"ToString",
"PrintMembers",
"op_Inequality",
"op_Equality",
"GetHashCode",
"Equals",
"Equals",
"<Clone>$",
".ctor",
"Deconstruct");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, printMembers0, printMembers1)));
diff1.VerifySynthesizedMembers(
"<global namespace>: {Microsoft}",
"Microsoft: {CodeAnalysis}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}");
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "PrintMembers");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(21, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(22, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default)); // R.PrintMembers
CheckEncMap(reader1,
Handle(20, TableIndex.TypeRef),
Handle(21, TableIndex.TypeRef),
Handle(22, TableIndex.TypeRef),
Handle(10, TableIndex.MethodDef),
Handle(3, TableIndex.StandAloneSig),
Handle(4, TableIndex.TypeSpec),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void Records_RemoveWellKnownMember()
{
var source0 =
@"
namespace N
{
record R(int X)
{
protected virtual bool PrintMembers(System.Text.StringBuilder builder)
{
return true;
}
}
}
";
var source1 =
@"
namespace N
{
record R(int X)
{
}
}
";
var compilation0 = CreateCompilation(new[] { source0, IsExternalInitTypeDefinition }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(new[] { source1, IsExternalInitTypeDefinition });
var method0 = compilation0.GetMember<MethodSymbol>("N.R.PrintMembers");
var method1 = compilation1.GetMember<MethodSymbol>("N.R.PrintMembers");
var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped);
using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
diff1.VerifySynthesizedMembers(
"<global namespace>: {Microsoft}",
"Microsoft: {CodeAnalysis}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}");
}
[Fact]
public void TopLevelStatement_Update()
{
var source0 = @"
using System;
Console.WriteLine(""Hello"");
";
var source1 = @"
using System;
Console.WriteLine(""Hello World"");
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe);
var compilation1 = compilation0.WithSource(source1);
var method0 = compilation0.GetMember<MethodSymbol>("<Program>$.<Main>$");
var method1 = compilation1.GetMember<MethodSymbol>("<Program>$.<Main>$");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<Program>$");
CheckNames(reader0, reader0.GetMethodDefNames(), "<Main>$");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*Console.*/"WriteLine");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "<Main>$");
CheckNames(readers, reader1.GetMemberRefNames(), /*CompilerGenerated*/".ctor", /*Console.*/"WriteLine");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default)); // Synthesized Main method
CheckEncMap(reader1,
Handle(8, TableIndex.TypeRef),
Handle(9, TableIndex.TypeRef),
Handle(10, TableIndex.TypeRef),
Handle(1, TableIndex.MethodDef),
Handle(6, TableIndex.MemberRef),
Handle(7, TableIndex.MemberRef),
Handle(2, TableIndex.AssemblyRef));
}
}
}
| 1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Compilers/Core/Portable/Compilation/Compilation.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Symbols;
using Microsoft.DiaSymReader;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// The compilation object is an immutable representation of a single invocation of the
/// compiler. Although immutable, a compilation is also on-demand, and will realize and cache
/// data as necessary. A compilation can produce a new compilation from existing compilation
/// with the application of small deltas. In many cases, it is more efficient than creating a
/// new compilation from scratch, as the new compilation can reuse information from the old
/// compilation.
/// </summary>
public abstract partial class Compilation
{
/// <summary>
/// Returns true if this is a case sensitive compilation, false otherwise. Case sensitivity
/// affects compilation features such as name lookup as well as choosing what names to emit
/// when there are multiple different choices (for example between a virtual method and an
/// override).
/// </summary>
public abstract bool IsCaseSensitive { get; }
/// <summary>
/// Used for test purposes only to emulate missing members.
/// </summary>
private SmallDictionary<int, bool>? _lazyMakeWellKnownTypeMissingMap;
/// <summary>
/// Used for test purposes only to emulate missing members.
/// </summary>
private SmallDictionary<int, bool>? _lazyMakeMemberMissingMap;
// Protected for access in CSharpCompilation.WithAdditionalFeatures
protected readonly IReadOnlyDictionary<string, string> _features;
public ScriptCompilationInfo? ScriptCompilationInfo => CommonScriptCompilationInfo;
internal abstract ScriptCompilationInfo? CommonScriptCompilationInfo { get; }
internal Compilation(
string? name,
ImmutableArray<MetadataReference> references,
IReadOnlyDictionary<string, string> features,
bool isSubmission,
SemanticModelProvider? semanticModelProvider,
AsyncQueue<CompilationEvent>? eventQueue)
{
RoslynDebug.Assert(!references.IsDefault);
RoslynDebug.Assert(features != null);
this.AssemblyName = name;
this.ExternalReferences = references;
this.SemanticModelProvider = semanticModelProvider;
this.EventQueue = eventQueue;
_lazySubmissionSlotIndex = isSubmission ? SubmissionSlotIndexToBeAllocated : SubmissionSlotIndexNotApplicable;
_features = features;
}
protected static IReadOnlyDictionary<string, string> SyntaxTreeCommonFeatures(IEnumerable<SyntaxTree> trees)
{
IReadOnlyDictionary<string, string>? set = null;
foreach (var tree in trees)
{
var treeFeatures = tree.Options.Features;
if (set == null)
{
set = treeFeatures;
}
else
{
if ((object)set != treeFeatures && !set.SetEquals(treeFeatures))
{
throw new ArgumentException(CodeAnalysisResources.InconsistentSyntaxTreeFeature, nameof(trees));
}
}
}
if (set == null)
{
// Edge case where there are no syntax trees
set = ImmutableDictionary<string, string>.Empty;
}
return set;
}
internal abstract AnalyzerDriver CreateAnalyzerDriver(ImmutableArray<DiagnosticAnalyzer> analyzers, AnalyzerManager analyzerManager, SeverityFilter severityFilter);
/// <summary>
/// Gets the source language ("C#" or "Visual Basic").
/// </summary>
public abstract string Language { get; }
internal abstract void SerializePdbEmbeddedCompilationOptions(BlobBuilder builder);
internal static void ValidateScriptCompilationParameters(Compilation? previousScriptCompilation, Type? returnType, ref Type? globalsType)
{
if (globalsType != null && !IsValidHostObjectType(globalsType))
{
throw new ArgumentException(CodeAnalysisResources.ReturnTypeCannotBeValuePointerbyRefOrOpen, nameof(globalsType));
}
if (returnType != null && !IsValidSubmissionReturnType(returnType))
{
throw new ArgumentException(CodeAnalysisResources.ReturnTypeCannotBeVoidByRefOrOpen, nameof(returnType));
}
if (previousScriptCompilation != null)
{
if (globalsType == null)
{
globalsType = previousScriptCompilation.HostObjectType;
}
else if (globalsType != previousScriptCompilation.HostObjectType)
{
throw new ArgumentException(CodeAnalysisResources.TypeMustBeSameAsHostObjectTypeOfPreviousSubmission, nameof(globalsType));
}
// Force the previous submission to be analyzed. This is required for anonymous types unification.
if (previousScriptCompilation.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error))
{
throw new InvalidOperationException(CodeAnalysisResources.PreviousSubmissionHasErrors);
}
}
}
/// <summary>
/// Checks options passed to submission compilation constructor.
/// Throws an exception if the options are not applicable to submissions.
/// </summary>
internal static void CheckSubmissionOptions(CompilationOptions? options)
{
if (options == null)
{
return;
}
if (options.OutputKind.IsValid() && options.OutputKind != OutputKind.DynamicallyLinkedLibrary)
{
throw new ArgumentException(CodeAnalysisResources.InvalidOutputKindForSubmission, nameof(options));
}
if (options.CryptoKeyContainer != null ||
options.CryptoKeyFile != null ||
options.DelaySign != null ||
!options.CryptoPublicKey.IsEmpty ||
(options.DelaySign == true && options.PublicSign))
{
throw new ArgumentException(CodeAnalysisResources.InvalidCompilationOptions, nameof(options));
}
}
/// <summary>
/// Creates a new compilation equivalent to this one with different symbol instances.
/// </summary>
public Compilation Clone()
{
return CommonClone();
}
protected abstract Compilation CommonClone();
/// <summary>
/// Returns a new compilation with a given event queue.
/// </summary>
internal abstract Compilation WithEventQueue(AsyncQueue<CompilationEvent>? eventQueue);
/// <summary>
/// Returns a new compilation with a given semantic model provider.
/// </summary>
internal abstract Compilation WithSemanticModelProvider(SemanticModelProvider semanticModelProvider);
/// <summary>
/// Gets a new <see cref="SemanticModel"/> for the specified syntax tree.
/// </summary>
/// <param name="syntaxTree">The specified syntax tree.</param>
/// <param name="ignoreAccessibility">
/// True if the SemanticModel should ignore accessibility rules when answering semantic questions.
/// </param>
public SemanticModel GetSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility = false)
=> CommonGetSemanticModel(syntaxTree, ignoreAccessibility);
/// <summary>
/// Gets a <see cref="SemanticModel"/> for the given <paramref name="syntaxTree"/>.
/// If <see cref="SemanticModelProvider"/> is non-null, it attempts to use <see cref="SemanticModelProvider.GetSemanticModel(SyntaxTree, Compilation, bool)"/>
/// to get a semantic model. Otherwise, it creates a new semantic model using <see cref="CreateSemanticModel(SyntaxTree, bool)"/>.
/// </summary>
/// <param name="syntaxTree"></param>
/// <param name="ignoreAccessibility"></param>
/// <returns></returns>
protected abstract SemanticModel CommonGetSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility);
/// <summary>
/// Creates a new <see cref="SemanticModel"/> for the given <paramref name="syntaxTree"/>.
/// Unlike the <see cref="GetSemanticModel(SyntaxTree, bool)"/> and <see cref="CommonGetSemanticModel(SyntaxTree, bool)"/>,
/// it does not attempt to use the <see cref="SemanticModelProvider"/> to get a semantic model, but instead always creates a new semantic model.
/// </summary>
/// <param name="syntaxTree"></param>
/// <param name="ignoreAccessibility"></param>
/// <returns></returns>
internal abstract SemanticModel CreateSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility);
/// <summary>
/// Returns a new INamedTypeSymbol representing an error type with the given name and arity
/// in the given optional container.
/// </summary>
public INamedTypeSymbol CreateErrorTypeSymbol(INamespaceOrTypeSymbol? container, string name, int arity)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (arity < 0)
{
throw new ArgumentException($"{nameof(arity)} must be >= 0", nameof(arity));
}
return CommonCreateErrorTypeSymbol(container, name, arity);
}
protected abstract INamedTypeSymbol CommonCreateErrorTypeSymbol(INamespaceOrTypeSymbol? container, string name, int arity);
/// <summary>
/// Returns a new INamespaceSymbol representing an error (missing) namespace with the given name.
/// </summary>
public INamespaceSymbol CreateErrorNamespaceSymbol(INamespaceSymbol container, string name)
{
if (container == null)
{
throw new ArgumentNullException(nameof(container));
}
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
return CommonCreateErrorNamespaceSymbol(container, name);
}
protected abstract INamespaceSymbol CommonCreateErrorNamespaceSymbol(INamespaceSymbol container, string name);
#region Name
internal const string UnspecifiedModuleAssemblyName = "?";
/// <summary>
/// Simple assembly name, or null if not specified.
/// </summary>
/// <remarks>
/// The name is used for determining internals-visible-to relationship with referenced assemblies.
///
/// If the compilation represents an assembly the value of <see cref="AssemblyName"/> is its simple name.
///
/// Unless <see cref="CompilationOptions.ModuleName"/> specifies otherwise the module name
/// written to metadata is <see cref="AssemblyName"/> with an extension based upon <see cref="CompilationOptions.OutputKind"/>.
/// </remarks>
public string? AssemblyName { get; }
internal void CheckAssemblyName(DiagnosticBag diagnostics)
{
// We could only allow name == null if OutputKind is Module.
// However, it does no harm that we allow name == null for assemblies as well, so we don't enforce it.
if (this.AssemblyName != null)
{
MetadataHelpers.CheckAssemblyOrModuleName(this.AssemblyName, MessageProvider, MessageProvider.ERR_BadAssemblyName, diagnostics);
}
}
internal string MakeSourceAssemblySimpleName()
{
return AssemblyName ?? UnspecifiedModuleAssemblyName;
}
internal string MakeSourceModuleName()
{
return Options.ModuleName ??
(AssemblyName != null ? AssemblyName + Options.OutputKind.GetDefaultExtension() : UnspecifiedModuleAssemblyName);
}
/// <summary>
/// Creates a compilation with the specified assembly name.
/// </summary>
/// <param name="assemblyName">The new assembly name.</param>
/// <returns>A new compilation.</returns>
public Compilation WithAssemblyName(string? assemblyName)
{
return CommonWithAssemblyName(assemblyName);
}
protected abstract Compilation CommonWithAssemblyName(string? outputName);
#endregion
#region Options
/// <summary>
/// Gets the options the compilation was created with.
/// </summary>
public CompilationOptions Options { get { return CommonOptions; } }
protected abstract CompilationOptions CommonOptions { get; }
/// <summary>
/// Creates a new compilation with the specified compilation options.
/// </summary>
/// <param name="options">The new options.</param>
/// <returns>A new compilation.</returns>
public Compilation WithOptions(CompilationOptions options)
{
return CommonWithOptions(options);
}
protected abstract Compilation CommonWithOptions(CompilationOptions options);
#endregion
#region Submissions
// An index in the submission slot array. Allocated lazily in compilation phase based upon the slot index of the previous submission.
// Special values:
// -1 ... neither this nor previous submissions in the chain allocated a slot (the submissions don't contain code)
// -2 ... the slot of this submission hasn't been determined yet
// -3 ... this is not a submission compilation
private int _lazySubmissionSlotIndex;
private const int SubmissionSlotIndexNotApplicable = -3;
private const int SubmissionSlotIndexToBeAllocated = -2;
/// <summary>
/// True if the compilation represents an interactive submission.
/// </summary>
internal bool IsSubmission
{
get
{
return _lazySubmissionSlotIndex != SubmissionSlotIndexNotApplicable;
}
}
/// <summary>
/// The previous submission, if any, or null.
/// </summary>
private Compilation? PreviousSubmission
{
get
{
return ScriptCompilationInfo?.PreviousScriptCompilation;
}
}
/// <summary>
/// Gets or allocates a runtime submission slot index for this compilation.
/// </summary>
/// <returns>Non-negative integer if this is a submission and it or a previous submission contains code, negative integer otherwise.</returns>
internal int GetSubmissionSlotIndex()
{
if (_lazySubmissionSlotIndex == SubmissionSlotIndexToBeAllocated)
{
// TODO (tomat): remove recursion
int lastSlotIndex = ScriptCompilationInfo!.PreviousScriptCompilation?.GetSubmissionSlotIndex() ?? 0;
_lazySubmissionSlotIndex = HasCodeToEmit() ? lastSlotIndex + 1 : lastSlotIndex;
}
return _lazySubmissionSlotIndex;
}
// The type of interactive submission result requested by the host, or null if this compilation doesn't represent a submission.
//
// The type is resolved to a symbol when the Script's instance ctor symbol is constructed. The symbol needs to be resolved against
// the references of this compilation.
//
// Consider (tomat): As an alternative to Reflection Type we could hold onto any piece of information that lets us
// resolve the type symbol when needed.
/// <summary>
/// The type object that represents the type of submission result the host requested.
/// </summary>
internal Type? SubmissionReturnType => ScriptCompilationInfo?.ReturnTypeOpt;
internal static bool IsValidSubmissionReturnType(Type type)
{
return !(type == typeof(void) || type.IsByRef || type.GetTypeInfo().ContainsGenericParameters);
}
/// <summary>
/// The type of the globals object or null if not specified for this compilation.
/// </summary>
internal Type? HostObjectType => ScriptCompilationInfo?.GlobalsType;
internal static bool IsValidHostObjectType(Type type)
{
var info = type.GetTypeInfo();
return !(info.IsValueType || info.IsPointer || info.IsByRef || info.ContainsGenericParameters);
}
internal abstract bool HasSubmissionResult();
public Compilation WithScriptCompilationInfo(ScriptCompilationInfo? info) => CommonWithScriptCompilationInfo(info);
protected abstract Compilation CommonWithScriptCompilationInfo(ScriptCompilationInfo? info);
#endregion
#region Syntax Trees
/// <summary>
/// Gets the syntax trees (parsed from source code) that this compilation was created with.
/// </summary>
public IEnumerable<SyntaxTree> SyntaxTrees { get { return CommonSyntaxTrees; } }
protected abstract ImmutableArray<SyntaxTree> CommonSyntaxTrees { get; }
/// <summary>
/// Creates a new compilation with additional syntax trees.
/// </summary>
/// <param name="trees">The new syntax trees.</param>
/// <returns>A new compilation.</returns>
public Compilation AddSyntaxTrees(params SyntaxTree[] trees)
{
return CommonAddSyntaxTrees(trees);
}
/// <summary>
/// Creates a new compilation with additional syntax trees.
/// </summary>
/// <param name="trees">The new syntax trees.</param>
/// <returns>A new compilation.</returns>
public Compilation AddSyntaxTrees(IEnumerable<SyntaxTree> trees)
{
return CommonAddSyntaxTrees(trees);
}
protected abstract Compilation CommonAddSyntaxTrees(IEnumerable<SyntaxTree> trees);
/// <summary>
/// Creates a new compilation without the specified syntax trees. Preserves metadata info for use with trees
/// added later.
/// </summary>
/// <param name="trees">The new syntax trees.</param>
/// <returns>A new compilation.</returns>
public Compilation RemoveSyntaxTrees(params SyntaxTree[] trees)
{
return CommonRemoveSyntaxTrees(trees);
}
/// <summary>
/// Creates a new compilation without the specified syntax trees. Preserves metadata info for use with trees
/// added later.
/// </summary>
/// <param name="trees">The new syntax trees.</param>
/// <returns>A new compilation.</returns>
public Compilation RemoveSyntaxTrees(IEnumerable<SyntaxTree> trees)
{
return CommonRemoveSyntaxTrees(trees);
}
protected abstract Compilation CommonRemoveSyntaxTrees(IEnumerable<SyntaxTree> trees);
/// <summary>
/// Creates a new compilation without any syntax trees. Preserves metadata info for use with
/// trees added later.
/// </summary>
public Compilation RemoveAllSyntaxTrees()
{
return CommonRemoveAllSyntaxTrees();
}
protected abstract Compilation CommonRemoveAllSyntaxTrees();
/// <summary>
/// Creates a new compilation with an old syntax tree replaced with a new syntax tree.
/// Reuses metadata from old compilation object.
/// </summary>
/// <param name="newTree">The new tree.</param>
/// <param name="oldTree">The old tree.</param>
/// <returns>A new compilation.</returns>
public Compilation ReplaceSyntaxTree(SyntaxTree oldTree, SyntaxTree newTree)
{
return CommonReplaceSyntaxTree(oldTree, newTree);
}
protected abstract Compilation CommonReplaceSyntaxTree(SyntaxTree oldTree, SyntaxTree newTree);
/// <summary>
/// Returns true if this compilation contains the specified tree. False otherwise.
/// </summary>
/// <param name="syntaxTree">A syntax tree.</param>
public bool ContainsSyntaxTree(SyntaxTree syntaxTree)
{
return CommonContainsSyntaxTree(syntaxTree);
}
protected abstract bool CommonContainsSyntaxTree(SyntaxTree? syntaxTree);
/// <summary>
/// Optional semantic model provider for this compilation.
/// </summary>
internal SemanticModelProvider? SemanticModelProvider { get; }
/// <summary>
/// The event queue that this compilation was created with.
/// </summary>
internal AsyncQueue<CompilationEvent>? EventQueue { get; }
#endregion
#region References
internal static ImmutableArray<MetadataReference> ValidateReferences<T>(IEnumerable<MetadataReference>? references)
where T : CompilationReference
{
var result = references.AsImmutableOrEmpty();
for (int i = 0; i < result.Length; i++)
{
var reference = result[i];
if (reference == null)
{
throw new ArgumentNullException($"{nameof(references)}[{i}]");
}
var peReference = reference as PortableExecutableReference;
if (peReference == null && !(reference is T))
{
Debug.Assert(reference is UnresolvedMetadataReference || reference is CompilationReference);
throw new ArgumentException(string.Format(CodeAnalysisResources.ReferenceOfTypeIsInvalid1, reference.GetType()),
$"{nameof(references)}[{i}]");
}
}
return result;
}
internal CommonReferenceManager GetBoundReferenceManager()
{
return CommonGetBoundReferenceManager();
}
internal abstract CommonReferenceManager CommonGetBoundReferenceManager();
/// <summary>
/// Metadata references passed to the compilation constructor.
/// </summary>
public ImmutableArray<MetadataReference> ExternalReferences { get; }
/// <summary>
/// Unique metadata references specified via #r directive in the source code of this compilation.
/// </summary>
public abstract ImmutableArray<MetadataReference> DirectiveReferences { get; }
/// <summary>
/// All reference directives used in this compilation.
/// </summary>
internal abstract IEnumerable<ReferenceDirective> ReferenceDirectives { get; }
/// <summary>
/// Maps values of #r references to resolved metadata references.
/// </summary>
internal abstract IDictionary<(string path, string content), MetadataReference> ReferenceDirectiveMap { get; }
/// <summary>
/// All metadata references -- references passed to the compilation
/// constructor as well as references specified via #r directives.
/// </summary>
public IEnumerable<MetadataReference> References
{
get
{
foreach (var reference in ExternalReferences)
{
yield return reference;
}
foreach (var reference in DirectiveReferences)
{
yield return reference;
}
}
}
/// <summary>
/// Creates a metadata reference for this compilation.
/// </summary>
/// <param name="aliases">
/// Optional aliases that can be used to refer to the compilation root namespace via extern alias directive.
/// </param>
/// <param name="embedInteropTypes">
/// Embed the COM types from the reference so that the compiled
/// application no longer requires a primary interop assembly (PIA).
/// </param>
public abstract CompilationReference ToMetadataReference(ImmutableArray<string> aliases = default(ImmutableArray<string>), bool embedInteropTypes = false);
/// <summary>
/// Creates a new compilation with the specified references.
/// </summary>
/// <param name="newReferences">
/// The new references.
/// </param>
/// <returns>A new compilation.</returns>
public Compilation WithReferences(IEnumerable<MetadataReference> newReferences)
{
return this.CommonWithReferences(newReferences);
}
/// <summary>
/// Creates a new compilation with the specified references.
/// </summary>
/// <param name="newReferences">The new references.</param>
/// <returns>A new compilation.</returns>
public Compilation WithReferences(params MetadataReference[] newReferences)
{
return this.WithReferences((IEnumerable<MetadataReference>)newReferences);
}
/// <summary>
/// Creates a new compilation with the specified references.
/// </summary>
protected abstract Compilation CommonWithReferences(IEnumerable<MetadataReference> newReferences);
/// <summary>
/// Creates a new compilation with additional metadata references.
/// </summary>
/// <param name="references">The new references.</param>
/// <returns>A new compilation.</returns>
public Compilation AddReferences(params MetadataReference[] references)
{
return AddReferences((IEnumerable<MetadataReference>)references);
}
/// <summary>
/// Creates a new compilation with additional metadata references.
/// </summary>
/// <param name="references">The new references.</param>
/// <returns>A new compilation.</returns>
public Compilation AddReferences(IEnumerable<MetadataReference> references)
{
if (references == null)
{
throw new ArgumentNullException(nameof(references));
}
if (references.IsEmpty())
{
return this;
}
return CommonWithReferences(this.ExternalReferences.Union(references));
}
/// <summary>
/// Creates a new compilation without the specified metadata references.
/// </summary>
/// <param name="references">The new references.</param>
/// <returns>A new compilation.</returns>
public Compilation RemoveReferences(params MetadataReference[] references)
{
return RemoveReferences((IEnumerable<MetadataReference>)references);
}
/// <summary>
/// Creates a new compilation without the specified metadata references.
/// </summary>
/// <param name="references">The new references.</param>
/// <returns>A new compilation.</returns>
public Compilation RemoveReferences(IEnumerable<MetadataReference> references)
{
if (references == null)
{
throw new ArgumentNullException(nameof(references));
}
if (references.IsEmpty())
{
return this;
}
var refSet = new HashSet<MetadataReference>(this.ExternalReferences);
//EDMAURER if AddingReferences accepts duplicates, then a consumer supplying a list with
//duplicates to add will not know exactly which to remove. Let them supply a list with
//duplicates here.
foreach (var r in references.Distinct())
{
if (!refSet.Remove(r))
{
throw new ArgumentException(string.Format(CodeAnalysisResources.MetadataRefNotFoundToRemove1, r),
nameof(references));
}
}
return CommonWithReferences(refSet);
}
/// <summary>
/// Creates a new compilation without any metadata references.
/// </summary>
public Compilation RemoveAllReferences()
{
return CommonWithReferences(SpecializedCollections.EmptyEnumerable<MetadataReference>());
}
/// <summary>
/// Creates a new compilation with an old metadata reference replaced with a new metadata
/// reference.
/// </summary>
/// <param name="newReference">The new reference.</param>
/// <param name="oldReference">The old reference.</param>
/// <returns>A new compilation.</returns>
public Compilation ReplaceReference(MetadataReference oldReference, MetadataReference? newReference)
{
if (oldReference == null)
{
throw new ArgumentNullException(nameof(oldReference));
}
if (newReference == null)
{
return this.RemoveReferences(oldReference);
}
return this.RemoveReferences(oldReference).AddReferences(newReference);
}
/// <summary>
/// Gets the <see cref="IAssemblySymbol"/> or <see cref="IModuleSymbol"/> for a metadata reference used to create this
/// compilation.
/// </summary>
/// <param name="reference">The target reference.</param>
/// <returns>
/// Assembly or module symbol corresponding to the given reference or null if there is none.
/// </returns>
public ISymbol? GetAssemblyOrModuleSymbol(MetadataReference reference)
{
return CommonGetAssemblyOrModuleSymbol(reference);
}
protected abstract ISymbol? CommonGetAssemblyOrModuleSymbol(MetadataReference reference);
/// <summary>
/// Gets the <see cref="MetadataReference"/> that corresponds to the assembly symbol.
/// </summary>
/// <param name="assemblySymbol">The target symbol.</param>
public MetadataReference? GetMetadataReference(IAssemblySymbol assemblySymbol)
{
return CommonGetMetadataReference(assemblySymbol);
}
private protected abstract MetadataReference? CommonGetMetadataReference(IAssemblySymbol assemblySymbol);
/// <summary>
/// Assembly identities of all assemblies directly referenced by this compilation.
/// </summary>
/// <remarks>
/// Includes identities of references passed in the compilation constructor
/// as well as those specified via directives in source code.
/// </remarks>
public abstract IEnumerable<AssemblyIdentity> ReferencedAssemblyNames { get; }
#endregion
#region Symbols
/// <summary>
/// The <see cref="IAssemblySymbol"/> that represents the assembly being created.
/// </summary>
public IAssemblySymbol Assembly { get { return CommonAssembly; } }
protected abstract IAssemblySymbol CommonAssembly { get; }
/// <summary>
/// Gets the <see cref="IModuleSymbol"/> for the module being created by compiling all of
/// the source code.
/// </summary>
public IModuleSymbol SourceModule { get { return CommonSourceModule; } }
protected abstract IModuleSymbol CommonSourceModule { get; }
/// <summary>
/// The root namespace that contains all namespaces and types defined in source code or in
/// referenced metadata, merged into a single namespace hierarchy.
/// </summary>
public INamespaceSymbol GlobalNamespace { get { return CommonGlobalNamespace; } }
protected abstract INamespaceSymbol CommonGlobalNamespace { get; }
/// <summary>
/// Gets the corresponding compilation namespace for the specified module or assembly namespace.
/// </summary>
public INamespaceSymbol? GetCompilationNamespace(INamespaceSymbol namespaceSymbol)
{
return CommonGetCompilationNamespace(namespaceSymbol);
}
protected abstract INamespaceSymbol? CommonGetCompilationNamespace(INamespaceSymbol namespaceSymbol);
internal abstract CommonAnonymousTypeManager CommonAnonymousTypeManager { get; }
/// <summary>
/// Returns the Main method that will serves as the entry point of the assembly, if it is
/// executable (and not a script).
/// </summary>
public IMethodSymbol? GetEntryPoint(CancellationToken cancellationToken)
{
return CommonGetEntryPoint(cancellationToken);
}
protected abstract IMethodSymbol? CommonGetEntryPoint(CancellationToken cancellationToken);
/// <summary>
/// Get the symbol for the predefined type from the Cor Library referenced by this
/// compilation.
/// </summary>
public INamedTypeSymbol GetSpecialType(SpecialType specialType)
{
return (INamedTypeSymbol)CommonGetSpecialType(specialType).GetITypeSymbol();
}
/// <summary>
/// Get the symbol for the predefined type member from the COR Library referenced by this compilation.
/// </summary>
internal abstract ISymbolInternal CommonGetSpecialTypeMember(SpecialMember specialMember);
/// <summary>
/// Returns true if the type is System.Type.
/// </summary>
internal abstract bool IsSystemTypeReference(ITypeSymbolInternal type);
private protected abstract INamedTypeSymbolInternal CommonGetSpecialType(SpecialType specialType);
/// <summary>
/// Lookup member declaration in well known type used by this Compilation.
/// </summary>
internal abstract ISymbolInternal? CommonGetWellKnownTypeMember(WellKnownMember member);
/// <summary>
/// Lookup well-known type used by this Compilation.
/// </summary>
internal abstract ITypeSymbolInternal CommonGetWellKnownType(WellKnownType wellknownType);
/// <summary>
/// Returns true if the specified type is equal to or derives from System.Attribute well-known type.
/// </summary>
internal abstract bool IsAttributeType(ITypeSymbol type);
/// <summary>
/// The INamedTypeSymbol for the .NET System.Object type, which could have a TypeKind of
/// Error if there was no COR Library in this Compilation.
/// </summary>
public INamedTypeSymbol ObjectType { get { return CommonObjectType; } }
protected abstract INamedTypeSymbol CommonObjectType { get; }
/// <summary>
/// The TypeSymbol for the type 'dynamic' in this Compilation.
/// </summary>
/// <exception cref="NotSupportedException">If the compilation is a VisualBasic compilation.</exception>
public ITypeSymbol DynamicType { get { return CommonDynamicType; } }
protected abstract ITypeSymbol CommonDynamicType { get; }
/// <summary>
/// A symbol representing the script globals type.
/// </summary>
internal ITypeSymbol? ScriptGlobalsType => CommonScriptGlobalsType;
protected abstract ITypeSymbol? CommonScriptGlobalsType { get; }
/// <summary>
/// A symbol representing the implicit Script class. This is null if the class is not
/// defined in the compilation.
/// </summary>
public INamedTypeSymbol? ScriptClass { get { return CommonScriptClass; } }
protected abstract INamedTypeSymbol? CommonScriptClass { get; }
/// <summary>
/// Resolves a symbol that represents script container (Script class). Uses the
/// full name of the container class stored in <see cref="CompilationOptions.ScriptClassName"/> to find the symbol.
/// </summary>
/// <returns>The Script class symbol or null if it is not defined.</returns>
protected INamedTypeSymbol? CommonBindScriptClass()
{
string scriptClassName = this.Options.ScriptClassName ?? "";
string[] parts = scriptClassName.Split('.');
INamespaceSymbol container = this.SourceModule.GlobalNamespace;
for (int i = 0; i < parts.Length - 1; i++)
{
INamespaceSymbol? next = container.GetNestedNamespace(parts[i]);
if (next == null)
{
AssertNoScriptTrees();
return null;
}
container = next;
}
foreach (INamedTypeSymbol candidate in container.GetTypeMembers(parts[parts.Length - 1]))
{
if (candidate.IsScriptClass)
{
return candidate;
}
}
AssertNoScriptTrees();
return null;
}
[Conditional("DEBUG")]
private void AssertNoScriptTrees()
{
foreach (var tree in this.CommonSyntaxTrees)
{
Debug.Assert(tree.Options.Kind != SourceCodeKind.Script);
}
}
/// <summary>
/// Returns a new ArrayTypeSymbol representing an array type tied to the base types of the
/// COR Library in this Compilation.
/// </summary>
public IArrayTypeSymbol CreateArrayTypeSymbol(ITypeSymbol elementType, int rank = 1, NullableAnnotation elementNullableAnnotation = NullableAnnotation.None)
{
return CommonCreateArrayTypeSymbol(elementType, rank, elementNullableAnnotation);
}
/// <summary>
/// Returns a new ArrayTypeSymbol representing an array type tied to the base types of the
/// COR Library in this Compilation.
/// </summary>
/// <remarks>This overload is for backwards compatibility. Do not remove.</remarks>
public IArrayTypeSymbol CreateArrayTypeSymbol(ITypeSymbol elementType, int rank)
{
return CreateArrayTypeSymbol(elementType, rank, elementNullableAnnotation: default);
}
protected abstract IArrayTypeSymbol CommonCreateArrayTypeSymbol(ITypeSymbol elementType, int rank, NullableAnnotation elementNullableAnnotation);
/// <summary>
/// Returns a new IPointerTypeSymbol representing a pointer type tied to a type in this
/// Compilation.
/// </summary>
/// <exception cref="NotSupportedException">If the compilation is a VisualBasic compilation.</exception>
public IPointerTypeSymbol CreatePointerTypeSymbol(ITypeSymbol pointedAtType)
{
return CommonCreatePointerTypeSymbol(pointedAtType);
}
protected abstract IPointerTypeSymbol CommonCreatePointerTypeSymbol(ITypeSymbol elementType);
/// <summary>
/// Returns a new IFunctionPointerTypeSymbol representing a function pointer type tied to types in this
/// Compilation.
/// </summary>
/// <exception cref="NotSupportedException">If the compilation is a VisualBasic compilation.</exception>
/// <exception cref="ArgumentException">
/// If:
/// * <see cref="RefKind.Out"/> is passed as the returnRefKind.
/// * parameterTypes and parameterRefKinds do not have the same length.
/// </exception>
/// <exception cref="ArgumentNullException">
/// If returnType is <see langword="null"/>, or if parameterTypes or parameterRefKinds are default,
/// or if any of the types in parameterTypes are null.</exception>
public IFunctionPointerTypeSymbol CreateFunctionPointerTypeSymbol(
ITypeSymbol returnType,
RefKind returnRefKind,
ImmutableArray<ITypeSymbol> parameterTypes,
ImmutableArray<RefKind> parameterRefKinds,
SignatureCallingConvention callingConvention = SignatureCallingConvention.Default,
ImmutableArray<INamedTypeSymbol> callingConventionTypes = default)
{
return CommonCreateFunctionPointerTypeSymbol(returnType, returnRefKind, parameterTypes, parameterRefKinds, callingConvention, callingConventionTypes);
}
protected abstract IFunctionPointerTypeSymbol CommonCreateFunctionPointerTypeSymbol(
ITypeSymbol returnType,
RefKind returnRefKind,
ImmutableArray<ITypeSymbol> parameterTypes,
ImmutableArray<RefKind> parameterRefKinds,
SignatureCallingConvention callingConvention,
ImmutableArray<INamedTypeSymbol> callingConventionTypes);
/// <summary>
/// Returns a new INamedTypeSymbol representing a native integer.
/// </summary>
/// <exception cref="NotSupportedException">If the compilation is a VisualBasic compilation.</exception>
public INamedTypeSymbol CreateNativeIntegerTypeSymbol(bool signed)
{
return CommonCreateNativeIntegerTypeSymbol(signed);
}
protected abstract INamedTypeSymbol CommonCreateNativeIntegerTypeSymbol(bool signed);
// PERF: ETW Traces show that analyzers may use this method frequently, often requesting
// the same symbol over and over again. XUnit analyzers, in particular, were consuming almost
// 1% of CPU time when building Roslyn itself. This is an extremely simple cache that evicts on
// hash code conflicts, but seems to do the trick. The size is mostly arbitrary. My guess
// is that there are maybe a couple dozen analyzers in the solution and each one has
// ~0-2 unique well-known types, and the chance of hash collision is very low.
private readonly ConcurrentCache<string, INamedTypeSymbol?> _getTypeCache =
new ConcurrentCache<string, INamedTypeSymbol?>(50, ReferenceEqualityComparer.Instance);
/// <summary>
/// Gets the type within the compilation's assembly and all referenced assemblies (other than
/// those that can only be referenced via an extern alias) using its canonical CLR metadata name.
/// </summary>
/// <returns>Null if the type can't be found.</returns>
/// <remarks>
/// Since VB does not have the concept of extern aliases, it considers all referenced assemblies.
/// </remarks>
public INamedTypeSymbol? GetTypeByMetadataName(string fullyQualifiedMetadataName)
{
if (!_getTypeCache.TryGetValue(fullyQualifiedMetadataName, out INamedTypeSymbol? val))
{
val = CommonGetTypeByMetadataName(fullyQualifiedMetadataName);
// Ignore if someone added the same value before us
_ = _getTypeCache.TryAdd(fullyQualifiedMetadataName, val);
}
return val;
}
protected abstract INamedTypeSymbol? CommonGetTypeByMetadataName(string metadataName);
#pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters
/// <summary>
/// Returns a new INamedTypeSymbol with the given element types and
/// (optional) element names, locations, and nullable annotations.
/// </summary>
public INamedTypeSymbol CreateTupleTypeSymbol(
ImmutableArray<ITypeSymbol> elementTypes,
ImmutableArray<string?> elementNames = default,
ImmutableArray<Location?> elementLocations = default,
ImmutableArray<NullableAnnotation> elementNullableAnnotations = default)
{
if (elementTypes.IsDefault)
{
throw new ArgumentNullException(nameof(elementTypes));
}
int n = elementTypes.Length;
if (elementTypes.Length <= 1)
{
throw new ArgumentException(CodeAnalysisResources.TuplesNeedAtLeastTwoElements, nameof(elementNames));
}
elementNames = CheckTupleElementNames(n, elementNames);
CheckTupleElementLocations(n, elementLocations);
CheckTupleElementNullableAnnotations(n, elementNullableAnnotations);
for (int i = 0; i < n; i++)
{
if (elementTypes[i] == null)
{
throw new ArgumentNullException($"{nameof(elementTypes)}[{i}]");
}
if (!elementLocations.IsDefault && elementLocations[i] == null)
{
throw new ArgumentNullException($"{nameof(elementLocations)}[{i}]");
}
}
return CommonCreateTupleTypeSymbol(elementTypes, elementNames, elementLocations, elementNullableAnnotations);
}
#pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters
/// <summary>
/// Returns a new INamedTypeSymbol with the given element types, names, and locations.
/// </summary>
/// <remarks>This overload is for backwards compatibility. Do not remove.</remarks>
public INamedTypeSymbol CreateTupleTypeSymbol(
ImmutableArray<ITypeSymbol> elementTypes,
ImmutableArray<string?> elementNames,
ImmutableArray<Location?> elementLocations)
{
return CreateTupleTypeSymbol(elementTypes, elementNames, elementLocations, elementNullableAnnotations: default);
}
protected static void CheckTupleElementNullableAnnotations(
int cardinality,
ImmutableArray<NullableAnnotation> elementNullableAnnotations)
{
if (!elementNullableAnnotations.IsDefault)
{
if (elementNullableAnnotations.Length != cardinality)
{
throw new ArgumentException(CodeAnalysisResources.TupleElementNullableAnnotationCountMismatch, nameof(elementNullableAnnotations));
}
}
}
/// <summary>
/// Check that if any names are provided, and their number matches the expected cardinality.
/// Returns a normalized version of the element names (empty array if all the names are null).
/// </summary>
protected static ImmutableArray<string?> CheckTupleElementNames(int cardinality, ImmutableArray<string?> elementNames)
{
if (!elementNames.IsDefault)
{
if (elementNames.Length != cardinality)
{
throw new ArgumentException(CodeAnalysisResources.TupleElementNameCountMismatch, nameof(elementNames));
}
for (int i = 0; i < elementNames.Length; i++)
{
if (elementNames[i] == "")
{
throw new ArgumentException(CodeAnalysisResources.TupleElementNameEmpty, $"{nameof(elementNames)}[{i}]");
}
}
if (elementNames.All(n => n == null))
{
return default;
}
}
return elementNames;
}
protected static void CheckTupleElementLocations(
int cardinality,
ImmutableArray<Location?> elementLocations)
{
if (!elementLocations.IsDefault)
{
if (elementLocations.Length != cardinality)
{
throw new ArgumentException(CodeAnalysisResources.TupleElementLocationCountMismatch, nameof(elementLocations));
}
}
}
protected abstract INamedTypeSymbol CommonCreateTupleTypeSymbol(
ImmutableArray<ITypeSymbol> elementTypes,
ImmutableArray<string?> elementNames,
ImmutableArray<Location?> elementLocations,
ImmutableArray<NullableAnnotation> elementNullableAnnotations);
#pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters
/// <summary>
/// Returns a new INamedTypeSymbol with the given underlying type and
/// (optional) element names, locations, and nullable annotations.
/// The underlying type needs to be tuple-compatible.
/// </summary>
public INamedTypeSymbol CreateTupleTypeSymbol(
INamedTypeSymbol underlyingType,
ImmutableArray<string?> elementNames = default,
ImmutableArray<Location?> elementLocations = default,
ImmutableArray<NullableAnnotation> elementNullableAnnotations = default)
{
if ((object)underlyingType == null)
{
throw new ArgumentNullException(nameof(underlyingType));
}
return CommonCreateTupleTypeSymbol(underlyingType, elementNames, elementLocations, elementNullableAnnotations);
}
#pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters
/// <summary>
/// Returns a new INamedTypeSymbol with the given underlying type and element names and locations.
/// The underlying type needs to be tuple-compatible.
/// </summary>
/// <remarks>This overload is for backwards compatibility. Do not remove.</remarks>
public INamedTypeSymbol CreateTupleTypeSymbol(
INamedTypeSymbol underlyingType,
ImmutableArray<string?> elementNames,
ImmutableArray<Location?> elementLocations)
{
return CreateTupleTypeSymbol(underlyingType, elementNames, elementLocations, elementNullableAnnotations: default);
}
protected abstract INamedTypeSymbol CommonCreateTupleTypeSymbol(
INamedTypeSymbol underlyingType,
ImmutableArray<string?> elementNames,
ImmutableArray<Location?> elementLocations,
ImmutableArray<NullableAnnotation> elementNullableAnnotations);
/// <summary>
/// Returns a new anonymous type symbol with the given member types, names, source locations, and nullable annotations.
/// Anonymous type members will be readonly by default. Writable properties are
/// supported in VB and can be created by passing in <see langword="false"/> in the
/// appropriate locations in <paramref name="memberIsReadOnly"/>.
/// </summary>
public INamedTypeSymbol CreateAnonymousTypeSymbol(
ImmutableArray<ITypeSymbol> memberTypes,
ImmutableArray<string> memberNames,
ImmutableArray<bool> memberIsReadOnly = default,
ImmutableArray<Location> memberLocations = default,
ImmutableArray<NullableAnnotation> memberNullableAnnotations = default)
{
if (memberTypes.IsDefault)
{
throw new ArgumentNullException(nameof(memberTypes));
}
if (memberNames.IsDefault)
{
throw new ArgumentNullException(nameof(memberNames));
}
if (memberTypes.Length != memberNames.Length)
{
throw new ArgumentException(string.Format(CodeAnalysisResources.AnonymousTypeMemberAndNamesCountMismatch2,
nameof(memberTypes), nameof(memberNames)));
}
if (!memberLocations.IsDefault && memberLocations.Length != memberTypes.Length)
{
throw new ArgumentException(string.Format(CodeAnalysisResources.AnonymousTypeArgumentCountMismatch2,
nameof(memberLocations), nameof(memberNames)));
}
if (!memberIsReadOnly.IsDefault && memberIsReadOnly.Length != memberTypes.Length)
{
throw new ArgumentException(string.Format(CodeAnalysisResources.AnonymousTypeArgumentCountMismatch2,
nameof(memberIsReadOnly), nameof(memberNames)));
}
if (!memberNullableAnnotations.IsDefault && memberNullableAnnotations.Length != memberTypes.Length)
{
throw new ArgumentException(string.Format(CodeAnalysisResources.AnonymousTypeArgumentCountMismatch2,
nameof(memberNullableAnnotations), nameof(memberNames)));
}
for (int i = 0, n = memberTypes.Length; i < n; i++)
{
if (memberTypes[i] == null)
{
throw new ArgumentNullException($"{nameof(memberTypes)}[{i}]");
}
if (memberNames[i] == null)
{
throw new ArgumentNullException($"{nameof(memberNames)}[{i}]");
}
if (!memberLocations.IsDefault && memberLocations[i] == null)
{
throw new ArgumentNullException($"{nameof(memberLocations)}[{i}]");
}
}
return CommonCreateAnonymousTypeSymbol(memberTypes, memberNames, memberLocations, memberIsReadOnly, memberNullableAnnotations);
}
/// <summary>
/// Returns a new anonymous type symbol with the given member types, names, and source locations.
/// Anonymous type members will be readonly by default. Writable properties are
/// supported in VB and can be created by passing in <see langword="false"/> in the
/// appropriate locations in <paramref name="memberIsReadOnly"/>.
/// </summary>
/// <remarks>This overload is for backwards compatibility. Do not remove.</remarks>
public INamedTypeSymbol CreateAnonymousTypeSymbol(
ImmutableArray<ITypeSymbol> memberTypes,
ImmutableArray<string> memberNames,
ImmutableArray<bool> memberIsReadOnly,
ImmutableArray<Location> memberLocations)
{
return CreateAnonymousTypeSymbol(memberTypes, memberNames, memberIsReadOnly, memberLocations, memberNullableAnnotations: default);
}
protected abstract INamedTypeSymbol CommonCreateAnonymousTypeSymbol(
ImmutableArray<ITypeSymbol> memberTypes,
ImmutableArray<string> memberNames,
ImmutableArray<Location> memberLocations,
ImmutableArray<bool> memberIsReadOnly,
ImmutableArray<NullableAnnotation> memberNullableAnnotations);
/// <summary>
/// Classifies a conversion from <paramref name="source"/> to <paramref name="destination"/> according
/// to this compilation's programming language.
/// </summary>
/// <param name="source">Source type of value to be converted</param>
/// <param name="destination">Destination type of value to be converted</param>
/// <returns>A <see cref="CommonConversion"/> that classifies the conversion from the
/// <paramref name="source"/> type to the <paramref name="destination"/> type.</returns>
public abstract CommonConversion ClassifyCommonConversion(ITypeSymbol source, ITypeSymbol destination);
/// <summary>
/// Returns true if there is an implicit (C#) or widening (VB) conversion from
/// <paramref name="fromType"/> to <paramref name="toType"/>. Returns false if
/// either <paramref name="fromType"/> or <paramref name="toType"/> is null, or
/// if no such conversion exists.
/// </summary>
public bool HasImplicitConversion(ITypeSymbol? fromType, ITypeSymbol? toType)
=> fromType != null && toType != null && this.ClassifyCommonConversion(fromType, toType).IsImplicit;
/// <summary>
/// Checks if <paramref name="symbol"/> is accessible from within <paramref name="within"/>. An optional qualifier of type
/// <paramref name="throughType"/> is used to resolve protected access for instance members. All symbols are
/// required to be from this compilation or some assembly referenced (<see cref="References"/>) by this
/// compilation. <paramref name="within"/> is required to be an <see cref="INamedTypeSymbol"/> or <see cref="IAssemblySymbol"/>.
/// </summary>
/// <remarks>
/// <para>Submissions can reference symbols from previous submissions and their referenced assemblies, even
/// though those references are missing from <see cref="References"/>.
/// See https://github.com/dotnet/roslyn/issues/27356.
/// This implementation works around that by permitting symbols from previous submissions as well.</para>
/// <para>It is advised to avoid the use of this API within the compilers, as the compilers have additional
/// requirements for access checking that are not satisfied by this implementation, including the
/// avoidance of infinite recursion that could result from the use of the ISymbol APIs here, the detection
/// of use-site diagnostics, and additional returned details (from the compiler's internal APIs) that are
/// helpful for more precisely diagnosing reasons for accessibility failure.</para>
/// </remarks>
public bool IsSymbolAccessibleWithin(
ISymbol symbol,
ISymbol within,
ITypeSymbol? throughType = null)
{
if (symbol is null)
{
throw new ArgumentNullException(nameof(symbol));
}
if (within is null)
{
throw new ArgumentNullException(nameof(within));
}
if (!(within is INamedTypeSymbol || within is IAssemblySymbol))
{
throw new ArgumentException(string.Format(CodeAnalysisResources.IsSymbolAccessibleBadWithin, nameof(within)), nameof(within));
}
checkInCompilationReferences(symbol, nameof(symbol));
checkInCompilationReferences(within, nameof(within));
if (throughType is object)
{
checkInCompilationReferences(throughType, nameof(throughType));
}
return IsSymbolAccessibleWithinCore(symbol, within, throughType);
void checkInCompilationReferences(ISymbol s, string parameterName)
{
if (!isContainingAssemblyInReferences(s))
{
throw new ArgumentException(string.Format(CodeAnalysisResources.IsSymbolAccessibleWrongAssembly, parameterName), parameterName);
}
}
bool assemblyIsInReferences(IAssemblySymbol a)
{
if (assemblyIsInCompilationReferences(a, this))
{
return true;
}
if (this.IsSubmission)
{
// Submissions can reference symbols from previous submissions and their referenced assemblies, even
// though those references are missing from this.References. We work around that by digging in
// to find references of previous submissions. See https://github.com/dotnet/roslyn/issues/27356
for (Compilation? c = this.PreviousSubmission; c != null; c = c.PreviousSubmission)
{
if (assemblyIsInCompilationReferences(a, c))
{
return true;
}
}
}
return false;
}
bool assemblyIsInCompilationReferences(IAssemblySymbol a, Compilation compilation)
{
if (a.Equals(compilation.Assembly))
{
return true;
}
foreach (var reference in compilation.References)
{
if (a.Equals(compilation.GetAssemblyOrModuleSymbol(reference)))
{
return true;
}
}
return false;
}
bool isContainingAssemblyInReferences(ISymbol s)
{
while (true)
{
switch (s.Kind)
{
case SymbolKind.Assembly:
return assemblyIsInReferences((IAssemblySymbol)s);
case SymbolKind.PointerType:
s = ((IPointerTypeSymbol)s).PointedAtType;
continue;
case SymbolKind.ArrayType:
s = ((IArrayTypeSymbol)s).ElementType;
continue;
case SymbolKind.Alias:
s = ((IAliasSymbol)s).Target;
continue;
case SymbolKind.Discard:
s = ((IDiscardSymbol)s).Type;
continue;
case SymbolKind.FunctionPointerType:
var funcPtr = (IFunctionPointerTypeSymbol)s;
if (!isContainingAssemblyInReferences(funcPtr.Signature.ReturnType))
{
return false;
}
foreach (var param in funcPtr.Signature.Parameters)
{
if (!isContainingAssemblyInReferences(param.Type))
{
return false;
}
}
return true;
case SymbolKind.DynamicType:
case SymbolKind.ErrorType:
case SymbolKind.Preprocessing:
case SymbolKind.Namespace:
// these symbols are not restricted in where they can be accessed, so unless they report
// a containing assembly, we treat them as in the current assembly for access purposes
return assemblyIsInReferences(s.ContainingAssembly ?? this.Assembly);
default:
return assemblyIsInReferences(s.ContainingAssembly);
}
}
}
}
private protected abstract bool IsSymbolAccessibleWithinCore(
ISymbol symbol,
ISymbol within,
ITypeSymbol? throughType);
internal abstract IConvertibleConversion ClassifyConvertibleConversion(IOperation source, ITypeSymbol destination, out ConstantValue? constantValue);
#endregion
#region Diagnostics
internal const CompilationStage DefaultDiagnosticsStage = CompilationStage.Compile;
/// <summary>
/// Gets the diagnostics produced during the parsing stage.
/// </summary>
public abstract ImmutableArray<Diagnostic> GetParseDiagnostics(CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the diagnostics produced during symbol declaration.
/// </summary>
public abstract ImmutableArray<Diagnostic> GetDeclarationDiagnostics(CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the diagnostics produced during the analysis of method bodies and field initializers.
/// </summary>
public abstract ImmutableArray<Diagnostic> GetMethodBodyDiagnostics(CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the diagnostics for the compilation, including syntax, declaration, and
/// binding. Does not include any diagnostics that might be produced during emit, see
/// <see cref="EmitResult"/>.
/// </summary>
public abstract ImmutableArray<Diagnostic> GetDiagnostics(CancellationToken cancellationToken = default(CancellationToken));
internal abstract void GetDiagnostics(CompilationStage stage, bool includeEarlierStages, DiagnosticBag diagnostics, CancellationToken cancellationToken = default);
/// <summary>
/// Unique metadata assembly references that are considered to be used by this compilation.
/// For example, if a type declared in a referenced assembly is referenced in source code
/// within this compilation, the reference is considered to be used. Etc.
/// The returned set is a subset of references returned by <see cref="References"/> API.
/// The result is undefined if the compilation contains errors.
/// </summary>
public abstract ImmutableArray<MetadataReference> GetUsedAssemblyReferences(CancellationToken cancellationToken = default(CancellationToken));
internal void EnsureCompilationEventQueueCompleted()
{
RoslynDebug.Assert(EventQueue != null);
lock (EventQueue)
{
if (!EventQueue.IsCompleted)
{
CompleteCompilationEventQueue_NoLock();
}
}
}
internal void CompleteCompilationEventQueue_NoLock()
{
RoslynDebug.Assert(EventQueue != null);
// Signal the end of compilation.
EventQueue.TryEnqueue(new CompilationCompletedEvent(this));
EventQueue.PromiseNotToEnqueue();
EventQueue.TryComplete();
}
internal abstract CommonMessageProvider MessageProvider { get; }
/// <summary>
/// Filter out warnings based on the compiler options (/nowarn, /warn and /warnaserror) and the pragma warning directives.
/// 'incoming' is freed.
/// </summary>
/// <param name="accumulator">Bag to which filtered diagnostics will be added.</param>
/// <param name="incoming">Diagnostics to be filtered.</param>
/// <returns>True if there are no unsuppressed errors (i.e., no errors which fail compilation).</returns>
internal bool FilterAndAppendAndFreeDiagnostics(DiagnosticBag accumulator, [DisallowNull] ref DiagnosticBag? incoming, CancellationToken cancellationToken)
{
RoslynDebug.Assert(incoming is object);
bool result = FilterAndAppendDiagnostics(accumulator, incoming.AsEnumerableWithoutResolution(), exclude: null, cancellationToken);
incoming.Free();
incoming = null;
return result;
}
/// <summary>
/// Filter out warnings based on the compiler options (/nowarn, /warn and /warnaserror) and the pragma warning directives.
/// </summary>
/// <returns>True if there are no unsuppressed errors (i.e., no errors which fail compilation).</returns>
internal bool FilterAndAppendDiagnostics(DiagnosticBag accumulator, IEnumerable<Diagnostic> incoming, HashSet<int>? exclude, CancellationToken cancellationToken)
{
bool hasError = false;
bool reportSuppressedDiagnostics = Options.ReportSuppressedDiagnostics;
foreach (Diagnostic d in incoming)
{
if (exclude?.Contains(d.Code) == true)
{
continue;
}
var filtered = Options.FilterDiagnostic(d, cancellationToken);
if (filtered == null ||
(!reportSuppressedDiagnostics && filtered.IsSuppressed))
{
continue;
}
else if (filtered.IsUnsuppressableError())
{
hasError = true;
}
accumulator.Add(filtered);
}
return !hasError;
}
#endregion
#region Resources
/// <summary>
/// Create a stream filled with default win32 resources.
/// </summary>
public Stream CreateDefaultWin32Resources(bool versionResource, bool noManifest, Stream? manifestContents, Stream? iconInIcoFormat)
{
//Win32 resource encodings use a lot of 16bit values. Do all of the math checked with the
//expectation that integer types are well-chosen with size in mind.
checked
{
var result = new MemoryStream(1024);
//start with a null resource just as rc.exe does
AppendNullResource(result);
if (versionResource)
AppendDefaultVersionResource(result);
if (!noManifest)
{
if (this.Options.OutputKind.IsApplication())
{
// Applications use a default manifest if one is not specified.
if (manifestContents == null)
{
manifestContents = typeof(Compilation).GetTypeInfo().Assembly.GetManifestResourceStream("Microsoft.CodeAnalysis.Resources.default.win32manifest");
}
}
else
{
// Modules never have manifests, even if one is specified.
//Debug.Assert(!this.Options.OutputKind.IsNetModule() || manifestContents == null);
}
if (manifestContents != null)
{
Win32ResourceConversions.AppendManifestToResourceStream(result, manifestContents, !this.Options.OutputKind.IsApplication());
}
}
if (iconInIcoFormat != null)
{
Win32ResourceConversions.AppendIconToResourceStream(result, iconInIcoFormat);
}
result.Position = 0;
return result;
}
}
internal static void AppendNullResource(Stream resourceStream)
{
var writer = new BinaryWriter(resourceStream);
writer.Write((UInt32)0);
writer.Write((UInt32)0x20);
writer.Write((UInt16)0xFFFF);
writer.Write((UInt16)0);
writer.Write((UInt16)0xFFFF);
writer.Write((UInt16)0);
writer.Write((UInt32)0); //DataVersion
writer.Write((UInt16)0); //MemoryFlags
writer.Write((UInt16)0); //LanguageId
writer.Write((UInt32)0); //Version
writer.Write((UInt32)0); //Characteristics
}
protected abstract void AppendDefaultVersionResource(Stream resourceStream);
internal enum Win32ResourceForm : byte
{
UNKNOWN,
COFF,
RES
}
internal static Win32ResourceForm DetectWin32ResourceForm(Stream win32Resources)
{
var reader = new BinaryReader(win32Resources, Encoding.Unicode);
var initialPosition = win32Resources.Position;
var initial32Bits = reader.ReadUInt32();
win32Resources.Position = initialPosition;
//RC.EXE output starts with a resource that contains no data.
if (initial32Bits == 0)
return Win32ResourceForm.RES;
else if ((initial32Bits & 0xFFFF0000) != 0 || (initial32Bits & 0x0000FFFF) != 0xFFFF)
// See CLiteWeightStgdbRW::FindObjMetaData in peparse.cpp
return Win32ResourceForm.COFF;
else
return Win32ResourceForm.UNKNOWN;
}
internal Cci.ResourceSection? MakeWin32ResourcesFromCOFF(Stream? win32Resources, DiagnosticBag diagnostics)
{
if (win32Resources == null)
{
return null;
}
Cci.ResourceSection resources;
try
{
resources = COFFResourceReader.ReadWin32ResourcesFromCOFF(win32Resources);
}
catch (BadImageFormatException ex)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, Location.None, ex.Message));
return null;
}
catch (IOException ex)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, Location.None, ex.Message));
return null;
}
catch (ResourceException ex)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, Location.None, ex.Message));
return null;
}
return resources;
}
internal List<Win32Resource>? MakeWin32ResourceList(Stream? win32Resources, DiagnosticBag diagnostics)
{
if (win32Resources == null)
{
return null;
}
List<RESOURCE> resources;
try
{
resources = CvtResFile.ReadResFile(win32Resources);
}
catch (ResourceException ex)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, Location.None, ex.Message));
return null;
}
if (resources == null)
{
return null;
}
var resourceList = new List<Win32Resource>();
foreach (var r in resources)
{
var result = new Win32Resource(
data: r.data,
codePage: 0,
languageId: r.LanguageId,
//EDMAURER converting to int from ushort.
//Go to short first to avoid sign extension.
id: unchecked((short)r.pstringName!.Ordinal),
name: r.pstringName.theString,
typeId: unchecked((short)r.pstringType!.Ordinal),
typeName: r.pstringType.theString
);
resourceList.Add(result);
}
return resourceList;
}
internal void SetupWin32Resources(CommonPEModuleBuilder moduleBeingBuilt, Stream? win32Resources, bool useRawWin32Resources, DiagnosticBag diagnostics)
{
if (win32Resources == null)
return;
if (useRawWin32Resources)
{
moduleBeingBuilt.RawWin32Resources = win32Resources;
return;
}
Win32ResourceForm resourceForm;
try
{
resourceForm = DetectWin32ResourceForm(win32Resources);
}
catch (EndOfStreamException)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, NoLocation.Singleton, CodeAnalysisResources.UnrecognizedResourceFileFormat));
return;
}
catch (Exception ex)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, NoLocation.Singleton, ex.Message));
return;
}
switch (resourceForm)
{
case Win32ResourceForm.COFF:
moduleBeingBuilt.Win32ResourceSection = MakeWin32ResourcesFromCOFF(win32Resources, diagnostics);
break;
case Win32ResourceForm.RES:
moduleBeingBuilt.Win32Resources = MakeWin32ResourceList(win32Resources, diagnostics);
break;
default:
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, NoLocation.Singleton, CodeAnalysisResources.UnrecognizedResourceFileFormat));
break;
}
}
internal void ReportManifestResourceDuplicates(
IEnumerable<ResourceDescription>? manifestResources,
IEnumerable<string> addedModuleNames,
IEnumerable<string> addedModuleResourceNames,
DiagnosticBag diagnostics)
{
if (Options.OutputKind == OutputKind.NetModule && !(manifestResources != null && manifestResources.Any()))
{
return;
}
var uniqueResourceNames = new HashSet<string>();
if (manifestResources != null && manifestResources.Any())
{
var uniqueFileNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var resource in manifestResources)
{
if (!uniqueResourceNames.Add(resource.ResourceName))
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceNotUnique, Location.None, resource.ResourceName));
}
// file name could be null if resource is embedded
var fileName = resource.FileName;
if (fileName != null && !uniqueFileNames.Add(fileName))
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceFileNameNotUnique, Location.None, fileName));
}
}
foreach (var fileName in addedModuleNames)
{
if (!uniqueFileNames.Add(fileName))
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceFileNameNotUnique, Location.None, fileName));
}
}
}
if (Options.OutputKind != OutputKind.NetModule)
{
foreach (string name in addedModuleResourceNames)
{
if (!uniqueResourceNames.Add(name))
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceNotUnique, Location.None, name));
}
}
}
}
#endregion
#region Emit
/// <summary>
/// There are two ways to sign PE files
/// 1. By directly signing the <see cref="PEBuilder"/>
/// 2. Write the unsigned PE to disk and use CLR COM APIs to sign.
/// The preferred method is #1 as it's more efficient and more resilient (no reliance on %TEMP%). But
/// we must continue to support #2 as it's the only way to do the following:
/// - Access private keys stored in a key container
/// - Do proper counter signature verification for AssemblySignatureKey attributes
/// </summary>
internal bool SignUsingBuilder =>
string.IsNullOrEmpty(StrongNameKeys.KeyContainer) &&
!StrongNameKeys.HasCounterSignature &&
!_features.ContainsKey("UseLegacyStrongNameProvider");
/// <summary>
/// Constructs the module serialization properties out of the compilation options of this compilation.
/// </summary>
internal Cci.ModulePropertiesForSerialization ConstructModuleSerializationProperties(
EmitOptions emitOptions,
string? targetRuntimeVersion,
Guid moduleVersionId = default(Guid))
{
CompilationOptions compilationOptions = this.Options;
Platform platform = compilationOptions.Platform;
OutputKind outputKind = compilationOptions.OutputKind;
if (!platform.IsValid())
{
platform = Platform.AnyCpu;
}
if (!outputKind.IsValid())
{
outputKind = OutputKind.DynamicallyLinkedLibrary;
}
bool requires64Bit = platform.Requires64Bit();
bool requires32Bit = platform.Requires32Bit();
ushort fileAlignment;
if (emitOptions.FileAlignment == 0 || !CompilationOptions.IsValidFileAlignment(emitOptions.FileAlignment))
{
fileAlignment = requires64Bit
? Cci.ModulePropertiesForSerialization.DefaultFileAlignment64Bit
: Cci.ModulePropertiesForSerialization.DefaultFileAlignment32Bit;
}
else
{
fileAlignment = (ushort)emitOptions.FileAlignment;
}
ulong baseAddress = unchecked(emitOptions.BaseAddress + 0x8000) & (requires64Bit ? 0xffffffffffff0000 : 0x00000000ffff0000);
// cover values smaller than 0x8000, overflow and default value 0):
if (baseAddress == 0)
{
if (outputKind == OutputKind.ConsoleApplication ||
outputKind == OutputKind.WindowsApplication ||
outputKind == OutputKind.WindowsRuntimeApplication)
{
baseAddress = (requires64Bit) ? Cci.ModulePropertiesForSerialization.DefaultExeBaseAddress64Bit : Cci.ModulePropertiesForSerialization.DefaultExeBaseAddress32Bit;
}
else
{
baseAddress = (requires64Bit) ? Cci.ModulePropertiesForSerialization.DefaultDllBaseAddress64Bit : Cci.ModulePropertiesForSerialization.DefaultDllBaseAddress32Bit;
}
}
ulong sizeOfHeapCommit = requires64Bit
? Cci.ModulePropertiesForSerialization.DefaultSizeOfHeapCommit64Bit
: Cci.ModulePropertiesForSerialization.DefaultSizeOfHeapCommit32Bit;
// Dev10 always uses the default value for 32bit for sizeOfHeapReserve.
// check with link -dump -headers <filename>
const ulong sizeOfHeapReserve = Cci.ModulePropertiesForSerialization.DefaultSizeOfHeapReserve32Bit;
ulong sizeOfStackReserve = requires64Bit
? Cci.ModulePropertiesForSerialization.DefaultSizeOfStackReserve64Bit
: Cci.ModulePropertiesForSerialization.DefaultSizeOfStackReserve32Bit;
ulong sizeOfStackCommit = requires64Bit
? Cci.ModulePropertiesForSerialization.DefaultSizeOfStackCommit64Bit
: Cci.ModulePropertiesForSerialization.DefaultSizeOfStackCommit32Bit;
SubsystemVersion subsystemVersion;
if (emitOptions.SubsystemVersion.Equals(SubsystemVersion.None) || !emitOptions.SubsystemVersion.IsValid)
{
subsystemVersion = SubsystemVersion.Default(outputKind, platform);
}
else
{
subsystemVersion = emitOptions.SubsystemVersion;
}
Machine machine;
switch (platform)
{
case Platform.Arm64:
machine = Machine.Arm64;
break;
case Platform.Arm:
machine = Machine.ArmThumb2;
break;
case Platform.X64:
machine = Machine.Amd64;
break;
case Platform.Itanium:
machine = Machine.IA64;
break;
case Platform.X86:
machine = Machine.I386;
break;
case Platform.AnyCpu:
case Platform.AnyCpu32BitPreferred:
machine = Machine.Unknown;
break;
default:
throw ExceptionUtilities.UnexpectedValue(platform);
}
return new Cci.ModulePropertiesForSerialization(
persistentIdentifier: moduleVersionId,
corFlags: GetCorHeaderFlags(machine, HasStrongName, prefers32Bit: platform == Platform.AnyCpu32BitPreferred),
fileAlignment: fileAlignment,
sectionAlignment: Cci.ModulePropertiesForSerialization.DefaultSectionAlignment,
targetRuntimeVersion: targetRuntimeVersion,
machine: machine,
baseAddress: baseAddress,
sizeOfHeapReserve: sizeOfHeapReserve,
sizeOfHeapCommit: sizeOfHeapCommit,
sizeOfStackReserve: sizeOfStackReserve,
sizeOfStackCommit: sizeOfStackCommit,
dllCharacteristics: GetDllCharacteristics(emitOptions.HighEntropyVirtualAddressSpace, compilationOptions.OutputKind == OutputKind.WindowsRuntimeApplication),
imageCharacteristics: GetCharacteristics(outputKind, requires32Bit),
subsystem: GetSubsystem(outputKind),
majorSubsystemVersion: (ushort)subsystemVersion.Major,
minorSubsystemVersion: (ushort)subsystemVersion.Minor,
linkerMajorVersion: this.LinkerMajorVersion,
linkerMinorVersion: 0);
}
private static CorFlags GetCorHeaderFlags(Machine machine, bool strongNameSigned, bool prefers32Bit)
{
CorFlags result = CorFlags.ILOnly;
if (machine == Machine.I386)
{
result |= CorFlags.Requires32Bit;
}
if (strongNameSigned)
{
result |= CorFlags.StrongNameSigned;
}
if (prefers32Bit)
{
result |= CorFlags.Requires32Bit | CorFlags.Prefers32Bit;
}
return result;
}
internal static DllCharacteristics GetDllCharacteristics(bool enableHighEntropyVA, bool configureToExecuteInAppContainer)
{
var result =
DllCharacteristics.DynamicBase |
DllCharacteristics.NxCompatible |
DllCharacteristics.NoSeh |
DllCharacteristics.TerminalServerAware;
if (enableHighEntropyVA)
{
result |= DllCharacteristics.HighEntropyVirtualAddressSpace;
}
if (configureToExecuteInAppContainer)
{
result |= DllCharacteristics.AppContainer;
}
return result;
}
private static Characteristics GetCharacteristics(OutputKind outputKind, bool requires32Bit)
{
var characteristics = Characteristics.ExecutableImage;
if (requires32Bit)
{
// 32 bit machine (The standard says to always set this, the linker team says otherwise)
// The loader team says that this is not used for anything in the OS.
characteristics |= Characteristics.Bit32Machine;
}
else
{
// Large address aware (the standard says never to set this, the linker team says otherwise).
// The loader team says that this is not overridden for managed binaries and will be respected if set.
characteristics |= Characteristics.LargeAddressAware;
}
switch (outputKind)
{
case OutputKind.WindowsRuntimeMetadata:
case OutputKind.DynamicallyLinkedLibrary:
case OutputKind.NetModule:
characteristics |= Characteristics.Dll;
break;
case OutputKind.ConsoleApplication:
case OutputKind.WindowsRuntimeApplication:
case OutputKind.WindowsApplication:
break;
default:
throw ExceptionUtilities.UnexpectedValue(outputKind);
}
return characteristics;
}
private static Subsystem GetSubsystem(OutputKind outputKind)
{
switch (outputKind)
{
case OutputKind.ConsoleApplication:
case OutputKind.DynamicallyLinkedLibrary:
case OutputKind.NetModule:
case OutputKind.WindowsRuntimeMetadata:
return Subsystem.WindowsCui;
case OutputKind.WindowsRuntimeApplication:
case OutputKind.WindowsApplication:
return Subsystem.WindowsGui;
default:
throw ExceptionUtilities.UnexpectedValue(outputKind);
}
}
/// <summary>
/// The value is not used by Windows loader, but the OS appcompat infrastructure uses it to identify apps.
/// It is useful for us to have a mechanism to identify the compiler that produced the binary.
/// This is the appropriate value to use for that. That is what it was invented for.
/// We don't want to have the high bit set for this in case some users perform a signed comparison to
/// determine if the value is less than some version. The C++ linker is at 0x0B.
/// We'll start our numbering at 0x30 for C#, 0x50 for VB.
/// </summary>
internal abstract byte LinkerMajorVersion { get; }
internal bool HasStrongName
{
get
{
return !IsDelaySigned
&& Options.OutputKind != OutputKind.NetModule
&& StrongNameKeys.CanProvideStrongName;
}
}
internal bool IsRealSigned
{
get
{
// A module cannot be signed. The native compiler allowed one to create a netmodule with an AssemblyKeyFile
// or Container attribute (or specify a key via the cmd line). When the module was linked into an assembly,
// alink would sign the assembly. So rather than give an error we just don't sign when outputting a module.
return !IsDelaySigned
&& !Options.PublicSign
&& Options.OutputKind != OutputKind.NetModule
&& StrongNameKeys.CanSign;
}
}
/// <summary>
/// Return true if the compilation contains any code or types.
/// </summary>
internal abstract bool HasCodeToEmit();
internal abstract bool IsDelaySigned { get; }
internal abstract StrongNameKeys StrongNameKeys { get; }
internal abstract CommonPEModuleBuilder? CreateModuleBuilder(
EmitOptions emitOptions,
IMethodSymbol? debugEntryPoint,
Stream? sourceLinkStream,
IEnumerable<EmbeddedText>? embeddedTexts,
IEnumerable<ResourceDescription>? manifestResources,
CompilationTestData? testData,
DiagnosticBag diagnostics,
CancellationToken cancellationToken);
/// <summary>
/// Report declaration diagnostics and compile and synthesize method bodies.
/// </summary>
/// <returns>True if successful.</returns>
internal abstract bool CompileMethods(
CommonPEModuleBuilder moduleBuilder,
bool emittingPdb,
bool emitMetadataOnly,
bool emitTestCoverageData,
DiagnosticBag diagnostics,
Predicate<ISymbolInternal>? filterOpt,
CancellationToken cancellationToken);
internal bool CreateDebugDocuments(DebugDocumentsBuilder documentsBuilder, IEnumerable<EmbeddedText> embeddedTexts, DiagnosticBag diagnostics)
{
// Check that all syntax trees are debuggable:
bool allTreesDebuggable = true;
foreach (var tree in CommonSyntaxTrees)
{
if (!string.IsNullOrEmpty(tree.FilePath) && tree.GetText().Encoding == null)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_EncodinglessSyntaxTree, tree.GetRoot().GetLocation()));
allTreesDebuggable = false;
}
}
if (!allTreesDebuggable)
{
return false;
}
// Add debug documents for all embedded text first. This ensures that embedding
// takes priority over the syntax tree pass, which will not embed.
if (!embeddedTexts.IsEmpty())
{
foreach (var text in embeddedTexts)
{
Debug.Assert(!string.IsNullOrEmpty(text.FilePath));
string normalizedPath = documentsBuilder.NormalizeDebugDocumentPath(text.FilePath, basePath: null);
var existingDoc = documentsBuilder.TryGetDebugDocumentForNormalizedPath(normalizedPath);
if (existingDoc == null)
{
var document = new Cci.DebugSourceDocument(
normalizedPath,
DebugSourceDocumentLanguageId,
() => text.GetDebugSourceInfo());
documentsBuilder.AddDebugDocument(document);
}
}
}
// Add debug documents for all trees with distinct paths.
foreach (var tree in CommonSyntaxTrees)
{
if (!string.IsNullOrEmpty(tree.FilePath))
{
// compilation does not guarantee that all trees will have distinct paths.
// Do not attempt adding a document for a particular path if we already added one.
string normalizedPath = documentsBuilder.NormalizeDebugDocumentPath(tree.FilePath, basePath: null);
var existingDoc = documentsBuilder.TryGetDebugDocumentForNormalizedPath(normalizedPath);
if (existingDoc == null)
{
documentsBuilder.AddDebugDocument(new Cci.DebugSourceDocument(
normalizedPath,
DebugSourceDocumentLanguageId,
() => tree.GetDebugSourceInfo()));
}
}
}
// Add debug documents for all pragmas.
// If there are clashes with already processed directives, report warnings.
// If there are clashes with debug documents that came from actual trees, ignore the pragma.
// Therefore we need to add these in a separate pass after documents for syntax trees were added.
foreach (var tree in CommonSyntaxTrees)
{
AddDebugSourceDocumentsForChecksumDirectives(documentsBuilder, tree, diagnostics);
}
return true;
}
internal abstract Guid DebugSourceDocumentLanguageId { get; }
internal abstract void AddDebugSourceDocumentsForChecksumDirectives(DebugDocumentsBuilder documentsBuilder, SyntaxTree tree, DiagnosticBag diagnostics);
/// <summary>
/// Update resources and generate XML documentation comments.
/// </summary>
/// <returns>True if successful.</returns>
internal abstract bool GenerateResourcesAndDocumentationComments(
CommonPEModuleBuilder moduleBeingBuilt,
Stream? xmlDocumentationStream,
Stream? win32ResourcesStream,
bool useRawWin32Resources,
string? outputNameOverride,
DiagnosticBag diagnostics,
CancellationToken cancellationToken);
/// <summary>
/// Reports all unused imports/usings so far (and thus it must be called as a last step of Emit)
/// </summary>
internal abstract void ReportUnusedImports(
DiagnosticBag diagnostics,
CancellationToken cancellationToken);
internal static bool ReportUnusedImportsInTree(SyntaxTree tree)
{
return tree.Options.DocumentationMode != DocumentationMode.None;
}
/// <summary>
/// Signals the event queue, if any, that we are done compiling.
/// There should not be more compiling actions after this step.
/// NOTE: once we signal about completion to analyzers they will cancel and thus in some cases we
/// may be effectively cutting off some diagnostics.
/// It is not clear if behavior is desirable.
/// See: https://github.com/dotnet/roslyn/issues/11470
/// </summary>
/// <param name="filterTree">What tree to complete. null means complete all trees. </param>
internal abstract void CompleteTrees(SyntaxTree? filterTree);
internal bool Compile(
CommonPEModuleBuilder moduleBuilder,
bool emittingPdb,
DiagnosticBag diagnostics,
Predicate<ISymbolInternal>? filterOpt,
CancellationToken cancellationToken)
{
try
{
return CompileMethods(
moduleBuilder,
emittingPdb,
emitMetadataOnly: false,
emitTestCoverageData: false,
diagnostics: diagnostics,
filterOpt: filterOpt,
cancellationToken: cancellationToken);
}
finally
{
moduleBuilder.CompilationFinished();
}
}
internal void EnsureAnonymousTypeTemplates(CancellationToken cancellationToken)
{
Debug.Assert(IsSubmission);
if (this.GetSubmissionSlotIndex() >= 0 && HasCodeToEmit())
{
if (!this.CommonAnonymousTypeManager.AreTemplatesSealed)
{
var discardedDiagnostics = DiagnosticBag.GetInstance();
var moduleBeingBuilt = this.CreateModuleBuilder(
emitOptions: EmitOptions.Default,
debugEntryPoint: null,
manifestResources: null,
sourceLinkStream: null,
embeddedTexts: null,
testData: null,
diagnostics: discardedDiagnostics,
cancellationToken: cancellationToken);
if (moduleBeingBuilt != null)
{
Compile(
moduleBeingBuilt,
diagnostics: discardedDiagnostics,
emittingPdb: false,
filterOpt: null,
cancellationToken: cancellationToken);
}
discardedDiagnostics.Free();
}
Debug.Assert(this.CommonAnonymousTypeManager.AreTemplatesSealed);
}
else
{
this.ScriptCompilationInfo?.PreviousScriptCompilation?.EnsureAnonymousTypeTemplates(cancellationToken);
}
}
// 1.0 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
[EditorBrowsable(EditorBrowsableState.Never)]
public EmitResult Emit(
Stream peStream,
Stream? pdbStream,
Stream? xmlDocumentationStream,
Stream? win32Resources,
IEnumerable<ResourceDescription>? manifestResources,
EmitOptions options,
CancellationToken cancellationToken)
{
return Emit(
peStream,
pdbStream,
xmlDocumentationStream,
win32Resources,
manifestResources,
options,
debugEntryPoint: null,
sourceLinkStream: null,
embeddedTexts: null,
cancellationToken);
}
// 1.3 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
[EditorBrowsable(EditorBrowsableState.Never)]
public EmitResult Emit(
Stream peStream,
Stream pdbStream,
Stream xmlDocumentationStream,
Stream win32Resources,
IEnumerable<ResourceDescription> manifestResources,
EmitOptions options,
IMethodSymbol debugEntryPoint,
CancellationToken cancellationToken)
{
return Emit(
peStream,
pdbStream,
xmlDocumentationStream,
win32Resources,
manifestResources,
options,
debugEntryPoint,
sourceLinkStream: null,
embeddedTexts: null,
cancellationToken);
}
// 2.0 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
public EmitResult Emit(
Stream peStream,
Stream? pdbStream,
Stream? xmlDocumentationStream,
Stream? win32Resources,
IEnumerable<ResourceDescription>? manifestResources,
EmitOptions options,
IMethodSymbol? debugEntryPoint,
Stream? sourceLinkStream,
IEnumerable<EmbeddedText>? embeddedTexts,
CancellationToken cancellationToken)
{
return Emit(
peStream,
pdbStream,
xmlDocumentationStream,
win32Resources,
manifestResources,
options,
debugEntryPoint,
sourceLinkStream,
embeddedTexts,
metadataPEStream: null,
cancellationToken: cancellationToken);
}
/// <summary>
/// Emit the IL for the compiled source code into the specified stream.
/// </summary>
/// <param name="peStream">Stream to which the compilation will be written.</param>
/// <param name="metadataPEStream">Stream to which the metadata-only output will be written.</param>
/// <param name="pdbStream">Stream to which the compilation's debug info will be written. Null to forego PDB generation.</param>
/// <param name="xmlDocumentationStream">Stream to which the compilation's XML documentation will be written. Null to forego XML generation.</param>
/// <param name="win32Resources">Stream from which the compilation's Win32 resources will be read (in RES format).
/// Null to indicate that there are none. The RES format begins with a null resource entry.
/// Note that the caller is responsible for disposing this stream, if provided.</param>
/// <param name="manifestResources">List of the compilation's managed resources. Null to indicate that there are none.</param>
/// <param name="options">Emit options.</param>
/// <param name="debugEntryPoint">
/// Debug entry-point of the assembly. The method token is stored in the generated PDB stream.
///
/// When a program launches with a debugger attached the debugger places the first breakpoint to the start of the debug entry-point method.
/// The CLR starts executing the static Main method of <see cref="CompilationOptions.MainTypeName"/> type. When the first breakpoint is hit
/// the debugger steps thru the code statement by statement until user code is reached, skipping methods marked by <see cref="DebuggerHiddenAttribute"/>,
/// and taking other debugging attributes into consideration.
///
/// By default both entry points in an executable program (<see cref="OutputKind.ConsoleApplication"/>, <see cref="OutputKind.WindowsApplication"/>, <see cref="OutputKind.WindowsRuntimeApplication"/>)
/// are the same method (Main). A non-executable program has no entry point. Runtimes that implement a custom loader may specify debug entry-point
/// to force the debugger to skip over complex custom loader logic executing at the beginning of the .exe and thus improve debugging experience.
///
/// Unlike ordinary entry-point which is limited to a non-generic static method of specific signature, there are no restrictions on the <paramref name="debugEntryPoint"/>
/// method other than having a method body (extern, interface, or abstract methods are not allowed).
/// </param>
/// <param name="sourceLinkStream">
/// Stream containing information linking the compilation to a source control.
/// </param>
/// <param name="embeddedTexts">
/// Texts to embed in the PDB.
/// Only supported when emitting Portable PDBs.
/// </param>
/// <param name="cancellationToken">To cancel the emit process.</param>
public EmitResult Emit(
Stream peStream,
Stream? pdbStream = null,
Stream? xmlDocumentationStream = null,
Stream? win32Resources = null,
IEnumerable<ResourceDescription>? manifestResources = null,
EmitOptions? options = null,
IMethodSymbol? debugEntryPoint = null,
Stream? sourceLinkStream = null,
IEnumerable<EmbeddedText>? embeddedTexts = null,
Stream? metadataPEStream = null,
CancellationToken cancellationToken = default(CancellationToken))
{
return Emit(
peStream,
pdbStream,
xmlDocumentationStream,
win32Resources,
manifestResources,
options,
debugEntryPoint,
sourceLinkStream,
embeddedTexts,
metadataPEStream,
rebuildData: null,
cancellationToken);
}
internal EmitResult Emit(
Stream peStream,
Stream? pdbStream,
Stream? xmlDocumentationStream,
Stream? win32Resources,
IEnumerable<ResourceDescription>? manifestResources,
EmitOptions? options,
IMethodSymbol? debugEntryPoint,
Stream? sourceLinkStream,
IEnumerable<EmbeddedText>? embeddedTexts,
Stream? metadataPEStream,
RebuildData? rebuildData,
CancellationToken cancellationToken)
{
if (peStream == null)
{
throw new ArgumentNullException(nameof(peStream));
}
if (!peStream.CanWrite)
{
throw new ArgumentException(CodeAnalysisResources.StreamMustSupportWrite, nameof(peStream));
}
if (pdbStream != null)
{
if (options?.DebugInformationFormat == DebugInformationFormat.Embedded)
{
throw new ArgumentException(CodeAnalysisResources.PdbStreamUnexpectedWhenEmbedding, nameof(pdbStream));
}
if (!pdbStream.CanWrite)
{
throw new ArgumentException(CodeAnalysisResources.StreamMustSupportWrite, nameof(pdbStream));
}
if (options?.EmitMetadataOnly == true)
{
throw new ArgumentException(CodeAnalysisResources.PdbStreamUnexpectedWhenEmittingMetadataOnly, nameof(pdbStream));
}
}
if (metadataPEStream != null && options?.EmitMetadataOnly == true)
{
throw new ArgumentException(CodeAnalysisResources.MetadataPeStreamUnexpectedWhenEmittingMetadataOnly, nameof(metadataPEStream));
}
if (metadataPEStream != null && options?.IncludePrivateMembers == true)
{
throw new ArgumentException(CodeAnalysisResources.IncludingPrivateMembersUnexpectedWhenEmittingToMetadataPeStream, nameof(metadataPEStream));
}
if (metadataPEStream == null && options?.EmitMetadataOnly == false)
{
// EmitOptions used to default to IncludePrivateMembers=false, so to preserve binary compatibility we silently correct that unless emitting regular assemblies
options = options.WithIncludePrivateMembers(true);
}
if (options?.DebugInformationFormat == DebugInformationFormat.Embedded &&
options?.EmitMetadataOnly == true)
{
throw new ArgumentException(CodeAnalysisResources.EmbeddingPdbUnexpectedWhenEmittingMetadata, nameof(metadataPEStream));
}
if (this.Options.OutputKind == OutputKind.NetModule)
{
if (metadataPEStream != null)
{
throw new ArgumentException(CodeAnalysisResources.CannotTargetNetModuleWhenEmittingRefAssembly, nameof(metadataPEStream));
}
else if (options?.EmitMetadataOnly == true)
{
throw new ArgumentException(CodeAnalysisResources.CannotTargetNetModuleWhenEmittingRefAssembly, nameof(options.EmitMetadataOnly));
}
}
if (win32Resources != null)
{
if (!win32Resources.CanRead || !win32Resources.CanSeek)
{
throw new ArgumentException(CodeAnalysisResources.StreamMustSupportReadAndSeek, nameof(win32Resources));
}
}
if (sourceLinkStream != null && !sourceLinkStream.CanRead)
{
throw new ArgumentException(CodeAnalysisResources.StreamMustSupportRead, nameof(sourceLinkStream));
}
if (embeddedTexts != null &&
!embeddedTexts.IsEmpty() &&
pdbStream == null &&
options?.DebugInformationFormat != DebugInformationFormat.Embedded)
{
throw new ArgumentException(CodeAnalysisResources.EmbeddedTextsRequirePdb, nameof(embeddedTexts));
}
return Emit(
peStream,
metadataPEStream,
pdbStream,
xmlDocumentationStream,
win32Resources,
manifestResources,
options,
debugEntryPoint,
sourceLinkStream,
embeddedTexts,
rebuildData,
testData: null,
cancellationToken: cancellationToken);
}
/// <summary>
/// This overload is only intended to be directly called by tests that want to pass <paramref name="testData"/>.
/// The map is used for storing a list of methods and their associated IL.
/// </summary>
internal EmitResult Emit(
Stream peStream,
Stream? metadataPEStream,
Stream? pdbStream,
Stream? xmlDocumentationStream,
Stream? win32Resources,
IEnumerable<ResourceDescription>? manifestResources,
EmitOptions? options,
IMethodSymbol? debugEntryPoint,
Stream? sourceLinkStream,
IEnumerable<EmbeddedText>? embeddedTexts,
RebuildData? rebuildData,
CompilationTestData? testData,
CancellationToken cancellationToken)
{
options = options ?? EmitOptions.Default.WithIncludePrivateMembers(metadataPEStream == null);
bool embedPdb = options.DebugInformationFormat == DebugInformationFormat.Embedded;
Debug.Assert(!embedPdb || pdbStream == null);
Debug.Assert(metadataPEStream == null || !options.IncludePrivateMembers); // you may not use a secondary stream and include private members together
var diagnostics = DiagnosticBag.GetInstance();
var moduleBeingBuilt = CheckOptionsAndCreateModuleBuilder(
diagnostics,
manifestResources,
options,
debugEntryPoint,
sourceLinkStream,
embeddedTexts,
testData,
cancellationToken);
bool success = false;
if (moduleBeingBuilt != null)
{
try
{
success = CompileMethods(
moduleBeingBuilt,
emittingPdb: pdbStream != null || embedPdb,
emitMetadataOnly: options.EmitMetadataOnly,
emitTestCoverageData: options.EmitTestCoverageData,
diagnostics: diagnostics,
filterOpt: null,
cancellationToken: cancellationToken);
if (!options.EmitMetadataOnly)
{
// NOTE: We generate documentation even in presence of compile errors.
// https://github.com/dotnet/roslyn/issues/37996 tracks revisiting this behavior.
if (!GenerateResourcesAndDocumentationComments(
moduleBeingBuilt,
xmlDocumentationStream,
win32Resources,
useRawWin32Resources: rebuildData is object,
options.OutputNameOverride,
diagnostics,
cancellationToken))
{
success = false;
}
if (success)
{
ReportUnusedImports(diagnostics, cancellationToken);
}
}
}
finally
{
moduleBeingBuilt.CompilationFinished();
}
RSAParameters? privateKeyOpt = null;
if (Options.StrongNameProvider != null && SignUsingBuilder && !Options.PublicSign)
{
privateKeyOpt = StrongNameKeys.PrivateKey;
}
if (!options.EmitMetadataOnly && CommonCompiler.HasUnsuppressedErrors(diagnostics))
{
success = false;
}
if (success)
{
success = SerializeToPeStream(
moduleBeingBuilt,
new SimpleEmitStreamProvider(peStream),
(metadataPEStream != null) ? new SimpleEmitStreamProvider(metadataPEStream) : null,
(pdbStream != null) ? new SimpleEmitStreamProvider(pdbStream) : null,
rebuildData,
testData?.SymWriterFactory,
diagnostics,
emitOptions: options,
privateKeyOpt: privateKeyOpt,
cancellationToken: cancellationToken);
}
}
return new EmitResult(success, diagnostics.ToReadOnlyAndFree());
}
#pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters
/// <summary>
/// Emit the differences between the compilation and the previous generation
/// for Edit and Continue. The differences are expressed as added and changed
/// symbols, and are emitted as metadata, IL, and PDB deltas. A representation
/// of the current compilation is returned as an EmitBaseline for use in a
/// subsequent Edit and Continue.
/// </summary>
[Obsolete("UpdatedMethods is now part of EmitDifferenceResult, so you should use an overload that doesn't take it.")]
public EmitDifferenceResult EmitDifference(
EmitBaseline baseline,
IEnumerable<SemanticEdit> edits,
Stream metadataStream,
Stream ilStream,
Stream pdbStream,
ICollection<MethodDefinitionHandle> updatedMethods,
CancellationToken cancellationToken = default(CancellationToken))
{
return EmitDifference(baseline, edits, s => false, metadataStream, ilStream, pdbStream, updatedMethods, cancellationToken);
}
/// <summary>
/// Emit the differences between the compilation and the previous generation
/// for Edit and Continue. The differences are expressed as added and changed
/// symbols, and are emitted as metadata, IL, and PDB deltas. A representation
/// of the current compilation is returned as an EmitBaseline for use in a
/// subsequent Edit and Continue.
/// </summary>
[Obsolete("UpdatedMethods is now part of EmitDifferenceResult, so you should use an overload that doesn't take it.")]
public EmitDifferenceResult EmitDifference(
EmitBaseline baseline,
IEnumerable<SemanticEdit> edits,
Func<ISymbol, bool> isAddedSymbol,
Stream metadataStream,
Stream ilStream,
Stream pdbStream,
ICollection<MethodDefinitionHandle> updatedMethods,
CancellationToken cancellationToken = default(CancellationToken))
{
var diff = EmitDifference(baseline, edits, isAddedSymbol, metadataStream, ilStream, pdbStream, cancellationToken);
foreach (var token in diff.UpdatedMethods)
{
updatedMethods.Add(token);
}
return diff;
}
/// <summary>
/// Emit the differences between the compilation and the previous generation
/// for Edit and Continue. The differences are expressed as added and changed
/// symbols, and are emitted as metadata, IL, and PDB deltas. A representation
/// of the current compilation is returned as an EmitBaseline for use in a
/// subsequent Edit and Continue.
/// </summary>
public EmitDifferenceResult EmitDifference(
EmitBaseline baseline,
IEnumerable<SemanticEdit> edits,
Func<ISymbol, bool> isAddedSymbol,
Stream metadataStream,
Stream ilStream,
Stream pdbStream,
CancellationToken cancellationToken = default(CancellationToken))
{
if (baseline == null)
{
throw new ArgumentNullException(nameof(baseline));
}
// TODO: check if baseline is an assembly manifest module/netmodule
// Do we support EnC on netmodules?
if (edits == null)
{
throw new ArgumentNullException(nameof(edits));
}
if (isAddedSymbol == null)
{
throw new ArgumentNullException(nameof(isAddedSymbol));
}
if (metadataStream == null)
{
throw new ArgumentNullException(nameof(metadataStream));
}
if (ilStream == null)
{
throw new ArgumentNullException(nameof(ilStream));
}
if (pdbStream == null)
{
throw new ArgumentNullException(nameof(pdbStream));
}
return this.EmitDifference(baseline, edits, isAddedSymbol, metadataStream, ilStream, pdbStream, testData: null, cancellationToken);
}
#pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters
internal abstract EmitDifferenceResult EmitDifference(
EmitBaseline baseline,
IEnumerable<SemanticEdit> edits,
Func<ISymbol, bool> isAddedSymbol,
Stream metadataStream,
Stream ilStream,
Stream pdbStream,
CompilationTestData? testData,
CancellationToken cancellationToken);
/// <summary>
/// Check compilation options and create <see cref="CommonPEModuleBuilder"/>.
/// </summary>
/// <returns><see cref="CommonPEModuleBuilder"/> if successful.</returns>
internal CommonPEModuleBuilder? CheckOptionsAndCreateModuleBuilder(
DiagnosticBag diagnostics,
IEnumerable<ResourceDescription>? manifestResources,
EmitOptions options,
IMethodSymbol? debugEntryPoint,
Stream? sourceLinkStream,
IEnumerable<EmbeddedText>? embeddedTexts,
CompilationTestData? testData,
CancellationToken cancellationToken)
{
options.ValidateOptions(diagnostics, MessageProvider, Options.Deterministic);
if (debugEntryPoint != null)
{
ValidateDebugEntryPoint(debugEntryPoint, diagnostics);
}
if (Options.OutputKind == OutputKind.NetModule && manifestResources != null)
{
foreach (ResourceDescription res in manifestResources)
{
if (res.FileName != null)
{
// Modules can have only embedded resources, not linked ones.
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceInModule, Location.None));
}
}
}
if (CommonCompiler.HasUnsuppressableErrors(diagnostics))
{
return null;
}
// Do not waste a slot in the submission chain for submissions that contain no executable code
// (they may only contain #r directives, usings, etc.)
if (IsSubmission && !HasCodeToEmit())
{
// Still report diagnostics since downstream submissions will assume there are no errors.
diagnostics.AddRange(this.GetDiagnostics(cancellationToken));
return null;
}
return this.CreateModuleBuilder(
options,
debugEntryPoint,
sourceLinkStream,
embeddedTexts,
manifestResources,
testData,
diagnostics,
cancellationToken);
}
internal abstract void ValidateDebugEntryPoint(IMethodSymbol debugEntryPoint, DiagnosticBag diagnostics);
internal bool IsEmitDeterministic => this.Options.Deterministic;
internal bool SerializeToPeStream(
CommonPEModuleBuilder moduleBeingBuilt,
EmitStreamProvider peStreamProvider,
EmitStreamProvider? metadataPEStreamProvider,
EmitStreamProvider? pdbStreamProvider,
RebuildData? rebuildData,
Func<ISymWriterMetadataProvider, SymUnmanagedWriter>? testSymWriterFactory,
DiagnosticBag diagnostics,
EmitOptions emitOptions,
RSAParameters? privateKeyOpt,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
Cci.PdbWriter? nativePdbWriter = null;
DiagnosticBag? metadataDiagnostics = null;
DiagnosticBag? pdbBag = null;
bool deterministic = IsEmitDeterministic;
// PDB Stream provider should not be given if PDB is to be embedded into the PE file:
Debug.Assert(moduleBeingBuilt.DebugInformationFormat != DebugInformationFormat.Embedded || pdbStreamProvider == null);
string? pePdbFilePath = emitOptions.PdbFilePath;
if (moduleBeingBuilt.DebugInformationFormat == DebugInformationFormat.Embedded || pdbStreamProvider != null)
{
pePdbFilePath = pePdbFilePath ?? FileNameUtilities.ChangeExtension(SourceModule.Name, "pdb");
}
else
{
pePdbFilePath = null;
}
if (moduleBeingBuilt.DebugInformationFormat == DebugInformationFormat.Embedded && !RoslynString.IsNullOrEmpty(pePdbFilePath))
{
pePdbFilePath = PathUtilities.GetFileName(pePdbFilePath);
}
EmitStream? emitPeStream = null;
EmitStream? emitMetadataStream = null;
try
{
var signKind = IsRealSigned
? (SignUsingBuilder ? EmitStreamSignKind.SignedWithBuilder : EmitStreamSignKind.SignedWithFile)
: EmitStreamSignKind.None;
emitPeStream = new EmitStream(peStreamProvider, signKind, Options.StrongNameProvider);
emitMetadataStream = metadataPEStreamProvider == null
? null
: new EmitStream(metadataPEStreamProvider, signKind, Options.StrongNameProvider);
metadataDiagnostics = DiagnosticBag.GetInstance();
if (moduleBeingBuilt.DebugInformationFormat == DebugInformationFormat.Pdb && pdbStreamProvider != null)
{
// The algorithm must be specified for deterministic builds (checked earlier).
Debug.Assert(!deterministic || moduleBeingBuilt.PdbChecksumAlgorithm.Name != null);
// The calls ISymUnmanagedWriter2.GetDebugInfo require a file name in order to succeed. This is
// frequently used during PDB writing. Ensure a name is provided here in the case we were given
// only a Stream value.
nativePdbWriter = new Cci.PdbWriter(pePdbFilePath, testSymWriterFactory, deterministic ? moduleBeingBuilt.PdbChecksumAlgorithm : default);
}
Func<Stream?>? getPortablePdbStream =
moduleBeingBuilt.DebugInformationFormat != DebugInformationFormat.PortablePdb || pdbStreamProvider == null
? null
: (Func<Stream?>)(() => ConditionalGetOrCreateStream(pdbStreamProvider, metadataDiagnostics));
try
{
if (SerializePeToStream(
moduleBeingBuilt,
metadataDiagnostics,
MessageProvider,
emitPeStream.GetCreateStreamFunc(metadataDiagnostics),
emitMetadataStream?.GetCreateStreamFunc(metadataDiagnostics),
getPortablePdbStream,
nativePdbWriter,
pePdbFilePath,
rebuildData,
emitOptions.EmitMetadataOnly,
emitOptions.IncludePrivateMembers,
deterministic,
emitOptions.EmitTestCoverageData,
privateKeyOpt,
cancellationToken))
{
if (nativePdbWriter != null)
{
var nativePdbStream = pdbStreamProvider!.GetOrCreateStream(metadataDiagnostics);
Debug.Assert(nativePdbStream != null || metadataDiagnostics.HasAnyErrors());
if (nativePdbStream != null)
{
nativePdbWriter.WriteTo(nativePdbStream);
}
}
}
}
catch (SymUnmanagedWriterException ex)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PdbWritingFailed, Location.None, ex.Message));
return false;
}
catch (Cci.PeWritingException e)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PeWritingFailure, Location.None, e.InnerException?.ToString() ?? ""));
return false;
}
catch (ResourceException e)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_CantReadResource, Location.None, e.Message, e.InnerException?.Message ?? ""));
return false;
}
catch (PermissionSetFileReadException e)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PermissionSetAttributeFileReadError, Location.None, e.FileName, e.PropertyName, e.Message));
return false;
}
// translate metadata errors.
if (!FilterAndAppendAndFreeDiagnostics(diagnostics, ref metadataDiagnostics, cancellationToken))
{
return false;
}
return
emitPeStream.Complete(StrongNameKeys, MessageProvider, diagnostics) &&
(emitMetadataStream?.Complete(StrongNameKeys, MessageProvider, diagnostics) ?? true);
}
finally
{
nativePdbWriter?.Dispose();
emitPeStream?.Close();
emitMetadataStream?.Close();
pdbBag?.Free();
metadataDiagnostics?.Free();
}
}
private static Stream? ConditionalGetOrCreateStream(EmitStreamProvider metadataPEStreamProvider, DiagnosticBag metadataDiagnostics)
{
if (metadataDiagnostics.HasAnyErrors())
{
return null;
}
var auxStream = metadataPEStreamProvider.GetOrCreateStream(metadataDiagnostics);
Debug.Assert(auxStream != null || metadataDiagnostics.HasAnyErrors());
return auxStream;
}
internal static bool SerializePeToStream(
CommonPEModuleBuilder moduleBeingBuilt,
DiagnosticBag metadataDiagnostics,
CommonMessageProvider messageProvider,
Func<Stream?> getPeStream,
Func<Stream?>? getMetadataPeStreamOpt,
Func<Stream?>? getPortablePdbStreamOpt,
Cci.PdbWriter? nativePdbWriterOpt,
string? pdbPathOpt,
RebuildData? rebuildData,
bool metadataOnly,
bool includePrivateMembers,
bool isDeterministic,
bool emitTestCoverageData,
RSAParameters? privateKeyOpt,
CancellationToken cancellationToken)
{
bool emitSecondaryAssembly = getMetadataPeStreamOpt != null;
bool includePrivateMembersOnPrimaryOutput = metadataOnly ? includePrivateMembers : true;
bool deterministicPrimaryOutput = (metadataOnly && !includePrivateMembers) || isDeterministic;
if (!Cci.PeWriter.WritePeToStream(
new EmitContext(moduleBeingBuilt, metadataDiagnostics, metadataOnly, includePrivateMembersOnPrimaryOutput, rebuildData: rebuildData),
messageProvider,
getPeStream,
getPortablePdbStreamOpt,
nativePdbWriterOpt,
pdbPathOpt,
metadataOnly,
deterministicPrimaryOutput,
emitTestCoverageData,
privateKeyOpt,
cancellationToken))
{
return false;
}
// produce the secondary output (ref assembly) if needed
if (emitSecondaryAssembly)
{
Debug.Assert(!metadataOnly);
Debug.Assert(!includePrivateMembers);
if (!Cci.PeWriter.WritePeToStream(
new EmitContext(moduleBeingBuilt, syntaxNode: null, metadataDiagnostics, metadataOnly: true, includePrivateMembers: false),
messageProvider,
getMetadataPeStreamOpt,
getPortablePdbStreamOpt: null,
nativePdbWriterOpt: null,
pdbPathOpt: null,
metadataOnly: true,
isDeterministic: true,
emitTestCoverageData: false,
privateKeyOpt: privateKeyOpt,
cancellationToken: cancellationToken))
{
return false;
}
}
return true;
}
internal EmitBaseline? SerializeToDeltaStreams(
CommonPEModuleBuilder moduleBeingBuilt,
EmitBaseline baseline,
DefinitionMap definitionMap,
SymbolChanges changes,
Stream metadataStream,
Stream ilStream,
Stream pdbStream,
ArrayBuilder<MethodDefinitionHandle> updatedMethods,
ArrayBuilder<TypeDefinitionHandle> updatedTypes,
DiagnosticBag diagnostics,
Func<ISymWriterMetadataProvider, SymUnmanagedWriter>? testSymWriterFactory,
string? pdbFilePath,
CancellationToken cancellationToken)
{
var nativePdbWriter = (moduleBeingBuilt.DebugInformationFormat != DebugInformationFormat.Pdb) ? null :
new Cci.PdbWriter(
pdbFilePath ?? FileNameUtilities.ChangeExtension(SourceModule.Name, "pdb"),
testSymWriterFactory,
hashAlgorithmNameOpt: default);
using (nativePdbWriter)
{
var context = new EmitContext(moduleBeingBuilt, diagnostics, metadataOnly: false, includePrivateMembers: true);
var encId = Guid.NewGuid();
try
{
var writer = new DeltaMetadataWriter(
context,
MessageProvider,
baseline,
encId,
definitionMap,
changes,
cancellationToken);
writer.WriteMetadataAndIL(
nativePdbWriter,
metadataStream,
ilStream,
(nativePdbWriter == null) ? pdbStream : null,
out MetadataSizes metadataSizes);
writer.GetUpdatedMethodTokens(updatedMethods);
writer.GetUpdatedTypeTokens(updatedTypes);
nativePdbWriter?.WriteTo(pdbStream);
return diagnostics.HasAnyErrors() ? null : writer.GetDelta(this, encId, metadataSizes);
}
catch (SymUnmanagedWriterException e)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PdbWritingFailed, Location.None, e.Message));
return null;
}
catch (Cci.PeWritingException e)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PeWritingFailure, Location.None, e.InnerException?.ToString() ?? ""));
return null;
}
catch (PermissionSetFileReadException e)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PermissionSetAttributeFileReadError, Location.None, e.FileName, e.PropertyName, e.Message));
return null;
}
}
}
internal string? Feature(string p)
{
string? v;
return _features.TryGetValue(p, out v) ? v : null;
}
#endregion
private ConcurrentDictionary<SyntaxTree, SmallConcurrentSetOfInts>? _lazyTreeToUsedImportDirectivesMap;
private static readonly Func<SyntaxTree, SmallConcurrentSetOfInts> s_createSetCallback = t => new SmallConcurrentSetOfInts();
private ConcurrentDictionary<SyntaxTree, SmallConcurrentSetOfInts> TreeToUsedImportDirectivesMap
{
get
{
return RoslynLazyInitializer.EnsureInitialized(ref _lazyTreeToUsedImportDirectivesMap);
}
}
internal void MarkImportDirectiveAsUsed(SyntaxReference node)
{
MarkImportDirectiveAsUsed(node.SyntaxTree, node.Span.Start);
}
internal void MarkImportDirectiveAsUsed(SyntaxTree? syntaxTree, int position)
{
// Optimization: Don't initialize TreeToUsedImportDirectivesMap in submissions.
if (!IsSubmission && syntaxTree != null)
{
var set = TreeToUsedImportDirectivesMap.GetOrAdd(syntaxTree, s_createSetCallback);
set.Add(position);
}
}
internal bool IsImportDirectiveUsed(SyntaxTree syntaxTree, int position)
{
if (IsSubmission)
{
// Since usings apply to subsequent submissions, we have to assume they are used.
return true;
}
SmallConcurrentSetOfInts? usedImports;
return syntaxTree != null &&
TreeToUsedImportDirectivesMap.TryGetValue(syntaxTree, out usedImports) &&
usedImports.Contains(position);
}
/// <summary>
/// The compiler needs to define an ordering among different partial class in different syntax trees
/// in some cases, because emit order for fields in structures, for example, is semantically important.
/// This function defines an ordering among syntax trees in this compilation.
/// </summary>
internal int CompareSyntaxTreeOrdering(SyntaxTree tree1, SyntaxTree tree2)
{
if (tree1 == tree2)
{
return 0;
}
Debug.Assert(this.ContainsSyntaxTree(tree1));
Debug.Assert(this.ContainsSyntaxTree(tree2));
return this.GetSyntaxTreeOrdinal(tree1) - this.GetSyntaxTreeOrdinal(tree2);
}
internal abstract int GetSyntaxTreeOrdinal(SyntaxTree tree);
/// <summary>
/// Compare two source locations, using their containing trees, and then by Span.First within a tree.
/// Can be used to get a total ordering on declarations, for example.
/// </summary>
internal abstract int CompareSourceLocations(Location loc1, Location loc2);
/// <summary>
/// Compare two source locations, using their containing trees, and then by Span.First within a tree.
/// Can be used to get a total ordering on declarations, for example.
/// </summary>
internal abstract int CompareSourceLocations(SyntaxReference loc1, SyntaxReference loc2);
/// <summary>
/// Return the lexically first of two locations.
/// </summary>
internal TLocation FirstSourceLocation<TLocation>(TLocation first, TLocation second)
where TLocation : Location
{
if (CompareSourceLocations(first, second) <= 0)
{
return first;
}
else
{
return second;
}
}
/// <summary>
/// Return the lexically first of multiple locations.
/// </summary>
internal TLocation? FirstSourceLocation<TLocation>(ImmutableArray<TLocation> locations)
where TLocation : Location
{
if (locations.IsEmpty)
{
return null;
}
var result = locations[0];
for (int i = 1; i < locations.Length; i++)
{
result = FirstSourceLocation(result, locations[i]);
}
return result;
}
#region Logging Helpers
// Following helpers are used when logging ETW events. These helpers are invoked only if we are running
// under an ETW listener that has requested 'verbose' logging. In other words, these helpers will never
// be invoked in the 'normal' case (i.e. when the code is running on user's machine and no ETW listener
// is involved).
// Note: Most of the below helpers are unused at the moment - but we would like to keep them around in
// case we decide we need more verbose logging in certain cases for debugging.
internal string GetMessage(CompilationStage stage)
{
return string.Format("{0} ({1})", this.AssemblyName, stage.ToString());
}
internal string GetMessage(ITypeSymbol source, ITypeSymbol destination)
{
if (source == null || destination == null) return this.AssemblyName ?? "";
return string.Format("{0}: {1} {2} -> {3} {4}", this.AssemblyName, source.TypeKind.ToString(), source.Name, destination.TypeKind.ToString(), destination.Name);
}
#endregion
#region Declaration Name Queries
/// <summary>
/// Return true if there is a source declaration symbol name that meets given predicate.
/// </summary>
public abstract bool ContainsSymbolsWithName(Func<string, bool> predicate, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return source declaration symbols whose name meets given predicate.
/// </summary>
public abstract IEnumerable<ISymbol> GetSymbolsWithName(Func<string, bool> predicate, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default(CancellationToken));
#pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters
/// <summary>
/// Return true if there is a source declaration symbol name that matches the provided name.
/// This may be faster than <see cref="ContainsSymbolsWithName(Func{string, bool},
/// SymbolFilter, CancellationToken)"/> when predicate is just a simple string check.
/// <paramref name="name"/> is case sensitive or not depending on the target language.
/// </summary>
public abstract bool ContainsSymbolsWithName(string name, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return source declaration symbols whose name matches the provided name. This may be
/// faster than <see cref="GetSymbolsWithName(Func{string, bool}, SymbolFilter,
/// CancellationToken)"/> when predicate is just a simple string check. <paramref
/// name="name"/> is case sensitive or not depending on the target language.
/// </summary>
public abstract IEnumerable<ISymbol> GetSymbolsWithName(string name, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default(CancellationToken));
#pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters
#endregion
internal void MakeMemberMissing(WellKnownMember member)
{
MakeMemberMissing((int)member);
}
internal void MakeMemberMissing(SpecialMember member)
{
MakeMemberMissing(-(int)member - 1);
}
internal bool IsMemberMissing(WellKnownMember member)
{
return IsMemberMissing((int)member);
}
internal bool IsMemberMissing(SpecialMember member)
{
return IsMemberMissing(-(int)member - 1);
}
private void MakeMemberMissing(int member)
{
if (_lazyMakeMemberMissingMap == null)
{
_lazyMakeMemberMissingMap = new SmallDictionary<int, bool>();
}
_lazyMakeMemberMissingMap[member] = true;
}
private bool IsMemberMissing(int member)
{
return _lazyMakeMemberMissingMap != null && _lazyMakeMemberMissingMap.ContainsKey(member);
}
internal void MakeTypeMissing(SpecialType type)
{
MakeTypeMissing((int)type);
}
internal void MakeTypeMissing(WellKnownType type)
{
MakeTypeMissing((int)type);
}
private void MakeTypeMissing(int type)
{
if (_lazyMakeWellKnownTypeMissingMap == null)
{
_lazyMakeWellKnownTypeMissingMap = new SmallDictionary<int, bool>();
}
_lazyMakeWellKnownTypeMissingMap[(int)type] = true;
}
internal bool IsTypeMissing(SpecialType type)
{
return IsTypeMissing((int)type);
}
internal bool IsTypeMissing(WellKnownType type)
{
return IsTypeMissing((int)type);
}
private bool IsTypeMissing(int type)
{
return _lazyMakeWellKnownTypeMissingMap != null && _lazyMakeWellKnownTypeMissingMap.ContainsKey((int)type);
}
/// <summary>
/// Given a <see cref="Diagnostic"/> reporting unreferenced <see cref="AssemblyIdentity"/>s, returns
/// the actual <see cref="AssemblyIdentity"/> instances that were not referenced.
/// </summary>
public ImmutableArray<AssemblyIdentity> GetUnreferencedAssemblyIdentities(Diagnostic diagnostic)
{
if (diagnostic == null)
{
throw new ArgumentNullException(nameof(diagnostic));
}
if (!IsUnreferencedAssemblyIdentityDiagnosticCode(diagnostic.Code))
{
return ImmutableArray<AssemblyIdentity>.Empty;
}
var builder = ArrayBuilder<AssemblyIdentity>.GetInstance();
foreach (var argument in diagnostic.Arguments)
{
if (argument is AssemblyIdentity id)
{
builder.Add(id);
}
}
return builder.ToImmutableAndFree();
}
internal abstract bool IsUnreferencedAssemblyIdentityDiagnosticCode(int code);
/// <summary>
/// Returns the required language version found in a <see cref="Diagnostic"/>, if any is found.
/// Returns null if none is found.
/// </summary>
public static string? GetRequiredLanguageVersion(Diagnostic diagnostic)
{
if (diagnostic == null)
{
throw new ArgumentNullException(nameof(diagnostic));
}
bool found = false;
string? foundVersion = null;
if (diagnostic.Arguments != null)
{
foreach (var argument in diagnostic.Arguments)
{
if (argument is RequiredLanguageVersion versionDiagnostic)
{
Debug.Assert(!found); // only one required language version in a given diagnostic
found = true;
foundVersion = versionDiagnostic.ToString();
}
}
}
return foundVersion;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Symbols;
using Microsoft.DiaSymReader;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// The compilation object is an immutable representation of a single invocation of the
/// compiler. Although immutable, a compilation is also on-demand, and will realize and cache
/// data as necessary. A compilation can produce a new compilation from existing compilation
/// with the application of small deltas. In many cases, it is more efficient than creating a
/// new compilation from scratch, as the new compilation can reuse information from the old
/// compilation.
/// </summary>
public abstract partial class Compilation
{
/// <summary>
/// Returns true if this is a case sensitive compilation, false otherwise. Case sensitivity
/// affects compilation features such as name lookup as well as choosing what names to emit
/// when there are multiple different choices (for example between a virtual method and an
/// override).
/// </summary>
public abstract bool IsCaseSensitive { get; }
/// <summary>
/// Used for test purposes only to emulate missing members.
/// </summary>
private SmallDictionary<int, bool>? _lazyMakeWellKnownTypeMissingMap;
/// <summary>
/// Used for test purposes only to emulate missing members.
/// </summary>
private SmallDictionary<int, bool>? _lazyMakeMemberMissingMap;
// Protected for access in CSharpCompilation.WithAdditionalFeatures
protected readonly IReadOnlyDictionary<string, string> _features;
public ScriptCompilationInfo? ScriptCompilationInfo => CommonScriptCompilationInfo;
internal abstract ScriptCompilationInfo? CommonScriptCompilationInfo { get; }
internal Compilation(
string? name,
ImmutableArray<MetadataReference> references,
IReadOnlyDictionary<string, string> features,
bool isSubmission,
SemanticModelProvider? semanticModelProvider,
AsyncQueue<CompilationEvent>? eventQueue)
{
RoslynDebug.Assert(!references.IsDefault);
RoslynDebug.Assert(features != null);
this.AssemblyName = name;
this.ExternalReferences = references;
this.SemanticModelProvider = semanticModelProvider;
this.EventQueue = eventQueue;
_lazySubmissionSlotIndex = isSubmission ? SubmissionSlotIndexToBeAllocated : SubmissionSlotIndexNotApplicable;
_features = features;
}
protected static IReadOnlyDictionary<string, string> SyntaxTreeCommonFeatures(IEnumerable<SyntaxTree> trees)
{
IReadOnlyDictionary<string, string>? set = null;
foreach (var tree in trees)
{
var treeFeatures = tree.Options.Features;
if (set == null)
{
set = treeFeatures;
}
else
{
if ((object)set != treeFeatures && !set.SetEquals(treeFeatures))
{
throw new ArgumentException(CodeAnalysisResources.InconsistentSyntaxTreeFeature, nameof(trees));
}
}
}
if (set == null)
{
// Edge case where there are no syntax trees
set = ImmutableDictionary<string, string>.Empty;
}
return set;
}
internal abstract AnalyzerDriver CreateAnalyzerDriver(ImmutableArray<DiagnosticAnalyzer> analyzers, AnalyzerManager analyzerManager, SeverityFilter severityFilter);
/// <summary>
/// Gets the source language ("C#" or "Visual Basic").
/// </summary>
public abstract string Language { get; }
internal abstract void SerializePdbEmbeddedCompilationOptions(BlobBuilder builder);
internal static void ValidateScriptCompilationParameters(Compilation? previousScriptCompilation, Type? returnType, ref Type? globalsType)
{
if (globalsType != null && !IsValidHostObjectType(globalsType))
{
throw new ArgumentException(CodeAnalysisResources.ReturnTypeCannotBeValuePointerbyRefOrOpen, nameof(globalsType));
}
if (returnType != null && !IsValidSubmissionReturnType(returnType))
{
throw new ArgumentException(CodeAnalysisResources.ReturnTypeCannotBeVoidByRefOrOpen, nameof(returnType));
}
if (previousScriptCompilation != null)
{
if (globalsType == null)
{
globalsType = previousScriptCompilation.HostObjectType;
}
else if (globalsType != previousScriptCompilation.HostObjectType)
{
throw new ArgumentException(CodeAnalysisResources.TypeMustBeSameAsHostObjectTypeOfPreviousSubmission, nameof(globalsType));
}
// Force the previous submission to be analyzed. This is required for anonymous types unification.
if (previousScriptCompilation.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error))
{
throw new InvalidOperationException(CodeAnalysisResources.PreviousSubmissionHasErrors);
}
}
}
/// <summary>
/// Checks options passed to submission compilation constructor.
/// Throws an exception if the options are not applicable to submissions.
/// </summary>
internal static void CheckSubmissionOptions(CompilationOptions? options)
{
if (options == null)
{
return;
}
if (options.OutputKind.IsValid() && options.OutputKind != OutputKind.DynamicallyLinkedLibrary)
{
throw new ArgumentException(CodeAnalysisResources.InvalidOutputKindForSubmission, nameof(options));
}
if (options.CryptoKeyContainer != null ||
options.CryptoKeyFile != null ||
options.DelaySign != null ||
!options.CryptoPublicKey.IsEmpty ||
(options.DelaySign == true && options.PublicSign))
{
throw new ArgumentException(CodeAnalysisResources.InvalidCompilationOptions, nameof(options));
}
}
/// <summary>
/// Creates a new compilation equivalent to this one with different symbol instances.
/// </summary>
public Compilation Clone()
{
return CommonClone();
}
protected abstract Compilation CommonClone();
/// <summary>
/// Returns a new compilation with a given event queue.
/// </summary>
internal abstract Compilation WithEventQueue(AsyncQueue<CompilationEvent>? eventQueue);
/// <summary>
/// Returns a new compilation with a given semantic model provider.
/// </summary>
internal abstract Compilation WithSemanticModelProvider(SemanticModelProvider semanticModelProvider);
/// <summary>
/// Gets a new <see cref="SemanticModel"/> for the specified syntax tree.
/// </summary>
/// <param name="syntaxTree">The specified syntax tree.</param>
/// <param name="ignoreAccessibility">
/// True if the SemanticModel should ignore accessibility rules when answering semantic questions.
/// </param>
public SemanticModel GetSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility = false)
=> CommonGetSemanticModel(syntaxTree, ignoreAccessibility);
/// <summary>
/// Gets a <see cref="SemanticModel"/> for the given <paramref name="syntaxTree"/>.
/// If <see cref="SemanticModelProvider"/> is non-null, it attempts to use <see cref="SemanticModelProvider.GetSemanticModel(SyntaxTree, Compilation, bool)"/>
/// to get a semantic model. Otherwise, it creates a new semantic model using <see cref="CreateSemanticModel(SyntaxTree, bool)"/>.
/// </summary>
/// <param name="syntaxTree"></param>
/// <param name="ignoreAccessibility"></param>
/// <returns></returns>
protected abstract SemanticModel CommonGetSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility);
/// <summary>
/// Creates a new <see cref="SemanticModel"/> for the given <paramref name="syntaxTree"/>.
/// Unlike the <see cref="GetSemanticModel(SyntaxTree, bool)"/> and <see cref="CommonGetSemanticModel(SyntaxTree, bool)"/>,
/// it does not attempt to use the <see cref="SemanticModelProvider"/> to get a semantic model, but instead always creates a new semantic model.
/// </summary>
/// <param name="syntaxTree"></param>
/// <param name="ignoreAccessibility"></param>
/// <returns></returns>
internal abstract SemanticModel CreateSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility);
/// <summary>
/// Returns a new INamedTypeSymbol representing an error type with the given name and arity
/// in the given optional container.
/// </summary>
public INamedTypeSymbol CreateErrorTypeSymbol(INamespaceOrTypeSymbol? container, string name, int arity)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
if (arity < 0)
{
throw new ArgumentException($"{nameof(arity)} must be >= 0", nameof(arity));
}
return CommonCreateErrorTypeSymbol(container, name, arity);
}
protected abstract INamedTypeSymbol CommonCreateErrorTypeSymbol(INamespaceOrTypeSymbol? container, string name, int arity);
/// <summary>
/// Returns a new INamespaceSymbol representing an error (missing) namespace with the given name.
/// </summary>
public INamespaceSymbol CreateErrorNamespaceSymbol(INamespaceSymbol container, string name)
{
if (container == null)
{
throw new ArgumentNullException(nameof(container));
}
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
return CommonCreateErrorNamespaceSymbol(container, name);
}
protected abstract INamespaceSymbol CommonCreateErrorNamespaceSymbol(INamespaceSymbol container, string name);
#region Name
internal const string UnspecifiedModuleAssemblyName = "?";
/// <summary>
/// Simple assembly name, or null if not specified.
/// </summary>
/// <remarks>
/// The name is used for determining internals-visible-to relationship with referenced assemblies.
///
/// If the compilation represents an assembly the value of <see cref="AssemblyName"/> is its simple name.
///
/// Unless <see cref="CompilationOptions.ModuleName"/> specifies otherwise the module name
/// written to metadata is <see cref="AssemblyName"/> with an extension based upon <see cref="CompilationOptions.OutputKind"/>.
/// </remarks>
public string? AssemblyName { get; }
internal void CheckAssemblyName(DiagnosticBag diagnostics)
{
// We could only allow name == null if OutputKind is Module.
// However, it does no harm that we allow name == null for assemblies as well, so we don't enforce it.
if (this.AssemblyName != null)
{
MetadataHelpers.CheckAssemblyOrModuleName(this.AssemblyName, MessageProvider, MessageProvider.ERR_BadAssemblyName, diagnostics);
}
}
internal string MakeSourceAssemblySimpleName()
{
return AssemblyName ?? UnspecifiedModuleAssemblyName;
}
internal string MakeSourceModuleName()
{
return Options.ModuleName ??
(AssemblyName != null ? AssemblyName + Options.OutputKind.GetDefaultExtension() : UnspecifiedModuleAssemblyName);
}
/// <summary>
/// Creates a compilation with the specified assembly name.
/// </summary>
/// <param name="assemblyName">The new assembly name.</param>
/// <returns>A new compilation.</returns>
public Compilation WithAssemblyName(string? assemblyName)
{
return CommonWithAssemblyName(assemblyName);
}
protected abstract Compilation CommonWithAssemblyName(string? outputName);
#endregion
#region Options
/// <summary>
/// Gets the options the compilation was created with.
/// </summary>
public CompilationOptions Options { get { return CommonOptions; } }
protected abstract CompilationOptions CommonOptions { get; }
/// <summary>
/// Creates a new compilation with the specified compilation options.
/// </summary>
/// <param name="options">The new options.</param>
/// <returns>A new compilation.</returns>
public Compilation WithOptions(CompilationOptions options)
{
return CommonWithOptions(options);
}
protected abstract Compilation CommonWithOptions(CompilationOptions options);
#endregion
#region Submissions
// An index in the submission slot array. Allocated lazily in compilation phase based upon the slot index of the previous submission.
// Special values:
// -1 ... neither this nor previous submissions in the chain allocated a slot (the submissions don't contain code)
// -2 ... the slot of this submission hasn't been determined yet
// -3 ... this is not a submission compilation
private int _lazySubmissionSlotIndex;
private const int SubmissionSlotIndexNotApplicable = -3;
private const int SubmissionSlotIndexToBeAllocated = -2;
/// <summary>
/// True if the compilation represents an interactive submission.
/// </summary>
internal bool IsSubmission
{
get
{
return _lazySubmissionSlotIndex != SubmissionSlotIndexNotApplicable;
}
}
/// <summary>
/// The previous submission, if any, or null.
/// </summary>
private Compilation? PreviousSubmission
{
get
{
return ScriptCompilationInfo?.PreviousScriptCompilation;
}
}
/// <summary>
/// Gets or allocates a runtime submission slot index for this compilation.
/// </summary>
/// <returns>Non-negative integer if this is a submission and it or a previous submission contains code, negative integer otherwise.</returns>
internal int GetSubmissionSlotIndex()
{
if (_lazySubmissionSlotIndex == SubmissionSlotIndexToBeAllocated)
{
// TODO (tomat): remove recursion
int lastSlotIndex = ScriptCompilationInfo!.PreviousScriptCompilation?.GetSubmissionSlotIndex() ?? 0;
_lazySubmissionSlotIndex = HasCodeToEmit() ? lastSlotIndex + 1 : lastSlotIndex;
}
return _lazySubmissionSlotIndex;
}
// The type of interactive submission result requested by the host, or null if this compilation doesn't represent a submission.
//
// The type is resolved to a symbol when the Script's instance ctor symbol is constructed. The symbol needs to be resolved against
// the references of this compilation.
//
// Consider (tomat): As an alternative to Reflection Type we could hold onto any piece of information that lets us
// resolve the type symbol when needed.
/// <summary>
/// The type object that represents the type of submission result the host requested.
/// </summary>
internal Type? SubmissionReturnType => ScriptCompilationInfo?.ReturnTypeOpt;
internal static bool IsValidSubmissionReturnType(Type type)
{
return !(type == typeof(void) || type.IsByRef || type.GetTypeInfo().ContainsGenericParameters);
}
/// <summary>
/// The type of the globals object or null if not specified for this compilation.
/// </summary>
internal Type? HostObjectType => ScriptCompilationInfo?.GlobalsType;
internal static bool IsValidHostObjectType(Type type)
{
var info = type.GetTypeInfo();
return !(info.IsValueType || info.IsPointer || info.IsByRef || info.ContainsGenericParameters);
}
internal abstract bool HasSubmissionResult();
public Compilation WithScriptCompilationInfo(ScriptCompilationInfo? info) => CommonWithScriptCompilationInfo(info);
protected abstract Compilation CommonWithScriptCompilationInfo(ScriptCompilationInfo? info);
#endregion
#region Syntax Trees
/// <summary>
/// Gets the syntax trees (parsed from source code) that this compilation was created with.
/// </summary>
public IEnumerable<SyntaxTree> SyntaxTrees { get { return CommonSyntaxTrees; } }
protected abstract ImmutableArray<SyntaxTree> CommonSyntaxTrees { get; }
/// <summary>
/// Creates a new compilation with additional syntax trees.
/// </summary>
/// <param name="trees">The new syntax trees.</param>
/// <returns>A new compilation.</returns>
public Compilation AddSyntaxTrees(params SyntaxTree[] trees)
{
return CommonAddSyntaxTrees(trees);
}
/// <summary>
/// Creates a new compilation with additional syntax trees.
/// </summary>
/// <param name="trees">The new syntax trees.</param>
/// <returns>A new compilation.</returns>
public Compilation AddSyntaxTrees(IEnumerable<SyntaxTree> trees)
{
return CommonAddSyntaxTrees(trees);
}
protected abstract Compilation CommonAddSyntaxTrees(IEnumerable<SyntaxTree> trees);
/// <summary>
/// Creates a new compilation without the specified syntax trees. Preserves metadata info for use with trees
/// added later.
/// </summary>
/// <param name="trees">The new syntax trees.</param>
/// <returns>A new compilation.</returns>
public Compilation RemoveSyntaxTrees(params SyntaxTree[] trees)
{
return CommonRemoveSyntaxTrees(trees);
}
/// <summary>
/// Creates a new compilation without the specified syntax trees. Preserves metadata info for use with trees
/// added later.
/// </summary>
/// <param name="trees">The new syntax trees.</param>
/// <returns>A new compilation.</returns>
public Compilation RemoveSyntaxTrees(IEnumerable<SyntaxTree> trees)
{
return CommonRemoveSyntaxTrees(trees);
}
protected abstract Compilation CommonRemoveSyntaxTrees(IEnumerable<SyntaxTree> trees);
/// <summary>
/// Creates a new compilation without any syntax trees. Preserves metadata info for use with
/// trees added later.
/// </summary>
public Compilation RemoveAllSyntaxTrees()
{
return CommonRemoveAllSyntaxTrees();
}
protected abstract Compilation CommonRemoveAllSyntaxTrees();
/// <summary>
/// Creates a new compilation with an old syntax tree replaced with a new syntax tree.
/// Reuses metadata from old compilation object.
/// </summary>
/// <param name="newTree">The new tree.</param>
/// <param name="oldTree">The old tree.</param>
/// <returns>A new compilation.</returns>
public Compilation ReplaceSyntaxTree(SyntaxTree oldTree, SyntaxTree newTree)
{
return CommonReplaceSyntaxTree(oldTree, newTree);
}
protected abstract Compilation CommonReplaceSyntaxTree(SyntaxTree oldTree, SyntaxTree newTree);
/// <summary>
/// Returns true if this compilation contains the specified tree. False otherwise.
/// </summary>
/// <param name="syntaxTree">A syntax tree.</param>
public bool ContainsSyntaxTree(SyntaxTree syntaxTree)
{
return CommonContainsSyntaxTree(syntaxTree);
}
protected abstract bool CommonContainsSyntaxTree(SyntaxTree? syntaxTree);
/// <summary>
/// Optional semantic model provider for this compilation.
/// </summary>
internal SemanticModelProvider? SemanticModelProvider { get; }
/// <summary>
/// The event queue that this compilation was created with.
/// </summary>
internal AsyncQueue<CompilationEvent>? EventQueue { get; }
#endregion
#region References
internal static ImmutableArray<MetadataReference> ValidateReferences<T>(IEnumerable<MetadataReference>? references)
where T : CompilationReference
{
var result = references.AsImmutableOrEmpty();
for (int i = 0; i < result.Length; i++)
{
var reference = result[i];
if (reference == null)
{
throw new ArgumentNullException($"{nameof(references)}[{i}]");
}
var peReference = reference as PortableExecutableReference;
if (peReference == null && !(reference is T))
{
Debug.Assert(reference is UnresolvedMetadataReference || reference is CompilationReference);
throw new ArgumentException(string.Format(CodeAnalysisResources.ReferenceOfTypeIsInvalid1, reference.GetType()),
$"{nameof(references)}[{i}]");
}
}
return result;
}
internal CommonReferenceManager GetBoundReferenceManager()
{
return CommonGetBoundReferenceManager();
}
internal abstract CommonReferenceManager CommonGetBoundReferenceManager();
/// <summary>
/// Metadata references passed to the compilation constructor.
/// </summary>
public ImmutableArray<MetadataReference> ExternalReferences { get; }
/// <summary>
/// Unique metadata references specified via #r directive in the source code of this compilation.
/// </summary>
public abstract ImmutableArray<MetadataReference> DirectiveReferences { get; }
/// <summary>
/// All reference directives used in this compilation.
/// </summary>
internal abstract IEnumerable<ReferenceDirective> ReferenceDirectives { get; }
/// <summary>
/// Maps values of #r references to resolved metadata references.
/// </summary>
internal abstract IDictionary<(string path, string content), MetadataReference> ReferenceDirectiveMap { get; }
/// <summary>
/// All metadata references -- references passed to the compilation
/// constructor as well as references specified via #r directives.
/// </summary>
public IEnumerable<MetadataReference> References
{
get
{
foreach (var reference in ExternalReferences)
{
yield return reference;
}
foreach (var reference in DirectiveReferences)
{
yield return reference;
}
}
}
/// <summary>
/// Creates a metadata reference for this compilation.
/// </summary>
/// <param name="aliases">
/// Optional aliases that can be used to refer to the compilation root namespace via extern alias directive.
/// </param>
/// <param name="embedInteropTypes">
/// Embed the COM types from the reference so that the compiled
/// application no longer requires a primary interop assembly (PIA).
/// </param>
public abstract CompilationReference ToMetadataReference(ImmutableArray<string> aliases = default(ImmutableArray<string>), bool embedInteropTypes = false);
/// <summary>
/// Creates a new compilation with the specified references.
/// </summary>
/// <param name="newReferences">
/// The new references.
/// </param>
/// <returns>A new compilation.</returns>
public Compilation WithReferences(IEnumerable<MetadataReference> newReferences)
{
return this.CommonWithReferences(newReferences);
}
/// <summary>
/// Creates a new compilation with the specified references.
/// </summary>
/// <param name="newReferences">The new references.</param>
/// <returns>A new compilation.</returns>
public Compilation WithReferences(params MetadataReference[] newReferences)
{
return this.WithReferences((IEnumerable<MetadataReference>)newReferences);
}
/// <summary>
/// Creates a new compilation with the specified references.
/// </summary>
protected abstract Compilation CommonWithReferences(IEnumerable<MetadataReference> newReferences);
/// <summary>
/// Creates a new compilation with additional metadata references.
/// </summary>
/// <param name="references">The new references.</param>
/// <returns>A new compilation.</returns>
public Compilation AddReferences(params MetadataReference[] references)
{
return AddReferences((IEnumerable<MetadataReference>)references);
}
/// <summary>
/// Creates a new compilation with additional metadata references.
/// </summary>
/// <param name="references">The new references.</param>
/// <returns>A new compilation.</returns>
public Compilation AddReferences(IEnumerable<MetadataReference> references)
{
if (references == null)
{
throw new ArgumentNullException(nameof(references));
}
if (references.IsEmpty())
{
return this;
}
return CommonWithReferences(this.ExternalReferences.Union(references));
}
/// <summary>
/// Creates a new compilation without the specified metadata references.
/// </summary>
/// <param name="references">The new references.</param>
/// <returns>A new compilation.</returns>
public Compilation RemoveReferences(params MetadataReference[] references)
{
return RemoveReferences((IEnumerable<MetadataReference>)references);
}
/// <summary>
/// Creates a new compilation without the specified metadata references.
/// </summary>
/// <param name="references">The new references.</param>
/// <returns>A new compilation.</returns>
public Compilation RemoveReferences(IEnumerable<MetadataReference> references)
{
if (references == null)
{
throw new ArgumentNullException(nameof(references));
}
if (references.IsEmpty())
{
return this;
}
var refSet = new HashSet<MetadataReference>(this.ExternalReferences);
//EDMAURER if AddingReferences accepts duplicates, then a consumer supplying a list with
//duplicates to add will not know exactly which to remove. Let them supply a list with
//duplicates here.
foreach (var r in references.Distinct())
{
if (!refSet.Remove(r))
{
throw new ArgumentException(string.Format(CodeAnalysisResources.MetadataRefNotFoundToRemove1, r),
nameof(references));
}
}
return CommonWithReferences(refSet);
}
/// <summary>
/// Creates a new compilation without any metadata references.
/// </summary>
public Compilation RemoveAllReferences()
{
return CommonWithReferences(SpecializedCollections.EmptyEnumerable<MetadataReference>());
}
/// <summary>
/// Creates a new compilation with an old metadata reference replaced with a new metadata
/// reference.
/// </summary>
/// <param name="newReference">The new reference.</param>
/// <param name="oldReference">The old reference.</param>
/// <returns>A new compilation.</returns>
public Compilation ReplaceReference(MetadataReference oldReference, MetadataReference? newReference)
{
if (oldReference == null)
{
throw new ArgumentNullException(nameof(oldReference));
}
if (newReference == null)
{
return this.RemoveReferences(oldReference);
}
return this.RemoveReferences(oldReference).AddReferences(newReference);
}
/// <summary>
/// Gets the <see cref="IAssemblySymbol"/> or <see cref="IModuleSymbol"/> for a metadata reference used to create this
/// compilation.
/// </summary>
/// <param name="reference">The target reference.</param>
/// <returns>
/// Assembly or module symbol corresponding to the given reference or null if there is none.
/// </returns>
public ISymbol? GetAssemblyOrModuleSymbol(MetadataReference reference)
{
return CommonGetAssemblyOrModuleSymbol(reference);
}
protected abstract ISymbol? CommonGetAssemblyOrModuleSymbol(MetadataReference reference);
/// <summary>
/// Gets the <see cref="MetadataReference"/> that corresponds to the assembly symbol.
/// </summary>
/// <param name="assemblySymbol">The target symbol.</param>
public MetadataReference? GetMetadataReference(IAssemblySymbol assemblySymbol)
{
return CommonGetMetadataReference(assemblySymbol);
}
private protected abstract MetadataReference? CommonGetMetadataReference(IAssemblySymbol assemblySymbol);
/// <summary>
/// Assembly identities of all assemblies directly referenced by this compilation.
/// </summary>
/// <remarks>
/// Includes identities of references passed in the compilation constructor
/// as well as those specified via directives in source code.
/// </remarks>
public abstract IEnumerable<AssemblyIdentity> ReferencedAssemblyNames { get; }
#endregion
#region Symbols
/// <summary>
/// The <see cref="IAssemblySymbol"/> that represents the assembly being created.
/// </summary>
public IAssemblySymbol Assembly { get { return CommonAssembly; } }
protected abstract IAssemblySymbol CommonAssembly { get; }
/// <summary>
/// Gets the <see cref="IModuleSymbol"/> for the module being created by compiling all of
/// the source code.
/// </summary>
public IModuleSymbol SourceModule { get { return CommonSourceModule; } }
protected abstract IModuleSymbol CommonSourceModule { get; }
/// <summary>
/// The root namespace that contains all namespaces and types defined in source code or in
/// referenced metadata, merged into a single namespace hierarchy.
/// </summary>
public INamespaceSymbol GlobalNamespace { get { return CommonGlobalNamespace; } }
protected abstract INamespaceSymbol CommonGlobalNamespace { get; }
/// <summary>
/// Gets the corresponding compilation namespace for the specified module or assembly namespace.
/// </summary>
public INamespaceSymbol? GetCompilationNamespace(INamespaceSymbol namespaceSymbol)
{
return CommonGetCompilationNamespace(namespaceSymbol);
}
protected abstract INamespaceSymbol? CommonGetCompilationNamespace(INamespaceSymbol namespaceSymbol);
internal abstract CommonAnonymousTypeManager CommonAnonymousTypeManager { get; }
/// <summary>
/// Returns the Main method that will serves as the entry point of the assembly, if it is
/// executable (and not a script).
/// </summary>
public IMethodSymbol? GetEntryPoint(CancellationToken cancellationToken)
{
return CommonGetEntryPoint(cancellationToken);
}
protected abstract IMethodSymbol? CommonGetEntryPoint(CancellationToken cancellationToken);
/// <summary>
/// Get the symbol for the predefined type from the Cor Library referenced by this
/// compilation.
/// </summary>
public INamedTypeSymbol GetSpecialType(SpecialType specialType)
{
return (INamedTypeSymbol)CommonGetSpecialType(specialType).GetITypeSymbol();
}
/// <summary>
/// Get the symbol for the predefined type member from the COR Library referenced by this compilation.
/// </summary>
internal abstract ISymbolInternal CommonGetSpecialTypeMember(SpecialMember specialMember);
/// <summary>
/// Returns true if the type is System.Type.
/// </summary>
internal abstract bool IsSystemTypeReference(ITypeSymbolInternal type);
private protected abstract INamedTypeSymbolInternal CommonGetSpecialType(SpecialType specialType);
/// <summary>
/// Lookup member declaration in well known type used by this Compilation.
/// </summary>
internal abstract ISymbolInternal? CommonGetWellKnownTypeMember(WellKnownMember member);
/// <summary>
/// Lookup well-known type used by this Compilation.
/// </summary>
internal abstract ITypeSymbolInternal CommonGetWellKnownType(WellKnownType wellknownType);
/// <summary>
/// Returns true if the specified type is equal to or derives from System.Attribute well-known type.
/// </summary>
internal abstract bool IsAttributeType(ITypeSymbol type);
/// <summary>
/// The INamedTypeSymbol for the .NET System.Object type, which could have a TypeKind of
/// Error if there was no COR Library in this Compilation.
/// </summary>
public INamedTypeSymbol ObjectType { get { return CommonObjectType; } }
protected abstract INamedTypeSymbol CommonObjectType { get; }
/// <summary>
/// The TypeSymbol for the type 'dynamic' in this Compilation.
/// </summary>
/// <exception cref="NotSupportedException">If the compilation is a VisualBasic compilation.</exception>
public ITypeSymbol DynamicType { get { return CommonDynamicType; } }
protected abstract ITypeSymbol CommonDynamicType { get; }
/// <summary>
/// A symbol representing the script globals type.
/// </summary>
internal ITypeSymbol? ScriptGlobalsType => CommonScriptGlobalsType;
protected abstract ITypeSymbol? CommonScriptGlobalsType { get; }
/// <summary>
/// A symbol representing the implicit Script class. This is null if the class is not
/// defined in the compilation.
/// </summary>
public INamedTypeSymbol? ScriptClass { get { return CommonScriptClass; } }
protected abstract INamedTypeSymbol? CommonScriptClass { get; }
/// <summary>
/// Resolves a symbol that represents script container (Script class). Uses the
/// full name of the container class stored in <see cref="CompilationOptions.ScriptClassName"/> to find the symbol.
/// </summary>
/// <returns>The Script class symbol or null if it is not defined.</returns>
protected INamedTypeSymbol? CommonBindScriptClass()
{
string scriptClassName = this.Options.ScriptClassName ?? "";
string[] parts = scriptClassName.Split('.');
INamespaceSymbol container = this.SourceModule.GlobalNamespace;
for (int i = 0; i < parts.Length - 1; i++)
{
INamespaceSymbol? next = container.GetNestedNamespace(parts[i]);
if (next == null)
{
AssertNoScriptTrees();
return null;
}
container = next;
}
foreach (INamedTypeSymbol candidate in container.GetTypeMembers(parts[parts.Length - 1]))
{
if (candidate.IsScriptClass)
{
return candidate;
}
}
AssertNoScriptTrees();
return null;
}
[Conditional("DEBUG")]
private void AssertNoScriptTrees()
{
foreach (var tree in this.CommonSyntaxTrees)
{
Debug.Assert(tree.Options.Kind != SourceCodeKind.Script);
}
}
/// <summary>
/// Returns a new ArrayTypeSymbol representing an array type tied to the base types of the
/// COR Library in this Compilation.
/// </summary>
public IArrayTypeSymbol CreateArrayTypeSymbol(ITypeSymbol elementType, int rank = 1, NullableAnnotation elementNullableAnnotation = NullableAnnotation.None)
{
return CommonCreateArrayTypeSymbol(elementType, rank, elementNullableAnnotation);
}
/// <summary>
/// Returns a new ArrayTypeSymbol representing an array type tied to the base types of the
/// COR Library in this Compilation.
/// </summary>
/// <remarks>This overload is for backwards compatibility. Do not remove.</remarks>
public IArrayTypeSymbol CreateArrayTypeSymbol(ITypeSymbol elementType, int rank)
{
return CreateArrayTypeSymbol(elementType, rank, elementNullableAnnotation: default);
}
protected abstract IArrayTypeSymbol CommonCreateArrayTypeSymbol(ITypeSymbol elementType, int rank, NullableAnnotation elementNullableAnnotation);
/// <summary>
/// Returns a new IPointerTypeSymbol representing a pointer type tied to a type in this
/// Compilation.
/// </summary>
/// <exception cref="NotSupportedException">If the compilation is a VisualBasic compilation.</exception>
public IPointerTypeSymbol CreatePointerTypeSymbol(ITypeSymbol pointedAtType)
{
return CommonCreatePointerTypeSymbol(pointedAtType);
}
protected abstract IPointerTypeSymbol CommonCreatePointerTypeSymbol(ITypeSymbol elementType);
/// <summary>
/// Returns a new IFunctionPointerTypeSymbol representing a function pointer type tied to types in this
/// Compilation.
/// </summary>
/// <exception cref="NotSupportedException">If the compilation is a VisualBasic compilation.</exception>
/// <exception cref="ArgumentException">
/// If:
/// * <see cref="RefKind.Out"/> is passed as the returnRefKind.
/// * parameterTypes and parameterRefKinds do not have the same length.
/// </exception>
/// <exception cref="ArgumentNullException">
/// If returnType is <see langword="null"/>, or if parameterTypes or parameterRefKinds are default,
/// or if any of the types in parameterTypes are null.</exception>
public IFunctionPointerTypeSymbol CreateFunctionPointerTypeSymbol(
ITypeSymbol returnType,
RefKind returnRefKind,
ImmutableArray<ITypeSymbol> parameterTypes,
ImmutableArray<RefKind> parameterRefKinds,
SignatureCallingConvention callingConvention = SignatureCallingConvention.Default,
ImmutableArray<INamedTypeSymbol> callingConventionTypes = default)
{
return CommonCreateFunctionPointerTypeSymbol(returnType, returnRefKind, parameterTypes, parameterRefKinds, callingConvention, callingConventionTypes);
}
protected abstract IFunctionPointerTypeSymbol CommonCreateFunctionPointerTypeSymbol(
ITypeSymbol returnType,
RefKind returnRefKind,
ImmutableArray<ITypeSymbol> parameterTypes,
ImmutableArray<RefKind> parameterRefKinds,
SignatureCallingConvention callingConvention,
ImmutableArray<INamedTypeSymbol> callingConventionTypes);
/// <summary>
/// Returns a new INamedTypeSymbol representing a native integer.
/// </summary>
/// <exception cref="NotSupportedException">If the compilation is a VisualBasic compilation.</exception>
public INamedTypeSymbol CreateNativeIntegerTypeSymbol(bool signed)
{
return CommonCreateNativeIntegerTypeSymbol(signed);
}
protected abstract INamedTypeSymbol CommonCreateNativeIntegerTypeSymbol(bool signed);
// PERF: ETW Traces show that analyzers may use this method frequently, often requesting
// the same symbol over and over again. XUnit analyzers, in particular, were consuming almost
// 1% of CPU time when building Roslyn itself. This is an extremely simple cache that evicts on
// hash code conflicts, but seems to do the trick. The size is mostly arbitrary. My guess
// is that there are maybe a couple dozen analyzers in the solution and each one has
// ~0-2 unique well-known types, and the chance of hash collision is very low.
private readonly ConcurrentCache<string, INamedTypeSymbol?> _getTypeCache =
new ConcurrentCache<string, INamedTypeSymbol?>(50, ReferenceEqualityComparer.Instance);
/// <summary>
/// Gets the type within the compilation's assembly and all referenced assemblies (other than
/// those that can only be referenced via an extern alias) using its canonical CLR metadata name.
/// </summary>
/// <returns>Null if the type can't be found.</returns>
/// <remarks>
/// Since VB does not have the concept of extern aliases, it considers all referenced assemblies.
/// </remarks>
public INamedTypeSymbol? GetTypeByMetadataName(string fullyQualifiedMetadataName)
{
if (!_getTypeCache.TryGetValue(fullyQualifiedMetadataName, out INamedTypeSymbol? val))
{
val = CommonGetTypeByMetadataName(fullyQualifiedMetadataName);
// Ignore if someone added the same value before us
_ = _getTypeCache.TryAdd(fullyQualifiedMetadataName, val);
}
return val;
}
protected abstract INamedTypeSymbol? CommonGetTypeByMetadataName(string metadataName);
#pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters
/// <summary>
/// Returns a new INamedTypeSymbol with the given element types and
/// (optional) element names, locations, and nullable annotations.
/// </summary>
public INamedTypeSymbol CreateTupleTypeSymbol(
ImmutableArray<ITypeSymbol> elementTypes,
ImmutableArray<string?> elementNames = default,
ImmutableArray<Location?> elementLocations = default,
ImmutableArray<NullableAnnotation> elementNullableAnnotations = default)
{
if (elementTypes.IsDefault)
{
throw new ArgumentNullException(nameof(elementTypes));
}
int n = elementTypes.Length;
if (elementTypes.Length <= 1)
{
throw new ArgumentException(CodeAnalysisResources.TuplesNeedAtLeastTwoElements, nameof(elementNames));
}
elementNames = CheckTupleElementNames(n, elementNames);
CheckTupleElementLocations(n, elementLocations);
CheckTupleElementNullableAnnotations(n, elementNullableAnnotations);
for (int i = 0; i < n; i++)
{
if (elementTypes[i] == null)
{
throw new ArgumentNullException($"{nameof(elementTypes)}[{i}]");
}
if (!elementLocations.IsDefault && elementLocations[i] == null)
{
throw new ArgumentNullException($"{nameof(elementLocations)}[{i}]");
}
}
return CommonCreateTupleTypeSymbol(elementTypes, elementNames, elementLocations, elementNullableAnnotations);
}
#pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters
/// <summary>
/// Returns a new INamedTypeSymbol with the given element types, names, and locations.
/// </summary>
/// <remarks>This overload is for backwards compatibility. Do not remove.</remarks>
public INamedTypeSymbol CreateTupleTypeSymbol(
ImmutableArray<ITypeSymbol> elementTypes,
ImmutableArray<string?> elementNames,
ImmutableArray<Location?> elementLocations)
{
return CreateTupleTypeSymbol(elementTypes, elementNames, elementLocations, elementNullableAnnotations: default);
}
protected static void CheckTupleElementNullableAnnotations(
int cardinality,
ImmutableArray<NullableAnnotation> elementNullableAnnotations)
{
if (!elementNullableAnnotations.IsDefault)
{
if (elementNullableAnnotations.Length != cardinality)
{
throw new ArgumentException(CodeAnalysisResources.TupleElementNullableAnnotationCountMismatch, nameof(elementNullableAnnotations));
}
}
}
/// <summary>
/// Check that if any names are provided, and their number matches the expected cardinality.
/// Returns a normalized version of the element names (empty array if all the names are null).
/// </summary>
protected static ImmutableArray<string?> CheckTupleElementNames(int cardinality, ImmutableArray<string?> elementNames)
{
if (!elementNames.IsDefault)
{
if (elementNames.Length != cardinality)
{
throw new ArgumentException(CodeAnalysisResources.TupleElementNameCountMismatch, nameof(elementNames));
}
for (int i = 0; i < elementNames.Length; i++)
{
if (elementNames[i] == "")
{
throw new ArgumentException(CodeAnalysisResources.TupleElementNameEmpty, $"{nameof(elementNames)}[{i}]");
}
}
if (elementNames.All(n => n == null))
{
return default;
}
}
return elementNames;
}
protected static void CheckTupleElementLocations(
int cardinality,
ImmutableArray<Location?> elementLocations)
{
if (!elementLocations.IsDefault)
{
if (elementLocations.Length != cardinality)
{
throw new ArgumentException(CodeAnalysisResources.TupleElementLocationCountMismatch, nameof(elementLocations));
}
}
}
protected abstract INamedTypeSymbol CommonCreateTupleTypeSymbol(
ImmutableArray<ITypeSymbol> elementTypes,
ImmutableArray<string?> elementNames,
ImmutableArray<Location?> elementLocations,
ImmutableArray<NullableAnnotation> elementNullableAnnotations);
#pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters
/// <summary>
/// Returns a new INamedTypeSymbol with the given underlying type and
/// (optional) element names, locations, and nullable annotations.
/// The underlying type needs to be tuple-compatible.
/// </summary>
public INamedTypeSymbol CreateTupleTypeSymbol(
INamedTypeSymbol underlyingType,
ImmutableArray<string?> elementNames = default,
ImmutableArray<Location?> elementLocations = default,
ImmutableArray<NullableAnnotation> elementNullableAnnotations = default)
{
if ((object)underlyingType == null)
{
throw new ArgumentNullException(nameof(underlyingType));
}
return CommonCreateTupleTypeSymbol(underlyingType, elementNames, elementLocations, elementNullableAnnotations);
}
#pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters
/// <summary>
/// Returns a new INamedTypeSymbol with the given underlying type and element names and locations.
/// The underlying type needs to be tuple-compatible.
/// </summary>
/// <remarks>This overload is for backwards compatibility. Do not remove.</remarks>
public INamedTypeSymbol CreateTupleTypeSymbol(
INamedTypeSymbol underlyingType,
ImmutableArray<string?> elementNames,
ImmutableArray<Location?> elementLocations)
{
return CreateTupleTypeSymbol(underlyingType, elementNames, elementLocations, elementNullableAnnotations: default);
}
protected abstract INamedTypeSymbol CommonCreateTupleTypeSymbol(
INamedTypeSymbol underlyingType,
ImmutableArray<string?> elementNames,
ImmutableArray<Location?> elementLocations,
ImmutableArray<NullableAnnotation> elementNullableAnnotations);
/// <summary>
/// Returns a new anonymous type symbol with the given member types, names, source locations, and nullable annotations.
/// Anonymous type members will be readonly by default. Writable properties are
/// supported in VB and can be created by passing in <see langword="false"/> in the
/// appropriate locations in <paramref name="memberIsReadOnly"/>.
/// </summary>
public INamedTypeSymbol CreateAnonymousTypeSymbol(
ImmutableArray<ITypeSymbol> memberTypes,
ImmutableArray<string> memberNames,
ImmutableArray<bool> memberIsReadOnly = default,
ImmutableArray<Location> memberLocations = default,
ImmutableArray<NullableAnnotation> memberNullableAnnotations = default)
{
if (memberTypes.IsDefault)
{
throw new ArgumentNullException(nameof(memberTypes));
}
if (memberNames.IsDefault)
{
throw new ArgumentNullException(nameof(memberNames));
}
if (memberTypes.Length != memberNames.Length)
{
throw new ArgumentException(string.Format(CodeAnalysisResources.AnonymousTypeMemberAndNamesCountMismatch2,
nameof(memberTypes), nameof(memberNames)));
}
if (!memberLocations.IsDefault && memberLocations.Length != memberTypes.Length)
{
throw new ArgumentException(string.Format(CodeAnalysisResources.AnonymousTypeArgumentCountMismatch2,
nameof(memberLocations), nameof(memberNames)));
}
if (!memberIsReadOnly.IsDefault && memberIsReadOnly.Length != memberTypes.Length)
{
throw new ArgumentException(string.Format(CodeAnalysisResources.AnonymousTypeArgumentCountMismatch2,
nameof(memberIsReadOnly), nameof(memberNames)));
}
if (!memberNullableAnnotations.IsDefault && memberNullableAnnotations.Length != memberTypes.Length)
{
throw new ArgumentException(string.Format(CodeAnalysisResources.AnonymousTypeArgumentCountMismatch2,
nameof(memberNullableAnnotations), nameof(memberNames)));
}
for (int i = 0, n = memberTypes.Length; i < n; i++)
{
if (memberTypes[i] == null)
{
throw new ArgumentNullException($"{nameof(memberTypes)}[{i}]");
}
if (memberNames[i] == null)
{
throw new ArgumentNullException($"{nameof(memberNames)}[{i}]");
}
if (!memberLocations.IsDefault && memberLocations[i] == null)
{
throw new ArgumentNullException($"{nameof(memberLocations)}[{i}]");
}
}
return CommonCreateAnonymousTypeSymbol(memberTypes, memberNames, memberLocations, memberIsReadOnly, memberNullableAnnotations);
}
/// <summary>
/// Returns a new anonymous type symbol with the given member types, names, and source locations.
/// Anonymous type members will be readonly by default. Writable properties are
/// supported in VB and can be created by passing in <see langword="false"/> in the
/// appropriate locations in <paramref name="memberIsReadOnly"/>.
/// </summary>
/// <remarks>This overload is for backwards compatibility. Do not remove.</remarks>
public INamedTypeSymbol CreateAnonymousTypeSymbol(
ImmutableArray<ITypeSymbol> memberTypes,
ImmutableArray<string> memberNames,
ImmutableArray<bool> memberIsReadOnly,
ImmutableArray<Location> memberLocations)
{
return CreateAnonymousTypeSymbol(memberTypes, memberNames, memberIsReadOnly, memberLocations, memberNullableAnnotations: default);
}
protected abstract INamedTypeSymbol CommonCreateAnonymousTypeSymbol(
ImmutableArray<ITypeSymbol> memberTypes,
ImmutableArray<string> memberNames,
ImmutableArray<Location> memberLocations,
ImmutableArray<bool> memberIsReadOnly,
ImmutableArray<NullableAnnotation> memberNullableAnnotations);
/// <summary>
/// Classifies a conversion from <paramref name="source"/> to <paramref name="destination"/> according
/// to this compilation's programming language.
/// </summary>
/// <param name="source">Source type of value to be converted</param>
/// <param name="destination">Destination type of value to be converted</param>
/// <returns>A <see cref="CommonConversion"/> that classifies the conversion from the
/// <paramref name="source"/> type to the <paramref name="destination"/> type.</returns>
public abstract CommonConversion ClassifyCommonConversion(ITypeSymbol source, ITypeSymbol destination);
/// <summary>
/// Returns true if there is an implicit (C#) or widening (VB) conversion from
/// <paramref name="fromType"/> to <paramref name="toType"/>. Returns false if
/// either <paramref name="fromType"/> or <paramref name="toType"/> is null, or
/// if no such conversion exists.
/// </summary>
public bool HasImplicitConversion(ITypeSymbol? fromType, ITypeSymbol? toType)
=> fromType != null && toType != null && this.ClassifyCommonConversion(fromType, toType).IsImplicit;
/// <summary>
/// Checks if <paramref name="symbol"/> is accessible from within <paramref name="within"/>. An optional qualifier of type
/// <paramref name="throughType"/> is used to resolve protected access for instance members. All symbols are
/// required to be from this compilation or some assembly referenced (<see cref="References"/>) by this
/// compilation. <paramref name="within"/> is required to be an <see cref="INamedTypeSymbol"/> or <see cref="IAssemblySymbol"/>.
/// </summary>
/// <remarks>
/// <para>Submissions can reference symbols from previous submissions and their referenced assemblies, even
/// though those references are missing from <see cref="References"/>.
/// See https://github.com/dotnet/roslyn/issues/27356.
/// This implementation works around that by permitting symbols from previous submissions as well.</para>
/// <para>It is advised to avoid the use of this API within the compilers, as the compilers have additional
/// requirements for access checking that are not satisfied by this implementation, including the
/// avoidance of infinite recursion that could result from the use of the ISymbol APIs here, the detection
/// of use-site diagnostics, and additional returned details (from the compiler's internal APIs) that are
/// helpful for more precisely diagnosing reasons for accessibility failure.</para>
/// </remarks>
public bool IsSymbolAccessibleWithin(
ISymbol symbol,
ISymbol within,
ITypeSymbol? throughType = null)
{
if (symbol is null)
{
throw new ArgumentNullException(nameof(symbol));
}
if (within is null)
{
throw new ArgumentNullException(nameof(within));
}
if (!(within is INamedTypeSymbol || within is IAssemblySymbol))
{
throw new ArgumentException(string.Format(CodeAnalysisResources.IsSymbolAccessibleBadWithin, nameof(within)), nameof(within));
}
checkInCompilationReferences(symbol, nameof(symbol));
checkInCompilationReferences(within, nameof(within));
if (throughType is object)
{
checkInCompilationReferences(throughType, nameof(throughType));
}
return IsSymbolAccessibleWithinCore(symbol, within, throughType);
void checkInCompilationReferences(ISymbol s, string parameterName)
{
if (!isContainingAssemblyInReferences(s))
{
throw new ArgumentException(string.Format(CodeAnalysisResources.IsSymbolAccessibleWrongAssembly, parameterName), parameterName);
}
}
bool assemblyIsInReferences(IAssemblySymbol a)
{
if (assemblyIsInCompilationReferences(a, this))
{
return true;
}
if (this.IsSubmission)
{
// Submissions can reference symbols from previous submissions and their referenced assemblies, even
// though those references are missing from this.References. We work around that by digging in
// to find references of previous submissions. See https://github.com/dotnet/roslyn/issues/27356
for (Compilation? c = this.PreviousSubmission; c != null; c = c.PreviousSubmission)
{
if (assemblyIsInCompilationReferences(a, c))
{
return true;
}
}
}
return false;
}
bool assemblyIsInCompilationReferences(IAssemblySymbol a, Compilation compilation)
{
if (a.Equals(compilation.Assembly))
{
return true;
}
foreach (var reference in compilation.References)
{
if (a.Equals(compilation.GetAssemblyOrModuleSymbol(reference)))
{
return true;
}
}
return false;
}
bool isContainingAssemblyInReferences(ISymbol s)
{
while (true)
{
switch (s.Kind)
{
case SymbolKind.Assembly:
return assemblyIsInReferences((IAssemblySymbol)s);
case SymbolKind.PointerType:
s = ((IPointerTypeSymbol)s).PointedAtType;
continue;
case SymbolKind.ArrayType:
s = ((IArrayTypeSymbol)s).ElementType;
continue;
case SymbolKind.Alias:
s = ((IAliasSymbol)s).Target;
continue;
case SymbolKind.Discard:
s = ((IDiscardSymbol)s).Type;
continue;
case SymbolKind.FunctionPointerType:
var funcPtr = (IFunctionPointerTypeSymbol)s;
if (!isContainingAssemblyInReferences(funcPtr.Signature.ReturnType))
{
return false;
}
foreach (var param in funcPtr.Signature.Parameters)
{
if (!isContainingAssemblyInReferences(param.Type))
{
return false;
}
}
return true;
case SymbolKind.DynamicType:
case SymbolKind.ErrorType:
case SymbolKind.Preprocessing:
case SymbolKind.Namespace:
// these symbols are not restricted in where they can be accessed, so unless they report
// a containing assembly, we treat them as in the current assembly for access purposes
return assemblyIsInReferences(s.ContainingAssembly ?? this.Assembly);
default:
return assemblyIsInReferences(s.ContainingAssembly);
}
}
}
}
private protected abstract bool IsSymbolAccessibleWithinCore(
ISymbol symbol,
ISymbol within,
ITypeSymbol? throughType);
internal abstract IConvertibleConversion ClassifyConvertibleConversion(IOperation source, ITypeSymbol destination, out ConstantValue? constantValue);
#endregion
#region Diagnostics
internal const CompilationStage DefaultDiagnosticsStage = CompilationStage.Compile;
/// <summary>
/// Gets the diagnostics produced during the parsing stage.
/// </summary>
public abstract ImmutableArray<Diagnostic> GetParseDiagnostics(CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the diagnostics produced during symbol declaration.
/// </summary>
public abstract ImmutableArray<Diagnostic> GetDeclarationDiagnostics(CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the diagnostics produced during the analysis of method bodies and field initializers.
/// </summary>
public abstract ImmutableArray<Diagnostic> GetMethodBodyDiagnostics(CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the diagnostics for the compilation, including syntax, declaration, and
/// binding. Does not include any diagnostics that might be produced during emit, see
/// <see cref="EmitResult"/>.
/// </summary>
public abstract ImmutableArray<Diagnostic> GetDiagnostics(CancellationToken cancellationToken = default(CancellationToken));
internal abstract void GetDiagnostics(CompilationStage stage, bool includeEarlierStages, DiagnosticBag diagnostics, CancellationToken cancellationToken = default);
/// <summary>
/// Unique metadata assembly references that are considered to be used by this compilation.
/// For example, if a type declared in a referenced assembly is referenced in source code
/// within this compilation, the reference is considered to be used. Etc.
/// The returned set is a subset of references returned by <see cref="References"/> API.
/// The result is undefined if the compilation contains errors.
/// </summary>
public abstract ImmutableArray<MetadataReference> GetUsedAssemblyReferences(CancellationToken cancellationToken = default(CancellationToken));
internal void EnsureCompilationEventQueueCompleted()
{
RoslynDebug.Assert(EventQueue != null);
lock (EventQueue)
{
if (!EventQueue.IsCompleted)
{
CompleteCompilationEventQueue_NoLock();
}
}
}
internal void CompleteCompilationEventQueue_NoLock()
{
RoslynDebug.Assert(EventQueue != null);
// Signal the end of compilation.
EventQueue.TryEnqueue(new CompilationCompletedEvent(this));
EventQueue.PromiseNotToEnqueue();
EventQueue.TryComplete();
}
internal abstract CommonMessageProvider MessageProvider { get; }
/// <summary>
/// Filter out warnings based on the compiler options (/nowarn, /warn and /warnaserror) and the pragma warning directives.
/// 'incoming' is freed.
/// </summary>
/// <param name="accumulator">Bag to which filtered diagnostics will be added.</param>
/// <param name="incoming">Diagnostics to be filtered.</param>
/// <returns>True if there are no unsuppressed errors (i.e., no errors which fail compilation).</returns>
internal bool FilterAndAppendAndFreeDiagnostics(DiagnosticBag accumulator, [DisallowNull] ref DiagnosticBag? incoming, CancellationToken cancellationToken)
{
RoslynDebug.Assert(incoming is object);
bool result = FilterAndAppendDiagnostics(accumulator, incoming.AsEnumerableWithoutResolution(), exclude: null, cancellationToken);
incoming.Free();
incoming = null;
return result;
}
/// <summary>
/// Filter out warnings based on the compiler options (/nowarn, /warn and /warnaserror) and the pragma warning directives.
/// </summary>
/// <returns>True if there are no unsuppressed errors (i.e., no errors which fail compilation).</returns>
internal bool FilterAndAppendDiagnostics(DiagnosticBag accumulator, IEnumerable<Diagnostic> incoming, HashSet<int>? exclude, CancellationToken cancellationToken)
{
bool hasError = false;
bool reportSuppressedDiagnostics = Options.ReportSuppressedDiagnostics;
foreach (Diagnostic d in incoming)
{
if (exclude?.Contains(d.Code) == true)
{
continue;
}
var filtered = Options.FilterDiagnostic(d, cancellationToken);
if (filtered == null ||
(!reportSuppressedDiagnostics && filtered.IsSuppressed))
{
continue;
}
else if (filtered.IsUnsuppressableError())
{
hasError = true;
}
accumulator.Add(filtered);
}
return !hasError;
}
#endregion
#region Resources
/// <summary>
/// Create a stream filled with default win32 resources.
/// </summary>
public Stream CreateDefaultWin32Resources(bool versionResource, bool noManifest, Stream? manifestContents, Stream? iconInIcoFormat)
{
//Win32 resource encodings use a lot of 16bit values. Do all of the math checked with the
//expectation that integer types are well-chosen with size in mind.
checked
{
var result = new MemoryStream(1024);
//start with a null resource just as rc.exe does
AppendNullResource(result);
if (versionResource)
AppendDefaultVersionResource(result);
if (!noManifest)
{
if (this.Options.OutputKind.IsApplication())
{
// Applications use a default manifest if one is not specified.
if (manifestContents == null)
{
manifestContents = typeof(Compilation).GetTypeInfo().Assembly.GetManifestResourceStream("Microsoft.CodeAnalysis.Resources.default.win32manifest");
}
}
else
{
// Modules never have manifests, even if one is specified.
//Debug.Assert(!this.Options.OutputKind.IsNetModule() || manifestContents == null);
}
if (manifestContents != null)
{
Win32ResourceConversions.AppendManifestToResourceStream(result, manifestContents, !this.Options.OutputKind.IsApplication());
}
}
if (iconInIcoFormat != null)
{
Win32ResourceConversions.AppendIconToResourceStream(result, iconInIcoFormat);
}
result.Position = 0;
return result;
}
}
internal static void AppendNullResource(Stream resourceStream)
{
var writer = new BinaryWriter(resourceStream);
writer.Write((UInt32)0);
writer.Write((UInt32)0x20);
writer.Write((UInt16)0xFFFF);
writer.Write((UInt16)0);
writer.Write((UInt16)0xFFFF);
writer.Write((UInt16)0);
writer.Write((UInt32)0); //DataVersion
writer.Write((UInt16)0); //MemoryFlags
writer.Write((UInt16)0); //LanguageId
writer.Write((UInt32)0); //Version
writer.Write((UInt32)0); //Characteristics
}
protected abstract void AppendDefaultVersionResource(Stream resourceStream);
internal enum Win32ResourceForm : byte
{
UNKNOWN,
COFF,
RES
}
internal static Win32ResourceForm DetectWin32ResourceForm(Stream win32Resources)
{
var reader = new BinaryReader(win32Resources, Encoding.Unicode);
var initialPosition = win32Resources.Position;
var initial32Bits = reader.ReadUInt32();
win32Resources.Position = initialPosition;
//RC.EXE output starts with a resource that contains no data.
if (initial32Bits == 0)
return Win32ResourceForm.RES;
else if ((initial32Bits & 0xFFFF0000) != 0 || (initial32Bits & 0x0000FFFF) != 0xFFFF)
// See CLiteWeightStgdbRW::FindObjMetaData in peparse.cpp
return Win32ResourceForm.COFF;
else
return Win32ResourceForm.UNKNOWN;
}
internal Cci.ResourceSection? MakeWin32ResourcesFromCOFF(Stream? win32Resources, DiagnosticBag diagnostics)
{
if (win32Resources == null)
{
return null;
}
Cci.ResourceSection resources;
try
{
resources = COFFResourceReader.ReadWin32ResourcesFromCOFF(win32Resources);
}
catch (BadImageFormatException ex)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, Location.None, ex.Message));
return null;
}
catch (IOException ex)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, Location.None, ex.Message));
return null;
}
catch (ResourceException ex)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, Location.None, ex.Message));
return null;
}
return resources;
}
internal List<Win32Resource>? MakeWin32ResourceList(Stream? win32Resources, DiagnosticBag diagnostics)
{
if (win32Resources == null)
{
return null;
}
List<RESOURCE> resources;
try
{
resources = CvtResFile.ReadResFile(win32Resources);
}
catch (ResourceException ex)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, Location.None, ex.Message));
return null;
}
if (resources == null)
{
return null;
}
var resourceList = new List<Win32Resource>();
foreach (var r in resources)
{
var result = new Win32Resource(
data: r.data,
codePage: 0,
languageId: r.LanguageId,
//EDMAURER converting to int from ushort.
//Go to short first to avoid sign extension.
id: unchecked((short)r.pstringName!.Ordinal),
name: r.pstringName.theString,
typeId: unchecked((short)r.pstringType!.Ordinal),
typeName: r.pstringType.theString
);
resourceList.Add(result);
}
return resourceList;
}
internal void SetupWin32Resources(CommonPEModuleBuilder moduleBeingBuilt, Stream? win32Resources, bool useRawWin32Resources, DiagnosticBag diagnostics)
{
if (win32Resources == null)
return;
if (useRawWin32Resources)
{
moduleBeingBuilt.RawWin32Resources = win32Resources;
return;
}
Win32ResourceForm resourceForm;
try
{
resourceForm = DetectWin32ResourceForm(win32Resources);
}
catch (EndOfStreamException)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, NoLocation.Singleton, CodeAnalysisResources.UnrecognizedResourceFileFormat));
return;
}
catch (Exception ex)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, NoLocation.Singleton, ex.Message));
return;
}
switch (resourceForm)
{
case Win32ResourceForm.COFF:
moduleBeingBuilt.Win32ResourceSection = MakeWin32ResourcesFromCOFF(win32Resources, diagnostics);
break;
case Win32ResourceForm.RES:
moduleBeingBuilt.Win32Resources = MakeWin32ResourceList(win32Resources, diagnostics);
break;
default:
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, NoLocation.Singleton, CodeAnalysisResources.UnrecognizedResourceFileFormat));
break;
}
}
internal void ReportManifestResourceDuplicates(
IEnumerable<ResourceDescription>? manifestResources,
IEnumerable<string> addedModuleNames,
IEnumerable<string> addedModuleResourceNames,
DiagnosticBag diagnostics)
{
if (Options.OutputKind == OutputKind.NetModule && !(manifestResources != null && manifestResources.Any()))
{
return;
}
var uniqueResourceNames = new HashSet<string>();
if (manifestResources != null && manifestResources.Any())
{
var uniqueFileNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var resource in manifestResources)
{
if (!uniqueResourceNames.Add(resource.ResourceName))
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceNotUnique, Location.None, resource.ResourceName));
}
// file name could be null if resource is embedded
var fileName = resource.FileName;
if (fileName != null && !uniqueFileNames.Add(fileName))
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceFileNameNotUnique, Location.None, fileName));
}
}
foreach (var fileName in addedModuleNames)
{
if (!uniqueFileNames.Add(fileName))
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceFileNameNotUnique, Location.None, fileName));
}
}
}
if (Options.OutputKind != OutputKind.NetModule)
{
foreach (string name in addedModuleResourceNames)
{
if (!uniqueResourceNames.Add(name))
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceNotUnique, Location.None, name));
}
}
}
}
#endregion
#region Emit
/// <summary>
/// There are two ways to sign PE files
/// 1. By directly signing the <see cref="PEBuilder"/>
/// 2. Write the unsigned PE to disk and use CLR COM APIs to sign.
/// The preferred method is #1 as it's more efficient and more resilient (no reliance on %TEMP%). But
/// we must continue to support #2 as it's the only way to do the following:
/// - Access private keys stored in a key container
/// - Do proper counter signature verification for AssemblySignatureKey attributes
/// </summary>
internal bool SignUsingBuilder =>
string.IsNullOrEmpty(StrongNameKeys.KeyContainer) &&
!StrongNameKeys.HasCounterSignature &&
!_features.ContainsKey("UseLegacyStrongNameProvider");
/// <summary>
/// Constructs the module serialization properties out of the compilation options of this compilation.
/// </summary>
internal Cci.ModulePropertiesForSerialization ConstructModuleSerializationProperties(
EmitOptions emitOptions,
string? targetRuntimeVersion,
Guid moduleVersionId = default(Guid))
{
CompilationOptions compilationOptions = this.Options;
Platform platform = compilationOptions.Platform;
OutputKind outputKind = compilationOptions.OutputKind;
if (!platform.IsValid())
{
platform = Platform.AnyCpu;
}
if (!outputKind.IsValid())
{
outputKind = OutputKind.DynamicallyLinkedLibrary;
}
bool requires64Bit = platform.Requires64Bit();
bool requires32Bit = platform.Requires32Bit();
ushort fileAlignment;
if (emitOptions.FileAlignment == 0 || !CompilationOptions.IsValidFileAlignment(emitOptions.FileAlignment))
{
fileAlignment = requires64Bit
? Cci.ModulePropertiesForSerialization.DefaultFileAlignment64Bit
: Cci.ModulePropertiesForSerialization.DefaultFileAlignment32Bit;
}
else
{
fileAlignment = (ushort)emitOptions.FileAlignment;
}
ulong baseAddress = unchecked(emitOptions.BaseAddress + 0x8000) & (requires64Bit ? 0xffffffffffff0000 : 0x00000000ffff0000);
// cover values smaller than 0x8000, overflow and default value 0):
if (baseAddress == 0)
{
if (outputKind == OutputKind.ConsoleApplication ||
outputKind == OutputKind.WindowsApplication ||
outputKind == OutputKind.WindowsRuntimeApplication)
{
baseAddress = (requires64Bit) ? Cci.ModulePropertiesForSerialization.DefaultExeBaseAddress64Bit : Cci.ModulePropertiesForSerialization.DefaultExeBaseAddress32Bit;
}
else
{
baseAddress = (requires64Bit) ? Cci.ModulePropertiesForSerialization.DefaultDllBaseAddress64Bit : Cci.ModulePropertiesForSerialization.DefaultDllBaseAddress32Bit;
}
}
ulong sizeOfHeapCommit = requires64Bit
? Cci.ModulePropertiesForSerialization.DefaultSizeOfHeapCommit64Bit
: Cci.ModulePropertiesForSerialization.DefaultSizeOfHeapCommit32Bit;
// Dev10 always uses the default value for 32bit for sizeOfHeapReserve.
// check with link -dump -headers <filename>
const ulong sizeOfHeapReserve = Cci.ModulePropertiesForSerialization.DefaultSizeOfHeapReserve32Bit;
ulong sizeOfStackReserve = requires64Bit
? Cci.ModulePropertiesForSerialization.DefaultSizeOfStackReserve64Bit
: Cci.ModulePropertiesForSerialization.DefaultSizeOfStackReserve32Bit;
ulong sizeOfStackCommit = requires64Bit
? Cci.ModulePropertiesForSerialization.DefaultSizeOfStackCommit64Bit
: Cci.ModulePropertiesForSerialization.DefaultSizeOfStackCommit32Bit;
SubsystemVersion subsystemVersion;
if (emitOptions.SubsystemVersion.Equals(SubsystemVersion.None) || !emitOptions.SubsystemVersion.IsValid)
{
subsystemVersion = SubsystemVersion.Default(outputKind, platform);
}
else
{
subsystemVersion = emitOptions.SubsystemVersion;
}
Machine machine;
switch (platform)
{
case Platform.Arm64:
machine = Machine.Arm64;
break;
case Platform.Arm:
machine = Machine.ArmThumb2;
break;
case Platform.X64:
machine = Machine.Amd64;
break;
case Platform.Itanium:
machine = Machine.IA64;
break;
case Platform.X86:
machine = Machine.I386;
break;
case Platform.AnyCpu:
case Platform.AnyCpu32BitPreferred:
machine = Machine.Unknown;
break;
default:
throw ExceptionUtilities.UnexpectedValue(platform);
}
return new Cci.ModulePropertiesForSerialization(
persistentIdentifier: moduleVersionId,
corFlags: GetCorHeaderFlags(machine, HasStrongName, prefers32Bit: platform == Platform.AnyCpu32BitPreferred),
fileAlignment: fileAlignment,
sectionAlignment: Cci.ModulePropertiesForSerialization.DefaultSectionAlignment,
targetRuntimeVersion: targetRuntimeVersion,
machine: machine,
baseAddress: baseAddress,
sizeOfHeapReserve: sizeOfHeapReserve,
sizeOfHeapCommit: sizeOfHeapCommit,
sizeOfStackReserve: sizeOfStackReserve,
sizeOfStackCommit: sizeOfStackCommit,
dllCharacteristics: GetDllCharacteristics(emitOptions.HighEntropyVirtualAddressSpace, compilationOptions.OutputKind == OutputKind.WindowsRuntimeApplication),
imageCharacteristics: GetCharacteristics(outputKind, requires32Bit),
subsystem: GetSubsystem(outputKind),
majorSubsystemVersion: (ushort)subsystemVersion.Major,
minorSubsystemVersion: (ushort)subsystemVersion.Minor,
linkerMajorVersion: this.LinkerMajorVersion,
linkerMinorVersion: 0);
}
private static CorFlags GetCorHeaderFlags(Machine machine, bool strongNameSigned, bool prefers32Bit)
{
CorFlags result = CorFlags.ILOnly;
if (machine == Machine.I386)
{
result |= CorFlags.Requires32Bit;
}
if (strongNameSigned)
{
result |= CorFlags.StrongNameSigned;
}
if (prefers32Bit)
{
result |= CorFlags.Requires32Bit | CorFlags.Prefers32Bit;
}
return result;
}
internal static DllCharacteristics GetDllCharacteristics(bool enableHighEntropyVA, bool configureToExecuteInAppContainer)
{
var result =
DllCharacteristics.DynamicBase |
DllCharacteristics.NxCompatible |
DllCharacteristics.NoSeh |
DllCharacteristics.TerminalServerAware;
if (enableHighEntropyVA)
{
result |= DllCharacteristics.HighEntropyVirtualAddressSpace;
}
if (configureToExecuteInAppContainer)
{
result |= DllCharacteristics.AppContainer;
}
return result;
}
private static Characteristics GetCharacteristics(OutputKind outputKind, bool requires32Bit)
{
var characteristics = Characteristics.ExecutableImage;
if (requires32Bit)
{
// 32 bit machine (The standard says to always set this, the linker team says otherwise)
// The loader team says that this is not used for anything in the OS.
characteristics |= Characteristics.Bit32Machine;
}
else
{
// Large address aware (the standard says never to set this, the linker team says otherwise).
// The loader team says that this is not overridden for managed binaries and will be respected if set.
characteristics |= Characteristics.LargeAddressAware;
}
switch (outputKind)
{
case OutputKind.WindowsRuntimeMetadata:
case OutputKind.DynamicallyLinkedLibrary:
case OutputKind.NetModule:
characteristics |= Characteristics.Dll;
break;
case OutputKind.ConsoleApplication:
case OutputKind.WindowsRuntimeApplication:
case OutputKind.WindowsApplication:
break;
default:
throw ExceptionUtilities.UnexpectedValue(outputKind);
}
return characteristics;
}
private static Subsystem GetSubsystem(OutputKind outputKind)
{
switch (outputKind)
{
case OutputKind.ConsoleApplication:
case OutputKind.DynamicallyLinkedLibrary:
case OutputKind.NetModule:
case OutputKind.WindowsRuntimeMetadata:
return Subsystem.WindowsCui;
case OutputKind.WindowsRuntimeApplication:
case OutputKind.WindowsApplication:
return Subsystem.WindowsGui;
default:
throw ExceptionUtilities.UnexpectedValue(outputKind);
}
}
/// <summary>
/// The value is not used by Windows loader, but the OS appcompat infrastructure uses it to identify apps.
/// It is useful for us to have a mechanism to identify the compiler that produced the binary.
/// This is the appropriate value to use for that. That is what it was invented for.
/// We don't want to have the high bit set for this in case some users perform a signed comparison to
/// determine if the value is less than some version. The C++ linker is at 0x0B.
/// We'll start our numbering at 0x30 for C#, 0x50 for VB.
/// </summary>
internal abstract byte LinkerMajorVersion { get; }
internal bool HasStrongName
{
get
{
return !IsDelaySigned
&& Options.OutputKind != OutputKind.NetModule
&& StrongNameKeys.CanProvideStrongName;
}
}
internal bool IsRealSigned
{
get
{
// A module cannot be signed. The native compiler allowed one to create a netmodule with an AssemblyKeyFile
// or Container attribute (or specify a key via the cmd line). When the module was linked into an assembly,
// alink would sign the assembly. So rather than give an error we just don't sign when outputting a module.
return !IsDelaySigned
&& !Options.PublicSign
&& Options.OutputKind != OutputKind.NetModule
&& StrongNameKeys.CanSign;
}
}
/// <summary>
/// Return true if the compilation contains any code or types.
/// </summary>
internal abstract bool HasCodeToEmit();
internal abstract bool IsDelaySigned { get; }
internal abstract StrongNameKeys StrongNameKeys { get; }
internal abstract CommonPEModuleBuilder? CreateModuleBuilder(
EmitOptions emitOptions,
IMethodSymbol? debugEntryPoint,
Stream? sourceLinkStream,
IEnumerable<EmbeddedText>? embeddedTexts,
IEnumerable<ResourceDescription>? manifestResources,
CompilationTestData? testData,
DiagnosticBag diagnostics,
CancellationToken cancellationToken);
/// <summary>
/// Report declaration diagnostics and compile and synthesize method bodies.
/// </summary>
/// <returns>True if successful.</returns>
internal abstract bool CompileMethods(
CommonPEModuleBuilder moduleBuilder,
bool emittingPdb,
bool emitMetadataOnly,
bool emitTestCoverageData,
DiagnosticBag diagnostics,
Predicate<ISymbolInternal>? filterOpt,
CancellationToken cancellationToken);
internal bool CreateDebugDocuments(DebugDocumentsBuilder documentsBuilder, IEnumerable<EmbeddedText> embeddedTexts, DiagnosticBag diagnostics)
{
// Check that all syntax trees are debuggable:
bool allTreesDebuggable = true;
foreach (var tree in CommonSyntaxTrees)
{
if (!string.IsNullOrEmpty(tree.FilePath) && tree.GetText().Encoding == null)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_EncodinglessSyntaxTree, tree.GetRoot().GetLocation()));
allTreesDebuggable = false;
}
}
if (!allTreesDebuggable)
{
return false;
}
// Add debug documents for all embedded text first. This ensures that embedding
// takes priority over the syntax tree pass, which will not embed.
if (!embeddedTexts.IsEmpty())
{
foreach (var text in embeddedTexts)
{
Debug.Assert(!string.IsNullOrEmpty(text.FilePath));
string normalizedPath = documentsBuilder.NormalizeDebugDocumentPath(text.FilePath, basePath: null);
var existingDoc = documentsBuilder.TryGetDebugDocumentForNormalizedPath(normalizedPath);
if (existingDoc == null)
{
var document = new Cci.DebugSourceDocument(
normalizedPath,
DebugSourceDocumentLanguageId,
() => text.GetDebugSourceInfo());
documentsBuilder.AddDebugDocument(document);
}
}
}
// Add debug documents for all trees with distinct paths.
foreach (var tree in CommonSyntaxTrees)
{
if (!string.IsNullOrEmpty(tree.FilePath))
{
// compilation does not guarantee that all trees will have distinct paths.
// Do not attempt adding a document for a particular path if we already added one.
string normalizedPath = documentsBuilder.NormalizeDebugDocumentPath(tree.FilePath, basePath: null);
var existingDoc = documentsBuilder.TryGetDebugDocumentForNormalizedPath(normalizedPath);
if (existingDoc == null)
{
documentsBuilder.AddDebugDocument(new Cci.DebugSourceDocument(
normalizedPath,
DebugSourceDocumentLanguageId,
() => tree.GetDebugSourceInfo()));
}
}
}
// Add debug documents for all pragmas.
// If there are clashes with already processed directives, report warnings.
// If there are clashes with debug documents that came from actual trees, ignore the pragma.
// Therefore we need to add these in a separate pass after documents for syntax trees were added.
foreach (var tree in CommonSyntaxTrees)
{
AddDebugSourceDocumentsForChecksumDirectives(documentsBuilder, tree, diagnostics);
}
return true;
}
internal abstract Guid DebugSourceDocumentLanguageId { get; }
internal abstract void AddDebugSourceDocumentsForChecksumDirectives(DebugDocumentsBuilder documentsBuilder, SyntaxTree tree, DiagnosticBag diagnostics);
/// <summary>
/// Update resources and generate XML documentation comments.
/// </summary>
/// <returns>True if successful.</returns>
internal abstract bool GenerateResourcesAndDocumentationComments(
CommonPEModuleBuilder moduleBeingBuilt,
Stream? xmlDocumentationStream,
Stream? win32ResourcesStream,
bool useRawWin32Resources,
string? outputNameOverride,
DiagnosticBag diagnostics,
CancellationToken cancellationToken);
/// <summary>
/// Reports all unused imports/usings so far (and thus it must be called as a last step of Emit)
/// </summary>
internal abstract void ReportUnusedImports(
DiagnosticBag diagnostics,
CancellationToken cancellationToken);
internal static bool ReportUnusedImportsInTree(SyntaxTree tree)
{
return tree.Options.DocumentationMode != DocumentationMode.None;
}
/// <summary>
/// Signals the event queue, if any, that we are done compiling.
/// There should not be more compiling actions after this step.
/// NOTE: once we signal about completion to analyzers they will cancel and thus in some cases we
/// may be effectively cutting off some diagnostics.
/// It is not clear if behavior is desirable.
/// See: https://github.com/dotnet/roslyn/issues/11470
/// </summary>
/// <param name="filterTree">What tree to complete. null means complete all trees. </param>
internal abstract void CompleteTrees(SyntaxTree? filterTree);
internal bool Compile(
CommonPEModuleBuilder moduleBuilder,
bool emittingPdb,
DiagnosticBag diagnostics,
Predicate<ISymbolInternal>? filterOpt,
CancellationToken cancellationToken)
{
try
{
return CompileMethods(
moduleBuilder,
emittingPdb,
emitMetadataOnly: false,
emitTestCoverageData: false,
diagnostics: diagnostics,
filterOpt: filterOpt,
cancellationToken: cancellationToken);
}
finally
{
moduleBuilder.CompilationFinished();
}
}
internal void EnsureAnonymousTypeTemplates(CancellationToken cancellationToken)
{
Debug.Assert(IsSubmission);
if (this.GetSubmissionSlotIndex() >= 0 && HasCodeToEmit())
{
if (!this.CommonAnonymousTypeManager.AreTemplatesSealed)
{
var discardedDiagnostics = DiagnosticBag.GetInstance();
var moduleBeingBuilt = this.CreateModuleBuilder(
emitOptions: EmitOptions.Default,
debugEntryPoint: null,
manifestResources: null,
sourceLinkStream: null,
embeddedTexts: null,
testData: null,
diagnostics: discardedDiagnostics,
cancellationToken: cancellationToken);
if (moduleBeingBuilt != null)
{
Compile(
moduleBeingBuilt,
diagnostics: discardedDiagnostics,
emittingPdb: false,
filterOpt: null,
cancellationToken: cancellationToken);
}
discardedDiagnostics.Free();
}
Debug.Assert(this.CommonAnonymousTypeManager.AreTemplatesSealed);
}
else
{
this.ScriptCompilationInfo?.PreviousScriptCompilation?.EnsureAnonymousTypeTemplates(cancellationToken);
}
}
// 1.0 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
[EditorBrowsable(EditorBrowsableState.Never)]
public EmitResult Emit(
Stream peStream,
Stream? pdbStream,
Stream? xmlDocumentationStream,
Stream? win32Resources,
IEnumerable<ResourceDescription>? manifestResources,
EmitOptions options,
CancellationToken cancellationToken)
{
return Emit(
peStream,
pdbStream,
xmlDocumentationStream,
win32Resources,
manifestResources,
options,
debugEntryPoint: null,
sourceLinkStream: null,
embeddedTexts: null,
cancellationToken);
}
// 1.3 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
[EditorBrowsable(EditorBrowsableState.Never)]
public EmitResult Emit(
Stream peStream,
Stream pdbStream,
Stream xmlDocumentationStream,
Stream win32Resources,
IEnumerable<ResourceDescription> manifestResources,
EmitOptions options,
IMethodSymbol debugEntryPoint,
CancellationToken cancellationToken)
{
return Emit(
peStream,
pdbStream,
xmlDocumentationStream,
win32Resources,
manifestResources,
options,
debugEntryPoint,
sourceLinkStream: null,
embeddedTexts: null,
cancellationToken);
}
// 2.0 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
public EmitResult Emit(
Stream peStream,
Stream? pdbStream,
Stream? xmlDocumentationStream,
Stream? win32Resources,
IEnumerable<ResourceDescription>? manifestResources,
EmitOptions options,
IMethodSymbol? debugEntryPoint,
Stream? sourceLinkStream,
IEnumerable<EmbeddedText>? embeddedTexts,
CancellationToken cancellationToken)
{
return Emit(
peStream,
pdbStream,
xmlDocumentationStream,
win32Resources,
manifestResources,
options,
debugEntryPoint,
sourceLinkStream,
embeddedTexts,
metadataPEStream: null,
cancellationToken: cancellationToken);
}
/// <summary>
/// Emit the IL for the compiled source code into the specified stream.
/// </summary>
/// <param name="peStream">Stream to which the compilation will be written.</param>
/// <param name="metadataPEStream">Stream to which the metadata-only output will be written.</param>
/// <param name="pdbStream">Stream to which the compilation's debug info will be written. Null to forego PDB generation.</param>
/// <param name="xmlDocumentationStream">Stream to which the compilation's XML documentation will be written. Null to forego XML generation.</param>
/// <param name="win32Resources">Stream from which the compilation's Win32 resources will be read (in RES format).
/// Null to indicate that there are none. The RES format begins with a null resource entry.
/// Note that the caller is responsible for disposing this stream, if provided.</param>
/// <param name="manifestResources">List of the compilation's managed resources. Null to indicate that there are none.</param>
/// <param name="options">Emit options.</param>
/// <param name="debugEntryPoint">
/// Debug entry-point of the assembly. The method token is stored in the generated PDB stream.
///
/// When a program launches with a debugger attached the debugger places the first breakpoint to the start of the debug entry-point method.
/// The CLR starts executing the static Main method of <see cref="CompilationOptions.MainTypeName"/> type. When the first breakpoint is hit
/// the debugger steps thru the code statement by statement until user code is reached, skipping methods marked by <see cref="DebuggerHiddenAttribute"/>,
/// and taking other debugging attributes into consideration.
///
/// By default both entry points in an executable program (<see cref="OutputKind.ConsoleApplication"/>, <see cref="OutputKind.WindowsApplication"/>, <see cref="OutputKind.WindowsRuntimeApplication"/>)
/// are the same method (Main). A non-executable program has no entry point. Runtimes that implement a custom loader may specify debug entry-point
/// to force the debugger to skip over complex custom loader logic executing at the beginning of the .exe and thus improve debugging experience.
///
/// Unlike ordinary entry-point which is limited to a non-generic static method of specific signature, there are no restrictions on the <paramref name="debugEntryPoint"/>
/// method other than having a method body (extern, interface, or abstract methods are not allowed).
/// </param>
/// <param name="sourceLinkStream">
/// Stream containing information linking the compilation to a source control.
/// </param>
/// <param name="embeddedTexts">
/// Texts to embed in the PDB.
/// Only supported when emitting Portable PDBs.
/// </param>
/// <param name="cancellationToken">To cancel the emit process.</param>
public EmitResult Emit(
Stream peStream,
Stream? pdbStream = null,
Stream? xmlDocumentationStream = null,
Stream? win32Resources = null,
IEnumerable<ResourceDescription>? manifestResources = null,
EmitOptions? options = null,
IMethodSymbol? debugEntryPoint = null,
Stream? sourceLinkStream = null,
IEnumerable<EmbeddedText>? embeddedTexts = null,
Stream? metadataPEStream = null,
CancellationToken cancellationToken = default(CancellationToken))
{
return Emit(
peStream,
pdbStream,
xmlDocumentationStream,
win32Resources,
manifestResources,
options,
debugEntryPoint,
sourceLinkStream,
embeddedTexts,
metadataPEStream,
rebuildData: null,
cancellationToken);
}
internal EmitResult Emit(
Stream peStream,
Stream? pdbStream,
Stream? xmlDocumentationStream,
Stream? win32Resources,
IEnumerable<ResourceDescription>? manifestResources,
EmitOptions? options,
IMethodSymbol? debugEntryPoint,
Stream? sourceLinkStream,
IEnumerable<EmbeddedText>? embeddedTexts,
Stream? metadataPEStream,
RebuildData? rebuildData,
CancellationToken cancellationToken)
{
if (peStream == null)
{
throw new ArgumentNullException(nameof(peStream));
}
if (!peStream.CanWrite)
{
throw new ArgumentException(CodeAnalysisResources.StreamMustSupportWrite, nameof(peStream));
}
if (pdbStream != null)
{
if (options?.DebugInformationFormat == DebugInformationFormat.Embedded)
{
throw new ArgumentException(CodeAnalysisResources.PdbStreamUnexpectedWhenEmbedding, nameof(pdbStream));
}
if (!pdbStream.CanWrite)
{
throw new ArgumentException(CodeAnalysisResources.StreamMustSupportWrite, nameof(pdbStream));
}
if (options?.EmitMetadataOnly == true)
{
throw new ArgumentException(CodeAnalysisResources.PdbStreamUnexpectedWhenEmittingMetadataOnly, nameof(pdbStream));
}
}
if (metadataPEStream != null && options?.EmitMetadataOnly == true)
{
throw new ArgumentException(CodeAnalysisResources.MetadataPeStreamUnexpectedWhenEmittingMetadataOnly, nameof(metadataPEStream));
}
if (metadataPEStream != null && options?.IncludePrivateMembers == true)
{
throw new ArgumentException(CodeAnalysisResources.IncludingPrivateMembersUnexpectedWhenEmittingToMetadataPeStream, nameof(metadataPEStream));
}
if (metadataPEStream == null && options?.EmitMetadataOnly == false)
{
// EmitOptions used to default to IncludePrivateMembers=false, so to preserve binary compatibility we silently correct that unless emitting regular assemblies
options = options.WithIncludePrivateMembers(true);
}
if (options?.DebugInformationFormat == DebugInformationFormat.Embedded &&
options?.EmitMetadataOnly == true)
{
throw new ArgumentException(CodeAnalysisResources.EmbeddingPdbUnexpectedWhenEmittingMetadata, nameof(metadataPEStream));
}
if (this.Options.OutputKind == OutputKind.NetModule)
{
if (metadataPEStream != null)
{
throw new ArgumentException(CodeAnalysisResources.CannotTargetNetModuleWhenEmittingRefAssembly, nameof(metadataPEStream));
}
else if (options?.EmitMetadataOnly == true)
{
throw new ArgumentException(CodeAnalysisResources.CannotTargetNetModuleWhenEmittingRefAssembly, nameof(options.EmitMetadataOnly));
}
}
if (win32Resources != null)
{
if (!win32Resources.CanRead || !win32Resources.CanSeek)
{
throw new ArgumentException(CodeAnalysisResources.StreamMustSupportReadAndSeek, nameof(win32Resources));
}
}
if (sourceLinkStream != null && !sourceLinkStream.CanRead)
{
throw new ArgumentException(CodeAnalysisResources.StreamMustSupportRead, nameof(sourceLinkStream));
}
if (embeddedTexts != null &&
!embeddedTexts.IsEmpty() &&
pdbStream == null &&
options?.DebugInformationFormat != DebugInformationFormat.Embedded)
{
throw new ArgumentException(CodeAnalysisResources.EmbeddedTextsRequirePdb, nameof(embeddedTexts));
}
return Emit(
peStream,
metadataPEStream,
pdbStream,
xmlDocumentationStream,
win32Resources,
manifestResources,
options,
debugEntryPoint,
sourceLinkStream,
embeddedTexts,
rebuildData,
testData: null,
cancellationToken: cancellationToken);
}
/// <summary>
/// This overload is only intended to be directly called by tests that want to pass <paramref name="testData"/>.
/// The map is used for storing a list of methods and their associated IL.
/// </summary>
internal EmitResult Emit(
Stream peStream,
Stream? metadataPEStream,
Stream? pdbStream,
Stream? xmlDocumentationStream,
Stream? win32Resources,
IEnumerable<ResourceDescription>? manifestResources,
EmitOptions? options,
IMethodSymbol? debugEntryPoint,
Stream? sourceLinkStream,
IEnumerable<EmbeddedText>? embeddedTexts,
RebuildData? rebuildData,
CompilationTestData? testData,
CancellationToken cancellationToken)
{
options = options ?? EmitOptions.Default.WithIncludePrivateMembers(metadataPEStream == null);
bool embedPdb = options.DebugInformationFormat == DebugInformationFormat.Embedded;
Debug.Assert(!embedPdb || pdbStream == null);
Debug.Assert(metadataPEStream == null || !options.IncludePrivateMembers); // you may not use a secondary stream and include private members together
var diagnostics = DiagnosticBag.GetInstance();
var moduleBeingBuilt = CheckOptionsAndCreateModuleBuilder(
diagnostics,
manifestResources,
options,
debugEntryPoint,
sourceLinkStream,
embeddedTexts,
testData,
cancellationToken);
bool success = false;
if (moduleBeingBuilt != null)
{
try
{
success = CompileMethods(
moduleBeingBuilt,
emittingPdb: pdbStream != null || embedPdb,
emitMetadataOnly: options.EmitMetadataOnly,
emitTestCoverageData: options.EmitTestCoverageData,
diagnostics: diagnostics,
filterOpt: null,
cancellationToken: cancellationToken);
if (!options.EmitMetadataOnly)
{
// NOTE: We generate documentation even in presence of compile errors.
// https://github.com/dotnet/roslyn/issues/37996 tracks revisiting this behavior.
if (!GenerateResourcesAndDocumentationComments(
moduleBeingBuilt,
xmlDocumentationStream,
win32Resources,
useRawWin32Resources: rebuildData is object,
options.OutputNameOverride,
diagnostics,
cancellationToken))
{
success = false;
}
if (success)
{
ReportUnusedImports(diagnostics, cancellationToken);
}
}
}
finally
{
moduleBeingBuilt.CompilationFinished();
}
RSAParameters? privateKeyOpt = null;
if (Options.StrongNameProvider != null && SignUsingBuilder && !Options.PublicSign)
{
privateKeyOpt = StrongNameKeys.PrivateKey;
}
if (!options.EmitMetadataOnly && CommonCompiler.HasUnsuppressedErrors(diagnostics))
{
success = false;
}
if (success)
{
success = SerializeToPeStream(
moduleBeingBuilt,
new SimpleEmitStreamProvider(peStream),
(metadataPEStream != null) ? new SimpleEmitStreamProvider(metadataPEStream) : null,
(pdbStream != null) ? new SimpleEmitStreamProvider(pdbStream) : null,
rebuildData,
testData?.SymWriterFactory,
diagnostics,
emitOptions: options,
privateKeyOpt: privateKeyOpt,
cancellationToken: cancellationToken);
}
}
return new EmitResult(success, diagnostics.ToReadOnlyAndFree());
}
#pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters
/// <summary>
/// Emit the differences between the compilation and the previous generation
/// for Edit and Continue. The differences are expressed as added and changed
/// symbols, and are emitted as metadata, IL, and PDB deltas. A representation
/// of the current compilation is returned as an EmitBaseline for use in a
/// subsequent Edit and Continue.
/// </summary>
[Obsolete("UpdatedMethods is now part of EmitDifferenceResult, so you should use an overload that doesn't take it.")]
public EmitDifferenceResult EmitDifference(
EmitBaseline baseline,
IEnumerable<SemanticEdit> edits,
Stream metadataStream,
Stream ilStream,
Stream pdbStream,
ICollection<MethodDefinitionHandle> updatedMethods,
CancellationToken cancellationToken = default(CancellationToken))
{
return EmitDifference(baseline, edits, s => false, metadataStream, ilStream, pdbStream, updatedMethods, cancellationToken);
}
/// <summary>
/// Emit the differences between the compilation and the previous generation
/// for Edit and Continue. The differences are expressed as added and changed
/// symbols, and are emitted as metadata, IL, and PDB deltas. A representation
/// of the current compilation is returned as an EmitBaseline for use in a
/// subsequent Edit and Continue.
/// </summary>
[Obsolete("UpdatedMethods is now part of EmitDifferenceResult, so you should use an overload that doesn't take it.")]
public EmitDifferenceResult EmitDifference(
EmitBaseline baseline,
IEnumerable<SemanticEdit> edits,
Func<ISymbol, bool> isAddedSymbol,
Stream metadataStream,
Stream ilStream,
Stream pdbStream,
ICollection<MethodDefinitionHandle> updatedMethods,
CancellationToken cancellationToken = default(CancellationToken))
{
var diff = EmitDifference(baseline, edits, isAddedSymbol, metadataStream, ilStream, pdbStream, cancellationToken);
foreach (var token in diff.UpdatedMethods)
{
updatedMethods.Add(token);
}
return diff;
}
/// <summary>
/// Emit the differences between the compilation and the previous generation
/// for Edit and Continue. The differences are expressed as added and changed
/// symbols, and are emitted as metadata, IL, and PDB deltas. A representation
/// of the current compilation is returned as an EmitBaseline for use in a
/// subsequent Edit and Continue.
/// </summary>
public EmitDifferenceResult EmitDifference(
EmitBaseline baseline,
IEnumerable<SemanticEdit> edits,
Func<ISymbol, bool> isAddedSymbol,
Stream metadataStream,
Stream ilStream,
Stream pdbStream,
CancellationToken cancellationToken = default(CancellationToken))
{
if (baseline == null)
{
throw new ArgumentNullException(nameof(baseline));
}
// TODO: check if baseline is an assembly manifest module/netmodule
// Do we support EnC on netmodules?
if (edits == null)
{
throw new ArgumentNullException(nameof(edits));
}
if (isAddedSymbol == null)
{
throw new ArgumentNullException(nameof(isAddedSymbol));
}
if (metadataStream == null)
{
throw new ArgumentNullException(nameof(metadataStream));
}
if (ilStream == null)
{
throw new ArgumentNullException(nameof(ilStream));
}
if (pdbStream == null)
{
throw new ArgumentNullException(nameof(pdbStream));
}
return this.EmitDifference(baseline, edits, isAddedSymbol, metadataStream, ilStream, pdbStream, testData: null, cancellationToken);
}
#pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters
internal abstract EmitDifferenceResult EmitDifference(
EmitBaseline baseline,
IEnumerable<SemanticEdit> edits,
Func<ISymbol, bool> isAddedSymbol,
Stream metadataStream,
Stream ilStream,
Stream pdbStream,
CompilationTestData? testData,
CancellationToken cancellationToken);
/// <summary>
/// Check compilation options and create <see cref="CommonPEModuleBuilder"/>.
/// </summary>
/// <returns><see cref="CommonPEModuleBuilder"/> if successful.</returns>
internal CommonPEModuleBuilder? CheckOptionsAndCreateModuleBuilder(
DiagnosticBag diagnostics,
IEnumerable<ResourceDescription>? manifestResources,
EmitOptions options,
IMethodSymbol? debugEntryPoint,
Stream? sourceLinkStream,
IEnumerable<EmbeddedText>? embeddedTexts,
CompilationTestData? testData,
CancellationToken cancellationToken)
{
options.ValidateOptions(diagnostics, MessageProvider, Options.Deterministic);
if (debugEntryPoint != null)
{
ValidateDebugEntryPoint(debugEntryPoint, diagnostics);
}
if (Options.OutputKind == OutputKind.NetModule && manifestResources != null)
{
foreach (ResourceDescription res in manifestResources)
{
if (res.FileName != null)
{
// Modules can have only embedded resources, not linked ones.
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceInModule, Location.None));
}
}
}
if (CommonCompiler.HasUnsuppressableErrors(diagnostics))
{
return null;
}
// Do not waste a slot in the submission chain for submissions that contain no executable code
// (they may only contain #r directives, usings, etc.)
if (IsSubmission && !HasCodeToEmit())
{
// Still report diagnostics since downstream submissions will assume there are no errors.
diagnostics.AddRange(this.GetDiagnostics(cancellationToken));
return null;
}
return this.CreateModuleBuilder(
options,
debugEntryPoint,
sourceLinkStream,
embeddedTexts,
manifestResources,
testData,
diagnostics,
cancellationToken);
}
internal abstract void ValidateDebugEntryPoint(IMethodSymbol debugEntryPoint, DiagnosticBag diagnostics);
internal bool IsEmitDeterministic => this.Options.Deterministic;
internal bool SerializeToPeStream(
CommonPEModuleBuilder moduleBeingBuilt,
EmitStreamProvider peStreamProvider,
EmitStreamProvider? metadataPEStreamProvider,
EmitStreamProvider? pdbStreamProvider,
RebuildData? rebuildData,
Func<ISymWriterMetadataProvider, SymUnmanagedWriter>? testSymWriterFactory,
DiagnosticBag diagnostics,
EmitOptions emitOptions,
RSAParameters? privateKeyOpt,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
Cci.PdbWriter? nativePdbWriter = null;
DiagnosticBag? metadataDiagnostics = null;
DiagnosticBag? pdbBag = null;
bool deterministic = IsEmitDeterministic;
// PDB Stream provider should not be given if PDB is to be embedded into the PE file:
Debug.Assert(moduleBeingBuilt.DebugInformationFormat != DebugInformationFormat.Embedded || pdbStreamProvider == null);
string? pePdbFilePath = emitOptions.PdbFilePath;
if (moduleBeingBuilt.DebugInformationFormat == DebugInformationFormat.Embedded || pdbStreamProvider != null)
{
pePdbFilePath = pePdbFilePath ?? FileNameUtilities.ChangeExtension(SourceModule.Name, "pdb");
}
else
{
pePdbFilePath = null;
}
if (moduleBeingBuilt.DebugInformationFormat == DebugInformationFormat.Embedded && !RoslynString.IsNullOrEmpty(pePdbFilePath))
{
pePdbFilePath = PathUtilities.GetFileName(pePdbFilePath);
}
EmitStream? emitPeStream = null;
EmitStream? emitMetadataStream = null;
try
{
var signKind = IsRealSigned
? (SignUsingBuilder ? EmitStreamSignKind.SignedWithBuilder : EmitStreamSignKind.SignedWithFile)
: EmitStreamSignKind.None;
emitPeStream = new EmitStream(peStreamProvider, signKind, Options.StrongNameProvider);
emitMetadataStream = metadataPEStreamProvider == null
? null
: new EmitStream(metadataPEStreamProvider, signKind, Options.StrongNameProvider);
metadataDiagnostics = DiagnosticBag.GetInstance();
if (moduleBeingBuilt.DebugInformationFormat == DebugInformationFormat.Pdb && pdbStreamProvider != null)
{
// The algorithm must be specified for deterministic builds (checked earlier).
Debug.Assert(!deterministic || moduleBeingBuilt.PdbChecksumAlgorithm.Name != null);
// The calls ISymUnmanagedWriter2.GetDebugInfo require a file name in order to succeed. This is
// frequently used during PDB writing. Ensure a name is provided here in the case we were given
// only a Stream value.
nativePdbWriter = new Cci.PdbWriter(pePdbFilePath, testSymWriterFactory, deterministic ? moduleBeingBuilt.PdbChecksumAlgorithm : default);
}
Func<Stream?>? getPortablePdbStream =
moduleBeingBuilt.DebugInformationFormat != DebugInformationFormat.PortablePdb || pdbStreamProvider == null
? null
: (Func<Stream?>)(() => ConditionalGetOrCreateStream(pdbStreamProvider, metadataDiagnostics));
try
{
if (SerializePeToStream(
moduleBeingBuilt,
metadataDiagnostics,
MessageProvider,
emitPeStream.GetCreateStreamFunc(metadataDiagnostics),
emitMetadataStream?.GetCreateStreamFunc(metadataDiagnostics),
getPortablePdbStream,
nativePdbWriter,
pePdbFilePath,
rebuildData,
emitOptions.EmitMetadataOnly,
emitOptions.IncludePrivateMembers,
deterministic,
emitOptions.EmitTestCoverageData,
privateKeyOpt,
cancellationToken))
{
if (nativePdbWriter != null)
{
var nativePdbStream = pdbStreamProvider!.GetOrCreateStream(metadataDiagnostics);
Debug.Assert(nativePdbStream != null || metadataDiagnostics.HasAnyErrors());
if (nativePdbStream != null)
{
nativePdbWriter.WriteTo(nativePdbStream);
}
}
}
}
catch (SymUnmanagedWriterException ex)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PdbWritingFailed, Location.None, ex.Message));
return false;
}
catch (Cci.PeWritingException e)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PeWritingFailure, Location.None, e.InnerException?.ToString() ?? ""));
return false;
}
catch (ResourceException e)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_CantReadResource, Location.None, e.Message, e.InnerException?.Message ?? ""));
return false;
}
catch (PermissionSetFileReadException e)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PermissionSetAttributeFileReadError, Location.None, e.FileName, e.PropertyName, e.Message));
return false;
}
// translate metadata errors.
if (!FilterAndAppendAndFreeDiagnostics(diagnostics, ref metadataDiagnostics, cancellationToken))
{
return false;
}
return
emitPeStream.Complete(StrongNameKeys, MessageProvider, diagnostics) &&
(emitMetadataStream?.Complete(StrongNameKeys, MessageProvider, diagnostics) ?? true);
}
finally
{
nativePdbWriter?.Dispose();
emitPeStream?.Close();
emitMetadataStream?.Close();
pdbBag?.Free();
metadataDiagnostics?.Free();
}
}
private static Stream? ConditionalGetOrCreateStream(EmitStreamProvider metadataPEStreamProvider, DiagnosticBag metadataDiagnostics)
{
if (metadataDiagnostics.HasAnyErrors())
{
return null;
}
var auxStream = metadataPEStreamProvider.GetOrCreateStream(metadataDiagnostics);
Debug.Assert(auxStream != null || metadataDiagnostics.HasAnyErrors());
return auxStream;
}
internal static bool SerializePeToStream(
CommonPEModuleBuilder moduleBeingBuilt,
DiagnosticBag metadataDiagnostics,
CommonMessageProvider messageProvider,
Func<Stream?> getPeStream,
Func<Stream?>? getMetadataPeStreamOpt,
Func<Stream?>? getPortablePdbStreamOpt,
Cci.PdbWriter? nativePdbWriterOpt,
string? pdbPathOpt,
RebuildData? rebuildData,
bool metadataOnly,
bool includePrivateMembers,
bool isDeterministic,
bool emitTestCoverageData,
RSAParameters? privateKeyOpt,
CancellationToken cancellationToken)
{
bool emitSecondaryAssembly = getMetadataPeStreamOpt != null;
bool includePrivateMembersOnPrimaryOutput = metadataOnly ? includePrivateMembers : true;
bool deterministicPrimaryOutput = (metadataOnly && !includePrivateMembers) || isDeterministic;
if (!Cci.PeWriter.WritePeToStream(
new EmitContext(moduleBeingBuilt, metadataDiagnostics, metadataOnly, includePrivateMembersOnPrimaryOutput, rebuildData: rebuildData),
messageProvider,
getPeStream,
getPortablePdbStreamOpt,
nativePdbWriterOpt,
pdbPathOpt,
metadataOnly,
deterministicPrimaryOutput,
emitTestCoverageData,
privateKeyOpt,
cancellationToken))
{
return false;
}
// produce the secondary output (ref assembly) if needed
if (emitSecondaryAssembly)
{
Debug.Assert(!metadataOnly);
Debug.Assert(!includePrivateMembers);
if (!Cci.PeWriter.WritePeToStream(
new EmitContext(moduleBeingBuilt, syntaxNode: null, metadataDiagnostics, metadataOnly: true, includePrivateMembers: false),
messageProvider,
getMetadataPeStreamOpt,
getPortablePdbStreamOpt: null,
nativePdbWriterOpt: null,
pdbPathOpt: null,
metadataOnly: true,
isDeterministic: true,
emitTestCoverageData: false,
privateKeyOpt: privateKeyOpt,
cancellationToken: cancellationToken))
{
return false;
}
}
return true;
}
internal EmitBaseline? SerializeToDeltaStreams(
CommonPEModuleBuilder moduleBeingBuilt,
EmitBaseline baseline,
DefinitionMap definitionMap,
SymbolChanges changes,
Stream metadataStream,
Stream ilStream,
Stream pdbStream,
ArrayBuilder<MethodDefinitionHandle> updatedMethods,
ArrayBuilder<TypeDefinitionHandle> changedTypes,
DiagnosticBag diagnostics,
Func<ISymWriterMetadataProvider, SymUnmanagedWriter>? testSymWriterFactory,
string? pdbFilePath,
CancellationToken cancellationToken)
{
var nativePdbWriter = (moduleBeingBuilt.DebugInformationFormat != DebugInformationFormat.Pdb) ? null :
new Cci.PdbWriter(
pdbFilePath ?? FileNameUtilities.ChangeExtension(SourceModule.Name, "pdb"),
testSymWriterFactory,
hashAlgorithmNameOpt: default);
using (nativePdbWriter)
{
var context = new EmitContext(moduleBeingBuilt, diagnostics, metadataOnly: false, includePrivateMembers: true);
var encId = Guid.NewGuid();
try
{
var writer = new DeltaMetadataWriter(
context,
MessageProvider,
baseline,
encId,
definitionMap,
changes,
cancellationToken);
writer.WriteMetadataAndIL(
nativePdbWriter,
metadataStream,
ilStream,
(nativePdbWriter == null) ? pdbStream : null,
out MetadataSizes metadataSizes);
writer.GetUpdatedMethodTokens(updatedMethods);
writer.GetChangedTypeTokens(changedTypes);
nativePdbWriter?.WriteTo(pdbStream);
return diagnostics.HasAnyErrors() ? null : writer.GetDelta(this, encId, metadataSizes);
}
catch (SymUnmanagedWriterException e)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PdbWritingFailed, Location.None, e.Message));
return null;
}
catch (Cci.PeWritingException e)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PeWritingFailure, Location.None, e.InnerException?.ToString() ?? ""));
return null;
}
catch (PermissionSetFileReadException e)
{
diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PermissionSetAttributeFileReadError, Location.None, e.FileName, e.PropertyName, e.Message));
return null;
}
}
}
internal string? Feature(string p)
{
string? v;
return _features.TryGetValue(p, out v) ? v : null;
}
#endregion
private ConcurrentDictionary<SyntaxTree, SmallConcurrentSetOfInts>? _lazyTreeToUsedImportDirectivesMap;
private static readonly Func<SyntaxTree, SmallConcurrentSetOfInts> s_createSetCallback = t => new SmallConcurrentSetOfInts();
private ConcurrentDictionary<SyntaxTree, SmallConcurrentSetOfInts> TreeToUsedImportDirectivesMap
{
get
{
return RoslynLazyInitializer.EnsureInitialized(ref _lazyTreeToUsedImportDirectivesMap);
}
}
internal void MarkImportDirectiveAsUsed(SyntaxReference node)
{
MarkImportDirectiveAsUsed(node.SyntaxTree, node.Span.Start);
}
internal void MarkImportDirectiveAsUsed(SyntaxTree? syntaxTree, int position)
{
// Optimization: Don't initialize TreeToUsedImportDirectivesMap in submissions.
if (!IsSubmission && syntaxTree != null)
{
var set = TreeToUsedImportDirectivesMap.GetOrAdd(syntaxTree, s_createSetCallback);
set.Add(position);
}
}
internal bool IsImportDirectiveUsed(SyntaxTree syntaxTree, int position)
{
if (IsSubmission)
{
// Since usings apply to subsequent submissions, we have to assume they are used.
return true;
}
SmallConcurrentSetOfInts? usedImports;
return syntaxTree != null &&
TreeToUsedImportDirectivesMap.TryGetValue(syntaxTree, out usedImports) &&
usedImports.Contains(position);
}
/// <summary>
/// The compiler needs to define an ordering among different partial class in different syntax trees
/// in some cases, because emit order for fields in structures, for example, is semantically important.
/// This function defines an ordering among syntax trees in this compilation.
/// </summary>
internal int CompareSyntaxTreeOrdering(SyntaxTree tree1, SyntaxTree tree2)
{
if (tree1 == tree2)
{
return 0;
}
Debug.Assert(this.ContainsSyntaxTree(tree1));
Debug.Assert(this.ContainsSyntaxTree(tree2));
return this.GetSyntaxTreeOrdinal(tree1) - this.GetSyntaxTreeOrdinal(tree2);
}
internal abstract int GetSyntaxTreeOrdinal(SyntaxTree tree);
/// <summary>
/// Compare two source locations, using their containing trees, and then by Span.First within a tree.
/// Can be used to get a total ordering on declarations, for example.
/// </summary>
internal abstract int CompareSourceLocations(Location loc1, Location loc2);
/// <summary>
/// Compare two source locations, using their containing trees, and then by Span.First within a tree.
/// Can be used to get a total ordering on declarations, for example.
/// </summary>
internal abstract int CompareSourceLocations(SyntaxReference loc1, SyntaxReference loc2);
/// <summary>
/// Return the lexically first of two locations.
/// </summary>
internal TLocation FirstSourceLocation<TLocation>(TLocation first, TLocation second)
where TLocation : Location
{
if (CompareSourceLocations(first, second) <= 0)
{
return first;
}
else
{
return second;
}
}
/// <summary>
/// Return the lexically first of multiple locations.
/// </summary>
internal TLocation? FirstSourceLocation<TLocation>(ImmutableArray<TLocation> locations)
where TLocation : Location
{
if (locations.IsEmpty)
{
return null;
}
var result = locations[0];
for (int i = 1; i < locations.Length; i++)
{
result = FirstSourceLocation(result, locations[i]);
}
return result;
}
#region Logging Helpers
// Following helpers are used when logging ETW events. These helpers are invoked only if we are running
// under an ETW listener that has requested 'verbose' logging. In other words, these helpers will never
// be invoked in the 'normal' case (i.e. when the code is running on user's machine and no ETW listener
// is involved).
// Note: Most of the below helpers are unused at the moment - but we would like to keep them around in
// case we decide we need more verbose logging in certain cases for debugging.
internal string GetMessage(CompilationStage stage)
{
return string.Format("{0} ({1})", this.AssemblyName, stage.ToString());
}
internal string GetMessage(ITypeSymbol source, ITypeSymbol destination)
{
if (source == null || destination == null) return this.AssemblyName ?? "";
return string.Format("{0}: {1} {2} -> {3} {4}", this.AssemblyName, source.TypeKind.ToString(), source.Name, destination.TypeKind.ToString(), destination.Name);
}
#endregion
#region Declaration Name Queries
/// <summary>
/// Return true if there is a source declaration symbol name that meets given predicate.
/// </summary>
public abstract bool ContainsSymbolsWithName(Func<string, bool> predicate, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return source declaration symbols whose name meets given predicate.
/// </summary>
public abstract IEnumerable<ISymbol> GetSymbolsWithName(Func<string, bool> predicate, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default(CancellationToken));
#pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters
/// <summary>
/// Return true if there is a source declaration symbol name that matches the provided name.
/// This may be faster than <see cref="ContainsSymbolsWithName(Func{string, bool},
/// SymbolFilter, CancellationToken)"/> when predicate is just a simple string check.
/// <paramref name="name"/> is case sensitive or not depending on the target language.
/// </summary>
public abstract bool ContainsSymbolsWithName(string name, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return source declaration symbols whose name matches the provided name. This may be
/// faster than <see cref="GetSymbolsWithName(Func{string, bool}, SymbolFilter,
/// CancellationToken)"/> when predicate is just a simple string check. <paramref
/// name="name"/> is case sensitive or not depending on the target language.
/// </summary>
public abstract IEnumerable<ISymbol> GetSymbolsWithName(string name, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default(CancellationToken));
#pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters
#endregion
internal void MakeMemberMissing(WellKnownMember member)
{
MakeMemberMissing((int)member);
}
internal void MakeMemberMissing(SpecialMember member)
{
MakeMemberMissing(-(int)member - 1);
}
internal bool IsMemberMissing(WellKnownMember member)
{
return IsMemberMissing((int)member);
}
internal bool IsMemberMissing(SpecialMember member)
{
return IsMemberMissing(-(int)member - 1);
}
private void MakeMemberMissing(int member)
{
if (_lazyMakeMemberMissingMap == null)
{
_lazyMakeMemberMissingMap = new SmallDictionary<int, bool>();
}
_lazyMakeMemberMissingMap[member] = true;
}
private bool IsMemberMissing(int member)
{
return _lazyMakeMemberMissingMap != null && _lazyMakeMemberMissingMap.ContainsKey(member);
}
internal void MakeTypeMissing(SpecialType type)
{
MakeTypeMissing((int)type);
}
internal void MakeTypeMissing(WellKnownType type)
{
MakeTypeMissing((int)type);
}
private void MakeTypeMissing(int type)
{
if (_lazyMakeWellKnownTypeMissingMap == null)
{
_lazyMakeWellKnownTypeMissingMap = new SmallDictionary<int, bool>();
}
_lazyMakeWellKnownTypeMissingMap[(int)type] = true;
}
internal bool IsTypeMissing(SpecialType type)
{
return IsTypeMissing((int)type);
}
internal bool IsTypeMissing(WellKnownType type)
{
return IsTypeMissing((int)type);
}
private bool IsTypeMissing(int type)
{
return _lazyMakeWellKnownTypeMissingMap != null && _lazyMakeWellKnownTypeMissingMap.ContainsKey((int)type);
}
/// <summary>
/// Given a <see cref="Diagnostic"/> reporting unreferenced <see cref="AssemblyIdentity"/>s, returns
/// the actual <see cref="AssemblyIdentity"/> instances that were not referenced.
/// </summary>
public ImmutableArray<AssemblyIdentity> GetUnreferencedAssemblyIdentities(Diagnostic diagnostic)
{
if (diagnostic == null)
{
throw new ArgumentNullException(nameof(diagnostic));
}
if (!IsUnreferencedAssemblyIdentityDiagnosticCode(diagnostic.Code))
{
return ImmutableArray<AssemblyIdentity>.Empty;
}
var builder = ArrayBuilder<AssemblyIdentity>.GetInstance();
foreach (var argument in diagnostic.Arguments)
{
if (argument is AssemblyIdentity id)
{
builder.Add(id);
}
}
return builder.ToImmutableAndFree();
}
internal abstract bool IsUnreferencedAssemblyIdentityDiagnosticCode(int code);
/// <summary>
/// Returns the required language version found in a <see cref="Diagnostic"/>, if any is found.
/// Returns null if none is found.
/// </summary>
public static string? GetRequiredLanguageVersion(Diagnostic diagnostic)
{
if (diagnostic == null)
{
throw new ArgumentNullException(nameof(diagnostic));
}
bool found = false;
string? foundVersion = null;
if (diagnostic.Arguments != null)
{
foreach (var argument in diagnostic.Arguments)
{
if (argument is RequiredLanguageVersion versionDiagnostic)
{
Debug.Assert(!found); // only one required language version in a given diagnostic
found = true;
foundVersion = versionDiagnostic.ToString();
}
}
}
return foundVersion;
}
}
}
| 1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Compilers/Core/Portable/Emit/EditAndContinue/DeltaMetadataWriter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Threading;
using Microsoft.Cci;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.Symbols;
namespace Microsoft.CodeAnalysis.Emit
{
internal sealed class DeltaMetadataWriter : MetadataWriter
{
private readonly EmitBaseline _previousGeneration;
private readonly Guid _encId;
private readonly DefinitionMap _definitionMap;
private readonly SymbolChanges _changes;
private readonly List<ITypeDefinition> _updatedTypeDefs;
private readonly DefinitionIndex<ITypeDefinition> _typeDefs;
private readonly DefinitionIndex<IEventDefinition> _eventDefs;
private readonly DefinitionIndex<IFieldDefinition> _fieldDefs;
private readonly DefinitionIndex<IMethodDefinition> _methodDefs;
private readonly DefinitionIndex<IPropertyDefinition> _propertyDefs;
private readonly ParameterDefinitionIndex _parameterDefs;
private readonly List<KeyValuePair<IMethodDefinition, IParameterDefinition>> _parameterDefList;
private readonly GenericParameterIndex _genericParameters;
private readonly EventOrPropertyMapIndex _eventMap;
private readonly EventOrPropertyMapIndex _propertyMap;
private readonly MethodImplIndex _methodImpls;
// For the EncLog table we need to know which things we're emitting custom attributes for so we can
// correctly map the attributes to row numbers of existing attributes for that target
private readonly Dictionary<EntityHandle, int> _customAttributeParentCounts;
// For the EncMap table we need to keep a list of exactly which rows in the CustomAttributes table are updated
// since we spread these out amongst existing rows, it's not just a contiguous set
private readonly List<int> _customAttributeEncMapRows;
// Keep track of which CustomAttributes rows are added in this and previous deltas, over what is in the
// original metadata
private readonly Dictionary<EntityHandle, ImmutableArray<int>> _customAttributesAdded;
private readonly HeapOrReferenceIndex<AssemblyIdentity> _assemblyRefIndex;
private readonly HeapOrReferenceIndex<string> _moduleRefIndex;
private readonly InstanceAndStructuralReferenceIndex<ITypeMemberReference> _memberRefIndex;
private readonly InstanceAndStructuralReferenceIndex<IGenericMethodInstanceReference> _methodSpecIndex;
private readonly TypeReferenceIndex _typeRefIndex;
private readonly InstanceAndStructuralReferenceIndex<ITypeReference> _typeSpecIndex;
private readonly HeapOrReferenceIndex<BlobHandle> _standAloneSignatureIndex;
private readonly Dictionary<IMethodDefinition, AddedOrChangedMethodInfo> _addedOrChangedMethods;
public DeltaMetadataWriter(
EmitContext context,
CommonMessageProvider messageProvider,
EmitBaseline previousGeneration,
Guid encId,
DefinitionMap definitionMap,
SymbolChanges changes,
CancellationToken cancellationToken)
: base(metadata: MakeTablesBuilder(previousGeneration),
debugMetadataOpt: (context.Module.DebugInformationFormat == DebugInformationFormat.PortablePdb) ? new MetadataBuilder() : null,
dynamicAnalysisDataWriterOpt: null,
context: context,
messageProvider: messageProvider,
metadataOnly: false,
deterministic: false,
emitTestCoverageData: false,
cancellationToken: cancellationToken)
{
Debug.Assert(previousGeneration != null);
Debug.Assert(encId != default(Guid));
Debug.Assert(encId != previousGeneration.EncId);
Debug.Assert(context.Module.DebugInformationFormat != DebugInformationFormat.Embedded);
_previousGeneration = previousGeneration;
_encId = encId;
_definitionMap = definitionMap;
_changes = changes;
var sizes = previousGeneration.TableSizes;
_updatedTypeDefs = new List<ITypeDefinition>();
_typeDefs = new DefinitionIndex<ITypeDefinition>(this.TryGetExistingTypeDefIndex, sizes[(int)TableIndex.TypeDef]);
_eventDefs = new DefinitionIndex<IEventDefinition>(this.TryGetExistingEventDefIndex, sizes[(int)TableIndex.Event]);
_fieldDefs = new DefinitionIndex<IFieldDefinition>(this.TryGetExistingFieldDefIndex, sizes[(int)TableIndex.Field]);
_methodDefs = new DefinitionIndex<IMethodDefinition>(this.TryGetExistingMethodDefIndex, sizes[(int)TableIndex.MethodDef]);
_propertyDefs = new DefinitionIndex<IPropertyDefinition>(this.TryGetExistingPropertyDefIndex, sizes[(int)TableIndex.Property]);
_parameterDefs = new ParameterDefinitionIndex(sizes[(int)TableIndex.Param]);
_parameterDefList = new List<KeyValuePair<IMethodDefinition, IParameterDefinition>>();
_genericParameters = new GenericParameterIndex(sizes[(int)TableIndex.GenericParam]);
_eventMap = new EventOrPropertyMapIndex(this.TryGetExistingEventMapIndex, sizes[(int)TableIndex.EventMap]);
_propertyMap = new EventOrPropertyMapIndex(this.TryGetExistingPropertyMapIndex, sizes[(int)TableIndex.PropertyMap]);
_methodImpls = new MethodImplIndex(this, sizes[(int)TableIndex.MethodImpl]);
_customAttributeParentCounts = new Dictionary<EntityHandle, int>();
_customAttributeEncMapRows = new List<int>();
_customAttributesAdded = new Dictionary<EntityHandle, ImmutableArray<int>>();
_assemblyRefIndex = new HeapOrReferenceIndex<AssemblyIdentity>(this, lastRowId: sizes[(int)TableIndex.AssemblyRef]);
_moduleRefIndex = new HeapOrReferenceIndex<string>(this, lastRowId: sizes[(int)TableIndex.ModuleRef]);
_memberRefIndex = new InstanceAndStructuralReferenceIndex<ITypeMemberReference>(this, new MemberRefComparer(this), lastRowId: sizes[(int)TableIndex.MemberRef]);
_methodSpecIndex = new InstanceAndStructuralReferenceIndex<IGenericMethodInstanceReference>(this, new MethodSpecComparer(this), lastRowId: sizes[(int)TableIndex.MethodSpec]);
_typeRefIndex = new TypeReferenceIndex(this, lastRowId: sizes[(int)TableIndex.TypeRef]);
_typeSpecIndex = new InstanceAndStructuralReferenceIndex<ITypeReference>(this, new TypeSpecComparer(this), lastRowId: sizes[(int)TableIndex.TypeSpec]);
_standAloneSignatureIndex = new HeapOrReferenceIndex<BlobHandle>(this, lastRowId: sizes[(int)TableIndex.StandAloneSig]);
_addedOrChangedMethods = new Dictionary<IMethodDefinition, AddedOrChangedMethodInfo>(Cci.SymbolEquivalentEqualityComparer.Instance);
}
private static MetadataBuilder MakeTablesBuilder(EmitBaseline previousGeneration)
{
return new MetadataBuilder(
previousGeneration.UserStringStreamLength,
previousGeneration.StringStreamLength,
previousGeneration.BlobStreamLength,
previousGeneration.GuidStreamLength);
}
private ImmutableArray<int> GetDeltaTableSizes(ImmutableArray<int> rowCounts)
{
var sizes = new int[MetadataTokens.TableCount];
rowCounts.CopyTo(sizes);
sizes[(int)TableIndex.TypeRef] = _typeRefIndex.Rows.Count;
sizes[(int)TableIndex.TypeDef] = _typeDefs.GetAdded().Count;
sizes[(int)TableIndex.Field] = _fieldDefs.GetAdded().Count;
sizes[(int)TableIndex.MethodDef] = _methodDefs.GetAdded().Count;
sizes[(int)TableIndex.Param] = _parameterDefs.GetAdded().Count;
sizes[(int)TableIndex.MemberRef] = _memberRefIndex.Rows.Count;
sizes[(int)TableIndex.StandAloneSig] = _standAloneSignatureIndex.Rows.Count;
sizes[(int)TableIndex.EventMap] = _eventMap.GetAdded().Count;
sizes[(int)TableIndex.Event] = _eventDefs.GetAdded().Count;
sizes[(int)TableIndex.PropertyMap] = _propertyMap.GetAdded().Count;
sizes[(int)TableIndex.Property] = _propertyDefs.GetAdded().Count;
sizes[(int)TableIndex.MethodImpl] = _methodImpls.GetAdded().Count;
sizes[(int)TableIndex.ModuleRef] = _moduleRefIndex.Rows.Count;
sizes[(int)TableIndex.TypeSpec] = _typeSpecIndex.Rows.Count;
sizes[(int)TableIndex.AssemblyRef] = _assemblyRefIndex.Rows.Count;
sizes[(int)TableIndex.GenericParam] = _genericParameters.GetAdded().Count;
sizes[(int)TableIndex.MethodSpec] = _methodSpecIndex.Rows.Count;
return ImmutableArray.Create(sizes);
}
internal EmitBaseline GetDelta(Compilation compilation, Guid encId, MetadataSizes metadataSizes)
{
var addedOrChangedMethodsByIndex = new Dictionary<int, AddedOrChangedMethodInfo>();
foreach (var pair in _addedOrChangedMethods)
{
addedOrChangedMethodsByIndex.Add(MetadataTokens.GetRowNumber(GetMethodDefinitionHandle(pair.Key)), pair.Value);
}
var previousTableSizes = _previousGeneration.TableEntriesAdded;
var deltaTableSizes = GetDeltaTableSizes(metadataSizes.RowCounts);
var tableSizes = new int[MetadataTokens.TableCount];
for (int i = 0; i < tableSizes.Length; i++)
{
tableSizes[i] = previousTableSizes[i] + deltaTableSizes[i];
}
// If the previous generation is 0 (metadata) get the synthesized members from the current compilation's builder,
// otherwise members from the current compilation have already been merged into the baseline.
var synthesizedMembers = (_previousGeneration.Ordinal == 0) ? module.GetAllSynthesizedMembers() : _previousGeneration.SynthesizedMembers;
var currentGenerationOrdinal = _previousGeneration.Ordinal + 1;
var addedTypes = _typeDefs.GetAdded();
var generationOrdinals = CreateDictionary(_previousGeneration.GenerationOrdinals, SymbolEquivalentEqualityComparer.Instance);
foreach (var (addedType, _) in addedTypes)
{
if (_changes.IsReplaced(addedType))
{
generationOrdinals[addedType] = currentGenerationOrdinal;
}
}
return _previousGeneration.With(
compilation,
module,
currentGenerationOrdinal,
encId,
generationOrdinals,
typesAdded: AddRange(_previousGeneration.TypesAdded, addedTypes, comparer: SymbolEquivalentEqualityComparer.Instance),
eventsAdded: AddRange(_previousGeneration.EventsAdded, _eventDefs.GetAdded(), comparer: SymbolEquivalentEqualityComparer.Instance),
fieldsAdded: AddRange(_previousGeneration.FieldsAdded, _fieldDefs.GetAdded(), comparer: SymbolEquivalentEqualityComparer.Instance),
methodsAdded: AddRange(_previousGeneration.MethodsAdded, _methodDefs.GetAdded(), comparer: SymbolEquivalentEqualityComparer.Instance),
propertiesAdded: AddRange(_previousGeneration.PropertiesAdded, _propertyDefs.GetAdded(), comparer: SymbolEquivalentEqualityComparer.Instance),
eventMapAdded: AddRange(_previousGeneration.EventMapAdded, _eventMap.GetAdded()),
propertyMapAdded: AddRange(_previousGeneration.PropertyMapAdded, _propertyMap.GetAdded()),
methodImplsAdded: AddRange(_previousGeneration.MethodImplsAdded, _methodImpls.GetAdded()),
customAttributesAdded: AddRange(_previousGeneration.CustomAttributesAdded, _customAttributesAdded),
tableEntriesAdded: ImmutableArray.Create(tableSizes),
// Blob stream is concatenated aligned.
blobStreamLengthAdded: metadataSizes.GetAlignedHeapSize(HeapIndex.Blob) + _previousGeneration.BlobStreamLengthAdded,
// String stream is concatenated unaligned.
stringStreamLengthAdded: metadataSizes.HeapSizes[(int)HeapIndex.String] + _previousGeneration.StringStreamLengthAdded,
// UserString stream is concatenated aligned.
userStringStreamLengthAdded: metadataSizes.GetAlignedHeapSize(HeapIndex.UserString) + _previousGeneration.UserStringStreamLengthAdded,
// Guid stream accumulates on the GUID heap unlike other heaps, so the previous generations are already included.
guidStreamLengthAdded: metadataSizes.HeapSizes[(int)HeapIndex.Guid],
anonymousTypeMap: ((IPEDeltaAssemblyBuilder)module).GetAnonymousTypeMap(),
synthesizedMembers: synthesizedMembers,
addedOrChangedMethods: AddRange(_previousGeneration.AddedOrChangedMethods, addedOrChangedMethodsByIndex),
debugInformationProvider: _previousGeneration.DebugInformationProvider,
localSignatureProvider: _previousGeneration.LocalSignatureProvider);
}
private static Dictionary<K, V> CreateDictionary<K, V>(IReadOnlyDictionary<K, V> dictionary, IEqualityComparer<K>? comparer)
where K : notnull
{
var result = new Dictionary<K, V>(comparer);
foreach (var pair in dictionary)
{
result.Add(pair.Key, pair.Value);
}
return result;
}
private static IReadOnlyDictionary<K, V> AddRange<K, V>(IReadOnlyDictionary<K, V> previous, IReadOnlyDictionary<K, V> current, IEqualityComparer<K>? comparer = null)
where K : notnull
{
if (previous.Count == 0)
{
return current;
}
if (current.Count == 0)
{
return previous;
}
var result = CreateDictionary(previous, comparer);
foreach (var pair in current)
{
// Use the latest symbol.
result[pair.Key] = pair.Value;
}
return result;
}
/// <summary>
/// Return tokens for all modified debuggable methods.
/// </summary>
public void GetUpdatedMethodTokens(ArrayBuilder<MethodDefinitionHandle> methods)
{
foreach (var def in _methodDefs.GetRows())
{
// The debugger tries to remap all modified methods, which requires presence of sequence points.
if (!_methodDefs.IsAddedNotChanged(def) && def.GetBody(Context)?.SequencePoints.Length > 0)
{
methods.Add(MetadataTokens.MethodDefinitionHandle(_methodDefs[def]));
}
}
}
/// <summary>
/// Return tokens for all modified debuggable types.
/// </summary>
public void GetUpdatedTypeTokens(ArrayBuilder<TypeDefinitionHandle> types)
{
foreach (var def in _updatedTypeDefs)
{
types.Add(MetadataTokens.TypeDefinitionHandle(_typeDefs[def]));
}
}
protected override ushort Generation
{
get { return (ushort)(_previousGeneration.Ordinal + 1); }
}
protected override Guid EncId
{
get { return _encId; }
}
protected override Guid EncBaseId
{
get { return _previousGeneration.EncId; }
}
protected override EventDefinitionHandle GetEventDefinitionHandle(IEventDefinition def)
{
return MetadataTokens.EventDefinitionHandle(_eventDefs[def]);
}
protected override IReadOnlyList<IEventDefinition> GetEventDefs()
{
return _eventDefs.GetRows();
}
protected override FieldDefinitionHandle GetFieldDefinitionHandle(IFieldDefinition def)
{
return MetadataTokens.FieldDefinitionHandle(_fieldDefs[def]);
}
protected override IReadOnlyList<IFieldDefinition> GetFieldDefs()
{
return _fieldDefs.GetRows();
}
protected override bool TryGetTypeDefinitionHandle(ITypeDefinition def, out TypeDefinitionHandle handle)
{
int index;
bool result = _typeDefs.TryGetValue(def, out index);
handle = MetadataTokens.TypeDefinitionHandle(index);
return result;
}
protected override TypeDefinitionHandle GetTypeDefinitionHandle(ITypeDefinition def)
{
return MetadataTokens.TypeDefinitionHandle(_typeDefs[def]);
}
protected override ITypeDefinition GetTypeDef(TypeDefinitionHandle handle)
{
return _typeDefs[MetadataTokens.GetRowNumber(handle)];
}
protected override IReadOnlyList<ITypeDefinition> GetTypeDefs()
{
return _typeDefs.GetRows();
}
protected override bool TryGetMethodDefinitionHandle(IMethodDefinition def, out MethodDefinitionHandle handle)
{
int index;
bool result = _methodDefs.TryGetValue(def, out index);
handle = MetadataTokens.MethodDefinitionHandle(index);
return result;
}
protected override MethodDefinitionHandle GetMethodDefinitionHandle(IMethodDefinition def)
=> MetadataTokens.MethodDefinitionHandle(_methodDefs[def]);
protected override IMethodDefinition GetMethodDef(MethodDefinitionHandle index)
=> _methodDefs[MetadataTokens.GetRowNumber(index)];
protected override IReadOnlyList<IMethodDefinition> GetMethodDefs()
=> _methodDefs.GetRows();
protected override PropertyDefinitionHandle GetPropertyDefIndex(IPropertyDefinition def)
=> MetadataTokens.PropertyDefinitionHandle(_propertyDefs[def]);
protected override IReadOnlyList<IPropertyDefinition> GetPropertyDefs()
=> _propertyDefs.GetRows();
protected override ParameterHandle GetParameterHandle(IParameterDefinition def)
=> MetadataTokens.ParameterHandle(_parameterDefs[def]);
protected override IReadOnlyList<IParameterDefinition> GetParameterDefs()
=> _parameterDefs.GetRows();
protected override IReadOnlyList<IGenericParameter> GetGenericParameters()
=> _genericParameters.GetRows();
// Fields are associated with the type through the EncLog table.
protected override FieldDefinitionHandle GetFirstFieldDefinitionHandle(INamedTypeDefinition typeDef)
=> default;
// Methods are associated with the type through the EncLog table.
protected override MethodDefinitionHandle GetFirstMethodDefinitionHandle(INamedTypeDefinition typeDef)
=> default;
// Parameters are associated with the method through the EncLog table.
protected override ParameterHandle GetFirstParameterHandle(IMethodDefinition methodDef)
=> default;
protected override AssemblyReferenceHandle GetOrAddAssemblyReferenceHandle(IAssemblyReference reference)
{
var identity = reference.Identity;
var versionPattern = reference.AssemblyVersionPattern;
if (versionPattern is not null)
{
RoslynDebug.AssertNotNull(_previousGeneration.InitialBaseline.LazyMetadataSymbols);
identity = _previousGeneration.InitialBaseline.LazyMetadataSymbols.AssemblyReferenceIdentityMap[identity.WithVersion(versionPattern)];
}
return MetadataTokens.AssemblyReferenceHandle(_assemblyRefIndex.GetOrAdd(identity));
}
protected override IReadOnlyList<AssemblyIdentity> GetAssemblyRefs()
{
return _assemblyRefIndex.Rows;
}
protected override ModuleReferenceHandle GetOrAddModuleReferenceHandle(string reference)
{
return MetadataTokens.ModuleReferenceHandle(_moduleRefIndex.GetOrAdd(reference));
}
protected override IReadOnlyList<string> GetModuleRefs()
{
return _moduleRefIndex.Rows;
}
protected override MemberReferenceHandle GetOrAddMemberReferenceHandle(ITypeMemberReference reference)
{
return MetadataTokens.MemberReferenceHandle(_memberRefIndex.GetOrAdd(reference));
}
protected override IReadOnlyList<ITypeMemberReference> GetMemberRefs()
{
return _memberRefIndex.Rows;
}
protected override MethodSpecificationHandle GetOrAddMethodSpecificationHandle(IGenericMethodInstanceReference reference)
{
return MetadataTokens.MethodSpecificationHandle(_methodSpecIndex.GetOrAdd(reference));
}
protected override IReadOnlyList<IGenericMethodInstanceReference> GetMethodSpecs()
{
return _methodSpecIndex.Rows;
}
protected override int GreatestMethodDefIndex => _methodDefs.NextRowId;
protected override bool TryGetTypeReferenceHandle(ITypeReference reference, out TypeReferenceHandle handle)
{
int index;
bool result = _typeRefIndex.TryGetValue(reference, out index);
handle = MetadataTokens.TypeReferenceHandle(index);
return result;
}
protected override TypeReferenceHandle GetOrAddTypeReferenceHandle(ITypeReference reference)
{
return MetadataTokens.TypeReferenceHandle(_typeRefIndex.GetOrAdd(reference));
}
protected override IReadOnlyList<ITypeReference> GetTypeRefs()
{
return _typeRefIndex.Rows;
}
protected override TypeSpecificationHandle GetOrAddTypeSpecificationHandle(ITypeReference reference)
{
return MetadataTokens.TypeSpecificationHandle(_typeSpecIndex.GetOrAdd(reference));
}
protected override IReadOnlyList<ITypeReference> GetTypeSpecs()
{
return _typeSpecIndex.Rows;
}
protected override StandaloneSignatureHandle GetOrAddStandaloneSignatureHandle(BlobHandle blobIndex)
{
return MetadataTokens.StandaloneSignatureHandle(_standAloneSignatureIndex.GetOrAdd(blobIndex));
}
protected override IReadOnlyList<BlobHandle> GetStandaloneSignatureBlobHandles()
{
return _standAloneSignatureIndex.Rows;
}
protected override void OnIndicesCreated()
{
var module = (IPEDeltaAssemblyBuilder)this.module;
module.OnCreatedIndices(this.Context.Diagnostics);
}
protected override void CreateIndicesForNonTypeMembers(ITypeDefinition typeDef)
{
var change = _changes.GetChange(typeDef);
switch (change)
{
case SymbolChange.Added:
_typeDefs.Add(typeDef);
var typeParameters = this.GetConsolidatedTypeParameters(typeDef);
if (typeParameters != null)
{
foreach (var typeParameter in typeParameters)
{
_genericParameters.Add(typeParameter);
}
}
break;
case SymbolChange.Updated:
_typeDefs.AddUpdated(typeDef);
_updatedTypeDefs.Add(typeDef);
break;
case SymbolChange.ContainsChanges:
// Members changed.
// We keep this list separately because we don't want to output duplicate typedef entries in the EnC log,
// which uses _typeDefs, but it's simpler to let the members output those rows for the updated typedefs
// with the right update type.
_updatedTypeDefs.Add(typeDef);
break;
case SymbolChange.None:
// No changes to type.
return;
default:
throw ExceptionUtilities.UnexpectedValue(change);
}
int typeIndex;
var ok = _typeDefs.TryGetValue(typeDef, out typeIndex);
Debug.Assert(ok);
foreach (var eventDef in typeDef.GetEvents(this.Context))
{
int eventMapIndex;
if (!_eventMap.TryGetValue(typeIndex, out eventMapIndex))
{
_eventMap.Add(typeIndex);
}
this.AddDefIfNecessary(_eventDefs, eventDef);
}
foreach (var fieldDef in typeDef.GetFields(this.Context))
{
this.AddDefIfNecessary(_fieldDefs, fieldDef);
}
foreach (var methodDef in typeDef.GetMethods(this.Context))
{
if (this.AddDefIfNecessary(_methodDefs, methodDef))
{
foreach (var paramDef in this.GetParametersToEmit(methodDef))
{
_parameterDefs.Add(paramDef);
_parameterDefList.Add(KeyValuePairUtil.Create(methodDef, paramDef));
}
if (methodDef.GenericParameterCount > 0)
{
foreach (var typeParameter in methodDef.GenericParameters)
{
_genericParameters.Add(typeParameter);
}
}
}
}
foreach (var propertyDef in typeDef.GetProperties(this.Context))
{
int propertyMapIndex;
if (!_propertyMap.TryGetValue(typeIndex, out propertyMapIndex))
{
_propertyMap.Add(typeIndex);
}
this.AddDefIfNecessary(_propertyDefs, propertyDef);
}
var implementingMethods = ArrayBuilder<int>.GetInstance();
// First, visit all MethodImplementations and add to this.methodImplList.
foreach (var methodImpl in typeDef.GetExplicitImplementationOverrides(Context))
{
var methodDef = (IMethodDefinition?)methodImpl.ImplementingMethod.AsDefinition(this.Context);
RoslynDebug.AssertNotNull(methodDef);
int methodDefIndex;
ok = _methodDefs.TryGetValue(methodDef, out methodDefIndex);
Debug.Assert(ok);
// If there are N existing MethodImpl entries for this MethodDef,
// those will be index:1, ..., index:N, so it's sufficient to check for index:1.
int methodImplIndex;
var key = new MethodImplKey(methodDefIndex, index: 1);
if (!_methodImpls.TryGetValue(key, out methodImplIndex))
{
implementingMethods.Add(methodDefIndex);
this.methodImplList.Add(methodImpl);
}
}
// Next, add placeholders to this.methodImpls for items added above.
foreach (var methodDefIndex in implementingMethods)
{
int index = 1;
while (true)
{
int methodImplIndex;
var key = new MethodImplKey(methodDefIndex, index);
if (!_methodImpls.TryGetValue(key, out methodImplIndex))
{
_methodImpls.Add(key);
break;
}
index++;
}
}
implementingMethods.Free();
}
private bool AddDefIfNecessary<T>(DefinitionIndex<T> defIndex, T def)
where T : class, IDefinition
{
switch (_changes.GetChange(def))
{
case SymbolChange.Added:
defIndex.Add(def);
return true;
case SymbolChange.Updated:
defIndex.AddUpdated(def);
return false;
case SymbolChange.ContainsChanges:
Debug.Assert(def is INestedTypeDefinition);
// Changes to members within nested type only.
return false;
default:
// No changes to member or container.
return false;
}
}
protected override ReferenceIndexer CreateReferenceVisitor()
{
return new DeltaReferenceIndexer(this);
}
protected override void ReportReferencesToAddedSymbols()
{
foreach (var typeRef in GetTypeRefs())
{
ReportReferencesToAddedSymbol(typeRef.GetInternalSymbol());
}
foreach (var memberRef in GetMemberRefs())
{
ReportReferencesToAddedSymbol(memberRef.GetInternalSymbol());
}
}
private void ReportReferencesToAddedSymbol(ISymbolInternal? symbol)
{
if (symbol != null && _changes.IsAdded(symbol.GetISymbol()))
{
Context.Diagnostics.Add(messageProvider.CreateDiagnostic(
messageProvider.ERR_EncReferenceToAddedMember,
GetSymbolLocation(symbol),
symbol.Name,
symbol.ContainingAssembly.Name));
}
}
protected override StandaloneSignatureHandle SerializeLocalVariablesSignature(IMethodBody body)
{
StandaloneSignatureHandle localSignatureHandle;
var localVariables = body.LocalVariables;
var encInfos = ArrayBuilder<EncLocalInfo>.GetInstance();
if (localVariables.Length > 0)
{
var writer = PooledBlobBuilder.GetInstance();
var encoder = new BlobEncoder(writer).LocalVariableSignature(localVariables.Length);
foreach (ILocalDefinition local in localVariables)
{
var signature = local.Signature;
if (signature == null)
{
int start = writer.Count;
SerializeLocalVariableType(encoder.AddVariable(), local);
signature = writer.ToArray(start, writer.Count - start);
}
else
{
writer.WriteBytes(signature);
}
encInfos.Add(CreateEncLocalInfo(local, signature));
}
BlobHandle blobIndex = metadata.GetOrAddBlob(writer);
localSignatureHandle = GetOrAddStandaloneSignatureHandle(blobIndex);
writer.Free();
}
else
{
localSignatureHandle = default;
}
var info = new AddedOrChangedMethodInfo(
body.MethodId,
encInfos.ToImmutable(),
body.LambdaDebugInfo,
body.ClosureDebugInfo,
body.StateMachineTypeName,
body.StateMachineHoistedLocalSlots,
body.StateMachineAwaiterSlots);
_addedOrChangedMethods.Add(body.MethodDefinition, info);
encInfos.Free();
return localSignatureHandle;
}
private EncLocalInfo CreateEncLocalInfo(ILocalDefinition localDef, byte[] signature)
{
if (localDef.SlotInfo.Id.IsNone)
{
return new EncLocalInfo(signature);
}
// local type is already translated, but not recursively
ITypeReference translatedType = localDef.Type;
if (translatedType.GetInternalSymbol() is ITypeSymbolInternal typeSymbol)
{
translatedType = Context.Module.EncTranslateType(typeSymbol, Context.Diagnostics);
}
return new EncLocalInfo(localDef.SlotInfo, translatedType, localDef.Constraints, signature);
}
protected override int AddCustomAttributesToTable(EntityHandle parentHandle, IEnumerable<ICustomAttribute> attributes)
{
// The base class will write out the actual metadata for us
var numAttributesEmitted = base.AddCustomAttributesToTable(parentHandle, attributes);
// We need to keep track of all of the things attributes could be associated with in this delta, in order to populate the EncLog and Map tables
_customAttributeParentCounts.Add(parentHandle, numAttributesEmitted);
return numAttributesEmitted;
}
protected override void PopulateEncLogTableRows(ImmutableArray<int> rowCounts)
{
// The EncLog table is a log of all the operations needed
// to update the previous metadata. That means all
// new references must be added to the EncLog.
var previousSizes = _previousGeneration.TableSizes;
var deltaSizes = this.GetDeltaTableSizes(rowCounts);
PopulateEncLogTableRows(TableIndex.AssemblyRef, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.ModuleRef, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.MemberRef, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.MethodSpec, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.TypeRef, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.TypeSpec, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.StandAloneSig, previousSizes, deltaSizes);
PopulateEncLogTableRows(_typeDefs, TableIndex.TypeDef);
PopulateEncLogTableRows(TableIndex.EventMap, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.PropertyMap, previousSizes, deltaSizes);
PopulateEncLogTableEventsOrProperties(_eventDefs, TableIndex.Event, EditAndContinueOperation.AddEvent, _eventMap, TableIndex.EventMap);
PopulateEncLogTableFieldsOrMethods(_fieldDefs, TableIndex.Field, EditAndContinueOperation.AddField);
PopulateEncLogTableFieldsOrMethods(_methodDefs, TableIndex.MethodDef, EditAndContinueOperation.AddMethod);
PopulateEncLogTableEventsOrProperties(_propertyDefs, TableIndex.Property, EditAndContinueOperation.AddProperty, _propertyMap, TableIndex.PropertyMap);
PopulateEncLogTableParameters();
PopulateEncLogTableRows(TableIndex.Constant, previousSizes, deltaSizes);
PopulateEncLogTableCustomAttributes();
PopulateEncLogTableRows(TableIndex.DeclSecurity, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.ClassLayout, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.FieldLayout, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.MethodSemantics, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.MethodImpl, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.ImplMap, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.FieldRva, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.NestedClass, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.GenericParam, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.InterfaceImpl, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.GenericParamConstraint, previousSizes, deltaSizes);
}
private void PopulateEncLogTableEventsOrProperties<T>(
DefinitionIndex<T> index,
TableIndex table,
EditAndContinueOperation addCode,
EventOrPropertyMapIndex map,
TableIndex mapTable)
where T : class, ITypeDefinitionMember
{
foreach (var member in index.GetRows())
{
if (index.IsAddedNotChanged(member))
{
int typeIndex = _typeDefs[member.ContainingTypeDefinition];
Debug.Assert(typeIndex > 0);
int mapRowId;
var ok = map.TryGetValue(typeIndex, out mapRowId);
Debug.Assert(ok);
metadata.AddEncLogEntry(
entity: MetadataTokens.Handle(mapTable, mapRowId),
code: addCode);
}
metadata.AddEncLogEntry(
entity: MetadataTokens.Handle(table, index[member]),
code: EditAndContinueOperation.Default);
}
}
private void PopulateEncLogTableFieldsOrMethods<T>(
DefinitionIndex<T> index,
TableIndex tableIndex,
EditAndContinueOperation addCode)
where T : class, ITypeDefinitionMember
{
foreach (var member in index.GetRows())
{
if (index.IsAddedNotChanged(member))
{
metadata.AddEncLogEntry(
entity: MetadataTokens.TypeDefinitionHandle(_typeDefs[(INamedTypeDefinition)member.ContainingTypeDefinition]),
code: addCode);
}
metadata.AddEncLogEntry(
entity: MetadataTokens.Handle(tableIndex, index[member]),
code: EditAndContinueOperation.Default);
}
}
private void PopulateEncLogTableParameters()
{
var parameterFirstId = _parameterDefs.FirstRowId;
for (int i = 0; i < _parameterDefList.Count; i++)
{
var methodDef = _parameterDefList[i].Key;
metadata.AddEncLogEntry(
entity: MetadataTokens.MethodDefinitionHandle(_methodDefs[methodDef]),
code: EditAndContinueOperation.AddParameter);
metadata.AddEncLogEntry(
entity: MetadataTokens.ParameterHandle(parameterFirstId + i),
code: EditAndContinueOperation.Default);
}
}
/// <summary>
/// CustomAttributes point to their target via the Parent column so we cannot simply output new rows
/// in the delta or we would end up with duplicates, but we also don't want to do complex logic to determine
/// which attributes have changes, so we just emit them all.
/// This means our logic for emitting CustomAttributes is to update any existing rows, either from the original
/// compilation or subsequent deltas, and only add more if we need to. The EncLog table is the thing that tells
/// the runtime which row a CustomAttributes row is (ie, new or existing)
/// </summary>
private void PopulateEncLogTableCustomAttributes()
{
// List of attributes that need to be emitted to delete a previously emitted attribute
var deletedAttributeRows = new List<(int parentRowId, HandleKind kind)>();
var customAttributesAdded = new Dictionary<EntityHandle, ArrayBuilder<int>>();
// The data in _previousGeneration.CustomAttributesAdded is not nicely sorted, or even necessarily contiguous
// so we need to map each target onto the rows its attributes occupy so we know which rows to update
var lastRowId = _previousGeneration.OriginalMetadata.MetadataReader.GetTableRowCount(TableIndex.CustomAttribute);
if (_previousGeneration.CustomAttributesAdded.Count > 0)
{
lastRowId = _previousGeneration.CustomAttributesAdded.SelectMany(s => s.Value).Max();
}
// Iterate through the parents we emitted custom attributes for, in parent order
foreach (var (parent, count) in _customAttributeParentCounts.OrderBy(kvp => CodedIndex.HasCustomAttribute(kvp.Key)))
{
int index = 0;
// First we try to update any existing attributes.
// GetCustomAttributes does a binary search, so is fast. We presume that the number of rows in the original metadata
// greatly outnumbers the amount of parents emitted in this delta so even with repeated searches this is still
// quicker than iterating the entire original table, even once.
var existingCustomAttributes = _previousGeneration.OriginalMetadata.MetadataReader.GetCustomAttributes(parent);
foreach (var attributeHandle in existingCustomAttributes)
{
int rowId = MetadataTokens.GetRowNumber(attributeHandle);
AddLogEntryOrDelete(rowId, parent, add: index < count);
index++;
}
// If we emitted any attributes for this parent in previous deltas then we either need to update
// them next, or delete them if necessary
if (_previousGeneration.CustomAttributesAdded.TryGetValue(parent, out var rowIds))
{
foreach (var rowId in rowIds)
{
TrackCustomAttributeAdded(rowId, parent);
AddLogEntryOrDelete(rowId, parent, add: index < count);
index++;
}
}
// Finally if there are still attributes for this parent left, they are additions new to this delta
for (int i = index; i < count; i++)
{
lastRowId++;
TrackCustomAttributeAdded(lastRowId, parent);
AddEncLogEntry(lastRowId);
}
}
// Save the attributes we've emitted, and the ones from previous deltas, for use in the next generation
foreach (var (parent, rowIds) in customAttributesAdded)
{
_customAttributesAdded.Add(parent, rowIds.ToImmutableAndFree());
}
// Add attributes and log entries for everything we've deleted
foreach (var row in deletedAttributeRows)
{
// now emit a "delete" row with a parent that is for the 0 row of the same table as the existing one
if (!MetadataTokens.TryGetTableIndex(row.kind, out var tableIndex))
{
throw new InvalidOperationException("Trying to delete a custom attribute for a parent kind that doesn't have a matching table index.");
}
metadata.AddCustomAttribute(MetadataTokens.Handle(tableIndex, 0), MetadataTokens.EntityHandle(TableIndex.MemberRef, 0), value: default);
AddEncLogEntry(row.parentRowId);
}
void AddEncLogEntry(int rowId)
{
_customAttributeEncMapRows.Add(rowId);
metadata.AddEncLogEntry(
entity: MetadataTokens.CustomAttributeHandle(rowId),
code: EditAndContinueOperation.Default);
}
void AddLogEntryOrDelete(int rowId, EntityHandle parent, bool add)
{
if (add)
{
// Update this row
AddEncLogEntry(rowId);
}
else
{
// Delete this row
deletedAttributeRows.Add((rowId, parent.Kind));
}
}
void TrackCustomAttributeAdded(int nextRowId, EntityHandle parent)
{
if (!customAttributesAdded.TryGetValue(parent, out var existing))
{
existing = ArrayBuilder<int>.GetInstance();
customAttributesAdded.Add(parent, existing);
}
existing.Add(nextRowId);
}
}
private void PopulateEncLogTableRows<T>(DefinitionIndex<T> index, TableIndex tableIndex)
where T : class, IDefinition
{
foreach (var member in index.GetRows())
{
metadata.AddEncLogEntry(
entity: MetadataTokens.Handle(tableIndex, index[member]),
code: EditAndContinueOperation.Default);
}
}
private void PopulateEncLogTableRows(TableIndex tableIndex, ImmutableArray<int> previousSizes, ImmutableArray<int> deltaSizes)
{
PopulateEncLogTableRows(tableIndex, previousSizes[(int)tableIndex] + 1, deltaSizes[(int)tableIndex]);
}
private void PopulateEncLogTableRows(TableIndex tableIndex, int firstRowId, int tokenCount)
{
for (int i = 0; i < tokenCount; i++)
{
metadata.AddEncLogEntry(
entity: MetadataTokens.Handle(tableIndex, firstRowId + i),
code: EditAndContinueOperation.Default);
}
}
protected override void PopulateEncMapTableRows(ImmutableArray<int> rowCounts)
{
// The EncMap table maps from offset in each table in the delta
// metadata to token. As such, the EncMap is a concatenated
// list of all tokens in all tables from the delta sorted by table
// and, within each table, sorted by row.
var tokens = ArrayBuilder<EntityHandle>.GetInstance();
var previousSizes = _previousGeneration.TableSizes;
var deltaSizes = this.GetDeltaTableSizes(rowCounts);
AddReferencedTokens(tokens, TableIndex.AssemblyRef, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.ModuleRef, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.MemberRef, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.MethodSpec, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.TypeRef, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.TypeSpec, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.StandAloneSig, previousSizes, deltaSizes);
AddDefinitionTokens(tokens, _typeDefs, TableIndex.TypeDef);
AddDefinitionTokens(tokens, _eventDefs, TableIndex.Event);
AddDefinitionTokens(tokens, _fieldDefs, TableIndex.Field);
AddDefinitionTokens(tokens, _methodDefs, TableIndex.MethodDef);
AddDefinitionTokens(tokens, _propertyDefs, TableIndex.Property);
AddReferencedTokens(tokens, TableIndex.Param, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.Constant, previousSizes, deltaSizes);
AddRowNumberTokens(tokens, _customAttributeEncMapRows, TableIndex.CustomAttribute);
AddReferencedTokens(tokens, TableIndex.DeclSecurity, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.ClassLayout, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.FieldLayout, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.EventMap, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.PropertyMap, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.MethodSemantics, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.MethodImpl, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.ImplMap, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.FieldRva, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.NestedClass, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.GenericParam, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.InterfaceImpl, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.GenericParamConstraint, previousSizes, deltaSizes);
tokens.Sort(HandleComparer.Default);
// Should not be any duplicates.
Debug.Assert(tokens.Distinct().Count() == tokens.Count);
foreach (var token in tokens)
{
metadata.AddEncMapEntry(token);
}
tokens.Free();
// Populate Portable PDB EncMap table with MethodDebugInformation mapping,
// which corresponds 1:1 to MethodDef mapping.
if (_debugMetadataOpt != null)
{
var debugTokens = ArrayBuilder<EntityHandle>.GetInstance();
AddDefinitionTokens(debugTokens, _methodDefs, TableIndex.MethodDebugInformation);
debugTokens.Sort(HandleComparer.Default);
// Should not be any duplicates.
Debug.Assert(debugTokens.Distinct().Count() == debugTokens.Count);
foreach (var token in debugTokens)
{
_debugMetadataOpt.AddEncMapEntry(token);
}
debugTokens.Free();
}
#if DEBUG
// The following tables are either represented in the EncMap
// or specifically ignored. The rest should be empty.
var handledTables = new TableIndex[]
{
TableIndex.Module,
TableIndex.TypeRef,
TableIndex.TypeDef,
TableIndex.Field,
TableIndex.MethodDef,
TableIndex.Param,
TableIndex.MemberRef,
TableIndex.Constant,
TableIndex.CustomAttribute,
TableIndex.DeclSecurity,
TableIndex.ClassLayout,
TableIndex.FieldLayout,
TableIndex.StandAloneSig,
TableIndex.EventMap,
TableIndex.Event,
TableIndex.PropertyMap,
TableIndex.Property,
TableIndex.MethodSemantics,
TableIndex.MethodImpl,
TableIndex.ModuleRef,
TableIndex.TypeSpec,
TableIndex.ImplMap,
// FieldRva is not needed since we only emit fields with explicit mapping
// for <PrivateImplementationDetails> and that class is not used in ENC.
// If we need FieldRva in the future, we'll need a corresponding test.
// (See EditAndContinueTests.FieldRva that was deleted in this change.)
//TableIndex.FieldRva,
TableIndex.EncLog,
TableIndex.EncMap,
TableIndex.Assembly,
TableIndex.AssemblyRef,
TableIndex.MethodSpec,
TableIndex.NestedClass,
TableIndex.GenericParam,
TableIndex.InterfaceImpl,
TableIndex.GenericParamConstraint,
};
for (int i = 0; i < rowCounts.Length; i++)
{
if (handledTables.Contains((TableIndex)i))
{
continue;
}
Debug.Assert(rowCounts[i] == 0);
}
#endif
}
private static void AddReferencedTokens(
ArrayBuilder<EntityHandle> builder,
TableIndex tableIndex,
ImmutableArray<int> previousSizes,
ImmutableArray<int> deltaSizes)
{
AddReferencedTokens(builder, tableIndex, previousSizes[(int)tableIndex] + 1, deltaSizes[(int)tableIndex]);
}
private static void AddReferencedTokens(ArrayBuilder<EntityHandle> builder, TableIndex tableIndex, int firstRowId, int nTokens)
{
for (int i = 0; i < nTokens; i++)
{
builder.Add(MetadataTokens.Handle(tableIndex, firstRowId + i));
}
}
private static void AddDefinitionTokens<T>(ArrayBuilder<EntityHandle> tokens, DefinitionIndex<T> index, TableIndex tableIndex)
where T : class, IDefinition
{
foreach (var member in index.GetRows())
{
tokens.Add(MetadataTokens.Handle(tableIndex, index[member]));
}
}
private static void AddRowNumberTokens(ArrayBuilder<EntityHandle> tokens, IEnumerable<int> rowNumbers, TableIndex tableIndex)
{
foreach (var row in rowNumbers)
{
tokens.Add(MetadataTokens.Handle(tableIndex, row));
}
}
protected override void PopulateEventMapTableRows()
{
foreach (var typeId in _eventMap.GetRows())
{
metadata.AddEventMap(
declaringType: MetadataTokens.TypeDefinitionHandle(typeId),
eventList: MetadataTokens.EventDefinitionHandle(_eventMap[typeId]));
}
}
protected override void PopulatePropertyMapTableRows()
{
foreach (var typeId in _propertyMap.GetRows())
{
metadata.AddPropertyMap(
declaringType: MetadataTokens.TypeDefinitionHandle(typeId),
propertyList: MetadataTokens.PropertyDefinitionHandle(_propertyMap[typeId]));
}
}
private abstract class DefinitionIndexBase<T>
where T : notnull
{
protected readonly Dictionary<T, int> added; // Definitions added in this generation.
protected readonly List<T> rows; // Rows in this generation, containing adds and updates.
private readonly int _firstRowId; // First row in this generation.
private bool _frozen;
public DefinitionIndexBase(int lastRowId, IEqualityComparer<T>? comparer = null)
{
this.added = new Dictionary<T, int>(comparer);
this.rows = new List<T>();
_firstRowId = lastRowId + 1;
}
public abstract bool TryGetValue(T item, out int index);
public int this[T item]
{
get
{
int token;
this.TryGetValue(item, out token);
// Fails if we are attempting to make a change that should have been reported as rude,
// e.g. the corresponding definitions type don't match, etc.
Debug.Assert(token > 0);
return token;
}
}
// A method rather than a property since it freezes the table.
public IReadOnlyDictionary<T, int> GetAdded()
{
this.Freeze();
return this.added;
}
// A method rather than a property since it freezes the table.
public IReadOnlyList<T> GetRows()
{
this.Freeze();
return this.rows;
}
public int FirstRowId
{
get { return _firstRowId; }
}
public int NextRowId
{
get { return this.added.Count + _firstRowId; }
}
public bool IsFrozen
{
get { return _frozen; }
}
protected virtual void OnFrozen()
{
#if DEBUG
// Verify the rows are sorted.
int prev = 0;
foreach (var row in this.rows)
{
int next = this.added[row];
Debug.Assert(prev < next);
prev = next;
}
#endif
}
private void Freeze()
{
if (!_frozen)
{
_frozen = true;
this.OnFrozen();
}
}
}
private sealed class DefinitionIndex<T> : DefinitionIndexBase<T> where T : class, IDefinition
{
public delegate bool TryGetExistingIndex(T item, out int index);
private readonly TryGetExistingIndex _tryGetExistingIndex;
// Map of row id to def for all defs. This could be an array indexed
// by row id but the array could be large and sparsely populated
// if there are many defs in the previous generation but few
// references to those defs in the current generation.
private readonly Dictionary<int, T> _map;
public DefinitionIndex(TryGetExistingIndex tryGetExistingIndex, int lastRowId)
: base(lastRowId, ReferenceEqualityComparer.Instance)
{
_tryGetExistingIndex = tryGetExistingIndex;
_map = new Dictionary<int, T>();
}
public override bool TryGetValue(T item, out int index)
{
if (this.added.TryGetValue(item, out index))
{
return true;
}
if (_tryGetExistingIndex(item, out index))
{
#if DEBUG
T? other;
Debug.Assert(!_map.TryGetValue(index, out other) || ((object)other == (object)item));
#endif
_map[index] = item;
return true;
}
return false;
}
public T this[int rowId]
{
get
{
return _map[rowId];
}
}
public void Add(T item)
{
Debug.Assert(!this.IsFrozen);
int index = this.NextRowId;
this.added.Add(item, index);
_map[index] = item;
this.rows.Add(item);
}
/// <summary>
/// Add an item from a previous generation
/// that has been updated in this generation.
/// </summary>
public void AddUpdated(T item)
{
Debug.Assert(!this.IsFrozen);
this.rows.Add(item);
}
public bool IsAddedNotChanged(T item)
{
return this.added.ContainsKey(item);
}
protected override void OnFrozen()
{
this.rows.Sort(this.CompareRows);
}
private int CompareRows(T x, T y)
{
return this[x] - this[y];
}
}
private bool TryGetExistingTypeDefIndex(ITypeDefinition item, out int index)
{
if (_previousGeneration.TypesAdded.TryGetValue(item, out index))
{
return true;
}
TypeDefinitionHandle handle;
if (_definitionMap.TryGetTypeHandle(item, out handle))
{
index = MetadataTokens.GetRowNumber(handle);
Debug.Assert(index > 0);
return true;
}
index = 0;
return false;
}
private bool TryGetExistingEventDefIndex(IEventDefinition item, out int index)
{
if (_previousGeneration.EventsAdded.TryGetValue(item, out index))
{
return true;
}
EventDefinitionHandle handle;
if (_definitionMap.TryGetEventHandle(item, out handle))
{
index = MetadataTokens.GetRowNumber(handle);
Debug.Assert(index > 0);
return true;
}
index = 0;
return false;
}
private bool TryGetExistingFieldDefIndex(IFieldDefinition item, out int index)
{
if (_previousGeneration.FieldsAdded.TryGetValue(item, out index))
{
return true;
}
FieldDefinitionHandle handle;
if (_definitionMap.TryGetFieldHandle(item, out handle))
{
index = MetadataTokens.GetRowNumber(handle);
Debug.Assert(index > 0);
return true;
}
index = 0;
return false;
}
private bool TryGetExistingMethodDefIndex(IMethodDefinition item, out int index)
{
if (_previousGeneration.MethodsAdded.TryGetValue(item, out index))
{
return true;
}
MethodDefinitionHandle handle;
if (_definitionMap.TryGetMethodHandle(item, out handle))
{
index = MetadataTokens.GetRowNumber(handle);
Debug.Assert(index > 0);
return true;
}
index = 0;
return false;
}
private bool TryGetExistingPropertyDefIndex(IPropertyDefinition item, out int index)
{
if (_previousGeneration.PropertiesAdded.TryGetValue(item, out index))
{
return true;
}
PropertyDefinitionHandle handle;
if (_definitionMap.TryGetPropertyHandle(item, out handle))
{
index = MetadataTokens.GetRowNumber(handle);
Debug.Assert(index > 0);
return true;
}
index = 0;
return false;
}
private bool TryGetExistingEventMapIndex(int item, out int index)
{
if (_previousGeneration.EventMapAdded.TryGetValue(item, out index))
{
return true;
}
if (_previousGeneration.TypeToEventMap.TryGetValue(item, out index))
{
return true;
}
index = 0;
return false;
}
private bool TryGetExistingPropertyMapIndex(int item, out int index)
{
if (_previousGeneration.PropertyMapAdded.TryGetValue(item, out index))
{
return true;
}
if (_previousGeneration.TypeToPropertyMap.TryGetValue(item, out index))
{
return true;
}
index = 0;
return false;
}
private bool TryGetExistingMethodImplIndex(MethodImplKey item, out int index)
{
if (_previousGeneration.MethodImplsAdded.TryGetValue(item, out index))
{
return true;
}
if (_previousGeneration.MethodImpls.TryGetValue(item, out index))
{
return true;
}
index = 0;
return false;
}
private sealed class ParameterDefinitionIndex : DefinitionIndexBase<IParameterDefinition>
{
public ParameterDefinitionIndex(int lastRowId)
: base(lastRowId, ReferenceEqualityComparer.Instance)
{
}
public override bool TryGetValue(IParameterDefinition item, out int index)
{
return this.added.TryGetValue(item, out index);
}
public void Add(IParameterDefinition item)
{
Debug.Assert(!this.IsFrozen);
int index = this.NextRowId;
this.added.Add(item, index);
this.rows.Add(item);
}
}
private sealed class GenericParameterIndex : DefinitionIndexBase<IGenericParameter>
{
public GenericParameterIndex(int lastRowId)
: base(lastRowId, ReferenceEqualityComparer.Instance)
{
}
public override bool TryGetValue(IGenericParameter item, out int index)
{
return this.added.TryGetValue(item, out index);
}
public void Add(IGenericParameter item)
{
Debug.Assert(!this.IsFrozen);
int index = this.NextRowId;
this.added.Add(item, index);
this.rows.Add(item);
}
}
private sealed class EventOrPropertyMapIndex : DefinitionIndexBase<int>
{
public delegate bool TryGetExistingIndex(int item, out int index);
private readonly TryGetExistingIndex _tryGetExistingIndex;
public EventOrPropertyMapIndex(TryGetExistingIndex tryGetExistingIndex, int lastRowId)
: base(lastRowId)
{
_tryGetExistingIndex = tryGetExistingIndex;
}
public override bool TryGetValue(int item, out int index)
{
if (this.added.TryGetValue(item, out index))
{
return true;
}
if (_tryGetExistingIndex(item, out index))
{
return true;
}
index = 0;
return false;
}
public void Add(int item)
{
Debug.Assert(!this.IsFrozen);
int index = this.NextRowId;
this.added.Add(item, index);
this.rows.Add(item);
}
}
private sealed class MethodImplIndex : DefinitionIndexBase<MethodImplKey>
{
private readonly DeltaMetadataWriter _writer;
public MethodImplIndex(DeltaMetadataWriter writer, int lastRowId)
: base(lastRowId)
{
_writer = writer;
}
public override bool TryGetValue(MethodImplKey item, out int index)
{
if (this.added.TryGetValue(item, out index))
{
return true;
}
if (_writer.TryGetExistingMethodImplIndex(item, out index))
{
return true;
}
index = 0;
return false;
}
public void Add(MethodImplKey item)
{
Debug.Assert(!this.IsFrozen);
int index = this.NextRowId;
this.added.Add(item, index);
this.rows.Add(item);
}
}
private sealed class DeltaReferenceIndexer : ReferenceIndexer
{
private readonly SymbolChanges _changes;
public DeltaReferenceIndexer(DeltaMetadataWriter writer)
: base(writer)
{
_changes = writer._changes;
}
public override void Visit(CommonPEModuleBuilder module)
{
Visit(module.GetTopLevelTypeDefinitions(metadataWriter.Context));
}
public override void Visit(IEventDefinition eventDefinition)
{
Debug.Assert(this.ShouldVisit(eventDefinition));
base.Visit(eventDefinition);
}
public override void Visit(IFieldDefinition fieldDefinition)
{
Debug.Assert(this.ShouldVisit(fieldDefinition));
base.Visit(fieldDefinition);
}
public override void Visit(ILocalDefinition localDefinition)
{
if (localDefinition.Signature == null)
{
base.Visit(localDefinition);
}
}
public override void Visit(IMethodDefinition method)
{
Debug.Assert(this.ShouldVisit(method));
base.Visit(method);
}
public override void Visit(Cci.MethodImplementation methodImplementation)
{
// Unless the implementing method was added,
// the method implementation already exists.
var methodDef = (IMethodDefinition?)methodImplementation.ImplementingMethod.AsDefinition(this.Context);
RoslynDebug.AssertNotNull(methodDef);
if (_changes.GetChange(methodDef) == SymbolChange.Added)
{
base.Visit(methodImplementation);
}
}
public override void Visit(INamespaceTypeDefinition namespaceTypeDefinition)
{
Debug.Assert(this.ShouldVisit(namespaceTypeDefinition));
base.Visit(namespaceTypeDefinition);
}
public override void Visit(INestedTypeDefinition nestedTypeDefinition)
{
Debug.Assert(this.ShouldVisit(nestedTypeDefinition));
base.Visit(nestedTypeDefinition);
}
public override void Visit(IPropertyDefinition propertyDefinition)
{
Debug.Assert(this.ShouldVisit(propertyDefinition));
base.Visit(propertyDefinition);
}
public override void Visit(ITypeDefinition typeDefinition)
{
if (this.ShouldVisit(typeDefinition))
{
base.Visit(typeDefinition);
}
}
public override void Visit(ITypeDefinitionMember typeMember)
{
if (this.ShouldVisit(typeMember))
{
base.Visit(typeMember);
}
}
private bool ShouldVisit(IDefinition def)
{
return _changes.GetChange(def) != SymbolChange.None;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Threading;
using Microsoft.Cci;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.Symbols;
namespace Microsoft.CodeAnalysis.Emit
{
internal sealed class DeltaMetadataWriter : MetadataWriter
{
private readonly EmitBaseline _previousGeneration;
private readonly Guid _encId;
private readonly DefinitionMap _definitionMap;
private readonly SymbolChanges _changes;
/// <summary>
/// Type definitions containing any changes (includes added types).
/// </summary>
private readonly List<ITypeDefinition> _changedTypeDefs;
private readonly DefinitionIndex<ITypeDefinition> _typeDefs;
private readonly DefinitionIndex<IEventDefinition> _eventDefs;
private readonly DefinitionIndex<IFieldDefinition> _fieldDefs;
private readonly DefinitionIndex<IMethodDefinition> _methodDefs;
private readonly DefinitionIndex<IPropertyDefinition> _propertyDefs;
private readonly ParameterDefinitionIndex _parameterDefs;
private readonly List<KeyValuePair<IMethodDefinition, IParameterDefinition>> _parameterDefList;
private readonly GenericParameterIndex _genericParameters;
private readonly EventOrPropertyMapIndex _eventMap;
private readonly EventOrPropertyMapIndex _propertyMap;
private readonly MethodImplIndex _methodImpls;
// For the EncLog table we need to know which things we're emitting custom attributes for so we can
// correctly map the attributes to row numbers of existing attributes for that target
private readonly Dictionary<EntityHandle, int> _customAttributeParentCounts;
// For the EncMap table we need to keep a list of exactly which rows in the CustomAttributes table are updated
// since we spread these out amongst existing rows, it's not just a contiguous set
private readonly List<int> _customAttributeEncMapRows;
// Keep track of which CustomAttributes rows are added in this and previous deltas, over what is in the
// original metadata
private readonly Dictionary<EntityHandle, ImmutableArray<int>> _customAttributesAdded;
private readonly HeapOrReferenceIndex<AssemblyIdentity> _assemblyRefIndex;
private readonly HeapOrReferenceIndex<string> _moduleRefIndex;
private readonly InstanceAndStructuralReferenceIndex<ITypeMemberReference> _memberRefIndex;
private readonly InstanceAndStructuralReferenceIndex<IGenericMethodInstanceReference> _methodSpecIndex;
private readonly TypeReferenceIndex _typeRefIndex;
private readonly InstanceAndStructuralReferenceIndex<ITypeReference> _typeSpecIndex;
private readonly HeapOrReferenceIndex<BlobHandle> _standAloneSignatureIndex;
private readonly Dictionary<IMethodDefinition, AddedOrChangedMethodInfo> _addedOrChangedMethods;
public DeltaMetadataWriter(
EmitContext context,
CommonMessageProvider messageProvider,
EmitBaseline previousGeneration,
Guid encId,
DefinitionMap definitionMap,
SymbolChanges changes,
CancellationToken cancellationToken)
: base(metadata: MakeTablesBuilder(previousGeneration),
debugMetadataOpt: (context.Module.DebugInformationFormat == DebugInformationFormat.PortablePdb) ? new MetadataBuilder() : null,
dynamicAnalysisDataWriterOpt: null,
context: context,
messageProvider: messageProvider,
metadataOnly: false,
deterministic: false,
emitTestCoverageData: false,
cancellationToken: cancellationToken)
{
Debug.Assert(previousGeneration != null);
Debug.Assert(encId != default(Guid));
Debug.Assert(encId != previousGeneration.EncId);
Debug.Assert(context.Module.DebugInformationFormat != DebugInformationFormat.Embedded);
_previousGeneration = previousGeneration;
_encId = encId;
_definitionMap = definitionMap;
_changes = changes;
var sizes = previousGeneration.TableSizes;
_changedTypeDefs = new List<ITypeDefinition>();
_typeDefs = new DefinitionIndex<ITypeDefinition>(this.TryGetExistingTypeDefIndex, sizes[(int)TableIndex.TypeDef]);
_eventDefs = new DefinitionIndex<IEventDefinition>(this.TryGetExistingEventDefIndex, sizes[(int)TableIndex.Event]);
_fieldDefs = new DefinitionIndex<IFieldDefinition>(this.TryGetExistingFieldDefIndex, sizes[(int)TableIndex.Field]);
_methodDefs = new DefinitionIndex<IMethodDefinition>(this.TryGetExistingMethodDefIndex, sizes[(int)TableIndex.MethodDef]);
_propertyDefs = new DefinitionIndex<IPropertyDefinition>(this.TryGetExistingPropertyDefIndex, sizes[(int)TableIndex.Property]);
_parameterDefs = new ParameterDefinitionIndex(sizes[(int)TableIndex.Param]);
_parameterDefList = new List<KeyValuePair<IMethodDefinition, IParameterDefinition>>();
_genericParameters = new GenericParameterIndex(sizes[(int)TableIndex.GenericParam]);
_eventMap = new EventOrPropertyMapIndex(this.TryGetExistingEventMapIndex, sizes[(int)TableIndex.EventMap]);
_propertyMap = new EventOrPropertyMapIndex(this.TryGetExistingPropertyMapIndex, sizes[(int)TableIndex.PropertyMap]);
_methodImpls = new MethodImplIndex(this, sizes[(int)TableIndex.MethodImpl]);
_customAttributeParentCounts = new Dictionary<EntityHandle, int>();
_customAttributeEncMapRows = new List<int>();
_customAttributesAdded = new Dictionary<EntityHandle, ImmutableArray<int>>();
_assemblyRefIndex = new HeapOrReferenceIndex<AssemblyIdentity>(this, lastRowId: sizes[(int)TableIndex.AssemblyRef]);
_moduleRefIndex = new HeapOrReferenceIndex<string>(this, lastRowId: sizes[(int)TableIndex.ModuleRef]);
_memberRefIndex = new InstanceAndStructuralReferenceIndex<ITypeMemberReference>(this, new MemberRefComparer(this), lastRowId: sizes[(int)TableIndex.MemberRef]);
_methodSpecIndex = new InstanceAndStructuralReferenceIndex<IGenericMethodInstanceReference>(this, new MethodSpecComparer(this), lastRowId: sizes[(int)TableIndex.MethodSpec]);
_typeRefIndex = new TypeReferenceIndex(this, lastRowId: sizes[(int)TableIndex.TypeRef]);
_typeSpecIndex = new InstanceAndStructuralReferenceIndex<ITypeReference>(this, new TypeSpecComparer(this), lastRowId: sizes[(int)TableIndex.TypeSpec]);
_standAloneSignatureIndex = new HeapOrReferenceIndex<BlobHandle>(this, lastRowId: sizes[(int)TableIndex.StandAloneSig]);
_addedOrChangedMethods = new Dictionary<IMethodDefinition, AddedOrChangedMethodInfo>(Cci.SymbolEquivalentEqualityComparer.Instance);
}
private static MetadataBuilder MakeTablesBuilder(EmitBaseline previousGeneration)
{
return new MetadataBuilder(
previousGeneration.UserStringStreamLength,
previousGeneration.StringStreamLength,
previousGeneration.BlobStreamLength,
previousGeneration.GuidStreamLength);
}
private ImmutableArray<int> GetDeltaTableSizes(ImmutableArray<int> rowCounts)
{
var sizes = new int[MetadataTokens.TableCount];
rowCounts.CopyTo(sizes);
sizes[(int)TableIndex.TypeRef] = _typeRefIndex.Rows.Count;
sizes[(int)TableIndex.TypeDef] = _typeDefs.GetAdded().Count;
sizes[(int)TableIndex.Field] = _fieldDefs.GetAdded().Count;
sizes[(int)TableIndex.MethodDef] = _methodDefs.GetAdded().Count;
sizes[(int)TableIndex.Param] = _parameterDefs.GetAdded().Count;
sizes[(int)TableIndex.MemberRef] = _memberRefIndex.Rows.Count;
sizes[(int)TableIndex.StandAloneSig] = _standAloneSignatureIndex.Rows.Count;
sizes[(int)TableIndex.EventMap] = _eventMap.GetAdded().Count;
sizes[(int)TableIndex.Event] = _eventDefs.GetAdded().Count;
sizes[(int)TableIndex.PropertyMap] = _propertyMap.GetAdded().Count;
sizes[(int)TableIndex.Property] = _propertyDefs.GetAdded().Count;
sizes[(int)TableIndex.MethodImpl] = _methodImpls.GetAdded().Count;
sizes[(int)TableIndex.ModuleRef] = _moduleRefIndex.Rows.Count;
sizes[(int)TableIndex.TypeSpec] = _typeSpecIndex.Rows.Count;
sizes[(int)TableIndex.AssemblyRef] = _assemblyRefIndex.Rows.Count;
sizes[(int)TableIndex.GenericParam] = _genericParameters.GetAdded().Count;
sizes[(int)TableIndex.MethodSpec] = _methodSpecIndex.Rows.Count;
return ImmutableArray.Create(sizes);
}
internal EmitBaseline GetDelta(Compilation compilation, Guid encId, MetadataSizes metadataSizes)
{
var addedOrChangedMethodsByIndex = new Dictionary<int, AddedOrChangedMethodInfo>();
foreach (var pair in _addedOrChangedMethods)
{
addedOrChangedMethodsByIndex.Add(MetadataTokens.GetRowNumber(GetMethodDefinitionHandle(pair.Key)), pair.Value);
}
var previousTableSizes = _previousGeneration.TableEntriesAdded;
var deltaTableSizes = GetDeltaTableSizes(metadataSizes.RowCounts);
var tableSizes = new int[MetadataTokens.TableCount];
for (int i = 0; i < tableSizes.Length; i++)
{
tableSizes[i] = previousTableSizes[i] + deltaTableSizes[i];
}
// If the previous generation is 0 (metadata) get the synthesized members from the current compilation's builder,
// otherwise members from the current compilation have already been merged into the baseline.
var synthesizedMembers = (_previousGeneration.Ordinal == 0) ? module.GetAllSynthesizedMembers() : _previousGeneration.SynthesizedMembers;
var currentGenerationOrdinal = _previousGeneration.Ordinal + 1;
var addedTypes = _typeDefs.GetAdded();
var generationOrdinals = CreateDictionary(_previousGeneration.GenerationOrdinals, SymbolEquivalentEqualityComparer.Instance);
foreach (var (addedType, _) in addedTypes)
{
if (_changes.IsReplaced(addedType))
{
generationOrdinals[addedType] = currentGenerationOrdinal;
}
}
return _previousGeneration.With(
compilation,
module,
currentGenerationOrdinal,
encId,
generationOrdinals,
typesAdded: AddRange(_previousGeneration.TypesAdded, addedTypes, comparer: SymbolEquivalentEqualityComparer.Instance),
eventsAdded: AddRange(_previousGeneration.EventsAdded, _eventDefs.GetAdded(), comparer: SymbolEquivalentEqualityComparer.Instance),
fieldsAdded: AddRange(_previousGeneration.FieldsAdded, _fieldDefs.GetAdded(), comparer: SymbolEquivalentEqualityComparer.Instance),
methodsAdded: AddRange(_previousGeneration.MethodsAdded, _methodDefs.GetAdded(), comparer: SymbolEquivalentEqualityComparer.Instance),
propertiesAdded: AddRange(_previousGeneration.PropertiesAdded, _propertyDefs.GetAdded(), comparer: SymbolEquivalentEqualityComparer.Instance),
eventMapAdded: AddRange(_previousGeneration.EventMapAdded, _eventMap.GetAdded()),
propertyMapAdded: AddRange(_previousGeneration.PropertyMapAdded, _propertyMap.GetAdded()),
methodImplsAdded: AddRange(_previousGeneration.MethodImplsAdded, _methodImpls.GetAdded()),
customAttributesAdded: AddRange(_previousGeneration.CustomAttributesAdded, _customAttributesAdded),
tableEntriesAdded: ImmutableArray.Create(tableSizes),
// Blob stream is concatenated aligned.
blobStreamLengthAdded: metadataSizes.GetAlignedHeapSize(HeapIndex.Blob) + _previousGeneration.BlobStreamLengthAdded,
// String stream is concatenated unaligned.
stringStreamLengthAdded: metadataSizes.HeapSizes[(int)HeapIndex.String] + _previousGeneration.StringStreamLengthAdded,
// UserString stream is concatenated aligned.
userStringStreamLengthAdded: metadataSizes.GetAlignedHeapSize(HeapIndex.UserString) + _previousGeneration.UserStringStreamLengthAdded,
// Guid stream accumulates on the GUID heap unlike other heaps, so the previous generations are already included.
guidStreamLengthAdded: metadataSizes.HeapSizes[(int)HeapIndex.Guid],
anonymousTypeMap: ((IPEDeltaAssemblyBuilder)module).GetAnonymousTypeMap(),
synthesizedMembers: synthesizedMembers,
addedOrChangedMethods: AddRange(_previousGeneration.AddedOrChangedMethods, addedOrChangedMethodsByIndex),
debugInformationProvider: _previousGeneration.DebugInformationProvider,
localSignatureProvider: _previousGeneration.LocalSignatureProvider);
}
private static Dictionary<K, V> CreateDictionary<K, V>(IReadOnlyDictionary<K, V> dictionary, IEqualityComparer<K>? comparer)
where K : notnull
{
var result = new Dictionary<K, V>(comparer);
foreach (var pair in dictionary)
{
result.Add(pair.Key, pair.Value);
}
return result;
}
private static IReadOnlyDictionary<K, V> AddRange<K, V>(IReadOnlyDictionary<K, V> previous, IReadOnlyDictionary<K, V> current, IEqualityComparer<K>? comparer = null)
where K : notnull
{
if (previous.Count == 0)
{
return current;
}
if (current.Count == 0)
{
return previous;
}
var result = CreateDictionary(previous, comparer);
foreach (var pair in current)
{
// Use the latest symbol.
result[pair.Key] = pair.Value;
}
return result;
}
/// <summary>
/// Return tokens for all updated debuggable methods.
/// </summary>
public void GetUpdatedMethodTokens(ArrayBuilder<MethodDefinitionHandle> methods)
{
foreach (var def in _methodDefs.GetRows())
{
// The debugger tries to remap all modified methods, which requires presence of sequence points.
if (!_methodDefs.IsAddedNotChanged(def) && def.GetBody(Context)?.SequencePoints.Length > 0)
{
methods.Add(MetadataTokens.MethodDefinitionHandle(_methodDefs.GetRowId(def)));
}
}
}
/// <summary>
/// Return tokens for all updated or added types.
/// </summary>
public void GetChangedTypeTokens(ArrayBuilder<TypeDefinitionHandle> types)
{
foreach (var def in _changedTypeDefs)
{
types.Add(MetadataTokens.TypeDefinitionHandle(_typeDefs.GetRowId(def)));
}
}
protected override ushort Generation
{
get { return (ushort)(_previousGeneration.Ordinal + 1); }
}
protected override Guid EncId
{
get { return _encId; }
}
protected override Guid EncBaseId
{
get { return _previousGeneration.EncId; }
}
protected override EventDefinitionHandle GetEventDefinitionHandle(IEventDefinition def)
{
return MetadataTokens.EventDefinitionHandle(_eventDefs.GetRowId(def));
}
protected override IReadOnlyList<IEventDefinition> GetEventDefs()
{
return _eventDefs.GetRows();
}
protected override FieldDefinitionHandle GetFieldDefinitionHandle(IFieldDefinition def)
{
return MetadataTokens.FieldDefinitionHandle(_fieldDefs.GetRowId(def));
}
protected override IReadOnlyList<IFieldDefinition> GetFieldDefs()
{
return _fieldDefs.GetRows();
}
protected override bool TryGetTypeDefinitionHandle(ITypeDefinition def, out TypeDefinitionHandle handle)
{
bool result = _typeDefs.TryGetRowId(def, out int rowId);
handle = MetadataTokens.TypeDefinitionHandle(rowId);
return result;
}
protected override TypeDefinitionHandle GetTypeDefinitionHandle(ITypeDefinition def)
{
return MetadataTokens.TypeDefinitionHandle(_typeDefs.GetRowId(def));
}
protected override ITypeDefinition GetTypeDef(TypeDefinitionHandle handle)
{
return _typeDefs.GetDefinition(MetadataTokens.GetRowNumber(handle));
}
protected override IReadOnlyList<ITypeDefinition> GetTypeDefs()
{
return _typeDefs.GetRows();
}
protected override bool TryGetMethodDefinitionHandle(IMethodDefinition def, out MethodDefinitionHandle handle)
{
bool result = _methodDefs.TryGetRowId(def, out int rowId);
handle = MetadataTokens.MethodDefinitionHandle(rowId);
return result;
}
protected override MethodDefinitionHandle GetMethodDefinitionHandle(IMethodDefinition def)
=> MetadataTokens.MethodDefinitionHandle(_methodDefs.GetRowId(def));
protected override IMethodDefinition GetMethodDef(MethodDefinitionHandle index)
=> _methodDefs.GetDefinition(MetadataTokens.GetRowNumber(index));
protected override IReadOnlyList<IMethodDefinition> GetMethodDefs()
=> _methodDefs.GetRows();
protected override PropertyDefinitionHandle GetPropertyDefIndex(IPropertyDefinition def)
=> MetadataTokens.PropertyDefinitionHandle(_propertyDefs.GetRowId(def));
protected override IReadOnlyList<IPropertyDefinition> GetPropertyDefs()
=> _propertyDefs.GetRows();
protected override ParameterHandle GetParameterHandle(IParameterDefinition def)
=> MetadataTokens.ParameterHandle(_parameterDefs.GetRowId(def));
protected override IReadOnlyList<IParameterDefinition> GetParameterDefs()
=> _parameterDefs.GetRows();
protected override IReadOnlyList<IGenericParameter> GetGenericParameters()
=> _genericParameters.GetRows();
// Fields are associated with the type through the EncLog table.
protected override FieldDefinitionHandle GetFirstFieldDefinitionHandle(INamedTypeDefinition typeDef)
=> default;
// Methods are associated with the type through the EncLog table.
protected override MethodDefinitionHandle GetFirstMethodDefinitionHandle(INamedTypeDefinition typeDef)
=> default;
// Parameters are associated with the method through the EncLog table.
protected override ParameterHandle GetFirstParameterHandle(IMethodDefinition methodDef)
=> default;
protected override AssemblyReferenceHandle GetOrAddAssemblyReferenceHandle(IAssemblyReference reference)
{
var identity = reference.Identity;
var versionPattern = reference.AssemblyVersionPattern;
if (versionPattern is not null)
{
RoslynDebug.AssertNotNull(_previousGeneration.InitialBaseline.LazyMetadataSymbols);
identity = _previousGeneration.InitialBaseline.LazyMetadataSymbols.AssemblyReferenceIdentityMap[identity.WithVersion(versionPattern)];
}
return MetadataTokens.AssemblyReferenceHandle(_assemblyRefIndex.GetOrAdd(identity));
}
protected override IReadOnlyList<AssemblyIdentity> GetAssemblyRefs()
{
return _assemblyRefIndex.Rows;
}
protected override ModuleReferenceHandle GetOrAddModuleReferenceHandle(string reference)
{
return MetadataTokens.ModuleReferenceHandle(_moduleRefIndex.GetOrAdd(reference));
}
protected override IReadOnlyList<string> GetModuleRefs()
{
return _moduleRefIndex.Rows;
}
protected override MemberReferenceHandle GetOrAddMemberReferenceHandle(ITypeMemberReference reference)
{
return MetadataTokens.MemberReferenceHandle(_memberRefIndex.GetOrAdd(reference));
}
protected override IReadOnlyList<ITypeMemberReference> GetMemberRefs()
{
return _memberRefIndex.Rows;
}
protected override MethodSpecificationHandle GetOrAddMethodSpecificationHandle(IGenericMethodInstanceReference reference)
{
return MetadataTokens.MethodSpecificationHandle(_methodSpecIndex.GetOrAdd(reference));
}
protected override IReadOnlyList<IGenericMethodInstanceReference> GetMethodSpecs()
{
return _methodSpecIndex.Rows;
}
protected override int GreatestMethodDefIndex => _methodDefs.NextRowId;
protected override bool TryGetTypeReferenceHandle(ITypeReference reference, out TypeReferenceHandle handle)
{
int index;
bool result = _typeRefIndex.TryGetValue(reference, out index);
handle = MetadataTokens.TypeReferenceHandle(index);
return result;
}
protected override TypeReferenceHandle GetOrAddTypeReferenceHandle(ITypeReference reference)
{
return MetadataTokens.TypeReferenceHandle(_typeRefIndex.GetOrAdd(reference));
}
protected override IReadOnlyList<ITypeReference> GetTypeRefs()
{
return _typeRefIndex.Rows;
}
protected override TypeSpecificationHandle GetOrAddTypeSpecificationHandle(ITypeReference reference)
{
return MetadataTokens.TypeSpecificationHandle(_typeSpecIndex.GetOrAdd(reference));
}
protected override IReadOnlyList<ITypeReference> GetTypeSpecs()
{
return _typeSpecIndex.Rows;
}
protected override StandaloneSignatureHandle GetOrAddStandaloneSignatureHandle(BlobHandle blobIndex)
{
return MetadataTokens.StandaloneSignatureHandle(_standAloneSignatureIndex.GetOrAdd(blobIndex));
}
protected override IReadOnlyList<BlobHandle> GetStandaloneSignatureBlobHandles()
{
return _standAloneSignatureIndex.Rows;
}
protected override void OnIndicesCreated()
{
var module = (IPEDeltaAssemblyBuilder)this.module;
module.OnCreatedIndices(this.Context.Diagnostics);
}
protected override void CreateIndicesForNonTypeMembers(ITypeDefinition typeDef)
{
var change = _changes.GetChange(typeDef);
switch (change)
{
case SymbolChange.Added:
_typeDefs.Add(typeDef);
_changedTypeDefs.Add(typeDef);
var typeParameters = this.GetConsolidatedTypeParameters(typeDef);
if (typeParameters != null)
{
foreach (var typeParameter in typeParameters)
{
_genericParameters.Add(typeParameter);
}
}
break;
case SymbolChange.Updated:
_typeDefs.AddUpdated(typeDef);
_changedTypeDefs.Add(typeDef);
break;
case SymbolChange.ContainsChanges:
// Members changed.
// We keep this list separately because we don't want to output duplicate typedef entries in the EnC log,
// which uses _typeDefs, but it's simpler to let the members output those rows for the updated typedefs
// with the right update type.
_changedTypeDefs.Add(typeDef);
break;
case SymbolChange.None:
// No changes to type.
return;
default:
throw ExceptionUtilities.UnexpectedValue(change);
}
int typeRowId = _typeDefs.GetRowId(typeDef);
foreach (var eventDef in typeDef.GetEvents(this.Context))
{
if (!_eventMap.Contains(typeRowId))
{
_eventMap.Add(typeRowId);
}
this.AddDefIfNecessary(_eventDefs, eventDef);
}
foreach (var fieldDef in typeDef.GetFields(this.Context))
{
this.AddDefIfNecessary(_fieldDefs, fieldDef);
}
foreach (var methodDef in typeDef.GetMethods(this.Context))
{
if (this.AddDefIfNecessary(_methodDefs, methodDef))
{
foreach (var paramDef in this.GetParametersToEmit(methodDef))
{
_parameterDefs.Add(paramDef);
_parameterDefList.Add(KeyValuePairUtil.Create(methodDef, paramDef));
}
if (methodDef.GenericParameterCount > 0)
{
foreach (var typeParameter in methodDef.GenericParameters)
{
_genericParameters.Add(typeParameter);
}
}
}
}
foreach (var propertyDef in typeDef.GetProperties(this.Context))
{
if (!_propertyMap.Contains(typeRowId))
{
_propertyMap.Add(typeRowId);
}
this.AddDefIfNecessary(_propertyDefs, propertyDef);
}
var implementingMethods = ArrayBuilder<int>.GetInstance();
// First, visit all MethodImplementations and add to this.methodImplList.
foreach (var methodImpl in typeDef.GetExplicitImplementationOverrides(Context))
{
var methodDef = (IMethodDefinition?)methodImpl.ImplementingMethod.AsDefinition(this.Context);
RoslynDebug.AssertNotNull(methodDef);
int methodDefRowId = _methodDefs.GetRowId(methodDef);
// If there are N existing MethodImpl entries for this MethodDef,
// those will be index:1, ..., index:N, so it's sufficient to check for index:1.
var key = new MethodImplKey(methodDefRowId, index: 1);
if (!_methodImpls.Contains(key))
{
implementingMethods.Add(methodDefRowId);
this.methodImplList.Add(methodImpl);
}
}
// Next, add placeholders to this.methodImpls for items added above.
foreach (var methodDefIndex in implementingMethods)
{
int index = 1;
while (true)
{
var key = new MethodImplKey(methodDefIndex, index);
if (!_methodImpls.Contains(key))
{
_methodImpls.Add(key);
break;
}
index++;
}
}
implementingMethods.Free();
}
private bool AddDefIfNecessary<T>(DefinitionIndex<T> defIndex, T def)
where T : class, IDefinition
{
switch (_changes.GetChange(def))
{
case SymbolChange.Added:
defIndex.Add(def);
return true;
case SymbolChange.Updated:
defIndex.AddUpdated(def);
return false;
case SymbolChange.ContainsChanges:
Debug.Assert(def is INestedTypeDefinition);
// Changes to members within nested type only.
return false;
default:
// No changes to member or container.
return false;
}
}
protected override ReferenceIndexer CreateReferenceVisitor()
{
return new DeltaReferenceIndexer(this);
}
protected override void ReportReferencesToAddedSymbols()
{
foreach (var typeRef in GetTypeRefs())
{
ReportReferencesToAddedSymbol(typeRef.GetInternalSymbol());
}
foreach (var memberRef in GetMemberRefs())
{
ReportReferencesToAddedSymbol(memberRef.GetInternalSymbol());
}
}
private void ReportReferencesToAddedSymbol(ISymbolInternal? symbol)
{
if (symbol != null && _changes.IsAdded(symbol.GetISymbol()))
{
Context.Diagnostics.Add(messageProvider.CreateDiagnostic(
messageProvider.ERR_EncReferenceToAddedMember,
GetSymbolLocation(symbol),
symbol.Name,
symbol.ContainingAssembly.Name));
}
}
protected override StandaloneSignatureHandle SerializeLocalVariablesSignature(IMethodBody body)
{
StandaloneSignatureHandle localSignatureHandle;
var localVariables = body.LocalVariables;
var encInfos = ArrayBuilder<EncLocalInfo>.GetInstance();
if (localVariables.Length > 0)
{
var writer = PooledBlobBuilder.GetInstance();
var encoder = new BlobEncoder(writer).LocalVariableSignature(localVariables.Length);
foreach (ILocalDefinition local in localVariables)
{
var signature = local.Signature;
if (signature == null)
{
int start = writer.Count;
SerializeLocalVariableType(encoder.AddVariable(), local);
signature = writer.ToArray(start, writer.Count - start);
}
else
{
writer.WriteBytes(signature);
}
encInfos.Add(CreateEncLocalInfo(local, signature));
}
BlobHandle blobIndex = metadata.GetOrAddBlob(writer);
localSignatureHandle = GetOrAddStandaloneSignatureHandle(blobIndex);
writer.Free();
}
else
{
localSignatureHandle = default;
}
var info = new AddedOrChangedMethodInfo(
body.MethodId,
encInfos.ToImmutable(),
body.LambdaDebugInfo,
body.ClosureDebugInfo,
body.StateMachineTypeName,
body.StateMachineHoistedLocalSlots,
body.StateMachineAwaiterSlots);
_addedOrChangedMethods.Add(body.MethodDefinition, info);
encInfos.Free();
return localSignatureHandle;
}
private EncLocalInfo CreateEncLocalInfo(ILocalDefinition localDef, byte[] signature)
{
if (localDef.SlotInfo.Id.IsNone)
{
return new EncLocalInfo(signature);
}
// local type is already translated, but not recursively
ITypeReference translatedType = localDef.Type;
if (translatedType.GetInternalSymbol() is ITypeSymbolInternal typeSymbol)
{
translatedType = Context.Module.EncTranslateType(typeSymbol, Context.Diagnostics);
}
return new EncLocalInfo(localDef.SlotInfo, translatedType, localDef.Constraints, signature);
}
protected override int AddCustomAttributesToTable(EntityHandle parentHandle, IEnumerable<ICustomAttribute> attributes)
{
// The base class will write out the actual metadata for us
var numAttributesEmitted = base.AddCustomAttributesToTable(parentHandle, attributes);
// We need to keep track of all of the things attributes could be associated with in this delta, in order to populate the EncLog and Map tables
_customAttributeParentCounts.Add(parentHandle, numAttributesEmitted);
return numAttributesEmitted;
}
protected override void PopulateEncLogTableRows(ImmutableArray<int> rowCounts)
{
// The EncLog table is a log of all the operations needed
// to update the previous metadata. That means all
// new references must be added to the EncLog.
var previousSizes = _previousGeneration.TableSizes;
var deltaSizes = this.GetDeltaTableSizes(rowCounts);
PopulateEncLogTableRows(TableIndex.AssemblyRef, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.ModuleRef, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.MemberRef, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.MethodSpec, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.TypeRef, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.TypeSpec, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.StandAloneSig, previousSizes, deltaSizes);
PopulateEncLogTableRows(_typeDefs, TableIndex.TypeDef);
PopulateEncLogTableRows(TableIndex.EventMap, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.PropertyMap, previousSizes, deltaSizes);
PopulateEncLogTableEventsOrProperties(_eventDefs, TableIndex.Event, EditAndContinueOperation.AddEvent, _eventMap, TableIndex.EventMap);
PopulateEncLogTableFieldsOrMethods(_fieldDefs, TableIndex.Field, EditAndContinueOperation.AddField);
PopulateEncLogTableFieldsOrMethods(_methodDefs, TableIndex.MethodDef, EditAndContinueOperation.AddMethod);
PopulateEncLogTableEventsOrProperties(_propertyDefs, TableIndex.Property, EditAndContinueOperation.AddProperty, _propertyMap, TableIndex.PropertyMap);
PopulateEncLogTableParameters();
PopulateEncLogTableRows(TableIndex.Constant, previousSizes, deltaSizes);
PopulateEncLogTableCustomAttributes();
PopulateEncLogTableRows(TableIndex.DeclSecurity, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.ClassLayout, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.FieldLayout, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.MethodSemantics, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.MethodImpl, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.ImplMap, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.FieldRva, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.NestedClass, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.GenericParam, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.InterfaceImpl, previousSizes, deltaSizes);
PopulateEncLogTableRows(TableIndex.GenericParamConstraint, previousSizes, deltaSizes);
}
private void PopulateEncLogTableEventsOrProperties<T>(
DefinitionIndex<T> index,
TableIndex table,
EditAndContinueOperation addCode,
EventOrPropertyMapIndex map,
TableIndex mapTable)
where T : class, ITypeDefinitionMember
{
foreach (var member in index.GetRows())
{
if (index.IsAddedNotChanged(member))
{
int typeRowId = _typeDefs.GetRowId(member.ContainingTypeDefinition);
int mapRowId = map.GetRowId(typeRowId);
metadata.AddEncLogEntry(
entity: MetadataTokens.Handle(mapTable, mapRowId),
code: addCode);
}
metadata.AddEncLogEntry(
entity: MetadataTokens.Handle(table, index.GetRowId(member)),
code: EditAndContinueOperation.Default);
}
}
private void PopulateEncLogTableFieldsOrMethods<T>(
DefinitionIndex<T> index,
TableIndex tableIndex,
EditAndContinueOperation addCode)
where T : class, ITypeDefinitionMember
{
foreach (var member in index.GetRows())
{
if (index.IsAddedNotChanged(member))
{
metadata.AddEncLogEntry(
entity: MetadataTokens.TypeDefinitionHandle(_typeDefs.GetRowId(member.ContainingTypeDefinition)),
code: addCode);
}
metadata.AddEncLogEntry(
entity: MetadataTokens.Handle(tableIndex, index.GetRowId(member)),
code: EditAndContinueOperation.Default);
}
}
private void PopulateEncLogTableParameters()
{
var parameterFirstId = _parameterDefs.FirstRowId;
for (int i = 0; i < _parameterDefList.Count; i++)
{
var methodDef = _parameterDefList[i].Key;
metadata.AddEncLogEntry(
entity: MetadataTokens.MethodDefinitionHandle(_methodDefs.GetRowId(methodDef)),
code: EditAndContinueOperation.AddParameter);
metadata.AddEncLogEntry(
entity: MetadataTokens.ParameterHandle(parameterFirstId + i),
code: EditAndContinueOperation.Default);
}
}
/// <summary>
/// CustomAttributes point to their target via the Parent column so we cannot simply output new rows
/// in the delta or we would end up with duplicates, but we also don't want to do complex logic to determine
/// which attributes have changes, so we just emit them all.
/// This means our logic for emitting CustomAttributes is to update any existing rows, either from the original
/// compilation or subsequent deltas, and only add more if we need to. The EncLog table is the thing that tells
/// the runtime which row a CustomAttributes row is (ie, new or existing)
/// </summary>
private void PopulateEncLogTableCustomAttributes()
{
// List of attributes that need to be emitted to delete a previously emitted attribute
var deletedAttributeRows = new List<(int parentRowId, HandleKind kind)>();
var customAttributesAdded = new Dictionary<EntityHandle, ArrayBuilder<int>>();
// The data in _previousGeneration.CustomAttributesAdded is not nicely sorted, or even necessarily contiguous
// so we need to map each target onto the rows its attributes occupy so we know which rows to update
var lastRowId = _previousGeneration.OriginalMetadata.MetadataReader.GetTableRowCount(TableIndex.CustomAttribute);
if (_previousGeneration.CustomAttributesAdded.Count > 0)
{
lastRowId = _previousGeneration.CustomAttributesAdded.SelectMany(s => s.Value).Max();
}
// Iterate through the parents we emitted custom attributes for, in parent order
foreach (var (parent, count) in _customAttributeParentCounts.OrderBy(kvp => CodedIndex.HasCustomAttribute(kvp.Key)))
{
int index = 0;
// First we try to update any existing attributes.
// GetCustomAttributes does a binary search, so is fast. We presume that the number of rows in the original metadata
// greatly outnumbers the amount of parents emitted in this delta so even with repeated searches this is still
// quicker than iterating the entire original table, even once.
var existingCustomAttributes = _previousGeneration.OriginalMetadata.MetadataReader.GetCustomAttributes(parent);
foreach (var attributeHandle in existingCustomAttributes)
{
int rowId = MetadataTokens.GetRowNumber(attributeHandle);
AddLogEntryOrDelete(rowId, parent, add: index < count);
index++;
}
// If we emitted any attributes for this parent in previous deltas then we either need to update
// them next, or delete them if necessary
if (_previousGeneration.CustomAttributesAdded.TryGetValue(parent, out var rowIds))
{
foreach (var rowId in rowIds)
{
TrackCustomAttributeAdded(rowId, parent);
AddLogEntryOrDelete(rowId, parent, add: index < count);
index++;
}
}
// Finally if there are still attributes for this parent left, they are additions new to this delta
for (int i = index; i < count; i++)
{
lastRowId++;
TrackCustomAttributeAdded(lastRowId, parent);
AddEncLogEntry(lastRowId);
}
}
// Save the attributes we've emitted, and the ones from previous deltas, for use in the next generation
foreach (var (parent, rowIds) in customAttributesAdded)
{
_customAttributesAdded.Add(parent, rowIds.ToImmutableAndFree());
}
// Add attributes and log entries for everything we've deleted
foreach (var row in deletedAttributeRows)
{
// now emit a "delete" row with a parent that is for the 0 row of the same table as the existing one
if (!MetadataTokens.TryGetTableIndex(row.kind, out var tableIndex))
{
throw new InvalidOperationException("Trying to delete a custom attribute for a parent kind that doesn't have a matching table index.");
}
metadata.AddCustomAttribute(MetadataTokens.Handle(tableIndex, 0), MetadataTokens.EntityHandle(TableIndex.MemberRef, 0), value: default);
AddEncLogEntry(row.parentRowId);
}
void AddEncLogEntry(int rowId)
{
_customAttributeEncMapRows.Add(rowId);
metadata.AddEncLogEntry(
entity: MetadataTokens.CustomAttributeHandle(rowId),
code: EditAndContinueOperation.Default);
}
void AddLogEntryOrDelete(int rowId, EntityHandle parent, bool add)
{
if (add)
{
// Update this row
AddEncLogEntry(rowId);
}
else
{
// Delete this row
deletedAttributeRows.Add((rowId, parent.Kind));
}
}
void TrackCustomAttributeAdded(int nextRowId, EntityHandle parent)
{
if (!customAttributesAdded.TryGetValue(parent, out var existing))
{
existing = ArrayBuilder<int>.GetInstance();
customAttributesAdded.Add(parent, existing);
}
existing.Add(nextRowId);
}
}
private void PopulateEncLogTableRows<T>(DefinitionIndex<T> index, TableIndex tableIndex)
where T : class, IDefinition
{
foreach (var member in index.GetRows())
{
metadata.AddEncLogEntry(
entity: MetadataTokens.Handle(tableIndex, index.GetRowId(member)),
code: EditAndContinueOperation.Default);
}
}
private void PopulateEncLogTableRows(TableIndex tableIndex, ImmutableArray<int> previousSizes, ImmutableArray<int> deltaSizes)
{
PopulateEncLogTableRows(tableIndex, previousSizes[(int)tableIndex] + 1, deltaSizes[(int)tableIndex]);
}
private void PopulateEncLogTableRows(TableIndex tableIndex, int firstRowId, int tokenCount)
{
for (int i = 0; i < tokenCount; i++)
{
metadata.AddEncLogEntry(
entity: MetadataTokens.Handle(tableIndex, firstRowId + i),
code: EditAndContinueOperation.Default);
}
}
protected override void PopulateEncMapTableRows(ImmutableArray<int> rowCounts)
{
// The EncMap table maps from offset in each table in the delta
// metadata to token. As such, the EncMap is a concatenated
// list of all tokens in all tables from the delta sorted by table
// and, within each table, sorted by row.
var tokens = ArrayBuilder<EntityHandle>.GetInstance();
var previousSizes = _previousGeneration.TableSizes;
var deltaSizes = this.GetDeltaTableSizes(rowCounts);
AddReferencedTokens(tokens, TableIndex.AssemblyRef, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.ModuleRef, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.MemberRef, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.MethodSpec, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.TypeRef, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.TypeSpec, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.StandAloneSig, previousSizes, deltaSizes);
AddDefinitionTokens(tokens, _typeDefs, TableIndex.TypeDef);
AddDefinitionTokens(tokens, _eventDefs, TableIndex.Event);
AddDefinitionTokens(tokens, _fieldDefs, TableIndex.Field);
AddDefinitionTokens(tokens, _methodDefs, TableIndex.MethodDef);
AddDefinitionTokens(tokens, _propertyDefs, TableIndex.Property);
AddReferencedTokens(tokens, TableIndex.Param, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.Constant, previousSizes, deltaSizes);
AddRowNumberTokens(tokens, _customAttributeEncMapRows, TableIndex.CustomAttribute);
AddReferencedTokens(tokens, TableIndex.DeclSecurity, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.ClassLayout, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.FieldLayout, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.EventMap, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.PropertyMap, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.MethodSemantics, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.MethodImpl, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.ImplMap, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.FieldRva, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.NestedClass, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.GenericParam, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.InterfaceImpl, previousSizes, deltaSizes);
AddReferencedTokens(tokens, TableIndex.GenericParamConstraint, previousSizes, deltaSizes);
tokens.Sort(HandleComparer.Default);
// Should not be any duplicates.
Debug.Assert(tokens.Distinct().Count() == tokens.Count);
foreach (var token in tokens)
{
metadata.AddEncMapEntry(token);
}
tokens.Free();
// Populate Portable PDB EncMap table with MethodDebugInformation mapping,
// which corresponds 1:1 to MethodDef mapping.
if (_debugMetadataOpt != null)
{
var debugTokens = ArrayBuilder<EntityHandle>.GetInstance();
AddDefinitionTokens(debugTokens, _methodDefs, TableIndex.MethodDebugInformation);
debugTokens.Sort(HandleComparer.Default);
// Should not be any duplicates.
Debug.Assert(debugTokens.Distinct().Count() == debugTokens.Count);
foreach (var token in debugTokens)
{
_debugMetadataOpt.AddEncMapEntry(token);
}
debugTokens.Free();
}
#if DEBUG
// The following tables are either represented in the EncMap
// or specifically ignored. The rest should be empty.
var handledTables = new TableIndex[]
{
TableIndex.Module,
TableIndex.TypeRef,
TableIndex.TypeDef,
TableIndex.Field,
TableIndex.MethodDef,
TableIndex.Param,
TableIndex.MemberRef,
TableIndex.Constant,
TableIndex.CustomAttribute,
TableIndex.DeclSecurity,
TableIndex.ClassLayout,
TableIndex.FieldLayout,
TableIndex.StandAloneSig,
TableIndex.EventMap,
TableIndex.Event,
TableIndex.PropertyMap,
TableIndex.Property,
TableIndex.MethodSemantics,
TableIndex.MethodImpl,
TableIndex.ModuleRef,
TableIndex.TypeSpec,
TableIndex.ImplMap,
// FieldRva is not needed since we only emit fields with explicit mapping
// for <PrivateImplementationDetails> and that class is not used in ENC.
// If we need FieldRva in the future, we'll need a corresponding test.
// (See EditAndContinueTests.FieldRva that was deleted in this change.)
//TableIndex.FieldRva,
TableIndex.EncLog,
TableIndex.EncMap,
TableIndex.Assembly,
TableIndex.AssemblyRef,
TableIndex.MethodSpec,
TableIndex.NestedClass,
TableIndex.GenericParam,
TableIndex.InterfaceImpl,
TableIndex.GenericParamConstraint,
};
for (int i = 0; i < rowCounts.Length; i++)
{
if (handledTables.Contains((TableIndex)i))
{
continue;
}
Debug.Assert(rowCounts[i] == 0);
}
#endif
}
private static void AddReferencedTokens(
ArrayBuilder<EntityHandle> builder,
TableIndex tableIndex,
ImmutableArray<int> previousSizes,
ImmutableArray<int> deltaSizes)
{
AddReferencedTokens(builder, tableIndex, previousSizes[(int)tableIndex] + 1, deltaSizes[(int)tableIndex]);
}
private static void AddReferencedTokens(ArrayBuilder<EntityHandle> builder, TableIndex tableIndex, int firstRowId, int nTokens)
{
for (int i = 0; i < nTokens; i++)
{
builder.Add(MetadataTokens.Handle(tableIndex, firstRowId + i));
}
}
private static void AddDefinitionTokens<T>(ArrayBuilder<EntityHandle> tokens, DefinitionIndex<T> index, TableIndex tableIndex)
where T : class, IDefinition
{
foreach (var member in index.GetRows())
{
tokens.Add(MetadataTokens.Handle(tableIndex, index.GetRowId(member)));
}
}
private static void AddRowNumberTokens(ArrayBuilder<EntityHandle> tokens, IEnumerable<int> rowNumbers, TableIndex tableIndex)
{
foreach (var row in rowNumbers)
{
tokens.Add(MetadataTokens.Handle(tableIndex, row));
}
}
protected override void PopulateEventMapTableRows()
{
foreach (var typeId in _eventMap.GetRows())
{
metadata.AddEventMap(
declaringType: MetadataTokens.TypeDefinitionHandle(typeId),
eventList: MetadataTokens.EventDefinitionHandle(_eventMap.GetRowId(typeId)));
}
}
protected override void PopulatePropertyMapTableRows()
{
foreach (var typeId in _propertyMap.GetRows())
{
metadata.AddPropertyMap(
declaringType: MetadataTokens.TypeDefinitionHandle(typeId),
propertyList: MetadataTokens.PropertyDefinitionHandle(_propertyMap.GetRowId(typeId)));
}
}
private abstract class DefinitionIndexBase<T>
where T : notnull
{
protected readonly Dictionary<T, int> added; // Definitions added in this generation.
protected readonly List<T> rows; // Rows in this generation, containing adds and updates.
private readonly int _firstRowId; // First row in this generation.
private bool _frozen;
public DefinitionIndexBase(int lastRowId, IEqualityComparer<T>? comparer = null)
{
this.added = new Dictionary<T, int>(comparer);
this.rows = new List<T>();
_firstRowId = lastRowId + 1;
}
public abstract bool TryGetRowId(T item, out int rowId);
public int GetRowId(T item)
{
bool containsItem = TryGetRowId(item, out int rowId);
// Fails if we are attempting to make a change that should have been reported as rude,
// e.g. the corresponding definitions type don't match, etc.
Debug.Assert(containsItem);
Debug.Assert(rowId > 0);
return rowId;
}
public bool Contains(T item)
=> TryGetRowId(item, out _);
// A method rather than a property since it freezes the table.
public IReadOnlyDictionary<T, int> GetAdded()
{
this.Freeze();
return this.added;
}
// A method rather than a property since it freezes the table.
public IReadOnlyList<T> GetRows()
{
this.Freeze();
return this.rows;
}
public int FirstRowId
{
get { return _firstRowId; }
}
public int NextRowId
{
get { return this.added.Count + _firstRowId; }
}
public bool IsFrozen
{
get { return _frozen; }
}
protected virtual void OnFrozen()
{
#if DEBUG
// Verify the rows are sorted.
int prev = 0;
foreach (var row in this.rows)
{
int next = this.added[row];
Debug.Assert(prev < next);
prev = next;
}
#endif
}
private void Freeze()
{
if (!_frozen)
{
_frozen = true;
this.OnFrozen();
}
}
}
private sealed class DefinitionIndex<T> : DefinitionIndexBase<T> where T : class, IDefinition
{
public delegate bool TryGetExistingIndex(T item, out int index);
private readonly TryGetExistingIndex _tryGetExistingIndex;
// Map of row id to def for all defs. This could be an array indexed
// by row id but the array could be large and sparsely populated
// if there are many defs in the previous generation but few
// references to those defs in the current generation.
private readonly Dictionary<int, T> _map;
public DefinitionIndex(TryGetExistingIndex tryGetExistingIndex, int lastRowId)
: base(lastRowId, ReferenceEqualityComparer.Instance)
{
_tryGetExistingIndex = tryGetExistingIndex;
_map = new Dictionary<int, T>();
}
public override bool TryGetRowId(T item, out int index)
{
if (this.added.TryGetValue(item, out index))
{
return true;
}
if (_tryGetExistingIndex(item, out index))
{
#if DEBUG
Debug.Assert(!_map.TryGetValue(index, out var other) || ((object)other == (object)item));
#endif
_map[index] = item;
return true;
}
return false;
}
public T GetDefinition(int rowId)
=> _map[rowId];
public void Add(T item)
{
Debug.Assert(!this.IsFrozen);
int index = this.NextRowId;
this.added.Add(item, index);
_map[index] = item;
this.rows.Add(item);
}
/// <summary>
/// Add an item from a previous generation
/// that has been updated in this generation.
/// </summary>
public void AddUpdated(T item)
{
Debug.Assert(!this.IsFrozen);
this.rows.Add(item);
}
public bool IsAddedNotChanged(T item)
=> added.ContainsKey(item);
protected override void OnFrozen()
=> rows.Sort((x, y) => GetRowId(x).CompareTo(GetRowId(y)));
}
private bool TryGetExistingTypeDefIndex(ITypeDefinition item, out int index)
{
if (_previousGeneration.TypesAdded.TryGetValue(item, out index))
{
return true;
}
TypeDefinitionHandle handle;
if (_definitionMap.TryGetTypeHandle(item, out handle))
{
index = MetadataTokens.GetRowNumber(handle);
Debug.Assert(index > 0);
return true;
}
index = 0;
return false;
}
private bool TryGetExistingEventDefIndex(IEventDefinition item, out int index)
{
if (_previousGeneration.EventsAdded.TryGetValue(item, out index))
{
return true;
}
EventDefinitionHandle handle;
if (_definitionMap.TryGetEventHandle(item, out handle))
{
index = MetadataTokens.GetRowNumber(handle);
Debug.Assert(index > 0);
return true;
}
index = 0;
return false;
}
private bool TryGetExistingFieldDefIndex(IFieldDefinition item, out int index)
{
if (_previousGeneration.FieldsAdded.TryGetValue(item, out index))
{
return true;
}
FieldDefinitionHandle handle;
if (_definitionMap.TryGetFieldHandle(item, out handle))
{
index = MetadataTokens.GetRowNumber(handle);
Debug.Assert(index > 0);
return true;
}
index = 0;
return false;
}
private bool TryGetExistingMethodDefIndex(IMethodDefinition item, out int index)
{
if (_previousGeneration.MethodsAdded.TryGetValue(item, out index))
{
return true;
}
MethodDefinitionHandle handle;
if (_definitionMap.TryGetMethodHandle(item, out handle))
{
index = MetadataTokens.GetRowNumber(handle);
Debug.Assert(index > 0);
return true;
}
index = 0;
return false;
}
private bool TryGetExistingPropertyDefIndex(IPropertyDefinition item, out int index)
{
if (_previousGeneration.PropertiesAdded.TryGetValue(item, out index))
{
return true;
}
PropertyDefinitionHandle handle;
if (_definitionMap.TryGetPropertyHandle(item, out handle))
{
index = MetadataTokens.GetRowNumber(handle);
Debug.Assert(index > 0);
return true;
}
index = 0;
return false;
}
private bool TryGetExistingEventMapIndex(int item, out int index)
{
if (_previousGeneration.EventMapAdded.TryGetValue(item, out index))
{
return true;
}
if (_previousGeneration.TypeToEventMap.TryGetValue(item, out index))
{
return true;
}
index = 0;
return false;
}
private bool TryGetExistingPropertyMapIndex(int item, out int index)
{
if (_previousGeneration.PropertyMapAdded.TryGetValue(item, out index))
{
return true;
}
if (_previousGeneration.TypeToPropertyMap.TryGetValue(item, out index))
{
return true;
}
index = 0;
return false;
}
private bool TryGetExistingMethodImplIndex(MethodImplKey item, out int index)
{
if (_previousGeneration.MethodImplsAdded.TryGetValue(item, out index))
{
return true;
}
if (_previousGeneration.MethodImpls.TryGetValue(item, out index))
{
return true;
}
index = 0;
return false;
}
private sealed class ParameterDefinitionIndex : DefinitionIndexBase<IParameterDefinition>
{
public ParameterDefinitionIndex(int lastRowId)
: base(lastRowId, ReferenceEqualityComparer.Instance)
{
}
public override bool TryGetRowId(IParameterDefinition item, out int index)
{
return this.added.TryGetValue(item, out index);
}
public void Add(IParameterDefinition item)
{
Debug.Assert(!this.IsFrozen);
int index = this.NextRowId;
this.added.Add(item, index);
this.rows.Add(item);
}
}
private sealed class GenericParameterIndex : DefinitionIndexBase<IGenericParameter>
{
public GenericParameterIndex(int lastRowId)
: base(lastRowId, ReferenceEqualityComparer.Instance)
{
}
public override bool TryGetRowId(IGenericParameter item, out int index)
{
return this.added.TryGetValue(item, out index);
}
public void Add(IGenericParameter item)
{
Debug.Assert(!this.IsFrozen);
int index = this.NextRowId;
this.added.Add(item, index);
this.rows.Add(item);
}
}
private sealed class EventOrPropertyMapIndex : DefinitionIndexBase<int>
{
public delegate bool TryGetExistingIndex(int item, out int index);
private readonly TryGetExistingIndex _tryGetExistingIndex;
public EventOrPropertyMapIndex(TryGetExistingIndex tryGetExistingIndex, int lastRowId)
: base(lastRowId)
{
_tryGetExistingIndex = tryGetExistingIndex;
}
public override bool TryGetRowId(int item, out int index)
{
if (this.added.TryGetValue(item, out index))
{
return true;
}
if (_tryGetExistingIndex(item, out index))
{
return true;
}
index = 0;
return false;
}
public void Add(int item)
{
Debug.Assert(!this.IsFrozen);
int index = this.NextRowId;
this.added.Add(item, index);
this.rows.Add(item);
}
}
private sealed class MethodImplIndex : DefinitionIndexBase<MethodImplKey>
{
private readonly DeltaMetadataWriter _writer;
public MethodImplIndex(DeltaMetadataWriter writer, int lastRowId)
: base(lastRowId)
{
_writer = writer;
}
public override bool TryGetRowId(MethodImplKey item, out int index)
{
if (this.added.TryGetValue(item, out index))
{
return true;
}
if (_writer.TryGetExistingMethodImplIndex(item, out index))
{
return true;
}
index = 0;
return false;
}
public void Add(MethodImplKey item)
{
Debug.Assert(!this.IsFrozen);
int index = this.NextRowId;
this.added.Add(item, index);
this.rows.Add(item);
}
}
private sealed class DeltaReferenceIndexer : ReferenceIndexer
{
private readonly SymbolChanges _changes;
public DeltaReferenceIndexer(DeltaMetadataWriter writer)
: base(writer)
{
_changes = writer._changes;
}
public override void Visit(CommonPEModuleBuilder module)
{
Visit(module.GetTopLevelTypeDefinitions(metadataWriter.Context));
}
public override void Visit(IEventDefinition eventDefinition)
{
Debug.Assert(this.ShouldVisit(eventDefinition));
base.Visit(eventDefinition);
}
public override void Visit(IFieldDefinition fieldDefinition)
{
Debug.Assert(this.ShouldVisit(fieldDefinition));
base.Visit(fieldDefinition);
}
public override void Visit(ILocalDefinition localDefinition)
{
if (localDefinition.Signature == null)
{
base.Visit(localDefinition);
}
}
public override void Visit(IMethodDefinition method)
{
Debug.Assert(this.ShouldVisit(method));
base.Visit(method);
}
public override void Visit(Cci.MethodImplementation methodImplementation)
{
// Unless the implementing method was added,
// the method implementation already exists.
var methodDef = (IMethodDefinition?)methodImplementation.ImplementingMethod.AsDefinition(this.Context);
RoslynDebug.AssertNotNull(methodDef);
if (_changes.GetChange(methodDef) == SymbolChange.Added)
{
base.Visit(methodImplementation);
}
}
public override void Visit(INamespaceTypeDefinition namespaceTypeDefinition)
{
Debug.Assert(this.ShouldVisit(namespaceTypeDefinition));
base.Visit(namespaceTypeDefinition);
}
public override void Visit(INestedTypeDefinition nestedTypeDefinition)
{
Debug.Assert(this.ShouldVisit(nestedTypeDefinition));
base.Visit(nestedTypeDefinition);
}
public override void Visit(IPropertyDefinition propertyDefinition)
{
Debug.Assert(this.ShouldVisit(propertyDefinition));
base.Visit(propertyDefinition);
}
public override void Visit(ITypeDefinition typeDefinition)
{
if (this.ShouldVisit(typeDefinition))
{
base.Visit(typeDefinition);
}
}
public override void Visit(ITypeDefinitionMember typeMember)
{
if (this.ShouldVisit(typeMember))
{
base.Visit(typeMember);
}
}
private bool ShouldVisit(IDefinition def)
{
return _changes.GetChange(def) != SymbolChange.None;
}
}
}
}
| 1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Compilers/Core/Portable/Emit/EditAndContinue/EmitDifferenceResult.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Reflection.Metadata;
namespace Microsoft.CodeAnalysis.Emit
{
public sealed class EmitDifferenceResult : EmitResult
{
public EmitBaseline? Baseline { get; }
public ImmutableArray<MethodDefinitionHandle> UpdatedMethods { get; }
public ImmutableArray<TypeDefinitionHandle> UpdatedTypes { get; }
internal EmitDifferenceResult(bool success, ImmutableArray<Diagnostic> diagnostics, EmitBaseline? baseline, ImmutableArray<MethodDefinitionHandle> updatedMethods, ImmutableArray<TypeDefinitionHandle> updatedTypes)
: base(success, diagnostics)
{
Baseline = baseline;
UpdatedMethods = updatedMethods;
UpdatedTypes = updatedTypes;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Reflection.Metadata;
namespace Microsoft.CodeAnalysis.Emit
{
public sealed class EmitDifferenceResult : EmitResult
{
public EmitBaseline? Baseline { get; }
/// <summary>
/// Handles of methods with sequence points that have been updated in this delta.
/// </summary>
public ImmutableArray<MethodDefinitionHandle> UpdatedMethods { get; }
/// <summary>
/// Handles of types that were changed (updated or inserted) in this delta.
/// </summary>
public ImmutableArray<TypeDefinitionHandle> ChangedTypes { get; }
internal EmitDifferenceResult(bool success, ImmutableArray<Diagnostic> diagnostics, EmitBaseline? baseline, ImmutableArray<MethodDefinitionHandle> updatedMethods, ImmutableArray<TypeDefinitionHandle> changedTypes)
: base(success, diagnostics)
{
Baseline = baseline;
UpdatedMethods = updatedMethods;
ChangedTypes = changedTypes;
}
}
}
| 1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Compilers/Core/Portable/PublicAPI.Unshipped.txt | *REMOVED*Microsoft.CodeAnalysis.SyntaxNode.IsEquivalentTo(Microsoft.CodeAnalysis.SyntaxNode! other) -> bool
abstract Microsoft.CodeAnalysis.SyntaxTree.GetLineMappings(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.LineMapping>!
const Microsoft.CodeAnalysis.WellKnownMemberNames.PrintMembersMethodName = "PrintMembers" -> string!
Microsoft.CodeAnalysis.Compilation.EmitDifference(Microsoft.CodeAnalysis.Emit.EmitBaseline! baseline, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Emit.SemanticEdit>! edits, System.Func<Microsoft.CodeAnalysis.ISymbol!, bool>! isAddedSymbol, System.IO.Stream! metadataStream, System.IO.Stream! ilStream, System.IO.Stream! pdbStream, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> Microsoft.CodeAnalysis.Emit.EmitDifferenceResult!
Microsoft.CodeAnalysis.Emit.EmitDifferenceResult.UpdatedMethods.get -> System.Collections.Immutable.ImmutableArray<System.Reflection.Metadata.MethodDefinitionHandle>
Microsoft.CodeAnalysis.Emit.EmitDifferenceResult.UpdatedTypes.get -> System.Collections.Immutable.ImmutableArray<System.Reflection.Metadata.TypeDefinitionHandle>
Microsoft.CodeAnalysis.Emit.SemanticEditKind.Replace = 4 -> Microsoft.CodeAnalysis.Emit.SemanticEditKind
Microsoft.CodeAnalysis.GeneratorAttribute.GeneratorAttribute(string! firstLanguage, params string![]! additionalLanguages) -> void
Microsoft.CodeAnalysis.GeneratorAttribute.Languages.get -> string![]!
Microsoft.CodeAnalysis.GeneratorDriver.ReplaceAdditionalText(Microsoft.CodeAnalysis.AdditionalText! oldText, Microsoft.CodeAnalysis.AdditionalText! newText) -> Microsoft.CodeAnalysis.GeneratorDriver!
Microsoft.CodeAnalysis.GeneratorDriver.WithUpdatedAnalyzerConfigOptions(Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider! newOptions) -> Microsoft.CodeAnalysis.GeneratorDriver!
Microsoft.CodeAnalysis.GeneratorDriver.WithUpdatedParseOptions(Microsoft.CodeAnalysis.ParseOptions! newOptions) -> Microsoft.CodeAnalysis.GeneratorDriver!
Microsoft.CodeAnalysis.GeneratorDriverOptions
Microsoft.CodeAnalysis.GeneratorDriverOptions.GeneratorDriverOptions() -> void
Microsoft.CodeAnalysis.GeneratorDriverOptions.GeneratorDriverOptions(Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind disabledOutputs) -> void
Microsoft.CodeAnalysis.GeneratorExtensions
Microsoft.CodeAnalysis.IFieldSymbol.IsExplicitlyNamedTupleElement.get -> bool
Microsoft.CodeAnalysis.GeneratorExecutionContext.SyntaxContextReceiver.get -> Microsoft.CodeAnalysis.ISyntaxContextReceiver?
Microsoft.CodeAnalysis.GeneratorInitializationContext.RegisterForSyntaxNotifications(Microsoft.CodeAnalysis.SyntaxContextReceiverCreator! receiverCreator) -> void
Microsoft.CodeAnalysis.GeneratorSyntaxContext
Microsoft.CodeAnalysis.GeneratorSyntaxContext.GeneratorSyntaxContext() -> void
Microsoft.CodeAnalysis.GeneratorSyntaxContext.Node.get -> Microsoft.CodeAnalysis.SyntaxNode!
Microsoft.CodeAnalysis.GeneratorSyntaxContext.SemanticModel.get -> Microsoft.CodeAnalysis.SemanticModel!
Microsoft.CodeAnalysis.IIncrementalGenerator
Microsoft.CodeAnalysis.IIncrementalGenerator.Initialize(Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext context) -> void
Microsoft.CodeAnalysis.IMethodSymbol.IsPartialDefinition.get -> bool
Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext
Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.AdditionalTextsProvider.get -> Microsoft.CodeAnalysis.IncrementalValuesProvider<Microsoft.CodeAnalysis.AdditionalText!>
Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.AnalyzerConfigOptionsProvider.get -> Microsoft.CodeAnalysis.IncrementalValueProvider<Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider!>
Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.CompilationProvider.get -> Microsoft.CodeAnalysis.IncrementalValueProvider<Microsoft.CodeAnalysis.Compilation!>
Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.IncrementalGeneratorInitializationContext() -> void
Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.ParseOptionsProvider.get -> Microsoft.CodeAnalysis.IncrementalValueProvider<Microsoft.CodeAnalysis.ParseOptions!>
Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterImplementationSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void
Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterImplementationSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void
Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterPostInitializationOutput(System.Action<Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext>! callback) -> void
Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void
Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void
Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.SyntaxProvider.get -> Microsoft.CodeAnalysis.SyntaxValueProvider
Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind
Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.Implementation = 4 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind
Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.None = 0 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind
Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.PostInit = 2 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind
Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.Source = 1 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind
Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext
Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.AddSource(string! hintName, Microsoft.CodeAnalysis.Text.SourceText! sourceText) -> void
Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.AddSource(string! hintName, string! source) -> void
Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.CancellationToken.get -> System.Threading.CancellationToken
Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.IncrementalGeneratorPostInitializationContext() -> void
Microsoft.CodeAnalysis.IncrementalValueProvider<TValue>
Microsoft.CodeAnalysis.IncrementalValueProvider<TValue>.IncrementalValueProvider() -> void
Microsoft.CodeAnalysis.IncrementalValueProviderExtensions
Microsoft.CodeAnalysis.IncrementalValuesProvider<TValues>
Microsoft.CodeAnalysis.IncrementalValuesProvider<TValues>.IncrementalValuesProvider() -> void
Microsoft.CodeAnalysis.ISyntaxContextReceiver
Microsoft.CodeAnalysis.ISyntaxContextReceiver.OnVisitSyntaxNode(Microsoft.CodeAnalysis.GeneratorSyntaxContext context) -> void
Microsoft.CodeAnalysis.GeneratorInitializationContext.RegisterForPostInitialization(System.Action<Microsoft.CodeAnalysis.GeneratorPostInitializationContext>! callback) -> void
Microsoft.CodeAnalysis.GeneratorPostInitializationContext
Microsoft.CodeAnalysis.GeneratorPostInitializationContext.AddSource(string! hintName, Microsoft.CodeAnalysis.Text.SourceText! sourceText) -> void
Microsoft.CodeAnalysis.GeneratorPostInitializationContext.AddSource(string! hintName, string! source) -> void
Microsoft.CodeAnalysis.GeneratorPostInitializationContext.CancellationToken.get -> System.Threading.CancellationToken
Microsoft.CodeAnalysis.GeneratorPostInitializationContext.GeneratorPostInitializationContext() -> void
Microsoft.CodeAnalysis.IMethodSymbol.MethodImplementationFlags.get -> System.Reflection.MethodImplAttributes
Microsoft.CodeAnalysis.ITypeSymbol.IsRecord.get -> bool
Microsoft.CodeAnalysis.LineMapping
Microsoft.CodeAnalysis.LineMapping.CharacterOffset.get -> int?
Microsoft.CodeAnalysis.LineMapping.Equals(Microsoft.CodeAnalysis.LineMapping other) -> bool
Microsoft.CodeAnalysis.LineMapping.IsHidden.get -> bool
Microsoft.CodeAnalysis.LineMapping.LineMapping() -> void
Microsoft.CodeAnalysis.LineMapping.LineMapping(Microsoft.CodeAnalysis.Text.LinePositionSpan span, int? characterOffset, Microsoft.CodeAnalysis.FileLinePositionSpan mappedSpan) -> void
Microsoft.CodeAnalysis.LineMapping.MappedSpan.get -> Microsoft.CodeAnalysis.FileLinePositionSpan
Microsoft.CodeAnalysis.LineMapping.Span.get -> Microsoft.CodeAnalysis.Text.LinePositionSpan
override Microsoft.CodeAnalysis.LineMapping.Equals(object? obj) -> bool
override Microsoft.CodeAnalysis.LineMapping.GetHashCode() -> int
override Microsoft.CodeAnalysis.LineMapping.ToString() -> string?
Microsoft.CodeAnalysis.Operations.ISwitchExpressionOperation.IsExhaustive.get -> bool
Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument>
Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument>.OperationWalker() -> void
Microsoft.CodeAnalysis.SourceProductionContext
Microsoft.CodeAnalysis.SourceProductionContext.AddSource(string! hintName, Microsoft.CodeAnalysis.Text.SourceText! sourceText) -> void
Microsoft.CodeAnalysis.SourceProductionContext.AddSource(string! hintName, string! source) -> void
Microsoft.CodeAnalysis.SourceProductionContext.CancellationToken.get -> System.Threading.CancellationToken
Microsoft.CodeAnalysis.SourceProductionContext.ReportDiagnostic(Microsoft.CodeAnalysis.Diagnostic! diagnostic) -> void
Microsoft.CodeAnalysis.SourceProductionContext.SourceProductionContext() -> void
Microsoft.CodeAnalysis.SymbolDisplayPartKind.RecordClassName = 31 -> Microsoft.CodeAnalysis.SymbolDisplayPartKind
const Microsoft.CodeAnalysis.WellKnownDiagnosticTags.CompilationEnd = "CompilationEnd" -> string!
Microsoft.CodeAnalysis.SymbolDisplayPartKind.RecordStructName = 32 -> Microsoft.CodeAnalysis.SymbolDisplayPartKind
Microsoft.CodeAnalysis.SyntaxContextReceiverCreator
Microsoft.CodeAnalysis.SyntaxNode.IsEquivalentTo(Microsoft.CodeAnalysis.SyntaxNode? other) -> bool
Microsoft.CodeAnalysis.SyntaxNode.IsIncrementallyIdenticalTo(Microsoft.CodeAnalysis.SyntaxNode? other) -> bool
Microsoft.CodeAnalysis.SyntaxNodeOrToken.IsIncrementallyIdenticalTo(Microsoft.CodeAnalysis.SyntaxNodeOrToken other) -> bool
Microsoft.CodeAnalysis.SyntaxToken.IsIncrementallyIdenticalTo(Microsoft.CodeAnalysis.SyntaxToken token) -> bool
Microsoft.CodeAnalysis.SyntaxValueProvider
Microsoft.CodeAnalysis.SyntaxValueProvider.CreateSyntaxProvider<T>(System.Func<Microsoft.CodeAnalysis.SyntaxNode!, System.Threading.CancellationToken, bool>! predicate, System.Func<Microsoft.CodeAnalysis.GeneratorSyntaxContext, System.Threading.CancellationToken, T>! transform) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<T>
Microsoft.CodeAnalysis.SyntaxValueProvider.SyntaxValueProvider() -> void
override Microsoft.CodeAnalysis.Text.TextChangeRange.ToString() -> string!
readonly Microsoft.CodeAnalysis.GeneratorDriverOptions.DisabledOutputs -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind
static Microsoft.CodeAnalysis.CaseInsensitiveComparison.Compare(System.ReadOnlySpan<char> left, System.ReadOnlySpan<char> right) -> int
static Microsoft.CodeAnalysis.CaseInsensitiveComparison.Equals(System.ReadOnlySpan<char> left, System.ReadOnlySpan<char> right) -> bool
override Microsoft.CodeAnalysis.Diagnostics.AnalyzerFileReference.GetGenerators(string! language) -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!>
override Microsoft.CodeAnalysis.Diagnostics.AnalyzerFileReference.GetGeneratorsForAllLanguages() -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!>
override Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument>.DefaultVisit(Microsoft.CodeAnalysis.IOperation! operation, TArgument argument) -> object?
override Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument>.Visit(Microsoft.CodeAnalysis.IOperation? operation, TArgument argument) -> object?
static Microsoft.CodeAnalysis.Emit.SemanticEdit.operator !=(Microsoft.CodeAnalysis.Emit.SemanticEdit left, Microsoft.CodeAnalysis.Emit.SemanticEdit right) -> bool
static Microsoft.CodeAnalysis.Emit.SemanticEdit.operator ==(Microsoft.CodeAnalysis.Emit.SemanticEdit left, Microsoft.CodeAnalysis.Emit.SemanticEdit right) -> bool
static Microsoft.CodeAnalysis.FileLinePositionSpan.operator !=(Microsoft.CodeAnalysis.FileLinePositionSpan left, Microsoft.CodeAnalysis.FileLinePositionSpan right) -> bool
static Microsoft.CodeAnalysis.FileLinePositionSpan.operator ==(Microsoft.CodeAnalysis.FileLinePositionSpan left, Microsoft.CodeAnalysis.FileLinePositionSpan right) -> bool
static Microsoft.CodeAnalysis.GeneratorExtensions.AsSourceGenerator(this Microsoft.CodeAnalysis.IIncrementalGenerator! incrementalGenerator) -> Microsoft.CodeAnalysis.ISourceGenerator!
static Microsoft.CodeAnalysis.GeneratorExtensions.GetGeneratorType(this Microsoft.CodeAnalysis.ISourceGenerator! generator) -> System.Type!
static Microsoft.CodeAnalysis.LineMapping.operator !=(Microsoft.CodeAnalysis.LineMapping left, Microsoft.CodeAnalysis.LineMapping right) -> bool
static Microsoft.CodeAnalysis.LineMapping.operator ==(Microsoft.CodeAnalysis.LineMapping left, Microsoft.CodeAnalysis.LineMapping right) -> bool
static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Collect<TSource>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source) -> Microsoft.CodeAnalysis.IncrementalValueProvider<System.Collections.Immutable.ImmutableArray<TSource>>
static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Combine<TLeft, TRight>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TLeft> provider1, Microsoft.CodeAnalysis.IncrementalValueProvider<TRight> provider2) -> Microsoft.CodeAnalysis.IncrementalValueProvider<(TLeft Left, TRight Right)>
static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Combine<TLeft, TRight>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TLeft> provider1, Microsoft.CodeAnalysis.IncrementalValueProvider<TRight> provider2) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<(TLeft Left, TRight Right)>
static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Select<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, TResult>! selector) -> Microsoft.CodeAnalysis.IncrementalValueProvider<TResult>
static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Select<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, TResult>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult>
static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Generic.IEnumerable<TResult>!>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult>
static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Immutable.ImmutableArray<TResult>>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult>
static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Generic.IEnumerable<TResult>!>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult>
static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Immutable.ImmutableArray<TResult>>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult>
static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Where<TSource>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, bool>! predicate) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource>
static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.WithComparer<TSource>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Collections.Generic.IEqualityComparer<TSource>! comparer) -> Microsoft.CodeAnalysis.IncrementalValueProvider<TSource>
static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.WithComparer<TSource>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Collections.Generic.IEqualityComparer<TSource>! comparer) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource>
virtual Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference.GetGenerators(string! language) -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!>
virtual Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference.GetGeneratorsForAllLanguages() -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!>
abstract Microsoft.CodeAnalysis.Compilation.GetUsedAssemblyReferences(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.MetadataReference!>
| *REMOVED*Microsoft.CodeAnalysis.SyntaxNode.IsEquivalentTo(Microsoft.CodeAnalysis.SyntaxNode! other) -> bool
abstract Microsoft.CodeAnalysis.SyntaxTree.GetLineMappings(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.LineMapping>!
const Microsoft.CodeAnalysis.WellKnownMemberNames.PrintMembersMethodName = "PrintMembers" -> string!
Microsoft.CodeAnalysis.Compilation.EmitDifference(Microsoft.CodeAnalysis.Emit.EmitBaseline! baseline, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Emit.SemanticEdit>! edits, System.Func<Microsoft.CodeAnalysis.ISymbol!, bool>! isAddedSymbol, System.IO.Stream! metadataStream, System.IO.Stream! ilStream, System.IO.Stream! pdbStream, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> Microsoft.CodeAnalysis.Emit.EmitDifferenceResult!
Microsoft.CodeAnalysis.Emit.EmitDifferenceResult.ChangedTypes.get -> System.Collections.Immutable.ImmutableArray<System.Reflection.Metadata.TypeDefinitionHandle>
Microsoft.CodeAnalysis.Emit.EmitDifferenceResult.UpdatedMethods.get -> System.Collections.Immutable.ImmutableArray<System.Reflection.Metadata.MethodDefinitionHandle>
Microsoft.CodeAnalysis.Emit.SemanticEditKind.Replace = 4 -> Microsoft.CodeAnalysis.Emit.SemanticEditKind
Microsoft.CodeAnalysis.GeneratorAttribute.GeneratorAttribute(string! firstLanguage, params string![]! additionalLanguages) -> void
Microsoft.CodeAnalysis.GeneratorAttribute.Languages.get -> string![]!
Microsoft.CodeAnalysis.GeneratorDriver.ReplaceAdditionalText(Microsoft.CodeAnalysis.AdditionalText! oldText, Microsoft.CodeAnalysis.AdditionalText! newText) -> Microsoft.CodeAnalysis.GeneratorDriver!
Microsoft.CodeAnalysis.GeneratorDriver.WithUpdatedAnalyzerConfigOptions(Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider! newOptions) -> Microsoft.CodeAnalysis.GeneratorDriver!
Microsoft.CodeAnalysis.GeneratorDriver.WithUpdatedParseOptions(Microsoft.CodeAnalysis.ParseOptions! newOptions) -> Microsoft.CodeAnalysis.GeneratorDriver!
Microsoft.CodeAnalysis.GeneratorDriverOptions
Microsoft.CodeAnalysis.GeneratorDriverOptions.GeneratorDriverOptions() -> void
Microsoft.CodeAnalysis.GeneratorDriverOptions.GeneratorDriverOptions(Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind disabledOutputs) -> void
Microsoft.CodeAnalysis.GeneratorExtensions
Microsoft.CodeAnalysis.IFieldSymbol.IsExplicitlyNamedTupleElement.get -> bool
Microsoft.CodeAnalysis.GeneratorExecutionContext.SyntaxContextReceiver.get -> Microsoft.CodeAnalysis.ISyntaxContextReceiver?
Microsoft.CodeAnalysis.GeneratorInitializationContext.RegisterForSyntaxNotifications(Microsoft.CodeAnalysis.SyntaxContextReceiverCreator! receiverCreator) -> void
Microsoft.CodeAnalysis.GeneratorSyntaxContext
Microsoft.CodeAnalysis.GeneratorSyntaxContext.GeneratorSyntaxContext() -> void
Microsoft.CodeAnalysis.GeneratorSyntaxContext.Node.get -> Microsoft.CodeAnalysis.SyntaxNode!
Microsoft.CodeAnalysis.GeneratorSyntaxContext.SemanticModel.get -> Microsoft.CodeAnalysis.SemanticModel!
Microsoft.CodeAnalysis.IIncrementalGenerator
Microsoft.CodeAnalysis.IIncrementalGenerator.Initialize(Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext context) -> void
Microsoft.CodeAnalysis.IMethodSymbol.IsPartialDefinition.get -> bool
Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext
Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.AdditionalTextsProvider.get -> Microsoft.CodeAnalysis.IncrementalValuesProvider<Microsoft.CodeAnalysis.AdditionalText!>
Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.AnalyzerConfigOptionsProvider.get -> Microsoft.CodeAnalysis.IncrementalValueProvider<Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptionsProvider!>
Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.CompilationProvider.get -> Microsoft.CodeAnalysis.IncrementalValueProvider<Microsoft.CodeAnalysis.Compilation!>
Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.IncrementalGeneratorInitializationContext() -> void
Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.ParseOptionsProvider.get -> Microsoft.CodeAnalysis.IncrementalValueProvider<Microsoft.CodeAnalysis.ParseOptions!>
Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterImplementationSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void
Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterImplementationSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void
Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterPostInitializationOutput(System.Action<Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext>! callback) -> void
Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void
Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.RegisterSourceOutput<TSource>(Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Action<Microsoft.CodeAnalysis.SourceProductionContext, TSource>! action) -> void
Microsoft.CodeAnalysis.IncrementalGeneratorInitializationContext.SyntaxProvider.get -> Microsoft.CodeAnalysis.SyntaxValueProvider
Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind
Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.Implementation = 4 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind
Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.None = 0 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind
Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.PostInit = 2 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind
Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind.Source = 1 -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind
Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext
Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.AddSource(string! hintName, Microsoft.CodeAnalysis.Text.SourceText! sourceText) -> void
Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.AddSource(string! hintName, string! source) -> void
Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.CancellationToken.get -> System.Threading.CancellationToken
Microsoft.CodeAnalysis.IncrementalGeneratorPostInitializationContext.IncrementalGeneratorPostInitializationContext() -> void
Microsoft.CodeAnalysis.IncrementalValueProvider<TValue>
Microsoft.CodeAnalysis.IncrementalValueProvider<TValue>.IncrementalValueProvider() -> void
Microsoft.CodeAnalysis.IncrementalValueProviderExtensions
Microsoft.CodeAnalysis.IncrementalValuesProvider<TValues>
Microsoft.CodeAnalysis.IncrementalValuesProvider<TValues>.IncrementalValuesProvider() -> void
Microsoft.CodeAnalysis.ISyntaxContextReceiver
Microsoft.CodeAnalysis.ISyntaxContextReceiver.OnVisitSyntaxNode(Microsoft.CodeAnalysis.GeneratorSyntaxContext context) -> void
Microsoft.CodeAnalysis.GeneratorInitializationContext.RegisterForPostInitialization(System.Action<Microsoft.CodeAnalysis.GeneratorPostInitializationContext>! callback) -> void
Microsoft.CodeAnalysis.GeneratorPostInitializationContext
Microsoft.CodeAnalysis.GeneratorPostInitializationContext.AddSource(string! hintName, Microsoft.CodeAnalysis.Text.SourceText! sourceText) -> void
Microsoft.CodeAnalysis.GeneratorPostInitializationContext.AddSource(string! hintName, string! source) -> void
Microsoft.CodeAnalysis.GeneratorPostInitializationContext.CancellationToken.get -> System.Threading.CancellationToken
Microsoft.CodeAnalysis.GeneratorPostInitializationContext.GeneratorPostInitializationContext() -> void
Microsoft.CodeAnalysis.IMethodSymbol.MethodImplementationFlags.get -> System.Reflection.MethodImplAttributes
Microsoft.CodeAnalysis.ITypeSymbol.IsRecord.get -> bool
Microsoft.CodeAnalysis.LineMapping
Microsoft.CodeAnalysis.LineMapping.CharacterOffset.get -> int?
Microsoft.CodeAnalysis.LineMapping.Equals(Microsoft.CodeAnalysis.LineMapping other) -> bool
Microsoft.CodeAnalysis.LineMapping.IsHidden.get -> bool
Microsoft.CodeAnalysis.LineMapping.LineMapping() -> void
Microsoft.CodeAnalysis.LineMapping.LineMapping(Microsoft.CodeAnalysis.Text.LinePositionSpan span, int? characterOffset, Microsoft.CodeAnalysis.FileLinePositionSpan mappedSpan) -> void
Microsoft.CodeAnalysis.LineMapping.MappedSpan.get -> Microsoft.CodeAnalysis.FileLinePositionSpan
Microsoft.CodeAnalysis.LineMapping.Span.get -> Microsoft.CodeAnalysis.Text.LinePositionSpan
override Microsoft.CodeAnalysis.LineMapping.Equals(object? obj) -> bool
override Microsoft.CodeAnalysis.LineMapping.GetHashCode() -> int
override Microsoft.CodeAnalysis.LineMapping.ToString() -> string?
Microsoft.CodeAnalysis.Operations.ISwitchExpressionOperation.IsExhaustive.get -> bool
Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument>
Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument>.OperationWalker() -> void
Microsoft.CodeAnalysis.SourceProductionContext
Microsoft.CodeAnalysis.SourceProductionContext.AddSource(string! hintName, Microsoft.CodeAnalysis.Text.SourceText! sourceText) -> void
Microsoft.CodeAnalysis.SourceProductionContext.AddSource(string! hintName, string! source) -> void
Microsoft.CodeAnalysis.SourceProductionContext.CancellationToken.get -> System.Threading.CancellationToken
Microsoft.CodeAnalysis.SourceProductionContext.ReportDiagnostic(Microsoft.CodeAnalysis.Diagnostic! diagnostic) -> void
Microsoft.CodeAnalysis.SourceProductionContext.SourceProductionContext() -> void
Microsoft.CodeAnalysis.SymbolDisplayPartKind.RecordClassName = 31 -> Microsoft.CodeAnalysis.SymbolDisplayPartKind
const Microsoft.CodeAnalysis.WellKnownDiagnosticTags.CompilationEnd = "CompilationEnd" -> string!
Microsoft.CodeAnalysis.SymbolDisplayPartKind.RecordStructName = 32 -> Microsoft.CodeAnalysis.SymbolDisplayPartKind
Microsoft.CodeAnalysis.SyntaxContextReceiverCreator
Microsoft.CodeAnalysis.SyntaxNode.IsEquivalentTo(Microsoft.CodeAnalysis.SyntaxNode? other) -> bool
Microsoft.CodeAnalysis.SyntaxNode.IsIncrementallyIdenticalTo(Microsoft.CodeAnalysis.SyntaxNode? other) -> bool
Microsoft.CodeAnalysis.SyntaxNodeOrToken.IsIncrementallyIdenticalTo(Microsoft.CodeAnalysis.SyntaxNodeOrToken other) -> bool
Microsoft.CodeAnalysis.SyntaxToken.IsIncrementallyIdenticalTo(Microsoft.CodeAnalysis.SyntaxToken token) -> bool
Microsoft.CodeAnalysis.SyntaxValueProvider
Microsoft.CodeAnalysis.SyntaxValueProvider.CreateSyntaxProvider<T>(System.Func<Microsoft.CodeAnalysis.SyntaxNode!, System.Threading.CancellationToken, bool>! predicate, System.Func<Microsoft.CodeAnalysis.GeneratorSyntaxContext, System.Threading.CancellationToken, T>! transform) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<T>
Microsoft.CodeAnalysis.SyntaxValueProvider.SyntaxValueProvider() -> void
override Microsoft.CodeAnalysis.Text.TextChangeRange.ToString() -> string!
readonly Microsoft.CodeAnalysis.GeneratorDriverOptions.DisabledOutputs -> Microsoft.CodeAnalysis.IncrementalGeneratorOutputKind
static Microsoft.CodeAnalysis.CaseInsensitiveComparison.Compare(System.ReadOnlySpan<char> left, System.ReadOnlySpan<char> right) -> int
static Microsoft.CodeAnalysis.CaseInsensitiveComparison.Equals(System.ReadOnlySpan<char> left, System.ReadOnlySpan<char> right) -> bool
override Microsoft.CodeAnalysis.Diagnostics.AnalyzerFileReference.GetGenerators(string! language) -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!>
override Microsoft.CodeAnalysis.Diagnostics.AnalyzerFileReference.GetGeneratorsForAllLanguages() -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!>
override Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument>.DefaultVisit(Microsoft.CodeAnalysis.IOperation! operation, TArgument argument) -> object?
override Microsoft.CodeAnalysis.Operations.OperationWalker<TArgument>.Visit(Microsoft.CodeAnalysis.IOperation? operation, TArgument argument) -> object?
static Microsoft.CodeAnalysis.Emit.SemanticEdit.operator !=(Microsoft.CodeAnalysis.Emit.SemanticEdit left, Microsoft.CodeAnalysis.Emit.SemanticEdit right) -> bool
static Microsoft.CodeAnalysis.Emit.SemanticEdit.operator ==(Microsoft.CodeAnalysis.Emit.SemanticEdit left, Microsoft.CodeAnalysis.Emit.SemanticEdit right) -> bool
static Microsoft.CodeAnalysis.FileLinePositionSpan.operator !=(Microsoft.CodeAnalysis.FileLinePositionSpan left, Microsoft.CodeAnalysis.FileLinePositionSpan right) -> bool
static Microsoft.CodeAnalysis.FileLinePositionSpan.operator ==(Microsoft.CodeAnalysis.FileLinePositionSpan left, Microsoft.CodeAnalysis.FileLinePositionSpan right) -> bool
static Microsoft.CodeAnalysis.GeneratorExtensions.AsSourceGenerator(this Microsoft.CodeAnalysis.IIncrementalGenerator! incrementalGenerator) -> Microsoft.CodeAnalysis.ISourceGenerator!
static Microsoft.CodeAnalysis.GeneratorExtensions.GetGeneratorType(this Microsoft.CodeAnalysis.ISourceGenerator! generator) -> System.Type!
static Microsoft.CodeAnalysis.LineMapping.operator !=(Microsoft.CodeAnalysis.LineMapping left, Microsoft.CodeAnalysis.LineMapping right) -> bool
static Microsoft.CodeAnalysis.LineMapping.operator ==(Microsoft.CodeAnalysis.LineMapping left, Microsoft.CodeAnalysis.LineMapping right) -> bool
static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Collect<TSource>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source) -> Microsoft.CodeAnalysis.IncrementalValueProvider<System.Collections.Immutable.ImmutableArray<TSource>>
static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Combine<TLeft, TRight>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TLeft> provider1, Microsoft.CodeAnalysis.IncrementalValueProvider<TRight> provider2) -> Microsoft.CodeAnalysis.IncrementalValueProvider<(TLeft Left, TRight Right)>
static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Combine<TLeft, TRight>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TLeft> provider1, Microsoft.CodeAnalysis.IncrementalValueProvider<TRight> provider2) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<(TLeft Left, TRight Right)>
static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Select<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, TResult>! selector) -> Microsoft.CodeAnalysis.IncrementalValueProvider<TResult>
static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Select<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, TResult>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult>
static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Generic.IEnumerable<TResult>!>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult>
static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Immutable.ImmutableArray<TResult>>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult>
static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Generic.IEnumerable<TResult>!>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult>
static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.SelectMany<TSource, TResult>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, System.Threading.CancellationToken, System.Collections.Immutable.ImmutableArray<TResult>>! selector) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TResult>
static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.Where<TSource>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Func<TSource, bool>! predicate) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource>
static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.WithComparer<TSource>(this Microsoft.CodeAnalysis.IncrementalValueProvider<TSource> source, System.Collections.Generic.IEqualityComparer<TSource>! comparer) -> Microsoft.CodeAnalysis.IncrementalValueProvider<TSource>
static Microsoft.CodeAnalysis.IncrementalValueProviderExtensions.WithComparer<TSource>(this Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource> source, System.Collections.Generic.IEqualityComparer<TSource>! comparer) -> Microsoft.CodeAnalysis.IncrementalValuesProvider<TSource>
virtual Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference.GetGenerators(string! language) -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!>
virtual Microsoft.CodeAnalysis.Diagnostics.AnalyzerReference.GetGeneratorsForAllLanguages() -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ISourceGenerator!>
abstract Microsoft.CodeAnalysis.Compilation.GetUsedAssemblyReferences(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.MetadataReference!>
| 1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Compilers/Test/Core/Compilation/CompilationDifference.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.DiaSymReader.Tools;
using Microsoft.Metadata.Tools;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public sealed class CompilationDifference
{
public readonly ImmutableArray<byte> MetadataDelta;
public readonly ImmutableArray<byte> ILDelta;
public readonly ImmutableArray<byte> PdbDelta;
internal readonly CompilationTestData TestData;
public readonly EmitDifferenceResult EmitResult;
internal CompilationDifference(
ImmutableArray<byte> metadata,
ImmutableArray<byte> il,
ImmutableArray<byte> pdb,
CompilationTestData testData,
EmitDifferenceResult result)
{
MetadataDelta = metadata;
ILDelta = il;
PdbDelta = pdb;
TestData = testData;
EmitResult = result;
}
public EmitBaseline NextGeneration
{
get
{
return EmitResult.Baseline;
}
}
internal PinnedMetadata GetMetadata()
{
return new PinnedMetadata(MetadataDelta);
}
public void VerifyIL(
string expectedIL,
[CallerLineNumber] int callerLine = 0,
[CallerFilePath] string callerPath = null)
{
string actualIL = ILDelta.GetMethodIL();
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL, escapeQuotes: true, expectedValueSourcePath: callerPath, expectedValueSourceLine: callerLine);
}
public void VerifyLocalSignature(
string qualifiedMethodName,
string expectedSignature,
[CallerLineNumber] int callerLine = 0,
[CallerFilePath] string callerPath = null)
{
var ilBuilder = TestData.GetMethodData(qualifiedMethodName).ILBuilder;
string actualSignature = ILBuilderVisualizer.LocalSignatureToString(ilBuilder, ToLocalInfo);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedSignature, actualSignature, escapeQuotes: true, expectedValueSourcePath: callerPath, expectedValueSourceLine: callerLine);
}
internal void VerifyIL(
string qualifiedMethodName,
string expectedIL,
Func<Cci.ILocalDefinition, ILVisualizer.LocalInfo> mapLocal = null,
MethodDefinitionHandle methodToken = default,
[CallerFilePath] string callerPath = null,
[CallerLineNumber] int callerLine = 0)
{
var ilBuilder = TestData.GetMethodData(qualifiedMethodName).ILBuilder;
Dictionary<int, string> sequencePointMarkers = null;
if (!methodToken.IsNil)
{
string actualPdb = PdbToXmlConverter.DeltaPdbToXml(new ImmutableMemoryStream(PdbDelta), new[] { MetadataTokens.GetToken(methodToken) });
sequencePointMarkers = ILValidation.GetSequencePointMarkers(actualPdb);
Assert.True(sequencePointMarkers.Count > 0, $"No sequence points found in:{Environment.NewLine}{actualPdb}");
}
string actualIL = ILBuilderVisualizer.ILBuilderToString(ilBuilder, mapLocal ?? ToLocalInfo, sequencePointMarkers);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL, escapeQuotes: true, expectedValueSourcePath: callerPath, expectedValueSourceLine: callerLine);
}
internal string GetMethodIL(string qualifiedMethodName)
{
return ILBuilderVisualizer.ILBuilderToString(this.TestData.GetMethodData(qualifiedMethodName).ILBuilder, ToLocalInfo);
}
private static ILVisualizer.LocalInfo ToLocalInfo(Cci.ILocalDefinition local)
{
var signature = local.Signature;
if (signature == null)
{
return new ILVisualizer.LocalInfo(local.Name, local.Type, local.IsPinned, local.IsReference);
}
else
{
// Decode simple types only.
var typeName = (signature.Length == 1) ? GetTypeName((SignatureTypeCode)signature[0]) : null;
return new ILVisualizer.LocalInfo(null, typeName ?? "[unchanged]", false, false);
}
}
private static string GetTypeName(SignatureTypeCode typeCode)
{
switch (typeCode)
{
case SignatureTypeCode.Boolean: return "[bool]";
case SignatureTypeCode.Int32: return "[int]";
case SignatureTypeCode.String: return "[string]";
case SignatureTypeCode.Object: return "[object]";
default: return null;
}
}
public void VerifySynthesizedMembers(params string[] expectedSynthesizedTypesAndMemberCounts)
{
var actual = EmitResult.Baseline.SynthesizedMembers.Select(e => e.Key.ToString() + ": {" + string.Join(", ", e.Value.Select(v => v.Name)) + "}");
AssertEx.SetEqual(expectedSynthesizedTypesAndMemberCounts, actual, itemSeparator: "\r\n");
}
public void VerifySynthesizedFields(string typeName, params string[] expectedSynthesizedTypesAndMemberCounts)
{
var actual = EmitResult.Baseline.SynthesizedMembers.Single(e => e.Key.ToString() == typeName).Value.Where(s => s.Kind == SymbolKind.Field).Select(s => (IFieldSymbol)s.GetISymbol()).Select(f => f.Name + ": " + f.Type);
AssertEx.SetEqual(expectedSynthesizedTypesAndMemberCounts, actual, itemSeparator: "\r\n");
}
public void VerifyUpdatedMethods(params string[] expectedMethodTokens)
{
AssertEx.Equal(
expectedMethodTokens,
EmitResult.UpdatedMethods.Select(methodHandle => $"0x{MetadataTokens.GetToken(methodHandle):X8}"));
}
public void VerifyUpdatedTypes(params string[] expectedTypeTokens)
{
AssertEx.Equal(
expectedTypeTokens,
EmitResult.UpdatedTypes.Select(typeHandle => $"0x{MetadataTokens.GetToken(typeHandle):X8}"));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.DiaSymReader.Tools;
using Microsoft.Metadata.Tools;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public sealed class CompilationDifference
{
public readonly ImmutableArray<byte> MetadataDelta;
public readonly ImmutableArray<byte> ILDelta;
public readonly ImmutableArray<byte> PdbDelta;
internal readonly CompilationTestData TestData;
public readonly EmitDifferenceResult EmitResult;
internal CompilationDifference(
ImmutableArray<byte> metadata,
ImmutableArray<byte> il,
ImmutableArray<byte> pdb,
CompilationTestData testData,
EmitDifferenceResult result)
{
MetadataDelta = metadata;
ILDelta = il;
PdbDelta = pdb;
TestData = testData;
EmitResult = result;
}
public EmitBaseline NextGeneration
{
get
{
return EmitResult.Baseline;
}
}
internal PinnedMetadata GetMetadata()
{
return new PinnedMetadata(MetadataDelta);
}
public void VerifyIL(
string expectedIL,
[CallerLineNumber] int callerLine = 0,
[CallerFilePath] string callerPath = null)
{
string actualIL = ILDelta.GetMethodIL();
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL, escapeQuotes: true, expectedValueSourcePath: callerPath, expectedValueSourceLine: callerLine);
}
public void VerifyLocalSignature(
string qualifiedMethodName,
string expectedSignature,
[CallerLineNumber] int callerLine = 0,
[CallerFilePath] string callerPath = null)
{
var ilBuilder = TestData.GetMethodData(qualifiedMethodName).ILBuilder;
string actualSignature = ILBuilderVisualizer.LocalSignatureToString(ilBuilder, ToLocalInfo);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedSignature, actualSignature, escapeQuotes: true, expectedValueSourcePath: callerPath, expectedValueSourceLine: callerLine);
}
internal void VerifyIL(
string qualifiedMethodName,
string expectedIL,
Func<Cci.ILocalDefinition, ILVisualizer.LocalInfo> mapLocal = null,
MethodDefinitionHandle methodToken = default,
[CallerFilePath] string callerPath = null,
[CallerLineNumber] int callerLine = 0)
{
var ilBuilder = TestData.GetMethodData(qualifiedMethodName).ILBuilder;
Dictionary<int, string> sequencePointMarkers = null;
if (!methodToken.IsNil)
{
string actualPdb = PdbToXmlConverter.DeltaPdbToXml(new ImmutableMemoryStream(PdbDelta), new[] { MetadataTokens.GetToken(methodToken) });
sequencePointMarkers = ILValidation.GetSequencePointMarkers(actualPdb);
Assert.True(sequencePointMarkers.Count > 0, $"No sequence points found in:{Environment.NewLine}{actualPdb}");
}
string actualIL = ILBuilderVisualizer.ILBuilderToString(ilBuilder, mapLocal ?? ToLocalInfo, sequencePointMarkers);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL, escapeQuotes: true, expectedValueSourcePath: callerPath, expectedValueSourceLine: callerLine);
}
internal string GetMethodIL(string qualifiedMethodName)
{
return ILBuilderVisualizer.ILBuilderToString(this.TestData.GetMethodData(qualifiedMethodName).ILBuilder, ToLocalInfo);
}
private static ILVisualizer.LocalInfo ToLocalInfo(Cci.ILocalDefinition local)
{
var signature = local.Signature;
if (signature == null)
{
return new ILVisualizer.LocalInfo(local.Name, local.Type, local.IsPinned, local.IsReference);
}
else
{
// Decode simple types only.
var typeName = (signature.Length == 1) ? GetTypeName((SignatureTypeCode)signature[0]) : null;
return new ILVisualizer.LocalInfo(null, typeName ?? "[unchanged]", false, false);
}
}
private static string GetTypeName(SignatureTypeCode typeCode)
{
switch (typeCode)
{
case SignatureTypeCode.Boolean: return "[bool]";
case SignatureTypeCode.Int32: return "[int]";
case SignatureTypeCode.String: return "[string]";
case SignatureTypeCode.Object: return "[object]";
default: return null;
}
}
public void VerifySynthesizedMembers(params string[] expectedSynthesizedTypesAndMemberCounts)
{
var actual = EmitResult.Baseline.SynthesizedMembers.Select(e => e.Key.ToString() + ": {" + string.Join(", ", e.Value.Select(v => v.Name)) + "}");
AssertEx.SetEqual(expectedSynthesizedTypesAndMemberCounts, actual, itemSeparator: "\r\n");
}
public void VerifySynthesizedFields(string typeName, params string[] expectedSynthesizedTypesAndMemberCounts)
{
var actual = EmitResult.Baseline.SynthesizedMembers.Single(e => e.Key.ToString() == typeName).Value.Where(s => s.Kind == SymbolKind.Field).Select(s => (IFieldSymbol)s.GetISymbol()).Select(f => f.Name + ": " + f.Type);
AssertEx.SetEqual(expectedSynthesizedTypesAndMemberCounts, actual, itemSeparator: "\r\n");
}
public void VerifyUpdatedMethods(params string[] expectedMethodTokens)
{
AssertEx.Equal(
expectedMethodTokens,
EmitResult.UpdatedMethods.Select(methodHandle => $"0x{MetadataTokens.GetToken(methodHandle):X8}"));
}
}
}
| 1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Compilers/Test/Core/Metadata/MetadataReaderUtils.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Roslyn.Test.Utilities
{
internal static class MetadataReaderUtils
{
internal static IEnumerable<ConstantHandle> GetConstants(this MetadataReader reader)
{
for (int i = 1, n = reader.GetTableRowCount(TableIndex.Constant); i <= n; i++)
{
yield return MetadataTokens.ConstantHandle(i);
}
}
internal static IEnumerable<ParameterHandle> GetParameters(this MetadataReader reader)
{
for (int i = 1, n = reader.GetTableRowCount(TableIndex.Param); i <= n; i++)
{
yield return MetadataTokens.ParameterHandle(i);
}
}
internal static IEnumerable<GenericParameterHandle> GetGenericParameters(this MetadataReader reader)
{
for (int i = 1, n = reader.GetTableRowCount(TableIndex.GenericParam); i <= n; i++)
{
yield return MetadataTokens.GenericParameterHandle(i);
}
}
internal static IEnumerable<GenericParameterConstraintHandle> GetGenericParameterConstraints(this MetadataReader reader)
{
for (int i = 1, n = reader.GetTableRowCount(TableIndex.GenericParamConstraint); i <= n; i++)
{
yield return MetadataTokens.GenericParameterConstraintHandle(i);
}
}
internal static IEnumerable<ModuleReferenceHandle> GetModuleReferences(this MetadataReader reader)
{
for (int i = 1, n = reader.GetTableRowCount(TableIndex.ModuleRef); i <= n; i++)
{
yield return MetadataTokens.ModuleReferenceHandle(i);
}
}
internal static IEnumerable<MethodDefinition> GetImportedMethods(this MetadataReader reader)
{
return from handle in reader.MethodDefinitions
let method = reader.GetMethodDefinition(handle)
let import = method.GetImport()
where !import.Name.IsNil
select method;
}
internal static bool RequiresAmdInstructionSet(this PEHeaders headers)
{
return headers.CoffHeader.Machine == Machine.Amd64;
}
internal static bool Requires64Bits(this PEHeaders headers)
{
return headers.PEHeader != null && headers.PEHeader.Magic == PEMagic.PE32Plus
|| headers.CoffHeader.Machine == Machine.Amd64
|| headers.CoffHeader.Machine == Machine.IA64;
}
public static string GetString(this IEnumerable<MetadataReader> readers, StringHandle handle)
{
int index = MetadataTokens.GetHeapOffset(handle);
foreach (var reader in readers)
{
int length = reader.GetHeapSize(HeapIndex.String);
if (index < length)
{
return reader.GetString(MetadataTokens.StringHandle(index));
}
index -= length;
}
return null;
}
public static string[] GetStrings(this IEnumerable<MetadataReader> readers, IEnumerable<StringHandle> handles)
{
return handles.Select(handle => readers.GetString(handle)).ToArray();
}
public static Guid GetModuleVersionId(this MetadataReader reader)
{
return reader.GetGuid(reader.GetModuleDefinition().Mvid);
}
public static StringHandle[] GetUpdatedTypeDefNames(this MetadataReader reader, EmitDifferenceResult emitResult)
{
return emitResult.UpdatedTypes.Select(handle => reader.GetTypeDefinition(handle).Name).ToArray();
}
public static StringHandle[] GetAssemblyRefNames(this MetadataReader reader)
{
return reader.AssemblyReferences.Select(handle => reader.GetAssemblyReference(handle).Name).ToArray();
}
public static StringHandle[] GetTypeDefNames(this MetadataReader reader)
{
return reader.TypeDefinitions.Select(handle => reader.GetTypeDefinition(handle).Name).ToArray();
}
public static (StringHandle Namespace, StringHandle Name)[] GetTypeDefFullNames(this MetadataReader reader)
{
return reader.TypeDefinitions.Select(handle =>
{
var td = reader.GetTypeDefinition(handle);
return (td.Namespace, td.Name);
}).ToArray();
}
public static StringHandle[] GetTypeRefNames(this MetadataReader reader)
{
return reader.TypeReferences.Select(handle => reader.GetTypeReference(handle).Name).ToArray();
}
public static StringHandle[] GetEventDefNames(this MetadataReader reader)
{
return reader.EventDefinitions.Select(handle => reader.GetEventDefinition(handle).Name).ToArray();
}
public static StringHandle[] GetFieldDefNames(this MetadataReader reader)
{
return reader.FieldDefinitions.Select(handle => reader.GetFieldDefinition(handle).Name).ToArray();
}
public static StringHandle[] GetMethodDefNames(this MetadataReader reader)
{
return reader.MethodDefinitions.Select(handle => reader.GetMethodDefinition(handle).Name).ToArray();
}
public static StringHandle[] GetMemberRefNames(this MetadataReader reader)
{
return reader.MemberReferences.Select(handle => reader.GetMemberReference(handle).Name).ToArray();
}
public static StringHandle[] GetParameterDefNames(this MetadataReader reader)
{
return reader.GetParameters().Select(handle => reader.GetParameter(handle).Name).ToArray();
}
public static StringHandle[] GetPropertyDefNames(this MetadataReader reader)
{
return reader.PropertyDefinitions.Select(handle => reader.GetPropertyDefinition(handle).Name).ToArray();
}
public static StringHandle GetName(this MetadataReader reader, EntityHandle token)
{
switch (token.Kind)
{
case HandleKind.TypeReference:
return reader.GetTypeReference((TypeReferenceHandle)token).Name;
case HandleKind.TypeDefinition:
return reader.GetTypeDefinition((TypeDefinitionHandle)token).Name;
default:
throw ExceptionUtilities.UnexpectedValue(token.Kind);
}
}
private delegate T ReadBlobItemDelegate<T>(ref BlobReader blobReader);
private static ImmutableArray<T> ReadArray<T>(this MetadataReader reader, BlobHandle blobHandle, ReadBlobItemDelegate<T> readItem)
{
var blobReader = reader.GetBlobReader(blobHandle);
// Prolog
blobReader.ReadUInt16();
// Array size
int n = blobReader.ReadInt32();
var builder = ArrayBuilder<T>.GetInstance(n);
for (int i = 0; i < n; i++)
{
builder.Add(readItem(ref blobReader));
}
return builder.ToImmutableAndFree();
}
public static ImmutableArray<byte> ReadByteArray(this MetadataReader reader, BlobHandle blobHandle)
{
return ReadArray(reader, blobHandle, (ref BlobReader blobReader) => blobReader.ReadByte());
}
public static ImmutableArray<bool> ReadBoolArray(this MetadataReader reader, BlobHandle blobHandle)
{
return ReadArray(reader, blobHandle, (ref BlobReader blobReader) => blobReader.ReadBoolean());
}
public static IEnumerable<CustomAttributeRow> GetCustomAttributeRows(this MetadataReader reader)
{
foreach (var handle in reader.CustomAttributes)
{
var attribute = reader.GetCustomAttribute(handle);
yield return new CustomAttributeRow(attribute.Parent, attribute.Constructor);
}
}
public static string GetCustomAttributeName(this MetadataReader reader, CustomAttributeRow row)
{
EntityHandle parent;
var token = row.ConstructorToken;
switch (token.Kind)
{
case HandleKind.MemberReference:
parent = reader.GetMemberReference((MemberReferenceHandle)token).Parent;
break;
case HandleKind.MethodDefinition:
parent = reader.GetMethodDefinition((MethodDefinitionHandle)token).GetDeclaringType();
break;
default:
throw ExceptionUtilities.UnexpectedValue(token.Kind);
}
var strHandle = reader.GetName(parent);
return reader.GetString(strHandle);
}
public static bool IsIncluded(this ImmutableArray<byte> metadata, string str)
{
var builder = ArrayBuilder<byte>.GetInstance();
builder.AddRange(System.Text.Encoding.UTF8.GetBytes(str));
builder.Add(0); // Add null terminator.
var bytes = builder.ToImmutableAndFree();
for (int i = 0; i < metadata.Length - bytes.Length; i++)
{
if (metadata.IsAtIndex(bytes, i))
{
return true;
}
}
return false;
}
public static bool IsAtIndex(this ImmutableArray<byte> metadata, ImmutableArray<byte> bytes, int offset)
{
for (int i = 0; i < bytes.Length; i++)
{
if (metadata[i + offset] != bytes[i])
{
return false;
}
}
return true;
}
public static ImmutableArray<byte> GetSourceLinkBlob(this MetadataReader reader)
{
return (from handle in reader.CustomDebugInformation
let cdi = reader.GetCustomDebugInformation(handle)
where reader.GetGuid(cdi.Kind) == PortableCustomDebugInfoKinds.SourceLink
select reader.GetBlobContent(cdi.Value)).Single();
}
public static SourceText GetEmbeddedSource(this MetadataReader reader, DocumentHandle document)
{
byte[] bytes = (from handle in reader.GetCustomDebugInformation(document)
let cdi = reader.GetCustomDebugInformation(handle)
where reader.GetGuid(cdi.Kind) == PortableCustomDebugInfoKinds.EmbeddedSource
select reader.GetBlobBytes(cdi.Value)).SingleOrDefault();
if (bytes == null)
{
return null;
}
int uncompressedSize = BitConverter.ToInt32(bytes, 0);
var stream = new MemoryStream(bytes, sizeof(int), bytes.Length - sizeof(int));
if (uncompressedSize != 0)
{
var decompressed = new MemoryStream(uncompressedSize);
using (var deflater = new DeflateStream(stream, CompressionMode.Decompress))
{
deflater.CopyTo(decompressed);
}
if (decompressed.Length != uncompressedSize)
{
throw new InvalidDataException();
}
stream = decompressed;
}
using (stream)
{
return EncodedStringText.Create(stream);
}
}
public static IEnumerable<string> DumpAssemblyReferences(this MetadataReader reader)
{
return reader.AssemblyReferences.Select(r => reader.GetAssemblyReference(r))
.Select(row => $"{reader.GetString(row.Name)} {row.Version.Major}.{row.Version.Minor}");
}
public static IEnumerable<string> DumpTypeReferences(this MetadataReader reader)
{
return reader.TypeReferences
.Select(t => reader.GetTypeReference(t))
.Select(t => $"{reader.GetString(t.Name)}, {reader.GetString(t.Namespace)}, {reader.Dump(t.ResolutionScope)}");
}
public static string Dump(this MetadataReader reader, EntityHandle handle)
{
string value = DumpRec(reader, handle);
string kind = handle.Kind.ToString();
if (value != null)
{
return $"{kind}:{value}";
}
else
{
return kind;
}
}
private static string DumpRec(this MetadataReader reader, EntityHandle handle)
{
switch (handle.Kind)
{
case HandleKind.AssemblyReference:
return reader.GetString(reader.GetAssemblyReference((AssemblyReferenceHandle)handle).Name);
case HandleKind.TypeDefinition:
{
TypeDefinition type = reader.GetTypeDefinition((TypeDefinitionHandle)handle);
return getQualifiedName(type.Namespace, type.Name);
}
case HandleKind.MethodDefinition:
{
MethodDefinition method = reader.GetMethodDefinition((MethodDefinitionHandle)handle);
var blob = reader.GetBlobReader(method.Signature);
var decoder = new SignatureDecoder<string, object>(ConstantSignatureVisualizer.Instance, reader, genericContext: null);
var signature = decoder.DecodeMethodSignature(ref blob);
var parameters = signature.ParameterTypes.Join(", ");
return $"{signature.ReturnType} {DumpRec(reader, method.GetDeclaringType())}.{reader.GetString(method.Name)}({parameters})";
}
case HandleKind.MemberReference:
{
MemberReference member = reader.GetMemberReference((MemberReferenceHandle)handle);
var blob = reader.GetBlobReader(member.Signature);
var decoder = new SignatureDecoder<string, object>(ConstantSignatureVisualizer.Instance, reader, genericContext: null);
var signature = decoder.DecodeMethodSignature(ref blob);
var parameters = signature.ParameterTypes.Join(", ");
return $"{signature.ReturnType} {DumpRec(reader, member.Parent)}.{reader.GetString(member.Name)}({parameters})";
}
case HandleKind.TypeReference:
{
TypeReference type = reader.GetTypeReference((TypeReferenceHandle)handle);
return getQualifiedName(type.Namespace, type.Name);
}
case HandleKind.FieldDefinition:
{
FieldDefinition field = reader.GetFieldDefinition((FieldDefinitionHandle)handle);
var name = reader.GetString(field.Name);
var blob = reader.GetBlobReader(field.Signature);
var decoder = new SignatureDecoder<string, object>(ConstantSignatureVisualizer.Instance, reader, genericContext: null);
var type = decoder.DecodeFieldSignature(ref blob);
return $"{type} {name}";
}
case HandleKind.TypeSpecification:
{
var typeSpec = reader.GetTypeSpecification((TypeSpecificationHandle)handle);
var blob = reader.GetBlobReader(typeSpec.Signature);
var decoder = new SignatureDecoder<string, object>(ConstantSignatureVisualizer.Instance, reader, genericContext: null);
var type = decoder.DecodeType(ref blob);
return $"{type}";
}
default:
return null;
}
string getQualifiedName(StringHandle leftHandle, StringHandle rightHandle)
{
string name = reader.GetString(rightHandle);
if (!leftHandle.IsNil)
{
name = reader.GetString(leftHandle) + "." + name;
}
return name;
}
}
private sealed class ConstantSignatureVisualizer : ISignatureTypeProvider<string, object>
{
public static readonly ConstantSignatureVisualizer Instance = new ConstantSignatureVisualizer();
public string GetArrayType(string elementType, ArrayShape shape)
=> elementType + "[" + new string(',', shape.Rank) + "]";
public string GetByReferenceType(string elementType)
=> elementType + "&";
public string GetFunctionPointerType(MethodSignature<string> signature)
=> "method-ptr";
public string GetGenericInstantiation(string genericType, ImmutableArray<string> typeArguments)
=> genericType + "{" + string.Join(", ", typeArguments) + "}";
public string GetGenericMethodParameter(object genericContext, int index)
=> "!!" + index;
public string GetGenericTypeParameter(object genericContext, int index)
=> "!" + index;
public string GetModifiedType(string modifier, string unmodifiedType, bool isRequired)
=> (isRequired ? "modreq" : "modopt") + "(" + modifier + ") " + unmodifiedType;
public string GetPinnedType(string elementType)
=> "pinned " + elementType;
public string GetPointerType(string elementType)
=> elementType + "*";
public string GetPrimitiveType(PrimitiveTypeCode typeCode)
=> typeCode.ToString();
public string GetSZArrayType(string elementType)
=> elementType + "[]";
public string GetTypeFromDefinition(MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind)
{
var typeDef = reader.GetTypeDefinition(handle);
var name = reader.GetString(typeDef.Name);
return typeDef.Namespace.IsNil ? name : reader.GetString(typeDef.Namespace) + "." + name;
}
public string GetTypeFromReference(MetadataReader reader, TypeReferenceHandle handle, byte rawTypeKind)
{
var typeRef = reader.GetTypeReference(handle);
var name = reader.GetString(typeRef.Name);
return typeRef.Namespace.IsNil ? name : reader.GetString(typeRef.Namespace) + "." + name;
}
public string GetTypeFromSpecification(MetadataReader reader, object genericContext, TypeSpecificationHandle handle, byte rawTypeKind)
{
var sigReader = reader.GetBlobReader(reader.GetTypeSpecification(handle).Signature);
return new SignatureDecoder<string, object>(Instance, reader, genericContext).DecodeType(ref sigReader);
}
}
internal static void VerifyPEMetadata(string pePath, string[] types, string[] methods, string[] attributes)
{
using (var peStream = File.OpenRead(pePath))
using (var refPeReader = new PEReader(peStream))
{
var metadataReader = refPeReader.GetMetadataReader();
AssertEx.SetEqual(metadataReader.TypeDefinitions.Select(t => metadataReader.Dump(t)), types);
AssertEx.SetEqual(metadataReader.MethodDefinitions.Select(t => metadataReader.Dump(t)), methods);
AssertEx.SetEqual(
metadataReader.CustomAttributes.Select(a => metadataReader.GetCustomAttribute(a).Constructor)
.Select(c => metadataReader.GetMemberReference((MemberReferenceHandle)c).Parent)
.Select(p => metadataReader.GetTypeReference((TypeReferenceHandle)p).Name)
.Select(n => metadataReader.GetString(n)),
attributes);
}
}
internal static void VerifyMethodBodies(ImmutableArray<byte> peImage, Action<byte[]> ilValidator)
{
using (var peReader = new PEReader(peImage))
{
var metadataReader = peReader.GetMetadataReader();
foreach (var method in metadataReader.MethodDefinitions)
{
var rva = metadataReader.GetMethodDefinition(method).RelativeVirtualAddress;
if (rva != 0)
{
var il = peReader.GetMethodBody(rva).GetILBytes();
ilValidator(il);
}
else
{
ilValidator(null);
}
}
}
}
static readonly byte[] ThrowNull = new[] { (byte)ILOpCode.Ldnull, (byte)ILOpCode.Throw };
internal static void AssertEmptyOrThrowNull(ImmutableArray<byte> peImage)
{
VerifyMethodBodies(peImage, (il) =>
{
if (il != null)
{
AssertEx.Equal(ThrowNull, il);
}
});
}
internal static void AssertNotThrowNull(ImmutableArray<byte> peImage)
{
VerifyMethodBodies(peImage, (il) =>
{
if (il != null)
{
AssertEx.NotEqual(ThrowNull, il);
}
});
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Roslyn.Test.Utilities
{
internal static class MetadataReaderUtils
{
internal static IEnumerable<ConstantHandle> GetConstants(this MetadataReader reader)
{
for (int i = 1, n = reader.GetTableRowCount(TableIndex.Constant); i <= n; i++)
{
yield return MetadataTokens.ConstantHandle(i);
}
}
internal static IEnumerable<ParameterHandle> GetParameters(this MetadataReader reader)
{
for (int i = 1, n = reader.GetTableRowCount(TableIndex.Param); i <= n; i++)
{
yield return MetadataTokens.ParameterHandle(i);
}
}
internal static IEnumerable<GenericParameterHandle> GetGenericParameters(this MetadataReader reader)
{
for (int i = 1, n = reader.GetTableRowCount(TableIndex.GenericParam); i <= n; i++)
{
yield return MetadataTokens.GenericParameterHandle(i);
}
}
internal static IEnumerable<GenericParameterConstraintHandle> GetGenericParameterConstraints(this MetadataReader reader)
{
for (int i = 1, n = reader.GetTableRowCount(TableIndex.GenericParamConstraint); i <= n; i++)
{
yield return MetadataTokens.GenericParameterConstraintHandle(i);
}
}
internal static IEnumerable<ModuleReferenceHandle> GetModuleReferences(this MetadataReader reader)
{
for (int i = 1, n = reader.GetTableRowCount(TableIndex.ModuleRef); i <= n; i++)
{
yield return MetadataTokens.ModuleReferenceHandle(i);
}
}
internal static IEnumerable<MethodDefinition> GetImportedMethods(this MetadataReader reader)
{
return from handle in reader.MethodDefinitions
let method = reader.GetMethodDefinition(handle)
let import = method.GetImport()
where !import.Name.IsNil
select method;
}
internal static bool RequiresAmdInstructionSet(this PEHeaders headers)
{
return headers.CoffHeader.Machine == Machine.Amd64;
}
internal static bool Requires64Bits(this PEHeaders headers)
{
return headers.PEHeader != null && headers.PEHeader.Magic == PEMagic.PE32Plus
|| headers.CoffHeader.Machine == Machine.Amd64
|| headers.CoffHeader.Machine == Machine.IA64;
}
public static string GetString(this IEnumerable<MetadataReader> readers, StringHandle handle)
{
int index = MetadataTokens.GetHeapOffset(handle);
foreach (var reader in readers)
{
int length = reader.GetHeapSize(HeapIndex.String);
if (index < length)
{
return reader.GetString(MetadataTokens.StringHandle(index));
}
index -= length;
}
return null;
}
public static string[] GetStrings(this IEnumerable<MetadataReader> readers, IEnumerable<StringHandle> handles)
{
return handles.Select(handle => readers.GetString(handle)).ToArray();
}
public static Guid GetModuleVersionId(this MetadataReader reader)
{
return reader.GetGuid(reader.GetModuleDefinition().Mvid);
}
public static StringHandle[] GetAssemblyRefNames(this MetadataReader reader)
{
return reader.AssemblyReferences.Select(handle => reader.GetAssemblyReference(handle).Name).ToArray();
}
public static StringHandle[] GetTypeDefNames(this MetadataReader reader)
{
return reader.TypeDefinitions.Select(handle => reader.GetTypeDefinition(handle).Name).ToArray();
}
public static (StringHandle Namespace, StringHandle Name)[] GetTypeDefFullNames(this MetadataReader reader)
{
return reader.TypeDefinitions.Select(handle =>
{
var td = reader.GetTypeDefinition(handle);
return (td.Namespace, td.Name);
}).ToArray();
}
public static StringHandle[] GetTypeRefNames(this MetadataReader reader)
{
return reader.TypeReferences.Select(handle => reader.GetTypeReference(handle).Name).ToArray();
}
public static StringHandle[] GetEventDefNames(this MetadataReader reader)
{
return reader.EventDefinitions.Select(handle => reader.GetEventDefinition(handle).Name).ToArray();
}
public static StringHandle[] GetFieldDefNames(this MetadataReader reader)
{
return reader.FieldDefinitions.Select(handle => reader.GetFieldDefinition(handle).Name).ToArray();
}
public static StringHandle[] GetMethodDefNames(this MetadataReader reader)
{
return reader.MethodDefinitions.Select(handle => reader.GetMethodDefinition(handle).Name).ToArray();
}
public static StringHandle[] GetMemberRefNames(this MetadataReader reader)
{
return reader.MemberReferences.Select(handle => reader.GetMemberReference(handle).Name).ToArray();
}
public static StringHandle[] GetParameterDefNames(this MetadataReader reader)
{
return reader.GetParameters().Select(handle => reader.GetParameter(handle).Name).ToArray();
}
public static StringHandle[] GetPropertyDefNames(this MetadataReader reader)
{
return reader.PropertyDefinitions.Select(handle => reader.GetPropertyDefinition(handle).Name).ToArray();
}
public static StringHandle GetName(this MetadataReader reader, EntityHandle token)
{
switch (token.Kind)
{
case HandleKind.TypeReference:
return reader.GetTypeReference((TypeReferenceHandle)token).Name;
case HandleKind.TypeDefinition:
return reader.GetTypeDefinition((TypeDefinitionHandle)token).Name;
default:
throw ExceptionUtilities.UnexpectedValue(token.Kind);
}
}
private delegate T ReadBlobItemDelegate<T>(ref BlobReader blobReader);
private static ImmutableArray<T> ReadArray<T>(this MetadataReader reader, BlobHandle blobHandle, ReadBlobItemDelegate<T> readItem)
{
var blobReader = reader.GetBlobReader(blobHandle);
// Prolog
blobReader.ReadUInt16();
// Array size
int n = blobReader.ReadInt32();
var builder = ArrayBuilder<T>.GetInstance(n);
for (int i = 0; i < n; i++)
{
builder.Add(readItem(ref blobReader));
}
return builder.ToImmutableAndFree();
}
public static ImmutableArray<byte> ReadByteArray(this MetadataReader reader, BlobHandle blobHandle)
{
return ReadArray(reader, blobHandle, (ref BlobReader blobReader) => blobReader.ReadByte());
}
public static ImmutableArray<bool> ReadBoolArray(this MetadataReader reader, BlobHandle blobHandle)
{
return ReadArray(reader, blobHandle, (ref BlobReader blobReader) => blobReader.ReadBoolean());
}
public static IEnumerable<CustomAttributeRow> GetCustomAttributeRows(this MetadataReader reader)
{
foreach (var handle in reader.CustomAttributes)
{
var attribute = reader.GetCustomAttribute(handle);
yield return new CustomAttributeRow(attribute.Parent, attribute.Constructor);
}
}
public static string GetCustomAttributeName(this MetadataReader reader, CustomAttributeRow row)
{
EntityHandle parent;
var token = row.ConstructorToken;
switch (token.Kind)
{
case HandleKind.MemberReference:
parent = reader.GetMemberReference((MemberReferenceHandle)token).Parent;
break;
case HandleKind.MethodDefinition:
parent = reader.GetMethodDefinition((MethodDefinitionHandle)token).GetDeclaringType();
break;
default:
throw ExceptionUtilities.UnexpectedValue(token.Kind);
}
var strHandle = reader.GetName(parent);
return reader.GetString(strHandle);
}
public static bool IsIncluded(this ImmutableArray<byte> metadata, string str)
{
var builder = ArrayBuilder<byte>.GetInstance();
builder.AddRange(System.Text.Encoding.UTF8.GetBytes(str));
builder.Add(0); // Add null terminator.
var bytes = builder.ToImmutableAndFree();
for (int i = 0; i < metadata.Length - bytes.Length; i++)
{
if (metadata.IsAtIndex(bytes, i))
{
return true;
}
}
return false;
}
public static bool IsAtIndex(this ImmutableArray<byte> metadata, ImmutableArray<byte> bytes, int offset)
{
for (int i = 0; i < bytes.Length; i++)
{
if (metadata[i + offset] != bytes[i])
{
return false;
}
}
return true;
}
public static ImmutableArray<byte> GetSourceLinkBlob(this MetadataReader reader)
{
return (from handle in reader.CustomDebugInformation
let cdi = reader.GetCustomDebugInformation(handle)
where reader.GetGuid(cdi.Kind) == PortableCustomDebugInfoKinds.SourceLink
select reader.GetBlobContent(cdi.Value)).Single();
}
public static SourceText GetEmbeddedSource(this MetadataReader reader, DocumentHandle document)
{
byte[] bytes = (from handle in reader.GetCustomDebugInformation(document)
let cdi = reader.GetCustomDebugInformation(handle)
where reader.GetGuid(cdi.Kind) == PortableCustomDebugInfoKinds.EmbeddedSource
select reader.GetBlobBytes(cdi.Value)).SingleOrDefault();
if (bytes == null)
{
return null;
}
int uncompressedSize = BitConverter.ToInt32(bytes, 0);
var stream = new MemoryStream(bytes, sizeof(int), bytes.Length - sizeof(int));
if (uncompressedSize != 0)
{
var decompressed = new MemoryStream(uncompressedSize);
using (var deflater = new DeflateStream(stream, CompressionMode.Decompress))
{
deflater.CopyTo(decompressed);
}
if (decompressed.Length != uncompressedSize)
{
throw new InvalidDataException();
}
stream = decompressed;
}
using (stream)
{
return EncodedStringText.Create(stream);
}
}
public static IEnumerable<string> DumpAssemblyReferences(this MetadataReader reader)
{
return reader.AssemblyReferences.Select(r => reader.GetAssemblyReference(r))
.Select(row => $"{reader.GetString(row.Name)} {row.Version.Major}.{row.Version.Minor}");
}
public static IEnumerable<string> DumpTypeReferences(this MetadataReader reader)
{
return reader.TypeReferences
.Select(t => reader.GetTypeReference(t))
.Select(t => $"{reader.GetString(t.Name)}, {reader.GetString(t.Namespace)}, {reader.Dump(t.ResolutionScope)}");
}
public static string Dump(this MetadataReader reader, EntityHandle handle)
{
string value = DumpRec(reader, handle);
string kind = handle.Kind.ToString();
if (value != null)
{
return $"{kind}:{value}";
}
else
{
return kind;
}
}
private static string DumpRec(this MetadataReader reader, EntityHandle handle)
{
switch (handle.Kind)
{
case HandleKind.AssemblyReference:
return reader.GetString(reader.GetAssemblyReference((AssemblyReferenceHandle)handle).Name);
case HandleKind.TypeDefinition:
{
TypeDefinition type = reader.GetTypeDefinition((TypeDefinitionHandle)handle);
return getQualifiedName(type.Namespace, type.Name);
}
case HandleKind.MethodDefinition:
{
MethodDefinition method = reader.GetMethodDefinition((MethodDefinitionHandle)handle);
var blob = reader.GetBlobReader(method.Signature);
var decoder = new SignatureDecoder<string, object>(ConstantSignatureVisualizer.Instance, reader, genericContext: null);
var signature = decoder.DecodeMethodSignature(ref blob);
var parameters = signature.ParameterTypes.Join(", ");
return $"{signature.ReturnType} {DumpRec(reader, method.GetDeclaringType())}.{reader.GetString(method.Name)}({parameters})";
}
case HandleKind.MemberReference:
{
MemberReference member = reader.GetMemberReference((MemberReferenceHandle)handle);
var blob = reader.GetBlobReader(member.Signature);
var decoder = new SignatureDecoder<string, object>(ConstantSignatureVisualizer.Instance, reader, genericContext: null);
var signature = decoder.DecodeMethodSignature(ref blob);
var parameters = signature.ParameterTypes.Join(", ");
return $"{signature.ReturnType} {DumpRec(reader, member.Parent)}.{reader.GetString(member.Name)}({parameters})";
}
case HandleKind.TypeReference:
{
TypeReference type = reader.GetTypeReference((TypeReferenceHandle)handle);
return getQualifiedName(type.Namespace, type.Name);
}
case HandleKind.FieldDefinition:
{
FieldDefinition field = reader.GetFieldDefinition((FieldDefinitionHandle)handle);
var name = reader.GetString(field.Name);
var blob = reader.GetBlobReader(field.Signature);
var decoder = new SignatureDecoder<string, object>(ConstantSignatureVisualizer.Instance, reader, genericContext: null);
var type = decoder.DecodeFieldSignature(ref blob);
return $"{type} {name}";
}
case HandleKind.TypeSpecification:
{
var typeSpec = reader.GetTypeSpecification((TypeSpecificationHandle)handle);
var blob = reader.GetBlobReader(typeSpec.Signature);
var decoder = new SignatureDecoder<string, object>(ConstantSignatureVisualizer.Instance, reader, genericContext: null);
var type = decoder.DecodeType(ref blob);
return $"{type}";
}
default:
return null;
}
string getQualifiedName(StringHandle leftHandle, StringHandle rightHandle)
{
string name = reader.GetString(rightHandle);
if (!leftHandle.IsNil)
{
name = reader.GetString(leftHandle) + "." + name;
}
return name;
}
}
private sealed class ConstantSignatureVisualizer : ISignatureTypeProvider<string, object>
{
public static readonly ConstantSignatureVisualizer Instance = new ConstantSignatureVisualizer();
public string GetArrayType(string elementType, ArrayShape shape)
=> elementType + "[" + new string(',', shape.Rank) + "]";
public string GetByReferenceType(string elementType)
=> elementType + "&";
public string GetFunctionPointerType(MethodSignature<string> signature)
=> "method-ptr";
public string GetGenericInstantiation(string genericType, ImmutableArray<string> typeArguments)
=> genericType + "{" + string.Join(", ", typeArguments) + "}";
public string GetGenericMethodParameter(object genericContext, int index)
=> "!!" + index;
public string GetGenericTypeParameter(object genericContext, int index)
=> "!" + index;
public string GetModifiedType(string modifier, string unmodifiedType, bool isRequired)
=> (isRequired ? "modreq" : "modopt") + "(" + modifier + ") " + unmodifiedType;
public string GetPinnedType(string elementType)
=> "pinned " + elementType;
public string GetPointerType(string elementType)
=> elementType + "*";
public string GetPrimitiveType(PrimitiveTypeCode typeCode)
=> typeCode.ToString();
public string GetSZArrayType(string elementType)
=> elementType + "[]";
public string GetTypeFromDefinition(MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind)
{
var typeDef = reader.GetTypeDefinition(handle);
var name = reader.GetString(typeDef.Name);
return typeDef.Namespace.IsNil ? name : reader.GetString(typeDef.Namespace) + "." + name;
}
public string GetTypeFromReference(MetadataReader reader, TypeReferenceHandle handle, byte rawTypeKind)
{
var typeRef = reader.GetTypeReference(handle);
var name = reader.GetString(typeRef.Name);
return typeRef.Namespace.IsNil ? name : reader.GetString(typeRef.Namespace) + "." + name;
}
public string GetTypeFromSpecification(MetadataReader reader, object genericContext, TypeSpecificationHandle handle, byte rawTypeKind)
{
var sigReader = reader.GetBlobReader(reader.GetTypeSpecification(handle).Signature);
return new SignatureDecoder<string, object>(Instance, reader, genericContext).DecodeType(ref sigReader);
}
}
internal static void VerifyPEMetadata(string pePath, string[] types, string[] methods, string[] attributes)
{
using (var peStream = File.OpenRead(pePath))
using (var refPeReader = new PEReader(peStream))
{
var metadataReader = refPeReader.GetMetadataReader();
AssertEx.SetEqual(metadataReader.TypeDefinitions.Select(t => metadataReader.Dump(t)), types);
AssertEx.SetEqual(metadataReader.MethodDefinitions.Select(t => metadataReader.Dump(t)), methods);
AssertEx.SetEqual(
metadataReader.CustomAttributes.Select(a => metadataReader.GetCustomAttribute(a).Constructor)
.Select(c => metadataReader.GetMemberReference((MemberReferenceHandle)c).Parent)
.Select(p => metadataReader.GetTypeReference((TypeReferenceHandle)p).Name)
.Select(n => metadataReader.GetString(n)),
attributes);
}
}
internal static void VerifyMethodBodies(ImmutableArray<byte> peImage, Action<byte[]> ilValidator)
{
using (var peReader = new PEReader(peImage))
{
var metadataReader = peReader.GetMetadataReader();
foreach (var method in metadataReader.MethodDefinitions)
{
var rva = metadataReader.GetMethodDefinition(method).RelativeVirtualAddress;
if (rva != 0)
{
var il = peReader.GetMethodBody(rva).GetILBytes();
ilValidator(il);
}
else
{
ilValidator(null);
}
}
}
}
static readonly byte[] ThrowNull = new[] { (byte)ILOpCode.Ldnull, (byte)ILOpCode.Throw };
internal static void AssertEmptyOrThrowNull(ImmutableArray<byte> peImage)
{
VerifyMethodBodies(peImage, (il) =>
{
if (il != null)
{
AssertEx.Equal(ThrowNull, il);
}
});
}
internal static void AssertNotThrowNull(ImmutableArray<byte> peImage)
{
VerifyMethodBodies(peImage, (il) =>
{
if (il != null)
{
AssertEx.NotEqual(ThrowNull, il);
}
});
}
}
}
| 1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Compilers/VisualBasic/Portable/Emit/EditAndContinue/EmitHelpers.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.IO
Imports System.Reflection.Metadata
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.PooledObjects
Namespace Microsoft.CodeAnalysis.VisualBasic.Emit
Friend Module EmitHelpers
Friend Function EmitDifference(
compilation As VisualBasicCompilation,
baseline As EmitBaseline,
edits As IEnumerable(Of SemanticEdit),
isAddedSymbol As Func(Of ISymbol, Boolean),
metadataStream As Stream,
ilStream As Stream,
pdbStream As Stream,
testData As CompilationTestData,
cancellationToken As CancellationToken) As EmitDifferenceResult
Dim pdbName = FileNameUtilities.ChangeExtension(compilation.SourceModule.Name, "pdb")
Dim diagnostics = DiagnosticBag.GetInstance()
Dim emitOpts = EmitOptions.Default.WithDebugInformationFormat(If(baseline.HasPortablePdb, DebugInformationFormat.PortablePdb, DebugInformationFormat.Pdb))
Dim runtimeMDVersion = compilation.GetRuntimeMetadataVersion()
Dim serializationProperties = compilation.ConstructModuleSerializationProperties(emitOpts, runtimeMDVersion, baseline.ModuleVersionId)
Dim manifestResources = SpecializedCollections.EmptyEnumerable(Of ResourceDescription)()
Dim updatedMethods = ArrayBuilder(Of MethodDefinitionHandle).GetInstance()
Dim updatedTypes = ArrayBuilder(Of TypeDefinitionHandle).GetInstance()
Dim moduleBeingBuilt As PEDeltaAssemblyBuilder
Try
moduleBeingBuilt = New PEDeltaAssemblyBuilder(
compilation.SourceAssembly,
emitOptions:=emitOpts,
outputKind:=compilation.Options.OutputKind,
serializationProperties:=serializationProperties,
manifestResources:=manifestResources,
previousGeneration:=baseline,
edits:=edits,
isAddedSymbol:=isAddedSymbol)
Catch e As NotSupportedException
' TODO: https://github.com/dotnet/roslyn/issues/9004
diagnostics.Add(ERRID.ERR_ModuleEmitFailure, NoLocation.Singleton, compilation.AssemblyName, e.Message)
Return New EmitDifferenceResult(success:=False, diagnostics:=diagnostics.ToReadOnlyAndFree(), baseline:=Nothing, updatedMethods:=updatedMethods.ToImmutableAndFree(), updatedTypes:=updatedTypes.ToImmutableAndFree())
End Try
If testData IsNot Nothing Then
moduleBeingBuilt.SetMethodTestData(testData.Methods)
testData.Module = moduleBeingBuilt
End If
Dim definitionMap = moduleBeingBuilt.PreviousDefinitions
Dim changes = moduleBeingBuilt.EncSymbolChanges
Dim newBaseline As EmitBaseline = Nothing
If compilation.Compile(moduleBeingBuilt,
emittingPdb:=True,
diagnostics:=diagnostics,
filterOpt:=Function(s) changes.RequiresCompilation(s.GetISymbol()),
cancellationToken:=cancellationToken) Then
' Map the definitions from the previous compilation to the current compilation.
' This must be done after compiling above since synthesized definitions
' (generated when compiling method bodies) may be required.
Dim mappedBaseline = MapToCompilation(compilation, moduleBeingBuilt)
newBaseline = compilation.SerializeToDeltaStreams(
moduleBeingBuilt,
mappedBaseline,
definitionMap,
changes,
metadataStream,
ilStream,
pdbStream,
updatedMethods,
updatedTypes,
diagnostics,
testData?.SymWriterFactory,
emitOpts.PdbFilePath,
cancellationToken)
End If
Return New EmitDifferenceResult(
success:=newBaseline IsNot Nothing,
diagnostics:=diagnostics.ToReadOnlyAndFree(),
baseline:=newBaseline,
updatedMethods:=updatedMethods.ToImmutableAndFree(),
updatedTypes:=updatedTypes.ToImmutableAndFree())
End Function
Friend Function MapToCompilation(
compilation As VisualBasicCompilation,
moduleBeingBuilt As PEDeltaAssemblyBuilder) As EmitBaseline
Dim previousGeneration = moduleBeingBuilt.PreviousGeneration
Debug.Assert(previousGeneration.Compilation IsNot compilation)
If previousGeneration.Ordinal = 0 Then
' Initial generation, nothing to map. (Since the initial generation
' is always loaded from metadata in the context of the current
' compilation, there's no separate mapping step.)
Return previousGeneration
End If
Dim currentSynthesizedMembers = moduleBeingBuilt.GetAllSynthesizedMembers()
' Mapping from previous compilation to the current.
Dim anonymousTypeMap = moduleBeingBuilt.GetAnonymousTypeMap()
Dim sourceAssembly = DirectCast(previousGeneration.Compilation, VisualBasicCompilation).SourceAssembly
Dim sourceContext = New EmitContext(DirectCast(previousGeneration.PEModuleBuilder, PEModuleBuilder), Nothing, New DiagnosticBag(), metadataOnly:=False, includePrivateMembers:=True)
Dim otherContext = New EmitContext(moduleBeingBuilt, Nothing, New DiagnosticBag(), metadataOnly:=False, includePrivateMembers:=True)
Dim matcher = New VisualBasicSymbolMatcher(
anonymousTypeMap,
sourceAssembly,
sourceContext,
compilation.SourceAssembly,
otherContext,
currentSynthesizedMembers)
Dim mappedSynthesizedMembers = matcher.MapSynthesizedMembers(previousGeneration.SynthesizedMembers, currentSynthesizedMembers)
' TODO can we reuse some data from the previous matcher?
Dim matcherWithAllSynthesizedMembers = New VisualBasicSymbolMatcher(
anonymousTypeMap,
sourceAssembly,
sourceContext,
compilation.SourceAssembly,
otherContext,
mappedSynthesizedMembers)
Return matcherWithAllSynthesizedMembers.MapBaselineToCompilation(
previousGeneration,
compilation,
moduleBeingBuilt,
mappedSynthesizedMembers)
End Function
End Module
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.IO
Imports System.Reflection.Metadata
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.PooledObjects
Namespace Microsoft.CodeAnalysis.VisualBasic.Emit
Friend Module EmitHelpers
Friend Function EmitDifference(
compilation As VisualBasicCompilation,
baseline As EmitBaseline,
edits As IEnumerable(Of SemanticEdit),
isAddedSymbol As Func(Of ISymbol, Boolean),
metadataStream As Stream,
ilStream As Stream,
pdbStream As Stream,
testData As CompilationTestData,
cancellationToken As CancellationToken) As EmitDifferenceResult
Dim pdbName = FileNameUtilities.ChangeExtension(compilation.SourceModule.Name, "pdb")
Dim diagnostics = DiagnosticBag.GetInstance()
Dim emitOpts = EmitOptions.Default.WithDebugInformationFormat(If(baseline.HasPortablePdb, DebugInformationFormat.PortablePdb, DebugInformationFormat.Pdb))
Dim runtimeMDVersion = compilation.GetRuntimeMetadataVersion()
Dim serializationProperties = compilation.ConstructModuleSerializationProperties(emitOpts, runtimeMDVersion, baseline.ModuleVersionId)
Dim manifestResources = SpecializedCollections.EmptyEnumerable(Of ResourceDescription)()
Dim moduleBeingBuilt As PEDeltaAssemblyBuilder
Try
moduleBeingBuilt = New PEDeltaAssemblyBuilder(
compilation.SourceAssembly,
emitOptions:=emitOpts,
outputKind:=compilation.Options.OutputKind,
serializationProperties:=serializationProperties,
manifestResources:=manifestResources,
previousGeneration:=baseline,
edits:=edits,
isAddedSymbol:=isAddedSymbol)
Catch e As NotSupportedException
' TODO: https://github.com/dotnet/roslyn/issues/9004
diagnostics.Add(ERRID.ERR_ModuleEmitFailure, NoLocation.Singleton, compilation.AssemblyName, e.Message)
Return New EmitDifferenceResult(
success:=False,
diagnostics:=diagnostics.ToReadOnlyAndFree(),
baseline:=Nothing,
updatedMethods:=ImmutableArray(Of MethodDefinitionHandle).Empty,
changedTypes:=ImmutableArray(Of TypeDefinitionHandle).Empty)
End Try
If testData IsNot Nothing Then
moduleBeingBuilt.SetMethodTestData(testData.Methods)
testData.Module = moduleBeingBuilt
End If
Dim definitionMap = moduleBeingBuilt.PreviousDefinitions
Dim changes = moduleBeingBuilt.EncSymbolChanges
Dim newBaseline As EmitBaseline = Nothing
Dim updatedMethods = ArrayBuilder(Of MethodDefinitionHandle).GetInstance()
Dim changedTypes = ArrayBuilder(Of TypeDefinitionHandle).GetInstance()
If compilation.Compile(moduleBeingBuilt,
emittingPdb:=True,
diagnostics:=diagnostics,
filterOpt:=Function(s) changes.RequiresCompilation(s.GetISymbol()),
cancellationToken:=cancellationToken) Then
' Map the definitions from the previous compilation to the current compilation.
' This must be done after compiling above since synthesized definitions
' (generated when compiling method bodies) may be required.
Dim mappedBaseline = MapToCompilation(compilation, moduleBeingBuilt)
newBaseline = compilation.SerializeToDeltaStreams(
moduleBeingBuilt,
mappedBaseline,
definitionMap,
changes,
metadataStream,
ilStream,
pdbStream,
updatedMethods,
changedTypes,
diagnostics,
testData?.SymWriterFactory,
emitOpts.PdbFilePath,
cancellationToken)
End If
Return New EmitDifferenceResult(
success:=newBaseline IsNot Nothing,
diagnostics:=diagnostics.ToReadOnlyAndFree(),
baseline:=newBaseline,
updatedMethods:=updatedMethods.ToImmutableAndFree(),
changedTypes:=changedTypes.ToImmutableAndFree())
End Function
Friend Function MapToCompilation(
compilation As VisualBasicCompilation,
moduleBeingBuilt As PEDeltaAssemblyBuilder) As EmitBaseline
Dim previousGeneration = moduleBeingBuilt.PreviousGeneration
Debug.Assert(previousGeneration.Compilation IsNot compilation)
If previousGeneration.Ordinal = 0 Then
' Initial generation, nothing to map. (Since the initial generation
' is always loaded from metadata in the context of the current
' compilation, there's no separate mapping step.)
Return previousGeneration
End If
Dim currentSynthesizedMembers = moduleBeingBuilt.GetAllSynthesizedMembers()
' Mapping from previous compilation to the current.
Dim anonymousTypeMap = moduleBeingBuilt.GetAnonymousTypeMap()
Dim sourceAssembly = DirectCast(previousGeneration.Compilation, VisualBasicCompilation).SourceAssembly
Dim sourceContext = New EmitContext(DirectCast(previousGeneration.PEModuleBuilder, PEModuleBuilder), Nothing, New DiagnosticBag(), metadataOnly:=False, includePrivateMembers:=True)
Dim otherContext = New EmitContext(moduleBeingBuilt, Nothing, New DiagnosticBag(), metadataOnly:=False, includePrivateMembers:=True)
Dim matcher = New VisualBasicSymbolMatcher(
anonymousTypeMap,
sourceAssembly,
sourceContext,
compilation.SourceAssembly,
otherContext,
currentSynthesizedMembers)
Dim mappedSynthesizedMembers = matcher.MapSynthesizedMembers(previousGeneration.SynthesizedMembers, currentSynthesizedMembers)
' TODO can we reuse some data from the previous matcher?
Dim matcherWithAllSynthesizedMembers = New VisualBasicSymbolMatcher(
anonymousTypeMap,
sourceAssembly,
sourceContext,
compilation.SourceAssembly,
otherContext,
mappedSynthesizedMembers)
Return matcherWithAllSynthesizedMembers.MapBaselineToCompilation(
previousGeneration,
compilation,
moduleBeingBuilt,
mappedSynthesizedMembers)
End Function
End Module
End Namespace
| 1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Features/Core/Portable/EditAndContinue/EditSession.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.EditAndContinue
{
internal sealed class EditSession
{
internal readonly DebuggingSession DebuggingSession;
internal readonly EditSessionTelemetry Telemetry;
private readonly ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> _nonRemappableRegions;
/// <summary>
/// Lazily calculated map of base active statements.
/// </summary>
internal readonly AsyncLazy<ActiveStatementsMap> BaseActiveStatements;
/// <summary>
/// Cache of document EnC analyses.
/// </summary>
internal readonly EditAndContinueDocumentAnalysesCache Analyses;
internal readonly bool InBreakState;
/// <summary>
/// A <see cref="DocumentId"/> is added whenever EnC analyzer reports
/// rude edits or module diagnostics. At the end of the session we ask the diagnostic analyzer to reanalyze
/// the documents to clean up the diagnostics.
/// </summary>
private readonly HashSet<DocumentId> _documentsWithReportedDiagnostics = new();
private readonly object _documentsWithReportedDiagnosticsGuard = new();
internal EditSession(DebuggingSession debuggingSession, EditSessionTelemetry telemetry, bool inBreakState)
{
DebuggingSession = debuggingSession;
Telemetry = telemetry;
_nonRemappableRegions = debuggingSession.NonRemappableRegions;
InBreakState = inBreakState;
BaseActiveStatements = inBreakState ?
new AsyncLazy<ActiveStatementsMap>(cancellationToken => GetBaseActiveStatementsAsync(cancellationToken), cacheResult: true) :
new AsyncLazy<ActiveStatementsMap>(ActiveStatementsMap.Empty);
Analyses = new EditAndContinueDocumentAnalysesCache(BaseActiveStatements);
}
/// <summary>
/// Errors to be reported when a project is updated but the corresponding module does not support EnC.
/// </summary>
/// <returns><see langword="default"/> if the module is not loaded.</returns>
public async Task<ImmutableArray<Diagnostic>?> GetModuleDiagnosticsAsync(Guid mvid, string projectDisplayName, CancellationToken cancellationToken)
{
var availability = await DebuggingSession.DebuggerService.GetAvailabilityAsync(mvid, cancellationToken).ConfigureAwait(false);
if (availability.Status == ManagedEditAndContinueAvailabilityStatus.ModuleNotLoaded)
{
return null;
}
if (availability.Status == ManagedEditAndContinueAvailabilityStatus.Available)
{
return ImmutableArray<Diagnostic>.Empty;
}
var descriptor = EditAndContinueDiagnosticDescriptors.GetModuleDiagnosticDescriptor(availability.Status);
return ImmutableArray.Create(Diagnostic.Create(descriptor, Location.None, new[] { projectDisplayName, availability.LocalizedMessage }));
}
private async Task<ActiveStatementsMap> GetBaseActiveStatementsAsync(CancellationToken cancellationToken)
{
try
{
// Last committed solution reflects the state of the source that is in sync with the binaries that are loaded in the debuggee.
var debugInfos = await DebuggingSession.DebuggerService.GetActiveStatementsAsync(cancellationToken).ConfigureAwait(false);
return ActiveStatementsMap.Create(debugInfos, _nonRemappableRegions);
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
return ActiveStatementsMap.Empty;
}
}
private static async Task PopulateChangedAndAddedDocumentsAsync(CommittedSolution oldSolution, Project newProject, ArrayBuilder<Document> changedOrAddedDocuments, CancellationToken cancellationToken)
{
changedOrAddedDocuments.Clear();
if (!newProject.SupportsEditAndContinue())
{
return;
}
var oldProject = oldSolution.GetProject(newProject.Id);
// When debugging session is started some projects might not have been loaded to the workspace yet.
// We capture the base solution. Edits in files that are in projects that haven't been loaded won't be applied
// and will result in source mismatch when the user steps into them.
//
// TODO (https://github.com/dotnet/roslyn/issues/1204):
// hook up the debugger reported error, check that the project has not been loaded and report a better error.
// Here, we assume these projects are not modified.
if (oldProject == null)
{
EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not loaded", newProject.Id.DebugName, newProject.Id);
return;
}
if (oldProject.State == newProject.State)
{
return;
}
foreach (var documentId in newProject.State.DocumentStates.GetChangedStateIds(oldProject.State.DocumentStates, ignoreUnchangedContent: true))
{
var document = newProject.GetRequiredDocument(documentId);
if (document.State.Attributes.DesignTimeOnly)
{
continue;
}
// Check if the currently observed document content has changed compared to the base document content.
// This is an important optimization that aims to avoid IO while stepping in sources that have not changed.
//
// We may be comparing out-of-date committed document content but we only make a decision based on that content
// if it matches the current content. If the current content is equal to baseline content that does not match
// the debuggee then the workspace has not observed the change made to the file on disk since baseline was captured
// (there had to be one as the content doesn't match). When we are about to apply changes it is ok to ignore this
// document because the user does not see the change yet in the buffer (if the doc is open) and won't be confused
// if it is not applied yet. The change will be applied later after it's observed by the workspace.
var baseSource = await oldProject.GetRequiredDocument(documentId).GetTextAsync(cancellationToken).ConfigureAwait(false);
var source = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
if (baseSource.ContentEquals(source))
{
continue;
}
changedOrAddedDocuments.Add(document);
}
foreach (var documentId in newProject.State.DocumentStates.GetAddedStateIds(oldProject.State.DocumentStates))
{
var document = newProject.GetRequiredDocument(documentId);
if (document.State.Attributes.DesignTimeOnly)
{
continue;
}
changedOrAddedDocuments.Add(document);
}
// TODO: support document removal/rename (see https://github.com/dotnet/roslyn/issues/41144, https://github.com/dotnet/roslyn/issues/49013).
if (changedOrAddedDocuments.IsEmpty() && !HasChangesThatMayAffectSourceGenerators(oldProject.State, newProject.State))
{
// Based on the above assumption there are no changes in source generated files.
return;
}
cancellationToken.ThrowIfCancellationRequested();
var oldSourceGeneratedDocumentStates = await oldProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(oldProject.State, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
var newSourceGeneratedDocumentStates = await newProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(newProject.State, cancellationToken).ConfigureAwait(false);
foreach (var documentId in newSourceGeneratedDocumentStates.GetChangedStateIds(oldSourceGeneratedDocumentStates, ignoreUnchangedContent: true))
{
var newState = newSourceGeneratedDocumentStates.GetRequiredState(documentId);
if (newState.Attributes.DesignTimeOnly)
{
continue;
}
changedOrAddedDocuments.Add(newProject.GetOrCreateSourceGeneratedDocument(newState));
}
foreach (var documentId in newSourceGeneratedDocumentStates.GetAddedStateIds(oldSourceGeneratedDocumentStates))
{
var newState = newSourceGeneratedDocumentStates.GetRequiredState(documentId);
if (newState.Attributes.DesignTimeOnly)
{
continue;
}
changedOrAddedDocuments.Add(newProject.GetOrCreateSourceGeneratedDocument(newState));
}
}
internal static async IAsyncEnumerable<DocumentId> GetChangedDocumentsAsync(CommittedSolution oldSolution, Project newProject, [EnumeratorCancellation] CancellationToken cancellationToken)
{
var oldProject = oldSolution.GetRequiredProject(newProject.Id);
if (!newProject.SupportsEditAndContinue() || oldProject.State == newProject.State)
{
yield break;
}
foreach (var documentId in newProject.State.DocumentStates.GetChangedStateIds(oldProject.State.DocumentStates, ignoreUnchangedContent: true))
{
yield return documentId;
}
if (!HasChangesThatMayAffectSourceGenerators(oldProject.State, newProject.State))
{
// Based on the above assumption there are no changes in source generated files.
yield break;
}
cancellationToken.ThrowIfCancellationRequested();
var oldSourceGeneratedDocumentStates = await oldProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(oldProject.State, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
var newSourceGeneratedDocumentStates = await newProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(newProject.State, cancellationToken).ConfigureAwait(false);
foreach (var documentId in newSourceGeneratedDocumentStates.GetChangedStateIds(oldSourceGeneratedDocumentStates, ignoreUnchangedContent: true))
{
yield return documentId;
}
}
/// <summary>
/// Given the following assumptions:
/// - source generators are deterministic,
/// - source documents, metadata references and compilation options have not changed,
/// - additional documents have not changed,
/// - analyzer config documents have not changed,
/// the outputs of source generators will not change.
///
/// Currently it's not possible to change compilation options (Project System is readonly during debugging).
/// </summary>
private static bool HasChangesThatMayAffectSourceGenerators(ProjectState oldProject, ProjectState newProject)
=> newProject.DocumentStates.HasAnyStateChanges(oldProject.DocumentStates) ||
newProject.AdditionalDocumentStates.HasAnyStateChanges(oldProject.AdditionalDocumentStates) ||
newProject.AnalyzerConfigDocumentStates.HasAnyStateChanges(oldProject.AnalyzerConfigDocumentStates);
private async Task<(ImmutableArray<DocumentAnalysisResults> results, ImmutableArray<Diagnostic> diagnostics)> AnalyzeDocumentsAsync(
ArrayBuilder<Document> changedOrAddedDocuments,
ActiveStatementSpanProvider newDocumentActiveStatementSpanProvider,
CancellationToken cancellationToken)
{
using var _1 = ArrayBuilder<Diagnostic>.GetInstance(out var documentDiagnostics);
using var _2 = ArrayBuilder<(Document? oldDocument, Document newDocument)>.GetInstance(out var documents);
foreach (var newDocument in changedOrAddedDocuments)
{
var (oldDocument, oldDocumentState) = await DebuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken, reloadOutOfSyncDocument: true).ConfigureAwait(false);
switch (oldDocumentState)
{
case CommittedSolution.DocumentState.DesignTimeOnly:
break;
case CommittedSolution.DocumentState.Indeterminate:
case CommittedSolution.DocumentState.OutOfSync:
var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor((oldDocumentState == CommittedSolution.DocumentState.Indeterminate) ?
EditAndContinueErrorCode.UnableToReadSourceFileOrPdb : EditAndContinueErrorCode.DocumentIsOutOfSyncWithDebuggee);
documentDiagnostics.Add(Diagnostic.Create(descriptor, Location.Create(newDocument.FilePath!, textSpan: default, lineSpan: default), new[] { newDocument.FilePath }));
break;
case CommittedSolution.DocumentState.MatchesBuildOutput:
// Include the document regardless of whether the module it was built into has been loaded or not.
// If the module has been built it might get loaded later during the debugging session,
// at which point we apply all changes that have been made to the project so far.
documents.Add((oldDocument, newDocument));
break;
default:
throw ExceptionUtilities.UnexpectedValue(oldDocumentState);
}
}
var analyses = await Analyses.GetDocumentAnalysesAsync(DebuggingSession.LastCommittedSolution, documents, newDocumentActiveStatementSpanProvider, DebuggingSession.Capabilities, cancellationToken).ConfigureAwait(false);
return (analyses, documentDiagnostics.ToImmutable());
}
internal ImmutableArray<DocumentId> GetDocumentsWithReportedDiagnostics()
{
lock (_documentsWithReportedDiagnosticsGuard)
{
return ImmutableArray.CreateRange(_documentsWithReportedDiagnostics);
}
}
internal void TrackDocumentWithReportedDiagnostics(DocumentId documentId)
{
lock (_documentsWithReportedDiagnosticsGuard)
{
_documentsWithReportedDiagnostics.Add(documentId);
}
}
/// <summary>
/// Determines whether projects contain any changes that might need to be applied.
/// Checks only projects containing a given <paramref name="sourceFilePath"/> or all projects of the solution if <paramref name="sourceFilePath"/> is null.
/// Invoked by the debugger on every step. It is critical for stepping performance that this method returns as fast as possible in absence of changes.
/// </summary>
public async ValueTask<bool> HasChangesAsync(Solution solution, ActiveStatementSpanProvider solutionActiveStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken)
{
try
{
var baseSolution = DebuggingSession.LastCommittedSolution;
if (baseSolution.HasNoChanges(solution))
{
return false;
}
// TODO: source generated files?
var projects = (sourceFilePath == null) ? solution.Projects :
from documentId in solution.GetDocumentIdsWithFilePath(sourceFilePath)
select solution.GetProject(documentId.ProjectId)!;
using var _ = ArrayBuilder<Document>.GetInstance(out var changedOrAddedDocuments);
foreach (var project in projects)
{
await PopulateChangedAndAddedDocumentsAsync(baseSolution, project, changedOrAddedDocuments, cancellationToken).ConfigureAwait(false);
if (changedOrAddedDocuments.IsEmpty())
{
continue;
}
// Check MVID before analyzing documents as the analysis needs to read the PDB which will likely fail if we can't even read the MVID.
var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(project, cancellationToken).ConfigureAwait(false);
if (mvidReadError != null)
{
// Can't read MVID. This might be an intermittent failure, so don't report it here.
// Report the project as containing changes, so that we proceed to EmitSolutionUpdateAsync where we report the error if it still persists.
EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not built", project.Id.DebugName, project.Id);
return true;
}
if (mvid == Guid.Empty)
{
// Project not built. We ignore any changes made in its sources.
EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not built", project.Id.DebugName, project.Id);
continue;
}
var (changedDocumentAnalyses, documentDiagnostics) = await AnalyzeDocumentsAsync(changedOrAddedDocuments, solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false);
if (documentDiagnostics.Any())
{
EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: out-of-sync documents present (diagnostic: '{2}')",
project.Id.DebugName, project.Id, documentDiagnostics[0]);
// Although we do not apply changes in out-of-sync/indeterminate documents we report that changes are present,
// so that the debugger triggers emit of updates. There we check if these documents are still in a bad state and report warnings
// that any changes in such documents are not applied.
return true;
}
var projectSummary = GetProjectAnalysisSymmary(changedDocumentAnalyses);
if (projectSummary != ProjectAnalysisSummary.NoChanges)
{
EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: {2}", project.Id.DebugName, project.Id, projectSummary);
return true;
}
}
return false;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
private static ProjectAnalysisSummary GetProjectAnalysisSymmary(ImmutableArray<DocumentAnalysisResults> documentAnalyses)
{
var hasChanges = false;
var hasSignificantValidChanges = false;
foreach (var analysis in documentAnalyses)
{
// skip documents that actually were not changed:
if (!analysis.HasChanges)
{
continue;
}
// rude edit detection wasn't completed due to errors that prevent us from analyzing the document:
if (analysis.HasChangesAndSyntaxErrors)
{
return ProjectAnalysisSummary.CompilationErrors;
}
// rude edits detected:
if (!analysis.RudeEditErrors.IsEmpty)
{
return ProjectAnalysisSummary.RudeEdits;
}
hasChanges = true;
hasSignificantValidChanges |= analysis.HasSignificantValidChanges;
}
if (!hasChanges)
{
// we get here if a document is closed and reopen without any actual change:
return ProjectAnalysisSummary.NoChanges;
}
if (!hasSignificantValidChanges)
{
return ProjectAnalysisSummary.ValidInsignificantChanges;
}
return ProjectAnalysisSummary.ValidChanges;
}
internal static async ValueTask<ProjectChanges> GetProjectChangesAsync(
ActiveStatementsMap baseActiveStatements,
Compilation oldCompilation,
Compilation newCompilation,
Project oldProject,
Project newProject,
ImmutableArray<DocumentAnalysisResults> changedDocumentAnalyses,
CancellationToken cancellationToken)
{
try
{
using var _1 = ArrayBuilder<SemanticEditInfo>.GetInstance(out var allEdits);
using var _2 = ArrayBuilder<SequencePointUpdates>.GetInstance(out var allLineEdits);
using var _3 = ArrayBuilder<DocumentActiveStatementChanges>.GetInstance(out var activeStatementsInChangedDocuments);
var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>();
foreach (var analysis in changedDocumentAnalyses)
{
if (!analysis.HasSignificantValidChanges)
{
continue;
}
// we shouldn't be asking for deltas in presence of errors:
Contract.ThrowIfTrue(analysis.HasChangesAndErrors);
// Active statements are calculated if document changed and has no syntax errors:
Contract.ThrowIfTrue(analysis.ActiveStatements.IsDefault);
allEdits.AddRange(analysis.SemanticEdits);
allLineEdits.AddRange(analysis.LineEdits);
if (analysis.ActiveStatements.Length > 0)
{
var oldDocument = await oldProject.GetDocumentAsync(analysis.DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false);
var oldActiveStatements = (oldDocument == null) ? ImmutableArray<UnmappedActiveStatement>.Empty :
await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false);
activeStatementsInChangedDocuments.Add(new(oldActiveStatements, analysis.ActiveStatements, analysis.ExceptionRegions));
}
}
MergePartialEdits(oldCompilation, newCompilation, allEdits, out var mergedEdits, out var addedSymbols, cancellationToken);
return new ProjectChanges(
mergedEdits,
allLineEdits.ToImmutable(),
addedSymbols,
activeStatementsInChangedDocuments.ToImmutable());
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
internal static void MergePartialEdits(
Compilation oldCompilation,
Compilation newCompilation,
IReadOnlyList<SemanticEditInfo> edits,
out ImmutableArray<SemanticEdit> mergedEdits,
out ImmutableHashSet<ISymbol> addedSymbols,
CancellationToken cancellationToken)
{
using var _0 = ArrayBuilder<SemanticEdit>.GetInstance(edits.Count, out var mergedEditsBuilder);
using var _1 = PooledHashSet<ISymbol>.GetInstance(out var addedSymbolsBuilder);
using var _2 = ArrayBuilder<(ISymbol? oldSymbol, ISymbol? newSymbol)>.GetInstance(edits.Count, out var resolvedSymbols);
foreach (var edit in edits)
{
SymbolKeyResolution oldResolution;
if (edit.Kind is SemanticEditKind.Update or SemanticEditKind.Delete)
{
oldResolution = edit.Symbol.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken);
Contract.ThrowIfNull(oldResolution.Symbol);
}
else
{
oldResolution = default;
}
SymbolKeyResolution newResolution;
if (edit.Kind is SemanticEditKind.Update or SemanticEditKind.Insert or SemanticEditKind.Replace)
{
newResolution = edit.Symbol.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken);
Contract.ThrowIfNull(newResolution.Symbol);
}
else
{
newResolution = default;
}
resolvedSymbols.Add((oldResolution.Symbol, newResolution.Symbol));
}
for (var i = 0; i < edits.Count; i++)
{
var edit = edits[i];
if (edit.PartialType == null)
{
var (oldSymbol, newSymbol) = resolvedSymbols[i];
if (edit.Kind == SemanticEditKind.Insert)
{
Contract.ThrowIfNull(newSymbol);
addedSymbolsBuilder.Add(newSymbol);
}
mergedEditsBuilder.Add(new SemanticEdit(
edit.Kind,
oldSymbol: oldSymbol,
newSymbol: newSymbol,
syntaxMap: edit.SyntaxMap,
preserveLocalVariables: edit.SyntaxMap != null));
}
}
// no partial type merging needed:
if (edits.Count == mergedEditsBuilder.Count)
{
mergedEdits = mergedEditsBuilder.ToImmutable();
addedSymbols = addedSymbolsBuilder.ToImmutableHashSet();
return;
}
// Calculate merged syntax map for each partial type symbol:
var symbolKeyComparer = SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: true);
var mergedSyntaxMaps = new Dictionary<SymbolKey, Func<SyntaxNode, SyntaxNode?>?>(symbolKeyComparer);
var editsByPartialType = edits
.Where(edit => edit.PartialType != null)
.GroupBy(edit => edit.PartialType!.Value, symbolKeyComparer);
foreach (var partialTypeEdits in editsByPartialType)
{
// Either all edits have syntax map or none has.
Debug.Assert(
partialTypeEdits.All(edit => edit.SyntaxMapTree != null && edit.SyntaxMap != null) ||
partialTypeEdits.All(edit => edit.SyntaxMapTree == null && edit.SyntaxMap == null));
Func<SyntaxNode, SyntaxNode?>? mergedSyntaxMap;
if (partialTypeEdits.First().SyntaxMap != null)
{
var newTrees = partialTypeEdits.SelectAsArray(edit => edit.SyntaxMapTree!);
var syntaxMaps = partialTypeEdits.SelectAsArray(edit => edit.SyntaxMap!);
mergedSyntaxMap = node => syntaxMaps[newTrees.IndexOf(node.SyntaxTree)](node);
}
else
{
mergedSyntaxMap = null;
}
mergedSyntaxMaps.Add(partialTypeEdits.Key, mergedSyntaxMap);
}
// Deduplicate edits based on their target symbol and use merged syntax map calculated above for a given partial type.
using var _3 = PooledHashSet<ISymbol>.GetInstance(out var visitedSymbols);
for (var i = 0; i < edits.Count; i++)
{
var edit = edits[i];
if (edit.PartialType != null)
{
var (oldSymbol, newSymbol) = resolvedSymbols[i];
if (visitedSymbols.Add(newSymbol ?? oldSymbol!))
{
var syntaxMap = mergedSyntaxMaps[edit.PartialType.Value];
mergedEditsBuilder.Add(new SemanticEdit(edit.Kind, oldSymbol, newSymbol, syntaxMap, preserveLocalVariables: syntaxMap != null));
}
}
}
mergedEdits = mergedEditsBuilder.ToImmutable();
addedSymbols = addedSymbolsBuilder.ToImmutableHashSet();
}
public async ValueTask<SolutionUpdate> EmitSolutionUpdateAsync(Solution solution, ActiveStatementSpanProvider solutionActiveStatementSpanProvider, CancellationToken cancellationToken)
{
try
{
using var _1 = ArrayBuilder<ManagedModuleUpdate>.GetInstance(out var deltas);
using var _2 = ArrayBuilder<(Guid ModuleId, ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)>)>.GetInstance(out var nonRemappableRegions);
using var _3 = ArrayBuilder<(ProjectId, EmitBaseline)>.GetInstance(out var emitBaselines);
using var _4 = ArrayBuilder<(ProjectId, ImmutableArray<Diagnostic>)>.GetInstance(out var diagnostics);
using var _5 = ArrayBuilder<Document>.GetInstance(out var changedOrAddedDocuments);
using var _6 = ArrayBuilder<(DocumentId, ImmutableArray<RudeEditDiagnostic>)>.GetInstance(out var documentsWithRudeEdits);
var oldSolution = DebuggingSession.LastCommittedSolution;
var isBlocked = false;
foreach (var newProject in solution.Projects)
{
await PopulateChangedAndAddedDocumentsAsync(oldSolution, newProject, changedOrAddedDocuments, cancellationToken).ConfigureAwait(false);
if (changedOrAddedDocuments.IsEmpty())
{
continue;
}
var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(newProject, cancellationToken).ConfigureAwait(false);
if (mvidReadError != null)
{
// The error hasn't been reported by GetDocumentDiagnosticsAsync since it might have been intermittent.
// The MVID is required for emit so we consider the error permanent and report it here.
// Bail before analyzing documents as the analysis needs to read the PDB which will likely fail if we can't even read the MVID.
diagnostics.Add((newProject.Id, ImmutableArray.Create(mvidReadError)));
Telemetry.LogProjectAnalysisSummary(ProjectAnalysisSummary.ValidChanges, ImmutableArray.Create(mvidReadError.Descriptor.Id));
isBlocked = true;
continue;
}
if (mvid == Guid.Empty)
{
EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]: project not built", newProject.Id.DebugName, newProject.Id);
continue;
}
// PopulateChangedAndAddedDocumentsAsync returns no changes if base project does not exist
var oldProject = oldSolution.GetProject(newProject.Id);
Contract.ThrowIfNull(oldProject);
// Ensure that all changed documents are in-sync. Once a document is in-sync it can't get out-of-sync.
// Therefore, results of further computations based on base snapshots of changed documents can't be invalidated by
// incoming events updating the content of out-of-sync documents.
//
// If in past we concluded that a document is out-of-sync, attempt to check one more time before we block apply.
// The source file content might have been updated since the last time we checked.
//
// TODO (investigate): https://github.com/dotnet/roslyn/issues/38866
// It is possible that the result of Rude Edit semantic analysis of an unchanged document will change if there
// another document is updated. If we encounter a significant case of this we should consider caching such a result per project,
// rather then per document. Also, we might be observing an older semantics if the document that is causing the change is out-of-sync --
// e.g. the binary was built with an overload C.M(object), but a generator updated class C to also contain C.M(string),
// which change we have not observed yet. Then call-sites of C.M in a changed document observed by the analysis will be seen as C.M(object)
// instead of the true C.M(string).
var (changedDocumentAnalyses, documentDiagnostics) = await AnalyzeDocumentsAsync(changedOrAddedDocuments, solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false);
if (documentDiagnostics.Any())
{
// The diagnostic hasn't been reported by GetDocumentDiagnosticsAsync since out-of-sync documents are likely to be synchronized
// before the changes are attempted to be applied. If we still have any out-of-sync documents we report warnings and ignore changes in them.
// If in future the file is updated so that its content matches the PDB checksum, the document transitions to a matching state,
// and we consider any further changes to it for application.
diagnostics.Add((newProject.Id, documentDiagnostics));
}
// The capability of a module to apply edits may change during edit session if the user attaches debugger to
// an additional process that doesn't support EnC (or detaches from such process). Before we apply edits
// we need to check with the debugger.
var (moduleDiagnostics, isModuleLoaded) = await GetModuleDiagnosticsAsync(mvid, newProject.Name, cancellationToken).ConfigureAwait(false);
var isModuleEncBlocked = isModuleLoaded && !moduleDiagnostics.IsEmpty;
if (isModuleEncBlocked)
{
diagnostics.Add((newProject.Id, moduleDiagnostics));
isBlocked = true;
}
var projectSummary = GetProjectAnalysisSymmary(changedDocumentAnalyses);
if (projectSummary == ProjectAnalysisSummary.CompilationErrors)
{
isBlocked = true;
}
else if (projectSummary == ProjectAnalysisSummary.RudeEdits)
{
foreach (var analysis in changedDocumentAnalyses)
{
if (analysis.RudeEditErrors.Length > 0)
{
documentsWithRudeEdits.Add((analysis.DocumentId, analysis.RudeEditErrors));
}
}
isBlocked = true;
}
if (isModuleEncBlocked || projectSummary != ProjectAnalysisSummary.ValidChanges)
{
Telemetry.LogProjectAnalysisSummary(projectSummary, moduleDiagnostics.NullToEmpty().SelectAsArray(d => d.Descriptor.Id));
continue;
}
if (!DebuggingSession.TryGetOrCreateEmitBaseline(newProject, out var createBaselineDiagnostics, out var baseline))
{
Debug.Assert(!createBaselineDiagnostics.IsEmpty);
// Report diagnosics even when the module is never going to be loaded (e.g. in multi-targeting scenario, where only one framework being debugged).
// This is consistent with reporting compilation errors - the IDE reports them for all TFMs regardless of what framework the app is running on.
diagnostics.Add((newProject.Id, createBaselineDiagnostics));
Telemetry.LogProjectAnalysisSummary(projectSummary, createBaselineDiagnostics);
isBlocked = true;
continue;
}
EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]", newProject.Id.DebugName, newProject.Id);
var oldCompilation = await oldProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var newCompilation = await newProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
Contract.ThrowIfNull(oldCompilation);
Contract.ThrowIfNull(newCompilation);
var oldActiveStatementsMap = await BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false);
var projectChanges = await GetProjectChangesAsync(oldActiveStatementsMap, oldCompilation, newCompilation, oldProject, newProject, changedDocumentAnalyses, cancellationToken).ConfigureAwait(false);
using var pdbStream = SerializableBytes.CreateWritableStream();
using var metadataStream = SerializableBytes.CreateWritableStream();
using var ilStream = SerializableBytes.CreateWritableStream();
// project must support compilations since it supports EnC
Contract.ThrowIfNull(newCompilation);
var emitResult = newCompilation.EmitDifference(
baseline,
projectChanges.SemanticEdits,
projectChanges.AddedSymbols.Contains,
metadataStream,
ilStream,
pdbStream,
cancellationToken);
if (emitResult.Success)
{
Contract.ThrowIfNull(emitResult.Baseline);
var updatedMethodTokens = emitResult.UpdatedMethods.SelectAsArray(h => MetadataTokens.GetToken(h));
var updatedTypeTokens = emitResult.UpdatedTypes.SelectAsArray(h => MetadataTokens.GetToken(h));
// Determine all active statements whose span changed and exception region span deltas.
GetActiveStatementAndExceptionRegionSpans(
mvid,
oldActiveStatementsMap,
updatedMethodTokens,
_nonRemappableRegions,
projectChanges.ActiveStatementChanges,
out var activeStatementsInUpdatedMethods,
out var moduleNonRemappableRegions,
out var exceptionRegionUpdates);
deltas.Add(new ManagedModuleUpdate(
mvid,
ilStream.ToImmutableArray(),
metadataStream.ToImmutableArray(),
pdbStream.ToImmutableArray(),
projectChanges.LineChanges,
updatedMethodTokens,
updatedTypeTokens,
activeStatementsInUpdatedMethods,
exceptionRegionUpdates));
nonRemappableRegions.Add((mvid, moduleNonRemappableRegions));
emitBaselines.Add((newProject.Id, emitResult.Baseline));
}
else
{
// error
isBlocked = true;
}
// TODO: https://github.com/dotnet/roslyn/issues/36061
// We should only report diagnostics from emit phase.
// Syntax and semantic diagnostics are already reported by the diagnostic analyzer.
// Currently we do not have means to distinguish between diagnostics reported from compilation and emit phases.
// Querying diagnostics of the entire compilation or just the updated files migth be slow.
// In fact, it is desirable to allow emitting deltas for symbols affected by the change while allowing untouched
// method bodies to have errors.
if (!emitResult.Diagnostics.IsEmpty)
{
diagnostics.Add((newProject.Id, emitResult.Diagnostics));
}
Telemetry.LogProjectAnalysisSummary(projectSummary, emitResult.Diagnostics);
}
if (isBlocked)
{
return SolutionUpdate.Blocked(diagnostics.ToImmutable(), documentsWithRudeEdits.ToImmutable());
}
return new SolutionUpdate(
new ManagedModuleUpdates(
(deltas.Count > 0) ? ManagedModuleUpdateStatus.Ready : ManagedModuleUpdateStatus.None,
deltas.ToImmutable()),
nonRemappableRegions.ToImmutable(),
emitBaselines.ToImmutable(),
diagnostics.ToImmutable(),
documentsWithRudeEdits.ToImmutable());
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
// internal for testing
internal static void GetActiveStatementAndExceptionRegionSpans(
Guid moduleId,
ActiveStatementsMap oldActiveStatementMap,
ImmutableArray<int> updatedMethodTokens,
ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> previousNonRemappableRegions,
ImmutableArray<DocumentActiveStatementChanges> activeStatementsInChangedDocuments,
out ImmutableArray<ManagedActiveStatementUpdate> activeStatementsInUpdatedMethods,
out ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)> nonRemappableRegions,
out ImmutableArray<ManagedExceptionRegionUpdate> exceptionRegionUpdates)
{
using var _1 = PooledDictionary<(ManagedModuleMethodId MethodId, SourceFileSpan BaseSpan), SourceFileSpan>.GetInstance(out var changedNonRemappableSpans);
var activeStatementsInUpdatedMethodsBuilder = ArrayBuilder<ManagedActiveStatementUpdate>.GetInstance();
var nonRemappableRegionsBuilder = ArrayBuilder<(ManagedModuleMethodId Method, NonRemappableRegion Region)>.GetInstance();
// Process active statements and their exception regions in changed documents of this project/module:
foreach (var (oldActiveStatements, newActiveStatements, newExceptionRegions) in activeStatementsInChangedDocuments)
{
Debug.Assert(oldActiveStatements.Length == newExceptionRegions.Length);
Debug.Assert(newActiveStatements.Length == newExceptionRegions.Length);
for (var i = 0; i < newActiveStatements.Length; i++)
{
var (_, oldActiveStatement, oldActiveStatementExceptionRegions) = oldActiveStatements[i];
var newActiveStatement = newActiveStatements[i];
var newActiveStatementExceptionRegions = newExceptionRegions[i];
var instructionId = newActiveStatement.InstructionId;
var methodId = instructionId.Method.Method;
var isMethodUpdated = updatedMethodTokens.Contains(methodId.Token);
if (isMethodUpdated)
{
activeStatementsInUpdatedMethodsBuilder.Add(new ManagedActiveStatementUpdate(methodId, instructionId.ILOffset, newActiveStatement.Span.ToSourceSpan()));
}
// Adds a region with specified PDB spans.
void AddNonRemappableRegion(SourceFileSpan oldSpan, SourceFileSpan newSpan, bool isExceptionRegion)
{
// it is a rude edit to change the path of the region span:
Debug.Assert(oldSpan.Path == newSpan.Path);
if (newActiveStatement.IsMethodUpToDate)
{
// Start tracking non-remappable regions for active statements in methods that were up-to-date
// when break state was entered and now being updated (regardless of whether the active span changed or not).
if (isMethodUpdated)
{
var lineDelta = oldSpan.Span.GetLineDelta(newSpan: newSpan.Span);
nonRemappableRegionsBuilder.Add((methodId, new NonRemappableRegion(oldSpan, lineDelta, isExceptionRegion)));
}
// If the method has been up-to-date and it is not updated now then either the active statement span has not changed,
// or the entire method containing it moved. In neither case do we need to start tracking non-remapable region
// for the active statement since movement of whole method bodies (if any) is handled only on PDB level without
// triggering any remapping on the IL level.
}
else if (oldSpan.Span != newSpan.Span)
{
// The method is not up-to-date hence we maintain non-remapable span map for it that needs to be updated.
changedNonRemappableSpans[(methodId, oldSpan)] = newSpan;
}
}
AddNonRemappableRegion(oldActiveStatement.FileSpan, newActiveStatement.FileSpan, isExceptionRegion: false);
// The spans of the exception regions are known (non-default) for active statements in changed documents
// as we ensured earlier that all changed documents are in-sync.
for (var j = 0; j < oldActiveStatementExceptionRegions.Spans.Length; j++)
{
AddNonRemappableRegion(oldActiveStatementExceptionRegions.Spans[j], newActiveStatementExceptionRegions[j], isExceptionRegion: true);
}
}
}
activeStatementsInUpdatedMethods = activeStatementsInUpdatedMethodsBuilder.ToImmutableAndFree();
// Gather all active method instances contained in this project/module that are not up-to-date:
using var _2 = PooledHashSet<ManagedModuleMethodId>.GetInstance(out var unremappedActiveMethods);
foreach (var (instruction, baseActiveStatement) in oldActiveStatementMap.InstructionMap)
{
if (moduleId == instruction.Method.Module && !baseActiveStatement.IsMethodUpToDate)
{
unremappedActiveMethods.Add(instruction.Method.Method);
}
}
if (unremappedActiveMethods.Count > 0)
{
foreach (var (methodInstance, regionsInMethod) in previousNonRemappableRegions)
{
if (methodInstance.Module != moduleId)
{
continue;
}
// Skip non-remappable regions that belong to method instances that are from a different module
// or no longer active (all active statements in these method instances have been remapped to newer versions).
if (!unremappedActiveMethods.Contains(methodInstance.Method))
{
continue;
}
foreach (var region in regionsInMethod)
{
// We have calculated changes against a base snapshot (last break state):
var baseSpan = region.Span.AddLineDelta(region.LineDelta);
NonRemappableRegion newRegion;
if (changedNonRemappableSpans.TryGetValue((methodInstance.Method, baseSpan), out var newSpan))
{
// all spans must be of the same size:
Debug.Assert(newSpan.Span.End.Line - newSpan.Span.Start.Line == baseSpan.Span.End.Line - baseSpan.Span.Start.Line);
Debug.Assert(region.Span.Span.End.Line - region.Span.Span.Start.Line == baseSpan.Span.End.Line - baseSpan.Span.Start.Line);
Debug.Assert(newSpan.Path == region.Span.Path);
newRegion = region.WithLineDelta(region.Span.Span.GetLineDelta(newSpan: newSpan.Span));
}
else
{
newRegion = region;
}
nonRemappableRegionsBuilder.Add((methodInstance.Method, newRegion));
}
}
}
nonRemappableRegions = nonRemappableRegionsBuilder.ToImmutableAndFree();
// Note: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1319289
//
// The update should include the file name, otherwise it is not possible for the debugger to find
// the right IL span of the exception handler in case when multiple handlers in the same method
// have the same mapped span but different mapped file name:
//
// try { active statement }
// #line 20 "bar"
// catch (IOException) { }
// #line 20 "baz"
// catch (Exception) { }
//
// The range span in exception region updates is the new span. Deltas are inverse.
// old = new + delta
// new = old – delta
exceptionRegionUpdates = nonRemappableRegions.SelectAsArray(
r => r.Region.IsExceptionRegion,
r => new ManagedExceptionRegionUpdate(
r.Method,
-r.Region.LineDelta,
r.Region.Span.AddLineDelta(r.Region.LineDelta).Span.ToSourceSpan()));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.EditAndContinue
{
internal sealed class EditSession
{
internal readonly DebuggingSession DebuggingSession;
internal readonly EditSessionTelemetry Telemetry;
private readonly ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> _nonRemappableRegions;
/// <summary>
/// Lazily calculated map of base active statements.
/// </summary>
internal readonly AsyncLazy<ActiveStatementsMap> BaseActiveStatements;
/// <summary>
/// Cache of document EnC analyses.
/// </summary>
internal readonly EditAndContinueDocumentAnalysesCache Analyses;
internal readonly bool InBreakState;
/// <summary>
/// A <see cref="DocumentId"/> is added whenever EnC analyzer reports
/// rude edits or module diagnostics. At the end of the session we ask the diagnostic analyzer to reanalyze
/// the documents to clean up the diagnostics.
/// </summary>
private readonly HashSet<DocumentId> _documentsWithReportedDiagnostics = new();
private readonly object _documentsWithReportedDiagnosticsGuard = new();
internal EditSession(DebuggingSession debuggingSession, EditSessionTelemetry telemetry, bool inBreakState)
{
DebuggingSession = debuggingSession;
Telemetry = telemetry;
_nonRemappableRegions = debuggingSession.NonRemappableRegions;
InBreakState = inBreakState;
BaseActiveStatements = inBreakState ?
new AsyncLazy<ActiveStatementsMap>(cancellationToken => GetBaseActiveStatementsAsync(cancellationToken), cacheResult: true) :
new AsyncLazy<ActiveStatementsMap>(ActiveStatementsMap.Empty);
Analyses = new EditAndContinueDocumentAnalysesCache(BaseActiveStatements);
}
/// <summary>
/// Errors to be reported when a project is updated but the corresponding module does not support EnC.
/// </summary>
/// <returns><see langword="default"/> if the module is not loaded.</returns>
public async Task<ImmutableArray<Diagnostic>?> GetModuleDiagnosticsAsync(Guid mvid, string projectDisplayName, CancellationToken cancellationToken)
{
var availability = await DebuggingSession.DebuggerService.GetAvailabilityAsync(mvid, cancellationToken).ConfigureAwait(false);
if (availability.Status == ManagedEditAndContinueAvailabilityStatus.ModuleNotLoaded)
{
return null;
}
if (availability.Status == ManagedEditAndContinueAvailabilityStatus.Available)
{
return ImmutableArray<Diagnostic>.Empty;
}
var descriptor = EditAndContinueDiagnosticDescriptors.GetModuleDiagnosticDescriptor(availability.Status);
return ImmutableArray.Create(Diagnostic.Create(descriptor, Location.None, new[] { projectDisplayName, availability.LocalizedMessage }));
}
private async Task<ActiveStatementsMap> GetBaseActiveStatementsAsync(CancellationToken cancellationToken)
{
try
{
// Last committed solution reflects the state of the source that is in sync with the binaries that are loaded in the debuggee.
var debugInfos = await DebuggingSession.DebuggerService.GetActiveStatementsAsync(cancellationToken).ConfigureAwait(false);
return ActiveStatementsMap.Create(debugInfos, _nonRemappableRegions);
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
return ActiveStatementsMap.Empty;
}
}
private static async Task PopulateChangedAndAddedDocumentsAsync(CommittedSolution oldSolution, Project newProject, ArrayBuilder<Document> changedOrAddedDocuments, CancellationToken cancellationToken)
{
changedOrAddedDocuments.Clear();
if (!newProject.SupportsEditAndContinue())
{
return;
}
var oldProject = oldSolution.GetProject(newProject.Id);
// When debugging session is started some projects might not have been loaded to the workspace yet.
// We capture the base solution. Edits in files that are in projects that haven't been loaded won't be applied
// and will result in source mismatch when the user steps into them.
//
// TODO (https://github.com/dotnet/roslyn/issues/1204):
// hook up the debugger reported error, check that the project has not been loaded and report a better error.
// Here, we assume these projects are not modified.
if (oldProject == null)
{
EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not loaded", newProject.Id.DebugName, newProject.Id);
return;
}
if (oldProject.State == newProject.State)
{
return;
}
foreach (var documentId in newProject.State.DocumentStates.GetChangedStateIds(oldProject.State.DocumentStates, ignoreUnchangedContent: true))
{
var document = newProject.GetRequiredDocument(documentId);
if (document.State.Attributes.DesignTimeOnly)
{
continue;
}
// Check if the currently observed document content has changed compared to the base document content.
// This is an important optimization that aims to avoid IO while stepping in sources that have not changed.
//
// We may be comparing out-of-date committed document content but we only make a decision based on that content
// if it matches the current content. If the current content is equal to baseline content that does not match
// the debuggee then the workspace has not observed the change made to the file on disk since baseline was captured
// (there had to be one as the content doesn't match). When we are about to apply changes it is ok to ignore this
// document because the user does not see the change yet in the buffer (if the doc is open) and won't be confused
// if it is not applied yet. The change will be applied later after it's observed by the workspace.
var baseSource = await oldProject.GetRequiredDocument(documentId).GetTextAsync(cancellationToken).ConfigureAwait(false);
var source = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
if (baseSource.ContentEquals(source))
{
continue;
}
changedOrAddedDocuments.Add(document);
}
foreach (var documentId in newProject.State.DocumentStates.GetAddedStateIds(oldProject.State.DocumentStates))
{
var document = newProject.GetRequiredDocument(documentId);
if (document.State.Attributes.DesignTimeOnly)
{
continue;
}
changedOrAddedDocuments.Add(document);
}
// TODO: support document removal/rename (see https://github.com/dotnet/roslyn/issues/41144, https://github.com/dotnet/roslyn/issues/49013).
if (changedOrAddedDocuments.IsEmpty() && !HasChangesThatMayAffectSourceGenerators(oldProject.State, newProject.State))
{
// Based on the above assumption there are no changes in source generated files.
return;
}
cancellationToken.ThrowIfCancellationRequested();
var oldSourceGeneratedDocumentStates = await oldProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(oldProject.State, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
var newSourceGeneratedDocumentStates = await newProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(newProject.State, cancellationToken).ConfigureAwait(false);
foreach (var documentId in newSourceGeneratedDocumentStates.GetChangedStateIds(oldSourceGeneratedDocumentStates, ignoreUnchangedContent: true))
{
var newState = newSourceGeneratedDocumentStates.GetRequiredState(documentId);
if (newState.Attributes.DesignTimeOnly)
{
continue;
}
changedOrAddedDocuments.Add(newProject.GetOrCreateSourceGeneratedDocument(newState));
}
foreach (var documentId in newSourceGeneratedDocumentStates.GetAddedStateIds(oldSourceGeneratedDocumentStates))
{
var newState = newSourceGeneratedDocumentStates.GetRequiredState(documentId);
if (newState.Attributes.DesignTimeOnly)
{
continue;
}
changedOrAddedDocuments.Add(newProject.GetOrCreateSourceGeneratedDocument(newState));
}
}
internal static async IAsyncEnumerable<DocumentId> GetChangedDocumentsAsync(CommittedSolution oldSolution, Project newProject, [EnumeratorCancellation] CancellationToken cancellationToken)
{
var oldProject = oldSolution.GetRequiredProject(newProject.Id);
if (!newProject.SupportsEditAndContinue() || oldProject.State == newProject.State)
{
yield break;
}
foreach (var documentId in newProject.State.DocumentStates.GetChangedStateIds(oldProject.State.DocumentStates, ignoreUnchangedContent: true))
{
yield return documentId;
}
if (!HasChangesThatMayAffectSourceGenerators(oldProject.State, newProject.State))
{
// Based on the above assumption there are no changes in source generated files.
yield break;
}
cancellationToken.ThrowIfCancellationRequested();
var oldSourceGeneratedDocumentStates = await oldProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(oldProject.State, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
var newSourceGeneratedDocumentStates = await newProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(newProject.State, cancellationToken).ConfigureAwait(false);
foreach (var documentId in newSourceGeneratedDocumentStates.GetChangedStateIds(oldSourceGeneratedDocumentStates, ignoreUnchangedContent: true))
{
yield return documentId;
}
}
/// <summary>
/// Given the following assumptions:
/// - source generators are deterministic,
/// - source documents, metadata references and compilation options have not changed,
/// - additional documents have not changed,
/// - analyzer config documents have not changed,
/// the outputs of source generators will not change.
///
/// Currently it's not possible to change compilation options (Project System is readonly during debugging).
/// </summary>
private static bool HasChangesThatMayAffectSourceGenerators(ProjectState oldProject, ProjectState newProject)
=> newProject.DocumentStates.HasAnyStateChanges(oldProject.DocumentStates) ||
newProject.AdditionalDocumentStates.HasAnyStateChanges(oldProject.AdditionalDocumentStates) ||
newProject.AnalyzerConfigDocumentStates.HasAnyStateChanges(oldProject.AnalyzerConfigDocumentStates);
private async Task<(ImmutableArray<DocumentAnalysisResults> results, ImmutableArray<Diagnostic> diagnostics)> AnalyzeDocumentsAsync(
ArrayBuilder<Document> changedOrAddedDocuments,
ActiveStatementSpanProvider newDocumentActiveStatementSpanProvider,
CancellationToken cancellationToken)
{
using var _1 = ArrayBuilder<Diagnostic>.GetInstance(out var documentDiagnostics);
using var _2 = ArrayBuilder<(Document? oldDocument, Document newDocument)>.GetInstance(out var documents);
foreach (var newDocument in changedOrAddedDocuments)
{
var (oldDocument, oldDocumentState) = await DebuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken, reloadOutOfSyncDocument: true).ConfigureAwait(false);
switch (oldDocumentState)
{
case CommittedSolution.DocumentState.DesignTimeOnly:
break;
case CommittedSolution.DocumentState.Indeterminate:
case CommittedSolution.DocumentState.OutOfSync:
var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor((oldDocumentState == CommittedSolution.DocumentState.Indeterminate) ?
EditAndContinueErrorCode.UnableToReadSourceFileOrPdb : EditAndContinueErrorCode.DocumentIsOutOfSyncWithDebuggee);
documentDiagnostics.Add(Diagnostic.Create(descriptor, Location.Create(newDocument.FilePath!, textSpan: default, lineSpan: default), new[] { newDocument.FilePath }));
break;
case CommittedSolution.DocumentState.MatchesBuildOutput:
// Include the document regardless of whether the module it was built into has been loaded or not.
// If the module has been built it might get loaded later during the debugging session,
// at which point we apply all changes that have been made to the project so far.
documents.Add((oldDocument, newDocument));
break;
default:
throw ExceptionUtilities.UnexpectedValue(oldDocumentState);
}
}
var analyses = await Analyses.GetDocumentAnalysesAsync(DebuggingSession.LastCommittedSolution, documents, newDocumentActiveStatementSpanProvider, DebuggingSession.Capabilities, cancellationToken).ConfigureAwait(false);
return (analyses, documentDiagnostics.ToImmutable());
}
internal ImmutableArray<DocumentId> GetDocumentsWithReportedDiagnostics()
{
lock (_documentsWithReportedDiagnosticsGuard)
{
return ImmutableArray.CreateRange(_documentsWithReportedDiagnostics);
}
}
internal void TrackDocumentWithReportedDiagnostics(DocumentId documentId)
{
lock (_documentsWithReportedDiagnosticsGuard)
{
_documentsWithReportedDiagnostics.Add(documentId);
}
}
/// <summary>
/// Determines whether projects contain any changes that might need to be applied.
/// Checks only projects containing a given <paramref name="sourceFilePath"/> or all projects of the solution if <paramref name="sourceFilePath"/> is null.
/// Invoked by the debugger on every step. It is critical for stepping performance that this method returns as fast as possible in absence of changes.
/// </summary>
public async ValueTask<bool> HasChangesAsync(Solution solution, ActiveStatementSpanProvider solutionActiveStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken)
{
try
{
var baseSolution = DebuggingSession.LastCommittedSolution;
if (baseSolution.HasNoChanges(solution))
{
return false;
}
// TODO: source generated files?
var projects = (sourceFilePath == null) ? solution.Projects :
from documentId in solution.GetDocumentIdsWithFilePath(sourceFilePath)
select solution.GetProject(documentId.ProjectId)!;
using var _ = ArrayBuilder<Document>.GetInstance(out var changedOrAddedDocuments);
foreach (var project in projects)
{
await PopulateChangedAndAddedDocumentsAsync(baseSolution, project, changedOrAddedDocuments, cancellationToken).ConfigureAwait(false);
if (changedOrAddedDocuments.IsEmpty())
{
continue;
}
// Check MVID before analyzing documents as the analysis needs to read the PDB which will likely fail if we can't even read the MVID.
var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(project, cancellationToken).ConfigureAwait(false);
if (mvidReadError != null)
{
// Can't read MVID. This might be an intermittent failure, so don't report it here.
// Report the project as containing changes, so that we proceed to EmitSolutionUpdateAsync where we report the error if it still persists.
EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not built", project.Id.DebugName, project.Id);
return true;
}
if (mvid == Guid.Empty)
{
// Project not built. We ignore any changes made in its sources.
EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not built", project.Id.DebugName, project.Id);
continue;
}
var (changedDocumentAnalyses, documentDiagnostics) = await AnalyzeDocumentsAsync(changedOrAddedDocuments, solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false);
if (documentDiagnostics.Any())
{
EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: out-of-sync documents present (diagnostic: '{2}')",
project.Id.DebugName, project.Id, documentDiagnostics[0]);
// Although we do not apply changes in out-of-sync/indeterminate documents we report that changes are present,
// so that the debugger triggers emit of updates. There we check if these documents are still in a bad state and report warnings
// that any changes in such documents are not applied.
return true;
}
var projectSummary = GetProjectAnalysisSymmary(changedDocumentAnalyses);
if (projectSummary != ProjectAnalysisSummary.NoChanges)
{
EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: {2}", project.Id.DebugName, project.Id, projectSummary);
return true;
}
}
return false;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
private static ProjectAnalysisSummary GetProjectAnalysisSymmary(ImmutableArray<DocumentAnalysisResults> documentAnalyses)
{
var hasChanges = false;
var hasSignificantValidChanges = false;
foreach (var analysis in documentAnalyses)
{
// skip documents that actually were not changed:
if (!analysis.HasChanges)
{
continue;
}
// rude edit detection wasn't completed due to errors that prevent us from analyzing the document:
if (analysis.HasChangesAndSyntaxErrors)
{
return ProjectAnalysisSummary.CompilationErrors;
}
// rude edits detected:
if (!analysis.RudeEditErrors.IsEmpty)
{
return ProjectAnalysisSummary.RudeEdits;
}
hasChanges = true;
hasSignificantValidChanges |= analysis.HasSignificantValidChanges;
}
if (!hasChanges)
{
// we get here if a document is closed and reopen without any actual change:
return ProjectAnalysisSummary.NoChanges;
}
if (!hasSignificantValidChanges)
{
return ProjectAnalysisSummary.ValidInsignificantChanges;
}
return ProjectAnalysisSummary.ValidChanges;
}
internal static async ValueTask<ProjectChanges> GetProjectChangesAsync(
ActiveStatementsMap baseActiveStatements,
Compilation oldCompilation,
Compilation newCompilation,
Project oldProject,
Project newProject,
ImmutableArray<DocumentAnalysisResults> changedDocumentAnalyses,
CancellationToken cancellationToken)
{
try
{
using var _1 = ArrayBuilder<SemanticEditInfo>.GetInstance(out var allEdits);
using var _2 = ArrayBuilder<SequencePointUpdates>.GetInstance(out var allLineEdits);
using var _3 = ArrayBuilder<DocumentActiveStatementChanges>.GetInstance(out var activeStatementsInChangedDocuments);
var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>();
foreach (var analysis in changedDocumentAnalyses)
{
if (!analysis.HasSignificantValidChanges)
{
continue;
}
// we shouldn't be asking for deltas in presence of errors:
Contract.ThrowIfTrue(analysis.HasChangesAndErrors);
// Active statements are calculated if document changed and has no syntax errors:
Contract.ThrowIfTrue(analysis.ActiveStatements.IsDefault);
allEdits.AddRange(analysis.SemanticEdits);
allLineEdits.AddRange(analysis.LineEdits);
if (analysis.ActiveStatements.Length > 0)
{
var oldDocument = await oldProject.GetDocumentAsync(analysis.DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false);
var oldActiveStatements = (oldDocument == null) ? ImmutableArray<UnmappedActiveStatement>.Empty :
await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false);
activeStatementsInChangedDocuments.Add(new(oldActiveStatements, analysis.ActiveStatements, analysis.ExceptionRegions));
}
}
MergePartialEdits(oldCompilation, newCompilation, allEdits, out var mergedEdits, out var addedSymbols, cancellationToken);
return new ProjectChanges(
mergedEdits,
allLineEdits.ToImmutable(),
addedSymbols,
activeStatementsInChangedDocuments.ToImmutable());
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
internal static void MergePartialEdits(
Compilation oldCompilation,
Compilation newCompilation,
IReadOnlyList<SemanticEditInfo> edits,
out ImmutableArray<SemanticEdit> mergedEdits,
out ImmutableHashSet<ISymbol> addedSymbols,
CancellationToken cancellationToken)
{
using var _0 = ArrayBuilder<SemanticEdit>.GetInstance(edits.Count, out var mergedEditsBuilder);
using var _1 = PooledHashSet<ISymbol>.GetInstance(out var addedSymbolsBuilder);
using var _2 = ArrayBuilder<(ISymbol? oldSymbol, ISymbol? newSymbol)>.GetInstance(edits.Count, out var resolvedSymbols);
foreach (var edit in edits)
{
SymbolKeyResolution oldResolution;
if (edit.Kind is SemanticEditKind.Update or SemanticEditKind.Delete)
{
oldResolution = edit.Symbol.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken);
Contract.ThrowIfNull(oldResolution.Symbol);
}
else
{
oldResolution = default;
}
SymbolKeyResolution newResolution;
if (edit.Kind is SemanticEditKind.Update or SemanticEditKind.Insert or SemanticEditKind.Replace)
{
newResolution = edit.Symbol.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken);
Contract.ThrowIfNull(newResolution.Symbol);
}
else
{
newResolution = default;
}
resolvedSymbols.Add((oldResolution.Symbol, newResolution.Symbol));
}
for (var i = 0; i < edits.Count; i++)
{
var edit = edits[i];
if (edit.PartialType == null)
{
var (oldSymbol, newSymbol) = resolvedSymbols[i];
if (edit.Kind == SemanticEditKind.Insert)
{
Contract.ThrowIfNull(newSymbol);
addedSymbolsBuilder.Add(newSymbol);
}
mergedEditsBuilder.Add(new SemanticEdit(
edit.Kind,
oldSymbol: oldSymbol,
newSymbol: newSymbol,
syntaxMap: edit.SyntaxMap,
preserveLocalVariables: edit.SyntaxMap != null));
}
}
// no partial type merging needed:
if (edits.Count == mergedEditsBuilder.Count)
{
mergedEdits = mergedEditsBuilder.ToImmutable();
addedSymbols = addedSymbolsBuilder.ToImmutableHashSet();
return;
}
// Calculate merged syntax map for each partial type symbol:
var symbolKeyComparer = SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: true);
var mergedSyntaxMaps = new Dictionary<SymbolKey, Func<SyntaxNode, SyntaxNode?>?>(symbolKeyComparer);
var editsByPartialType = edits
.Where(edit => edit.PartialType != null)
.GroupBy(edit => edit.PartialType!.Value, symbolKeyComparer);
foreach (var partialTypeEdits in editsByPartialType)
{
// Either all edits have syntax map or none has.
Debug.Assert(
partialTypeEdits.All(edit => edit.SyntaxMapTree != null && edit.SyntaxMap != null) ||
partialTypeEdits.All(edit => edit.SyntaxMapTree == null && edit.SyntaxMap == null));
Func<SyntaxNode, SyntaxNode?>? mergedSyntaxMap;
if (partialTypeEdits.First().SyntaxMap != null)
{
var newTrees = partialTypeEdits.SelectAsArray(edit => edit.SyntaxMapTree!);
var syntaxMaps = partialTypeEdits.SelectAsArray(edit => edit.SyntaxMap!);
mergedSyntaxMap = node => syntaxMaps[newTrees.IndexOf(node.SyntaxTree)](node);
}
else
{
mergedSyntaxMap = null;
}
mergedSyntaxMaps.Add(partialTypeEdits.Key, mergedSyntaxMap);
}
// Deduplicate edits based on their target symbol and use merged syntax map calculated above for a given partial type.
using var _3 = PooledHashSet<ISymbol>.GetInstance(out var visitedSymbols);
for (var i = 0; i < edits.Count; i++)
{
var edit = edits[i];
if (edit.PartialType != null)
{
var (oldSymbol, newSymbol) = resolvedSymbols[i];
if (visitedSymbols.Add(newSymbol ?? oldSymbol!))
{
var syntaxMap = mergedSyntaxMaps[edit.PartialType.Value];
mergedEditsBuilder.Add(new SemanticEdit(edit.Kind, oldSymbol, newSymbol, syntaxMap, preserveLocalVariables: syntaxMap != null));
}
}
}
mergedEdits = mergedEditsBuilder.ToImmutable();
addedSymbols = addedSymbolsBuilder.ToImmutableHashSet();
}
public async ValueTask<SolutionUpdate> EmitSolutionUpdateAsync(Solution solution, ActiveStatementSpanProvider solutionActiveStatementSpanProvider, CancellationToken cancellationToken)
{
try
{
using var _1 = ArrayBuilder<ManagedModuleUpdate>.GetInstance(out var deltas);
using var _2 = ArrayBuilder<(Guid ModuleId, ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)>)>.GetInstance(out var nonRemappableRegions);
using var _3 = ArrayBuilder<(ProjectId, EmitBaseline)>.GetInstance(out var emitBaselines);
using var _4 = ArrayBuilder<(ProjectId, ImmutableArray<Diagnostic>)>.GetInstance(out var diagnostics);
using var _5 = ArrayBuilder<Document>.GetInstance(out var changedOrAddedDocuments);
using var _6 = ArrayBuilder<(DocumentId, ImmutableArray<RudeEditDiagnostic>)>.GetInstance(out var documentsWithRudeEdits);
var oldSolution = DebuggingSession.LastCommittedSolution;
var isBlocked = false;
foreach (var newProject in solution.Projects)
{
await PopulateChangedAndAddedDocumentsAsync(oldSolution, newProject, changedOrAddedDocuments, cancellationToken).ConfigureAwait(false);
if (changedOrAddedDocuments.IsEmpty())
{
continue;
}
var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(newProject, cancellationToken).ConfigureAwait(false);
if (mvidReadError != null)
{
// The error hasn't been reported by GetDocumentDiagnosticsAsync since it might have been intermittent.
// The MVID is required for emit so we consider the error permanent and report it here.
// Bail before analyzing documents as the analysis needs to read the PDB which will likely fail if we can't even read the MVID.
diagnostics.Add((newProject.Id, ImmutableArray.Create(mvidReadError)));
Telemetry.LogProjectAnalysisSummary(ProjectAnalysisSummary.ValidChanges, ImmutableArray.Create(mvidReadError.Descriptor.Id));
isBlocked = true;
continue;
}
if (mvid == Guid.Empty)
{
EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]: project not built", newProject.Id.DebugName, newProject.Id);
continue;
}
// PopulateChangedAndAddedDocumentsAsync returns no changes if base project does not exist
var oldProject = oldSolution.GetProject(newProject.Id);
Contract.ThrowIfNull(oldProject);
// Ensure that all changed documents are in-sync. Once a document is in-sync it can't get out-of-sync.
// Therefore, results of further computations based on base snapshots of changed documents can't be invalidated by
// incoming events updating the content of out-of-sync documents.
//
// If in past we concluded that a document is out-of-sync, attempt to check one more time before we block apply.
// The source file content might have been updated since the last time we checked.
//
// TODO (investigate): https://github.com/dotnet/roslyn/issues/38866
// It is possible that the result of Rude Edit semantic analysis of an unchanged document will change if there
// another document is updated. If we encounter a significant case of this we should consider caching such a result per project,
// rather then per document. Also, we might be observing an older semantics if the document that is causing the change is out-of-sync --
// e.g. the binary was built with an overload C.M(object), but a generator updated class C to also contain C.M(string),
// which change we have not observed yet. Then call-sites of C.M in a changed document observed by the analysis will be seen as C.M(object)
// instead of the true C.M(string).
var (changedDocumentAnalyses, documentDiagnostics) = await AnalyzeDocumentsAsync(changedOrAddedDocuments, solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false);
if (documentDiagnostics.Any())
{
// The diagnostic hasn't been reported by GetDocumentDiagnosticsAsync since out-of-sync documents are likely to be synchronized
// before the changes are attempted to be applied. If we still have any out-of-sync documents we report warnings and ignore changes in them.
// If in future the file is updated so that its content matches the PDB checksum, the document transitions to a matching state,
// and we consider any further changes to it for application.
diagnostics.Add((newProject.Id, documentDiagnostics));
}
// The capability of a module to apply edits may change during edit session if the user attaches debugger to
// an additional process that doesn't support EnC (or detaches from such process). Before we apply edits
// we need to check with the debugger.
var (moduleDiagnostics, isModuleLoaded) = await GetModuleDiagnosticsAsync(mvid, newProject.Name, cancellationToken).ConfigureAwait(false);
var isModuleEncBlocked = isModuleLoaded && !moduleDiagnostics.IsEmpty;
if (isModuleEncBlocked)
{
diagnostics.Add((newProject.Id, moduleDiagnostics));
isBlocked = true;
}
var projectSummary = GetProjectAnalysisSymmary(changedDocumentAnalyses);
if (projectSummary == ProjectAnalysisSummary.CompilationErrors)
{
isBlocked = true;
}
else if (projectSummary == ProjectAnalysisSummary.RudeEdits)
{
foreach (var analysis in changedDocumentAnalyses)
{
if (analysis.RudeEditErrors.Length > 0)
{
documentsWithRudeEdits.Add((analysis.DocumentId, analysis.RudeEditErrors));
}
}
isBlocked = true;
}
if (isModuleEncBlocked || projectSummary != ProjectAnalysisSummary.ValidChanges)
{
Telemetry.LogProjectAnalysisSummary(projectSummary, moduleDiagnostics.NullToEmpty().SelectAsArray(d => d.Descriptor.Id));
continue;
}
if (!DebuggingSession.TryGetOrCreateEmitBaseline(newProject, out var createBaselineDiagnostics, out var baseline))
{
Debug.Assert(!createBaselineDiagnostics.IsEmpty);
// Report diagnosics even when the module is never going to be loaded (e.g. in multi-targeting scenario, where only one framework being debugged).
// This is consistent with reporting compilation errors - the IDE reports them for all TFMs regardless of what framework the app is running on.
diagnostics.Add((newProject.Id, createBaselineDiagnostics));
Telemetry.LogProjectAnalysisSummary(projectSummary, createBaselineDiagnostics);
isBlocked = true;
continue;
}
EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]", newProject.Id.DebugName, newProject.Id);
var oldCompilation = await oldProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var newCompilation = await newProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
Contract.ThrowIfNull(oldCompilation);
Contract.ThrowIfNull(newCompilation);
var oldActiveStatementsMap = await BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false);
var projectChanges = await GetProjectChangesAsync(oldActiveStatementsMap, oldCompilation, newCompilation, oldProject, newProject, changedDocumentAnalyses, cancellationToken).ConfigureAwait(false);
using var pdbStream = SerializableBytes.CreateWritableStream();
using var metadataStream = SerializableBytes.CreateWritableStream();
using var ilStream = SerializableBytes.CreateWritableStream();
// project must support compilations since it supports EnC
Contract.ThrowIfNull(newCompilation);
var emitResult = newCompilation.EmitDifference(
baseline,
projectChanges.SemanticEdits,
projectChanges.AddedSymbols.Contains,
metadataStream,
ilStream,
pdbStream,
cancellationToken);
if (emitResult.Success)
{
Contract.ThrowIfNull(emitResult.Baseline);
var updatedMethodTokens = emitResult.UpdatedMethods.SelectAsArray(h => MetadataTokens.GetToken(h));
var changedTypeTokens = emitResult.ChangedTypes.SelectAsArray(h => MetadataTokens.GetToken(h));
// Determine all active statements whose span changed and exception region span deltas.
GetActiveStatementAndExceptionRegionSpans(
mvid,
oldActiveStatementsMap,
updatedMethodTokens,
_nonRemappableRegions,
projectChanges.ActiveStatementChanges,
out var activeStatementsInUpdatedMethods,
out var moduleNonRemappableRegions,
out var exceptionRegionUpdates);
deltas.Add(new ManagedModuleUpdate(
mvid,
ilStream.ToImmutableArray(),
metadataStream.ToImmutableArray(),
pdbStream.ToImmutableArray(),
projectChanges.LineChanges,
updatedMethodTokens,
changedTypeTokens,
activeStatementsInUpdatedMethods,
exceptionRegionUpdates));
nonRemappableRegions.Add((mvid, moduleNonRemappableRegions));
emitBaselines.Add((newProject.Id, emitResult.Baseline));
}
else
{
// error
isBlocked = true;
}
// TODO: https://github.com/dotnet/roslyn/issues/36061
// We should only report diagnostics from emit phase.
// Syntax and semantic diagnostics are already reported by the diagnostic analyzer.
// Currently we do not have means to distinguish between diagnostics reported from compilation and emit phases.
// Querying diagnostics of the entire compilation or just the updated files migth be slow.
// In fact, it is desirable to allow emitting deltas for symbols affected by the change while allowing untouched
// method bodies to have errors.
if (!emitResult.Diagnostics.IsEmpty)
{
diagnostics.Add((newProject.Id, emitResult.Diagnostics));
}
Telemetry.LogProjectAnalysisSummary(projectSummary, emitResult.Diagnostics);
}
if (isBlocked)
{
return SolutionUpdate.Blocked(diagnostics.ToImmutable(), documentsWithRudeEdits.ToImmutable());
}
return new SolutionUpdate(
new ManagedModuleUpdates(
(deltas.Count > 0) ? ManagedModuleUpdateStatus.Ready : ManagedModuleUpdateStatus.None,
deltas.ToImmutable()),
nonRemappableRegions.ToImmutable(),
emitBaselines.ToImmutable(),
diagnostics.ToImmutable(),
documentsWithRudeEdits.ToImmutable());
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
// internal for testing
internal static void GetActiveStatementAndExceptionRegionSpans(
Guid moduleId,
ActiveStatementsMap oldActiveStatementMap,
ImmutableArray<int> updatedMethodTokens,
ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> previousNonRemappableRegions,
ImmutableArray<DocumentActiveStatementChanges> activeStatementsInChangedDocuments,
out ImmutableArray<ManagedActiveStatementUpdate> activeStatementsInUpdatedMethods,
out ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)> nonRemappableRegions,
out ImmutableArray<ManagedExceptionRegionUpdate> exceptionRegionUpdates)
{
using var _1 = PooledDictionary<(ManagedModuleMethodId MethodId, SourceFileSpan BaseSpan), SourceFileSpan>.GetInstance(out var changedNonRemappableSpans);
var activeStatementsInUpdatedMethodsBuilder = ArrayBuilder<ManagedActiveStatementUpdate>.GetInstance();
var nonRemappableRegionsBuilder = ArrayBuilder<(ManagedModuleMethodId Method, NonRemappableRegion Region)>.GetInstance();
// Process active statements and their exception regions in changed documents of this project/module:
foreach (var (oldActiveStatements, newActiveStatements, newExceptionRegions) in activeStatementsInChangedDocuments)
{
Debug.Assert(oldActiveStatements.Length == newExceptionRegions.Length);
Debug.Assert(newActiveStatements.Length == newExceptionRegions.Length);
for (var i = 0; i < newActiveStatements.Length; i++)
{
var (_, oldActiveStatement, oldActiveStatementExceptionRegions) = oldActiveStatements[i];
var newActiveStatement = newActiveStatements[i];
var newActiveStatementExceptionRegions = newExceptionRegions[i];
var instructionId = newActiveStatement.InstructionId;
var methodId = instructionId.Method.Method;
var isMethodUpdated = updatedMethodTokens.Contains(methodId.Token);
if (isMethodUpdated)
{
activeStatementsInUpdatedMethodsBuilder.Add(new ManagedActiveStatementUpdate(methodId, instructionId.ILOffset, newActiveStatement.Span.ToSourceSpan()));
}
// Adds a region with specified PDB spans.
void AddNonRemappableRegion(SourceFileSpan oldSpan, SourceFileSpan newSpan, bool isExceptionRegion)
{
// it is a rude edit to change the path of the region span:
Debug.Assert(oldSpan.Path == newSpan.Path);
if (newActiveStatement.IsMethodUpToDate)
{
// Start tracking non-remappable regions for active statements in methods that were up-to-date
// when break state was entered and now being updated (regardless of whether the active span changed or not).
if (isMethodUpdated)
{
var lineDelta = oldSpan.Span.GetLineDelta(newSpan: newSpan.Span);
nonRemappableRegionsBuilder.Add((methodId, new NonRemappableRegion(oldSpan, lineDelta, isExceptionRegion)));
}
// If the method has been up-to-date and it is not updated now then either the active statement span has not changed,
// or the entire method containing it moved. In neither case do we need to start tracking non-remapable region
// for the active statement since movement of whole method bodies (if any) is handled only on PDB level without
// triggering any remapping on the IL level.
}
else if (oldSpan.Span != newSpan.Span)
{
// The method is not up-to-date hence we maintain non-remapable span map for it that needs to be updated.
changedNonRemappableSpans[(methodId, oldSpan)] = newSpan;
}
}
AddNonRemappableRegion(oldActiveStatement.FileSpan, newActiveStatement.FileSpan, isExceptionRegion: false);
// The spans of the exception regions are known (non-default) for active statements in changed documents
// as we ensured earlier that all changed documents are in-sync.
for (var j = 0; j < oldActiveStatementExceptionRegions.Spans.Length; j++)
{
AddNonRemappableRegion(oldActiveStatementExceptionRegions.Spans[j], newActiveStatementExceptionRegions[j], isExceptionRegion: true);
}
}
}
activeStatementsInUpdatedMethods = activeStatementsInUpdatedMethodsBuilder.ToImmutableAndFree();
// Gather all active method instances contained in this project/module that are not up-to-date:
using var _2 = PooledHashSet<ManagedModuleMethodId>.GetInstance(out var unremappedActiveMethods);
foreach (var (instruction, baseActiveStatement) in oldActiveStatementMap.InstructionMap)
{
if (moduleId == instruction.Method.Module && !baseActiveStatement.IsMethodUpToDate)
{
unremappedActiveMethods.Add(instruction.Method.Method);
}
}
if (unremappedActiveMethods.Count > 0)
{
foreach (var (methodInstance, regionsInMethod) in previousNonRemappableRegions)
{
if (methodInstance.Module != moduleId)
{
continue;
}
// Skip non-remappable regions that belong to method instances that are from a different module
// or no longer active (all active statements in these method instances have been remapped to newer versions).
if (!unremappedActiveMethods.Contains(methodInstance.Method))
{
continue;
}
foreach (var region in regionsInMethod)
{
// We have calculated changes against a base snapshot (last break state):
var baseSpan = region.Span.AddLineDelta(region.LineDelta);
NonRemappableRegion newRegion;
if (changedNonRemappableSpans.TryGetValue((methodInstance.Method, baseSpan), out var newSpan))
{
// all spans must be of the same size:
Debug.Assert(newSpan.Span.End.Line - newSpan.Span.Start.Line == baseSpan.Span.End.Line - baseSpan.Span.Start.Line);
Debug.Assert(region.Span.Span.End.Line - region.Span.Span.Start.Line == baseSpan.Span.End.Line - baseSpan.Span.Start.Line);
Debug.Assert(newSpan.Path == region.Span.Path);
newRegion = region.WithLineDelta(region.Span.Span.GetLineDelta(newSpan: newSpan.Span));
}
else
{
newRegion = region;
}
nonRemappableRegionsBuilder.Add((methodInstance.Method, newRegion));
}
}
}
nonRemappableRegions = nonRemappableRegionsBuilder.ToImmutableAndFree();
// Note: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1319289
//
// The update should include the file name, otherwise it is not possible for the debugger to find
// the right IL span of the exception handler in case when multiple handlers in the same method
// have the same mapped span but different mapped file name:
//
// try { active statement }
// #line 20 "bar"
// catch (IOException) { }
// #line 20 "baz"
// catch (Exception) { }
//
// The range span in exception region updates is the new span. Deltas are inverse.
// old = new + delta
// new = old – delta
exceptionRegionUpdates = nonRemappableRegions.SelectAsArray(
r => r.Region.IsExceptionRegion,
r => new ManagedExceptionRegionUpdate(
r.Method,
-r.Region.LineDelta,
r.Region.Span.AddLineDelta(r.Region.LineDelta).Span.ToSourceSpan()));
}
}
}
| 1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Compilers/VisualBasic/Test/Semantic/Binding/Binder_Expressions_Tests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
' This class tests binding of various expressions; i.e., the code in Binder_Expressions.vb
'
' Tests should be added here for every construct that can be bound
' correctly, with a test that compiles, verifies, and runs code for that construct.
' Tests should also be added here for every diagnostic that can be generated.
Public Class Binder_Expressions_Tests
Inherits BasicTestBase
' Test that BC30157 is generated for a member access off With when there is no containing With.
<Fact>
Public Sub MemberAccessNoContainingWith()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="MemberAccessNoContainingWith">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x as Integer
x = .goo
End Sub
End Module
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC30157: Leading '.' or '!' can only appear inside a 'With' statement.
x = .goo
~~~~
</expected>)
End Sub
' Test field access off a local variable of structure type.
<Fact>
Public Sub FieldAccessInLocalStruct()
CompileAndVerify(
<compilation name="FieldAccessInLocalStruct">
<file name="a.vb">
Imports System
Module M1
Structure S1
Public Field1 As Integer
End Structure
Sub Main()
Dim x as S1
x.Field1 = 123
Console.WriteLine(x.Field1)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="123")
End Sub
<WorkItem(679765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/679765")>
<ConditionalFact(GetType(NoIOperationValidation))>
Public Sub Bug679765()
CompileAndVerify(
<compilation>
<file name="a.vb">
<%= SemanticResourceUtil.T_68086 %>
</file>
</compilation>, references:={MsvbRef})
End Sub
<WorkItem(707924, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/707924")>
<Fact()>
Public Sub Bug707924a()
Dim source = SemanticResourceUtil.T_1247520
Dim result = VisualBasicSyntaxTree.ParseText(source).ToString()
Assert.Equal(source, result)
End Sub
' Test access to a local variable and assignment of them..
<Fact>
Public Sub LocalVariable1()
CompileAndVerify(
<compilation name="LocalVariable1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x as Integer
Dim y as Long
x = 143
y = x
Console.WriteLine(y)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="143")
End Sub
' Test access to a local variable, parameter, type parameter, namespace with arity.
<Fact>
Public Sub LocalVariableWrongArity()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LocalVariable1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x, y as Integer
x = 143
y = x(Of Integer)
x = System.Collections(Of Decimal)
End Sub
Sub goo(y as string)
dim z as string
z = y(of Boolean)
End Sub
End Module
Class Q(Of T, U)
Sub a()
dim x as integer = U(Of T)
End Sub
End Class
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC32045: 'x' has no type parameters and so cannot have type arguments.
y = x(Of Integer)
~~~~~~~~~~~~
BC32045: 'System.Collections' has no type parameters and so cannot have type arguments.
x = System.Collections(Of Decimal)
~~~~~~~~~~~~
BC32045: 'y As String' has no type parameters and so cannot have type arguments.
z = y(of Boolean)
~~~~~~~~~~~~
BC32045: 'U' has no type parameters and so cannot have type arguments.
dim x as integer = U(Of T)
~~~~~~
</expected>)
End Sub
' Test access to a local variable and assignment of them..
<Fact>
Public Sub ArrayAssignment1()
CompileAndVerify(
<compilation name="ArrayAssignment1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
dim z(10) as string
dim i as integer
i = 2
z(i) = "hello"
Console.WriteLine(z(i))
End Sub
End Module
</file>
</compilation>,
expectedOutput:="hello")
End Sub
' Test access to a local variable and assignment of them..
<Fact>
Public Sub ArrayAssignmentError1()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ArrayAssignmentError1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
dim z(10) as string
z(1,1) = "world"
z() = "world"
End Sub
End Module
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC30106: Number of indices exceeds the number of dimensions of the indexed array.
z(1,1) = "world"
~~~~~
BC30105: Number of indices is less than the number of dimensions of the indexed array.
z() = "world"
~~
</expected>)
End Sub
' Test array upper bound is correct
<WorkItem(4225, "DevDiv_Projects/Roslyn")>
<Fact>
Public Sub CheckArrayUpperBound()
Dim compilation = CompileAndVerify(
<compilation name="ArrayAssignmentError1">
<file name="a.vb">
Imports System
Module M
Sub Main()
dim a as integer() = New Integer(1) {}
Console.WriteLine(a.GetLength(0))
Console.WriteLine(New Integer(-1) {}.GetLength(0))
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
2
0
]]>)
End Sub
' Test access to a local variable and assignment of them..
<Fact()>
Public Sub ArrayAssignmentError2()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ArrayAssignmentErrors2">
<file name="a.vb">
Option strict on
Imports System
Module M1
Sub Main()
dim z(10) as string
dim i as uinteger
' Should report an implicit conversion error, uinteger can't be converted to integer
z(i) = "world"
End Sub
End Module
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC30512: Option Strict On disallows implicit conversions from 'UInteger' to 'Integer'.
z(i) = "world"
~
</expected>)
End Sub
' Test access to a parameter (both simple and byref)
<Fact>
Public Sub Parameter1()
CompileAndVerify(
<compilation name="Parameter1">
<file name="a.vb">
Imports System
Module M1
Sub Goo(xParam as Integer, ByRef yParam As Long)
Console.WriteLine("xParam = {0}", xParam)
Console.WriteLine("yParam = {0}", yParam)
xParam = 17
yParam = 189
Console.WriteLine("xParam = {0}", xParam)
Console.WriteLine("yParam = {0}", yParam)
End Sub
Sub Main()
Dim x as Integer
Dim y as Long
x = 143
y = 16442
Console.WriteLine("x = {0}", x)
Console.WriteLine("y = {0}", y)
Goo(x,y)
Console.WriteLine("x = {0}", x)
Console.WriteLine("y = {0}", y)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
x = 143
y = 16442
xParam = 143
yParam = 16442
xParam = 17
yParam = 189
x = 143
y = 189
]]>)
End Sub
' Test object creation expression
<Fact>
Public Sub SimpleObjectCreation1()
CompileAndVerify(
<compilation name="SimpleObjectCreation">
<file name="a.vb">
Imports System
Class C1
Public Sub New()
End Sub
Sub Goo()
Console.WriteLine("Called C1.Goo")
End Sub
End Class
Module M1
Sub Main()
dim c as C1
c = new C1()
c.Goo()
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Called C1.Goo")
End Sub
' Test object creation expression
<Fact>
Public Sub MeReference()
CompileAndVerify(
<compilation name="MeReference">
<file name="a.vb">
Imports System
Class C1
private _i as integer
Public Sub New(i as integer)
Me._i = i
Console.WriteLine(Me._i)
End Sub
End Class
Module M1
Sub Main()
dim c as C1
c = new C1(1)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="1")
End Sub
' Test access to simple identifier that isn't found anywhere.
<Fact>
Public Sub SimpleNameNotFound()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="SimpleNameNotFound">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x as Integer
x = goo
End Sub
End Module
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC30451: 'goo' is not declared. It may be inaccessible due to its protection level.
x = goo
~~~
</expected>)
End Sub
<WorkItem(538871, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538871")>
<Fact>
Public Sub QualifiedNameBeforeDotNotFound()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="QualifiedNameBeforeDotNotFound">
<file name="a.vb">
Imports System
Module MainModule
Class A
End Class
Sub Main()
Rdim123.Rdim456()
A.B.Rdim456()
End Sub
End Module
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC30451: 'Rdim123' is not declared. It may be inaccessible due to its protection level.
Rdim123.Rdim456()
~~~~~~~
BC30456: 'B' is not a member of 'MainModule.A'.
A.B.Rdim456()
~~~
</expected>)
End Sub
' Test access to qualified identifier not found, in various scopes
<Fact>
Public Sub QualifiedNameNotFound()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="QualifiedNameNotFound">
<file name="a.vb">
Imports System
Namespace N
End Namespace
Class C
Public y as Integer
End Class
Module M1
Sub Main()
Dim x as Integer
Dim cInstance as C
cInstance = Nothing
x = N.goo
x = C.goo
x = cInstance.goo
x = M1.goo
End Sub
End Module
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC30456: 'goo' is not a member of 'N'.
x = N.goo
~~~~~
BC30456: 'goo' is not a member of 'C'.
x = C.goo
~~~~~
BC30456: 'goo' is not a member of 'C'.
x = cInstance.goo
~~~~~~~~~~~~~
BC30456: 'goo' is not a member of 'M1'.
x = M1.goo
~~~~~~
</expected>)
End Sub
' Test access qualified identifier off of type parameter
<Fact>
Public Sub TypeParamCantQualify()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation name="TypeParamCantQualify">
<file name="a.vb">
Imports System
Class C(Of T)
Public Sub f()
dim x as Integer
x = T.goo
End Sub
End Class
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC32098: Type parameters cannot be used as qualifiers.
x = T.goo
~~~~~
</expected>)
End Sub
' Test access to simple identifier that can be found, but has an error.
<Fact>
Public Sub BadSimpleName()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadSimpleName">
<file name="a.vb">
Imports System
Class Goo(Of T)
Shared Public x As Integer
End Class
Module Module1
Sub Main()
Dim y As Integer
y = Goo.x
End Sub
End Module
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC32042: Too few type arguments to 'Goo(Of T)'.
y = Goo.x
~~~
</expected>)
End Sub
' Test access to qualified identifier that can be found, but has an error.
<Fact>
Public Sub BadQualifiedName()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadQualifiedName">
<file name="a.vb">
Imports System
Namespace N
Class Goo(Of T)
Shared Public x As Integer
End Class
End Namespace
Class C
Class Goo(Of T)
Shared Public x As Integer
End Class
End Class
Module Module1
Sub Main()
Dim y As Integer
Dim cInstance as C
cInstance = Nothing
y = N.Goo.x
y = C.Goo.x
y = cInstance.Goo.x
y = cInstance.Goo(Of Integer).x
End Sub
End Module
</file>
</compilation>)
' Note that we produce different (but I think better) error messages than Dev10.
AssertTheseDiagnostics(compilation,
<expected>
BC32042: Too few type arguments to 'Goo(Of T)'.
y = N.Goo.x
~~~~~
BC32042: Too few type arguments to 'C.Goo(Of T)'.
y = C.Goo.x
~~~~~
BC32042: Too few type arguments to 'C.Goo(Of T)'.
y = cInstance.Goo.x
~~~~~~~~~~~~~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
y = cInstance.Goo(Of Integer).x
~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
' Test access to instance member in various ways to get various errors.
<Fact>
Public Sub AccessInstanceFromStatic()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation name="AccessInstanceFromStatic">
<file name="a.vb">
Class K
Public Sub y()
End Sub
Public x As Integer
Class Z
Public Sub yy()
End Sub
Public xx As Integer
Public Shared Sub goo()
Dim v As Integer
Dim zInstance As Z
zInstance = Nothing
y()
v = x
yy()
v = xx
zInstance.yy()
v = zInstance.xx
Z.yy()
v = Z.xx
End Sub
End Class
End Class
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC30469: Reference to a non-shared member requires an object reference.
y()
~
BC30469: Reference to a non-shared member requires an object reference.
v = x
~
BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.
yy()
~~
BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.
v = xx
~~
BC30469: Reference to a non-shared member requires an object reference.
Z.yy()
~~~~
BC30469: Reference to a non-shared member requires an object reference.
v = Z.xx
~~~~
</expected>)
End Sub
' Test access to static member in various ways to get various errors.
<Fact>
Public Sub AccessStaticViaInstance()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation name="AccessStaticViaInstance">
<file name="a.vb">
Class K
Public Shared Sub y()
End Sub
Public Shared x As Integer
Class Z
Public Shared Sub yy()
End Sub
Public Shared xx As Integer
Public Sub goo()
Dim v As Integer
Dim zInstance As Z
zInstance = Nothing
y()
v = x
yy()
v = xx
zInstance.yy()
v = zInstance.xx
Z.yy()
v = Z.xx
End Sub
End Class
End Class
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
zInstance.yy()
~~~~~~~~~~~~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
v = zInstance.xx
~~~~~~~~~~~~
</expected>)
End Sub
<Fact(), WorkItem(531587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531587")>
Public Sub CircularSharedMemberAccessThroughInstance()
Dim source =
<compilation name="FieldsConst">
<file name="a.vb">
Option Strict On
Option Infer On
Class C1
Const i As Integer = j.MaxValue
Const j As Integer = i.MaxValue
Public shared Sub Main(args() as string)
End sub
End Class
</file>
</compilation>
Dim c1 = CreateCompilationWithMscorlib40AndVBRuntime(source)
c1.AssertTheseDiagnostics(
<expected>
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
Const i As Integer = j.MaxValue
~~~~~~~~~~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
Const j As Integer = i.MaxValue
~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub ConstantFields1()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="VBConstantFields1">
<file name="a.vb">
Module Module1
Sub Main()
System.Console.WriteLine("Int64Field: {0}", ConstFields.Int64Field)
System.Console.WriteLine("DateTimeField: {0}", ConstFields.DateTimeField.ToString("M/d/yyyy h:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture))
System.Console.WriteLine("DoubleField: {0}", ConstFields.DoubleField)
System.Console.WriteLine("SingleField: {0}", ConstFields.SingleField)
System.Console.WriteLine("StringField: {0}", ConstFields.StringField)
System.Console.WriteLine("StringNullField: [{0}]", ConstFields.StringNullField)
System.Console.WriteLine("ObjectNullField: [{0}]", ConstFields.ObjectNullField)
System.Console.WriteLine("ByteValue: {0}", ByteEnum.ByteValue)
System.Console.WriteLine("SByteValue: {0}", SByteEnum.SByteValue)
System.Console.WriteLine("UInt16Value: {0}", UInt16Enum.UInt16Value)
System.Console.WriteLine("Int16Value: {0}", Int16Enum.Int16Value)
System.Console.WriteLine("UInt32Value: {0}", UInt32Enum.UInt32Value)
System.Console.WriteLine("Int32Value: {0}", Int32Enum.Int32Value)
System.Console.WriteLine("UInt64Value: {0}", UInt64Enum.UInt64Value)
System.Console.WriteLine("Int64Value: {0}", Int64Enum.Int64Value)
End Sub
End Module
</file>
</compilation>, TestOptions.ReleaseExe)
compilation = compilation.AddReferences(TestReferences.SymbolsTests.Fields.ConstantFields)
CompileAndVerify(compilation, <![CDATA[
Int64Field: 634315546432909307
DateTimeField: 1/25/2011 12:17:23 PM
DoubleField: -10
SingleField: 9
StringField: 11
StringNullField: []
ObjectNullField: []
ByteValue: ByteValue
SByteValue: SByteValue
UInt16Value: UInt16Value
Int16Value: Int16Value
UInt32Value: UInt32Value
Int32Value: Int32Value
UInt64Value: UInt64Value
Int64Value: Int64Value
]]>)
End Sub
' Test member of built in type.
<Fact>
Public Sub MemberOfBuiltInType()
CompileAndVerify(
<compilation name="MeReference">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x as Integer
x = Integer.Parse("143")
Console.WriteLine(x)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="143")
End Sub
' Test member of nullable type.
<Fact>
Public Sub MemberOfNullableType()
CompileAndVerify(
<compilation name="MeReference">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x as boolean
x = Integer?.Equals("goo", "g" + "oo")
Console.WriteLine(x)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="True")
End Sub
<Fact>
Public Sub Bug4272()
Dim compilationDef =
<compilation name="Bug4272">
<file name="a.vb">
Option Strict On
Module M
Function Goo(x As Integer) As Integer()
Goo(1) = 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.
Goo(1) = Nothing
~~~~~~
BC42105: Function 'Goo' 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>)
compilationDef =
<compilation name="Bug4272">
<file name="a.vb">
Module Module1
Sub Main()
Goo()
End Sub
Private val As TestClass
Function Goo() As TestClass
If val Is Nothing Then
System.Console.WriteLine("Nothing")
val = New TestClass()
val.Field = 2
Else
System.Console.WriteLine("val")
Return val
End If
Dim x As TestClass = New TestClass()
x.Field = 1
Goo = x
System.Console.WriteLine(Goo.Field)
System.Console.WriteLine(Goo.GetField())
System.Console.WriteLine(Goo().Field)
System.Console.WriteLine(Goo(3))
End Function
Function Goo(x As Integer) As Integer
Return x
End Function
End Module
Class TestClass
Public Field As Integer
Public Function GetField() As Integer
Return Field
End Function
End Class
</file>
</compilation>
compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
Nothing
1
1
val
2
3
]]>)
compilationDef =
<compilation name="Bug4272">
<file name="a.vb">
Option Strict On
Module M
Function Goo(x As Integer) As Integer()
Dim y As Integer() = Goo(1)
End Function
End Module
Module M1
Function Goo(x As Object) As Integer
Return Goo(1)
End Function
Function Goo(x As Integer) As Integer
Return 1
End Function
End Module
</file>
</compilation>
compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertTheseDiagnostics(compilation,
<expected>
BC42105: Function 'Goo' 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
<WorkItem(538802, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538802")>
<Fact>
Public Sub MethodAccessibilityChecking()
CompileAndVerify(
<compilation name="MeReference">
<file name="a.vb">
Imports System
Public Class C1
Private Shared Sub goo(x as String)
Console.Writeline("Private")
End Sub
Public Shared Sub goo(x as Object)
Console.Writeline("Public")
End Sub
End class
Module Program
Sub Main()
'Below call should bind to public overload that takes object
c1.goo("")
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Public")
End Sub
<Fact>
Public Sub Bug4249()
Dim compilationDef =
<compilation name="Bug4249">
<file name="a.vb">
Module Program
Sub Main()
Main().ToString
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertTheseDiagnostics(compilation,
<expected>
BC30491: Expression does not produce a value.
Main().ToString
~~~~~~
</expected>)
End Sub
<Fact>
Public Sub Bug4250()
Dim compilationDef =
<compilation name="Bug4250">
<file name="a.vb">
Module Program
Sub Main()
System.Console.WriteLine(Goo.ToString)
System.Console.WriteLine(Bar(Of Integer).ToString)
End Sub
Function Goo() as Integer
return 123
End Function
Function Bar(Of T)() as Integer
return 231
End Function
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
123
231
]]>)
compilationDef =
<compilation name="Bug4250">
<file name="a.vb">
Module Program
Sub Main()
System.Console.WriteLine(Goo.ToString)
End Sub
Function Goo(x as Integer) as Integer
return 321
End Function
End Module
</file>
</compilation>
compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected>
BC30455: Argument not specified for parameter 'x' of 'Public Function Goo(x As Integer) As Integer'.
System.Console.WriteLine(Goo.ToString)
~~~
</expected>)
End Sub
<Fact>
Public Sub Bug4277()
Dim compilationDef =
<compilation name="Bug4277">
<file name="a.vb">
Option Strict Off
Module M
Sub Main()
End Sub
End Module
Class B
Sub T()
End Sub
End Class
Class A(Of T)
Inherits B
Sub Goo()
T()
End Sub
End Class
Class C
Sub S()
End Sub
Class A(Of S)
Sub Goo()
S()
End Sub
End Class
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertTheseDiagnostics(compilation,
<expected>
BC30108: 'S' is a type and cannot be used as an expression.
S()
~
</expected>)
End Sub
<WorkItem(538438, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538438")>
<Fact>
Public Sub TestRangeExpressionAllowableLowerBounds()
Dim compilationDef =
<compilation name="TestRangeExpressionAllowableLowerBounds">
<file name="a.vb">
Friend Module ExpArrBounds0LowerBound
Sub ExpArrBounds0LowerBound()
Dim x0(0 To 2&)
Dim x1(0& To 2&)
Dim x2(0ul To 2&)
Dim x3(0l To 2&)
Dim x4(0us To 2&)
Dim x5(0s To 2&)
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertNoErrors(compilation)
End Sub
<WorkItem(537219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537219")>
<Fact>
Public Sub BC32059ERR_OnlyNullLowerBound()
Dim compilationDef =
<compilation name="BC32059ERR_OnlyNullLowerBound">
<file name="a.b">
Friend Module ExpArrBounds003Errmod
Sub ExpArrBounds003Err()
' COMPILEERROR: BC32059, "0!"
Dim x1(0! To 5) as Single
Dim x2(0.0 to 5) as Single
Dim x3(0d to 5) as Single
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertTheseDiagnostics(compilation,
<errors>
BC32059: Array lower bounds can be only '0'.
Dim x1(0! To 5) as Single
~~
BC32059: Array lower bounds can be only '0'.
Dim x2(0.0 to 5) as Single
~~~
BC32059: Array lower bounds can be only '0'.
Dim x3(0d to 5) as Single
~~
</errors>)
End Sub
<Fact>
Public Sub LocalShadowsGenericMethod()
Dim compilationDef =
<compilation name="LocalShadowsGenericMethod">
<file name="a.vb">
Class Y
Sub f()
Dim goo As Integer
goo(Of Integer)()
End Sub
Public Sub goo(Of T)()
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertTheseDiagnostics(compilation,
<errors>
BC42024: Unused local variable: 'goo'.
Dim goo As Integer
~~~
BC32045: 'goo' has no type parameters and so cannot have type arguments.
goo(Of Integer)()
~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub AccessingMemberOffOfNothing()
Dim compilationDef =
<compilation name="AccessingMemberOffOfNothing">
<file name="a.vb">
Class Y
Sub f()
Dim x As System.Type = Nothing.GetType()
End Sub
End Class
</file>
</compilation>
CompileAndVerify(compilationDef).
VerifyIL("Y.f",
<![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldnull
IL_0001: callvirt "Function Object.GetType() As System.Type"
IL_0006: pop
IL_0007: ret
}
]]>)
End Sub
<Fact>
Public Sub ColorColor()
Dim compilationDef =
<compilation name="AccessingMemberOffOfNothing">
<file name="a.vb">
Option Strict On
Imports System
Module Module1
Sub main()
Dim o As New cls1
End Sub
End Module
Class cls1
Public Const s As Integer = 123
Shared o As Integer = cls1.s
Public ReadOnly Property cls1 As cls1
Get
Console.WriteLine("hi")
Return Me
End Get
End Property
Sub New()
' cls1 is a type here, no warnings needed, but colorizer should show it as a type
cls1.s.ToString()
End Sub
Shared Sub moo()
Console.WriteLine(cls1.s)
End Sub
End Class
Class Color
Public Shared Red As Color = Nothing
Public Shared Property Green As Color
Public Class TypeInColor
Public shared c as Color
End Class
Public Class GenericTypeInColor
Public shared c as Color
End Class
Public Class GenericTypeInColor(of T)
Public shared c as Color
End Class
End Class
Class Test
ReadOnly Property Color() As Color
Get
Return Color.Red
End Get
End Property
Shared Function DefaultColor() As Color
Dim c as Color = Color.Green ' Binds to the instance property!
c= Color.TypeInColor.c
c= Color.GenericTypeInColor.c
c= Color.GenericTypeInColor(of UShort).c
return c
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub FalseColorColor()
Dim compilationDef =
<compilation name="AccessingMemberOffOfNothing">
<file name="a.vb">
Imports Q = B
Class B
Public Shared Zip As Integer
Public ReadOnly Property Q As B
Get
Return Nothing
End Get
End Property
Shared Sub f()
Dim x As Integer = Q.Zip 'this should be an error
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertTheseDiagnostics(compilation,
<errors>
BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.
Dim x As Integer = Q.Zip 'this should be an error
~
</errors>)
End Sub
<Fact>
Public Sub ColorColor1()
Dim compilationDef =
<compilation name="AccessingMemberOffOfNothing">
<file name="a.vb">
Option Strict On
Imports System
Module Module1
Sub main()
Test.DefaultColor()
End Sub
End Module
Class Color
Public Shared Red As Color = Nothing
Public Shared Function G(Of T)(x As T) As Color
Return Red
End Function
End Class
Class Test
ReadOnly Property color(x as integer) As Color
Get
Console.WriteLine("evaluated")
Return Color.Red
End Get
End Property
Shared Function DefaultColor() As Color
dim a = color.G(1) ' error, missing parameter to color property
Return color.G(of Long)(1) ' error, missing parameter to color property
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertTheseDiagnostics(compilation, <expected>
BC30455: Argument not specified for parameter 'x' of 'Public ReadOnly Property color(x As Integer) As Color'.
dim a = color.G(1) ' error, missing parameter to color property
~~~~~
BC30455: Argument not specified for parameter 'x' of 'Public ReadOnly Property color(x As Integer) As Color'.
Return color.G(of Long)(1) ' error, missing parameter to color property
~~~~~
</expected>)
End Sub
<Fact>
Public Sub ColorColor2()
Dim compilationDef =
<compilation name="AccessingMemberOffOfNothing">
<file name="a.vb">
Option Strict On
Imports System
Module Module1
Sub main()
Test.DefaultColor()
End Sub
End Module
Class Color
Public Shared Red As Color = Nothing
Public Shared Function G(Of T)(x As T) As Color
Return Red
End Function
End Class
Class Test
ReadOnly Property color() As Color
Get
Console.WriteLine("evaluated")
Return Color.Red
End Get
End Property
Shared Function DefaultColor() As Color
Return color.G(1) ' Binds to the type
Return color.G(of Long)(1) ' Binds to the type
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub ColorColorOverloaded()
Dim compilationDef =
<compilation name="ColorColorOverloaded">
<file name="a.vb">
Option Strict On
Imports System
Module Module1
Public Sub Main()
Dim o as Test = New Test
o.DefaultColor()
End Sub
Class Color
Public Shared Red As Color = New Color
Public Shared Function G(x As Integer) As Color
Return Red
End Function
Public Function G() As Color
Return Red
End Function
End Class
Class Test
ReadOnly Property Color() As Color
Get
Console.Write("evaluated")
Return Color.Red
End Get
End Property
Function DefaultColor() As Color
Dim c1 As Color
c1 = Color.G(1) ' Binds to the type
c1 = Color.G() ' Binds to the member
Return c1
End Function
End Class
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertNoErrors(compilation)
CompileAndVerify(compilationDef, expectedOutput:="evaluated").
VerifyIL("Module1.Test.DefaultColor",
<![CDATA[
{
// Code size 19 (0x13)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: call "Function Module1.Color.G(Integer) As Module1.Color"
IL_0006: pop
IL_0007: ldarg.0
IL_0008: call "Function Module1.Test.get_Color() As Module1.Color"
IL_000d: callvirt "Function Module1.Color.G() As Module1.Color"
IL_0012: ret
}
]]>)
End Sub
<Fact()>
Public Sub ColorColorOverloadedOptional()
Dim compilationDef =
<compilation name="ColorColorOverloaded">
<file name="a.vb">
Option Strict On
Imports System
Module Module1
Public Sub Main()
Dim o as Test = New Test
o.DefaultColor()
End Sub
Class Color
Public Shared Red As Color = New Color
Public Shared Function G(x As Integer) As Color
Return Red
End Function
Public Function G() As Color
Return Red
End Function
End Class
Class Test
ReadOnly Property Color(optional x as integer = 1) As Color
Get
Console.Write("evaluated")
Return Color.Red
End Get
End Property
Function DefaultColor() As Color
Dim c1 As Color
c1 = Color.G(1) ' Binds to the type
c1 = Color.G() ' Binds to the member
Return c1
End Function
End Class
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertNoErrors(compilation)
CompileAndVerify(compilationDef, expectedOutput:="evaluated").
VerifyIL("Module1.Test.DefaultColor",
<![CDATA[
{
// Code size 20 (0x14)
.maxstack 2
IL_0000: ldc.i4.1
IL_0001: call "Function Module1.Color.G(Integer) As Module1.Color"
IL_0006: pop
IL_0007: ldarg.0
IL_0008: ldc.i4.1
IL_0009: call "Function Module1.Test.get_Color(Integer) As Module1.Color"
IL_000e: callvirt "Function Module1.Color.G() As Module1.Color"
IL_0013: ret
}
]]>)
End Sub
<Fact>
Public Sub ColorColorOverloadedErr()
Dim compilationDef =
<compilation name="ColorColorOverloaded">
<file name="a.vb">
Option Strict On
Imports System
Module Module1
Public Sub Main()
Dim o as Test = New Test
o.DefaultColor()
End Sub
Class Color
Public Shared Red As Color = New Color
Public Shared Function G(x As Integer) As Color
Return Red
End Function
Public Function G() As Color
Return Red
End Function
End Class
Class Test
ReadOnly Property Color(x as integer) As Color
Get
Console.Write("evaluated")
Return Color.Red
End Get
End Property
Function DefaultColor() As Color
Dim c1 As Color
c1 = Color.G(1) ' missing parameter x
c1 = Color.G() ' missing parameter x
Return c1
End Function
End Class
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertTheseDiagnostics(compilation,
<errors>
BC30455: Argument not specified for parameter 'x' of 'Public ReadOnly Property Color(x As Integer) As Module1.Color'.
c1 = Color.G(1) ' missing parameter x
~~~~~
BC30455: Argument not specified for parameter 'x' of 'Public ReadOnly Property Color(x As Integer) As Module1.Color'.
c1 = Color.G() ' missing parameter x
~~~~~
</errors>)
End Sub
<Fact>
Public Sub ColorColorOverloadedErr2()
Dim compilationDef =
<compilation name="ColorColorOverloaded">
<file name="a.vb">
Option Strict On
Imports System
Module Module1
Public Sub Main()
Dim o as Test = New Test
o.DefaultColor()
End Sub
Class Color
Public Shared Red As Color = New Color
Public Shared Function G(x As Integer) As Color
Return Red
End Function
Public Function G() As Color
Return Red
End Function
End Class
Class Test
ReadOnly Property Color As Color
Get
Console.Write("evaluated")
Return Color.Red
End Get
End Property
Function DefaultColor() As Color
Dim c1 As Color
c1 = Color.G(1) ' Binds to the type
c1 = Color.G() ' Binds to the member
Return c1
End Function
End Class
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertNoDiagnostics(compilation)
End Sub
<Fact>
Public Sub ColorColorOverloadedAddressOf()
Dim compilationDef =
<compilation name="ColorColorOverloadedAddressOf">
<file name="a.vb">
Option Strict On
Imports System
Module Module1
Public Sub Main()
Dim o as Test = New Test
o.DefaultColor()
End Sub
Class Color
Public Shared Red As Color = New Color
Public Shared Function G(x As Integer) As Color
Return Red
End Function
Public Function G() As Color
Return Red
End Function
End Class
Class Test
ReadOnly Property Color() As Color
Get
Console.Write("evaluated")
Return Color.Red
End Get
End Property
Function DefaultColor() As Color
Dim c1 As Color
Dim d1 As Func(Of Integer, Color) = AddressOf Color.G ' Binds to the type
c1 = d1(1)
Dim d2 As Func(Of Color) = AddressOf Color.G ' Binds to the member
c1 = d2()
Return c1
End Function
End Class
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertNoErrors(compilation)
CompileAndVerify(compilationDef, expectedOutput:="evaluated").
VerifyIL("Module1.Test.DefaultColor",
<![CDATA[
{
// Code size 42 (0x2a)
.maxstack 2
IL_0000: ldnull
IL_0001: ldftn "Function Module1.Color.G(Integer) As Module1.Color"
IL_0007: newobj "Sub System.Func(Of Integer, Module1.Color)..ctor(Object, System.IntPtr)"
IL_000c: ldc.i4.1
IL_000d: callvirt "Function System.Func(Of Integer, Module1.Color).Invoke(Integer) As Module1.Color"
IL_0012: pop
IL_0013: ldarg.0
IL_0014: call "Function Module1.Test.get_Color() As Module1.Color"
IL_0019: ldftn "Function Module1.Color.G() As Module1.Color"
IL_001f: newobj "Sub System.Func(Of Module1.Color)..ctor(Object, System.IntPtr)"
IL_0024: callvirt "Function System.Func(Of Module1.Color).Invoke() As Module1.Color"
IL_0029: ret
}
]]>)
End Sub
<Fact>
Public Sub ColorColorOverloadedAddressOfRelaxed()
Dim compilationDef =
<compilation name="ColorColorOverloadedAddressOfRelaxed">
<file name="a.vb">
Option Strict On
Imports System
Module Module1
Public Sub Main()
Dim o As Test = New Test
o.DefaultColor()
End Sub
Class Color
Public Shared Red As Color = New Color
Public Shared Function G(x As Integer) As Color
Return Red
End Function
Public Function G() As Color
Return Red
End Function
End Class
Class Test
ReadOnly Property Color() As Color
Get
Console.Write("evaluated")
Return Color.Red
End Get
End Property
Sub DefaultColor()
Dim d1 As Action(Of Integer) = AddressOf Color.G ' Binds to the type
d1(1)
Dim d2 As Action = AddressOf Color.G ' Binds to the member
d2()
End Sub
End Class
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertNoErrors(compilation)
CompileAndVerify(compilationDef, expectedOutput:="evaluated").
VerifyIL("Module1.Test.DefaultColor",
<![CDATA[
{
// Code size 76 (0x4c)
.maxstack 3
IL_0000: ldsfld "Module1.Test._Closure$__.$IR3-2 As System.Action(Of Integer)"
IL_0005: brfalse.s IL_000e
IL_0007: ldsfld "Module1.Test._Closure$__.$IR3-2 As System.Action(Of Integer)"
IL_000c: br.s IL_0024
IL_000e: ldsfld "Module1.Test._Closure$__.$I As Module1.Test._Closure$__"
IL_0013: ldftn "Sub Module1.Test._Closure$__._Lambda$__R3-2(Integer)"
IL_0019: newobj "Sub System.Action(Of Integer)..ctor(Object, System.IntPtr)"
IL_001e: dup
IL_001f: stsfld "Module1.Test._Closure$__.$IR3-2 As System.Action(Of Integer)"
IL_0024: ldc.i4.1
IL_0025: callvirt "Sub System.Action(Of Integer).Invoke(Integer)"
IL_002a: newobj "Sub Module1.Test._Closure$__R3-0..ctor()"
IL_002f: dup
IL_0030: ldarg.0
IL_0031: call "Function Module1.Test.get_Color() As Module1.Color"
IL_0036: stfld "Module1.Test._Closure$__R3-0.$VB$NonLocal_2 As Module1.Color"
IL_003b: ldftn "Sub Module1.Test._Closure$__R3-0._Lambda$__R3()"
IL_0041: newobj "Sub System.Action..ctor(Object, System.IntPtr)"
IL_0046: callvirt "Sub System.Action.Invoke()"
IL_004b: ret
}
]]>)
End Sub
<Fact>
Public Sub ColorColorExtension()
Dim compilationDef =
<compilation name="ColorColorOverloaded">
<file name="a.vb">
Option Strict On
Imports System
Imports System.Runtime.CompilerServices
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
Module Module1
Public Sub Main()
Dim o As Test = New Test
o.DefaultColor()
End Sub
Structure S1
End Structure
<Extension()>
Public Function G(this As Color) As Color
Return Color.Red
End Function
Class Color
Public Shared Red As Color = New Color
Public Shared Function G(x As Integer) As Color
Return Red
End Function
End Class
Class Test
Shared ReadOnly Property Color() As Color
Get
Console.Write("evaluated")
Return Color.Red
End Get
End Property
Function DefaultColor() As Color
Dim c1 As Color
c1 = Color.G(1) ' Binds to the type
c1 = Color.G() ' Binds to the member + extension
Return c1
End Function
End Class
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertNoErrors(compilation)
CompileAndVerify(compilationDef, expectedOutput:="evaluated").
VerifyIL("Module1.Test.DefaultColor",
<![CDATA[
{
// Code size 18 (0x12)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: call "Function Module1.Color.G(Integer) As Module1.Color"
IL_0006: pop
IL_0007: call "Function Module1.Test.get_Color() As Module1.Color"
IL_000c: call "Function Module1.G(Module1.Color) As Module1.Color"
IL_0011: ret
}
]]>)
End Sub
<Fact()>
Public Sub ColorColorAlias()
Dim compilationDef =
<compilation name="ColorColorAlias">
<file name="a.vb">
Option Strict On
Imports System
Imports Bar = NS1.Bar
Module Module1
Public Sub Main()
Dim o as Goo = New Goo()
Console.WriteLine(o.M())
End Sub
End Module
Namespace NS1
Public Class Bar
Public Shared c as Integer = 48
End Class
End Namespace
Class Goo
ReadOnly Property Bar As Bar
Get
Console.WriteLine("property called")
Return Nothing
End Get
End Property
Function M() As Integer
return Bar.c
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertNoDiagnostics(compilation)
CompileAndVerify(compilationDef, expectedOutput:="48").
VerifyIL("Goo.M",
<![CDATA[
{
// Code size 6 (0x6)
.maxstack 1
IL_0000: ldsfld "NS1.Bar.c As Integer"
IL_0005: ret
}
]]>)
End Sub
<Fact()>
Public Sub ColorColorWrongAlias()
Dim compilationDef =
<compilation name="ColorColorWrongAlias">
<file name="a.vb">
Option Strict On
Imports System
Imports Bar2 = NS1.Bar
Module Module1
Public Sub Main()
Dim o As Goo = New Goo()
Console.WriteLine(Goo.M())
End Sub
End Module
Namespace NS1
Public Class Bar
Public Shared c As Integer = 48
End Class
End Namespace
Class Goo
ReadOnly Property Bar2 As Bar2
Get
Console.WriteLine("property called")
Return Nothing
End Get
End Property
Public Shared Function M() As Integer
Return Bar2.c
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertTheseDiagnostics(compilation, <expected>
BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.
Return Bar2.c
~~~~
</expected>)
End Sub
<Fact>
Public Sub ModulesWhereTypesShouldBe()
Dim text =
<compilation name="ModulesWhereTypesShouldBe">
<file name="a.vb">
Module M
Sub GG()
Dim y As System.Collections.Generic.List(Of M)
Dim z As Object = Nothing
Dim q = TryCast(z, M)
Dim p = CType(z, M)
Dim r As M()
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(text)
AssertTheseDiagnostics(compilation,
<errors>
BC42024: Unused local variable: 'y'.
Dim y As System.Collections.Generic.List(Of M)
~
BC30371: Module 'M' cannot be used as a type.
Dim y As System.Collections.Generic.List(Of M)
~
BC30371: Module 'M' cannot be used as a type.
Dim q = TryCast(z, M)
~
BC30371: Module 'M' cannot be used as a type.
Dim p = CType(z, M)
~
BC42024: Unused local variable: 'r'.
Dim r As M()
~
BC30371: Module 'M' cannot be used as a type.
Dim r As M()
~
</errors>)
End Sub
<Fact>
Public Sub GetTypeOnNSAlias()
Dim text =
<compilation name="GetTypeOnNSAlias">
<file name="a.vb">
Imports NS=System.Collections
Module M
Sub S()
Dim x = GetType(NS)
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(text)
AssertTheseDiagnostics(compilation,
<errors>
BC30182: Type expected.
Dim x = GetType(NS)
~~
</errors>)
End Sub
<WorkItem(542383, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542383")>
<Fact>
Public Sub GetTypeOnModuleName()
Dim text =
<compilation name="GetTypeForModuleName">
<file name="a.vb">
Imports System
Namespace AttrUseCust011
Friend Module AttrUseCust011mod
Sub GG()
Dim x = GetType(AttrUseCust011mod)
End Sub
End Module
End Namespace
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(text)
AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub GetTypeOnAlias()
Dim text =
<compilation name="GetTypeOnAlias">
<file name="a.vb">
Imports System
Imports Con = System.Console
Module M
Sub GG()
Dim x = GetType(Con)
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(text)
AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub Bug9300_1()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="NotYetImplementedInRoslyn">
<file name="a.vb">
Imports System.Runtime.CompilerServices
Imports System.Collections
Imports System
Module M
Sub Main()
Goo(Sub(x) x.New())
End Sub
Sub Goo(x As Action(Of Object()))
System.Console.WriteLine("Action(Of Object())")
x(New Object() {})
End Sub
<Extension()>
Sub [New](Of T)(ByVal x As T)
System.Console.WriteLine("[New]")
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>)
Dim expectedErrors1 = <errors>
BC30251: Type 'Object()' has no constructors.
Goo(Sub(x) x.New())
~~~~~
</errors>
AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub Bug9300_2()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="NotYetImplementedInRoslyn">
<file name="a.vb">
Imports System.Runtime.CompilerServices
Imports System.Collections
Imports System
Module M
Sub Main()
Goo(Sub(x) x.New())
End Sub
Class TC1
End Class
Sub Goo(x As Action(Of TC1))
End Sub
<Extension()>
Sub [New](Of T)(ByVal x As T)
System.Console.WriteLine("[New]")
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>)
Dim expectedErrors1 = <errors>
BC30282: Constructor call is valid only as the first statement in an instance constructor.
Goo(Sub(x) x.New())
~~~~~
</errors>
AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub Bug9300_3()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="NotYetImplementedInRoslyn">
<file name="a.vb">
Imports System.Runtime.CompilerServices
Imports System.Collections
Imports System
Module M
Sub Main()
Goo(Sub(x) x.New())
End Sub
Sub Goo(x As Action(Of IEnumerable))
System.Console.WriteLine("Action(Of IEnumerable)")
x(New Object() {})
End Sub
Sub Goo(x As Action(Of Object()))
System.Console.WriteLine("Action(Of Object())")
x(New Object() {})
End Sub
<Extension()>
Sub [New](Of T)(ByVal x As T)
System.Console.WriteLine("[New]")
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>, TestOptions.ReleaseExe)
CompileAndVerify(compilation1, <![CDATA[
Action(Of IEnumerable)
[New]
]]>)
End Sub
<Fact>
Public Sub IllegalTypeExpressionsFromParserShouldNotBlowUpBinding()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="IllegalTypeExpressionsFromParserShouldNotBlowUpBinding">
<file name="a.vb">
Class Outer(Of T)
Public Shared Sub Print()
System.Console.WriteLine(GetType(Outer(Of ).Inner(Of T))) ' BC32099: Comma or ')' expected.
System.Console.WriteLine(GetType(Outer(Of ).Inner(Of Integer))) ' BC32099: Comma or ')' expected.
System.Console.WriteLine(GetType(Outer(Of T).Inner(Of ))) ' BC30182: Type expected.
System.Console.WriteLine(GetType(Outer(Of Integer).Inner(Of ))) ' BC30182: Type expected.
End Sub
Class Inner(Of U)
End Class
End Class
</file>
</compilation>)
AssertTheseDiagnostics(compilation1, <expected>
BC32099: Comma or ')' expected.
System.Console.WriteLine(GetType(Outer(Of ).Inner(Of T))) ' BC32099: Comma or ')' expected.
~
BC32099: Comma or ')' expected.
System.Console.WriteLine(GetType(Outer(Of ).Inner(Of Integer))) ' BC32099: Comma or ')' expected.
~~~~~~~
BC30182: Type expected.
System.Console.WriteLine(GetType(Outer(Of T).Inner(Of ))) ' BC30182: Type expected.
~
BC30182: Type expected.
System.Console.WriteLine(GetType(Outer(Of Integer).Inner(Of ))) ' BC30182: Type expected.
~
</expected>)
End Sub
<Fact()>
Public Sub Bug10335_1()
Dim source1_with =
<compilation name="Unavailable">
<file name="a.vb">
Public Interface IUnavailable
ReadOnly Default Property Item(p as Integer) as Integer
End Interface
</file>
</compilation>
Dim c1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source1_with)
Dim baseBuffer = CompileAndVerify(c1).EmittedAssemblyData
Dim source2 =
<compilation>
<file name="a.vb">
Public Class Class1
Implements IUnavailable
Public Default ReadOnly Property Item(p as Integer) as Integer implements IUnavailable.Item
Get
Return p
End Get
End Property
End Class
Public Class Class2
Public ReadOnly Property AProperty() as Class1
Get
Return new Class1()
End Get
End Property
End Class
</file>
</compilation>
Dim c2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source2, {MetadataReference.CreateFromImage(baseBuffer)})
Dim derivedBuffer = CompileAndVerify(c2).EmittedAssemblyData
Dim source3 =
<compilation>
<file name="a.vb">
Module M1
Sub Main()
Dim x as new Class2()
dim y = x.AProperty(23)
Dim z as Object = x.AProperty()
x.AProperty()
End Sub
End Module
</file>
</compilation>
Dim source1_without =
<compilation name="Unavailable">
<file name="a.vb">
Class Unused
End Class
</file>
</compilation>
Dim c1_without = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source1_without)
Dim image = CompileAndVerify(c1_without).EmittedAssemblyData
Dim c3 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source3, {MetadataReference.CreateFromImage(derivedBuffer), MetadataReference.CreateFromImage(image)})
AssertTheseDiagnostics(c3, <expected>
BC30545: Property access must assign to the property or use its value.
x.AProperty()
~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub ColorColorOverriddenProperty()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug12687">
<file name="a.vb">
Class TypeSubstitution
Shared Function Create() As Integer
Return 1
End Function
End Class
Class InstanceTypeSymbol
ReadOnly Property TypeSubstitution(a as Integer) As TypeSubstitution
Get
Return Nothing
End Get
End Property
End Class
Class Frame
Inherits InstanceTypeSymbol
Overloads ReadOnly Property TypeSubstitution As TypeSubstitution
Get
Return Nothing
End Get
End Property
Function Goo() As Integer
Return TypeSubstitution.Create()
End Function
End Class
</file>
</compilation>)
AssertNoDiagnostics(compilation)
End Sub
<Fact>
Public Sub ColorColorPropertyWithParam()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug12687">
<file name="a.vb">
Class TypeSubstitution
Shared Function Create() As Integer
Return 1
End Function
End Class
Class InstanceTypeSymbol
Overridable ReadOnly Property TypeSubstitution(a as Integer) As TypeSubstitution
Get
Return Nothing
End Get
End Property
End Class
Class Frame
Inherits InstanceTypeSymbol
Function Goo() As Integer
Return TypeSubstitution.Create()
End Function
End Class
</file>
</compilation>)
AssertTheseDiagnostics(compilation, <expected>
BC30455: Argument not specified for parameter 'a' of 'Public Overridable ReadOnly Property TypeSubstitution(a As Integer) As TypeSubstitution'.
Return TypeSubstitution.Create()
~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub ColorColorPropertyWithOverloading()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug12687">
<file name="a.vb">
Class TypeSubstitution
Shared Function Create() As Integer
Return 1
End Function
End Class
Class InstanceTypeSymbol
ReadOnly Property TypeSubstitution(a as Integer) As String
Get
Return Nothing
End Get
End Property
ReadOnly Property TypeSubstitution As TypeSubstitution
Get
Return Nothing
End Get
End Property
End Class
Class Frame
Inherits InstanceTypeSymbol
Function Goo() As Integer
Return TypeSubstitution.Create()
End Function
End Class
</file>
</compilation>)
AssertNoDiagnostics(compilation)
End Sub
' Tests IsValidAssignmentTarget for PropertyAccess
' and IsLValueFieldAccess for FieldAccess.
<Fact>
Public Sub IsValidAssignmentTarget()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Structure S
Public F As Object
Public Property P As Object
Sub M()
Me.F = Nothing ' IsLValue = False, IsMeReference = True
MyClass.F = Nothing ' IsLValue = False, IsMyClassReference = True
Me.P = Nothing ' IsLValue = False, IsMeReference = True
MyClass.P = Nothing ' IsLValue = False, IsMyClassReference = True
End Sub
End Structure
Class C
Private F1 As S
Private ReadOnly F2 As S
Sub M()
F1.F = Nothing ' IsLValue = True
F2.F = Nothing ' IsLValue = False
F1.P = Nothing ' IsLValue = True
F2.P = Nothing ' IsLValue = False
End Sub
End Class
</file>
</compilation>)
compilation.AssertTheseDiagnostics(<expected>
BC30064: 'ReadOnly' variable cannot be the target of an assignment.
F2.F = Nothing ' IsLValue = False
~~~~
BC30068: Expression is a value and therefore cannot be the target of an assignment.
F2.P = Nothing ' IsLValue = False
~~~~
</expected>)
End Sub
<Fact>
Public Sub Bug12900()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="MemberAccessNoContainingWith">
<file name="a.vb">
Imports System
Module Program
Sub Main(args As String())
Const local _? As Integer
End Sub
End Module
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC30438: Constants must have a value.
Const local _? As Integer
~~~~~
BC30203: Identifier expected.
Const local _? As Integer
~
</expected>)
End Sub
<Fact>
Public Sub Bug13080()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Module Program
Sub Main(args As String())
Const '
End Sub
End Module
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC30203: Identifier expected.
Const '
~
BC30438: Constants must have a value.
Const '
~
</expected>)
End Sub
<WorkItem(546469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546469")>
<Fact>
Public Sub GetTypeAllowsArrayOfModules()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Imports VoidAlias = System.Void
Namespace Bar
Module Test
Sub Main()
' Array of types
Dim x As Type = GetType(Test()) 'ok
x = GetType(Void()) ' error
' types direct
x = GetType(Test) ' ok
x = GetType(Void) ' ok
' nullable
x = GetType(Test?) ' error
x = GetType(Void?) ' error
x = GetType(List(Of Test)) ' error
x = GetType(List(Of Void)) ' error
x = GetType(Bar.Test) ' ok
x = GetType(System.Void) ' ok
x = GetType(VoidAlias) ' ok
End Sub
End Module
End Namespace
</file>
</compilation>)
AssertTheseDiagnostics(compilation, <expected>
BC31428: Arrays of type 'System.Void' are not allowed in this expression.
x = GetType(Void()) ' error
~~~~~~
BC30371: Module 'Test' cannot be used as a type.
x = GetType(Test?) ' error
~~~~
BC33101: Type 'Test' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
x = GetType(Test?) ' error
~~~~
BC31422: 'System.Void' can only be used in a GetType expression.
x = GetType(Void?) ' error
~~~~
BC30371: Module 'Test' cannot be used as a type.
x = GetType(List(Of Test)) ' error
~~~~
BC31422: 'System.Void' can only be used in a GetType expression.
x = GetType(List(Of Void)) ' error
~~~~
</expected>)
End Sub
<WorkItem(530438, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530438")>
<WorkItem(546469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546469")>
<Fact()>
Public Sub GetTypeAllowsModuleAlias()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports ModuleAlias = Bar.Test
Imports System
Namespace Bar
Module Test
Sub Main()
Dim x As Type = GetType(ModuleAlias) ' ok
End Sub
End Module
End Namespace
</file>
</compilation>)
AssertTheseDiagnostics(compilation, <expected></expected>)
End Sub
<Fact()>
Public Sub RangeVariableColorColor()
Dim source = _
<compilation>
<file name="a.vb">
Imports System.Linq
Class Program
Shared Sub Main()
Dim q = From X As X In New X() { New X() }
Where X.S()
Where X.I()
Select 42
System.Console.Write(q.Single())
End Sub
End Class
Class X
Public Shared Function S() As Boolean
Return True
End Function
Public Shared Function I() As Boolean
Return True
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, options:=TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation, <expected></expected>)
CompileAndVerify(compilation, expectedOutput:="42")
End Sub
<WorkItem(1108036, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108036")>
<Fact()>
Public Sub Bug1108036()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Class Color
Public Shared Sub Cat()
End Sub
End Class
Class Program
Shared Sub Main()
Color.Cat()
End Sub
ReadOnly Property Color(Optional x As Integer = 0) As Color
Get
Return Nothing
End Get
End Property
ReadOnly Property Color(Optional x As String = "") As Integer
Get
Return 0
End Get
End Property
End Class
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC30521: Overload resolution failed because no accessible 'Color' is most specific for these arguments:
'Public ReadOnly Property Color([x As Integer = 0]) As Color': Not most specific.
'Public ReadOnly Property Color([x As String = ""]) As Integer': Not most specific.
Color.Cat()
~~~~~
</expected>)
End Sub
<WorkItem(1108036, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108036")>
<Fact()>
Public Sub Bug1108036_2()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Class Color
Public Shared Sub Cat()
End Sub
End Class
Class Program
Shared Sub Main()
Color.Cat()
End Sub
ReadOnly Property Color(Optional x As Integer = 0) As Integer
Get
Return 0
End Get
End Property
ReadOnly Property Color(Optional x As String = "") As Color
Get
Return Nothing
End Get
End Property
End Class
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC30521: Overload resolution failed because no accessible 'Color' is most specific for these arguments:
'Public ReadOnly Property Color([x As Integer = 0]) As Integer': Not most specific.
'Public ReadOnly Property Color([x As String = ""]) As Color': Not most specific.
Color.Cat()
~~~~~
</expected>)
End Sub
<WorkItem(969006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/969006")>
<Fact()>
Public Sub Bug969006_1()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Enum E
A
End Enum
Class C
Sub M()
Const e As E = E.A
Dim z = e
End Sub
End Class
</file>
</compilation>)
Dim tree = compilation.SyntaxTrees(0)
Dim model1 = compilation.GetSemanticModel(tree)
Dim node1 = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Single()
Assert.Equal("E.A", node1.ToString())
Assert.Equal("E", node1.Expression.ToString())
Dim symbolInfo = model1.GetSymbolInfo(node1.Expression)
Assert.Equal("E", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.NamedType, symbolInfo.Symbol.Kind)
Dim model2 = compilation.GetSemanticModel(tree)
Dim node2 = tree.GetRoot().DescendantNodes.OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "e").Single()
Assert.Equal("= e", node2.Parent.ToString())
symbolInfo = model2.GetSymbolInfo(node2)
Assert.Equal("e As E", symbolInfo.Symbol.ToTestDisplayString())
symbolInfo = model2.GetSymbolInfo(node1.Expression)
Assert.Equal("E", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.NamedType, symbolInfo.Symbol.Kind)
AssertTheseDiagnostics(compilation)
End Sub
<WorkItem(969006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/969006")>
<Fact()>
Public Sub Bug969006_2()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Enum E
A
End Enum
Class C
Sub M()
Dim e As E = E.A
Dim z = e
End Sub
End Class
</file>
</compilation>)
Dim tree = compilation.SyntaxTrees(0)
Dim model1 = compilation.GetSemanticModel(tree)
Dim node1 = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Single()
Assert.Equal("E.A", node1.ToString())
Assert.Equal("E", node1.Expression.ToString())
Dim symbolInfo = model1.GetSymbolInfo(node1.Expression)
Assert.Equal("E", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.NamedType, symbolInfo.Symbol.Kind)
Dim model2 = compilation.GetSemanticModel(tree)
Dim node2 = tree.GetRoot().DescendantNodes.OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "e").Single()
Assert.Equal("= e", node2.Parent.ToString())
symbolInfo = model2.GetSymbolInfo(node2)
Assert.Equal("e As E", symbolInfo.Symbol.ToTestDisplayString())
symbolInfo = model2.GetSymbolInfo(node1.Expression)
Assert.Equal("E", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.NamedType, symbolInfo.Symbol.Kind)
AssertTheseDiagnostics(compilation)
End Sub
<WorkItem(969006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/969006")>
<Fact()>
Public Sub Bug969006_3()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Enum E
A
End Enum
Class C
Sub M()
Const e = E.A
Dim z = e
End Sub
End Class
</file>
</compilation>)
Dim tree = compilation.SyntaxTrees(0)
Dim model1 = compilation.GetSemanticModel(tree)
Dim node1 = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Single()
Assert.Equal("E.A", node1.ToString())
Assert.Equal("E", node1.Expression.ToString())
Dim symbolInfo = model1.GetSymbolInfo(node1.Expression)
Assert.Equal("e As System.Object", symbolInfo.Symbol.ToTestDisplayString())
Dim model2 = compilation.GetSemanticModel(tree)
Dim node2 = tree.GetRoot().DescendantNodes.OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "e").Single()
Assert.Equal("= e", node2.Parent.ToString())
symbolInfo = model2.GetSymbolInfo(node2)
Assert.Equal("e As System.Object", symbolInfo.Symbol.ToTestDisplayString())
symbolInfo = model2.GetSymbolInfo(node1.Expression)
Assert.Equal("e As System.Object", symbolInfo.Symbol.ToTestDisplayString())
AssertTheseDiagnostics(compilation, <expected>
BC30500: Constant 'e' cannot depend on its own value.
Const e = E.A
~
BC42104: Variable 'e' is used before it has been assigned a value. A null reference exception could result at runtime.
Const e = E.A
~
</expected>)
End Sub
<WorkItem(969006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/969006")>
<Fact()>
Public Sub Bug969006_4()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Enum E
A
End Enum
Class C
Sub M()
Dim e = E.A
Dim z = e
End Sub
End Class
</file>
</compilation>)
Dim tree = compilation.SyntaxTrees(0)
Dim model1 = compilation.GetSemanticModel(tree)
Dim node1 = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Single()
Assert.Equal("E.A", node1.ToString())
Assert.Equal("E", node1.Expression.ToString())
Dim symbolInfo = model1.GetSymbolInfo(node1.Expression)
Assert.Equal("e As ?", symbolInfo.Symbol.ToTestDisplayString())
Dim model2 = compilation.GetSemanticModel(tree)
Dim node2 = tree.GetRoot().DescendantNodes.OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "e").Single()
Assert.Equal("= e", node2.Parent.ToString())
symbolInfo = model2.GetSymbolInfo(node2)
Assert.Equal("e As ?", symbolInfo.Symbol.ToTestDisplayString())
symbolInfo = model2.GetSymbolInfo(node1.Expression)
Assert.Equal("e As ?", symbolInfo.Symbol.ToTestDisplayString())
AssertTheseDiagnostics(compilation, <expected>
BC30980: Type of 'e' cannot be inferred from an expression containing 'e'.
Dim e = E.A
~
BC42104: Variable 'e' is used before it has been assigned a value. A null reference exception could result at runtime.
Dim e = E.A
~
</expected>)
End Sub
<WorkItem(1108007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108007")>
<Fact()>
Public Sub Bug1108007_1()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Class Color
Public Shared Sub M(x As Integer)
System.Console.WriteLine(x)
End Sub
Public Sub M(x As String)
End Sub
End Class
Class Program
Dim Color As Color
Shared Sub Main()
Dim x As Object = 42
Color.M(x)
End Sub
End Class
</file>
</compilation>, TestOptions.ReleaseExe)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim node = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Select(Function(e) e.Expression).Where(Function(e) e.ToString() = "Color").Single()
Dim symbol = model.GetSymbolInfo(node).Symbol
Assert.NotNull(symbol)
Assert.Equal("Color", symbol.Name)
Assert.Equal(SymbolKind.NamedType, symbol.Kind)
AssertTheseDiagnostics(compilation, <expected></expected>)
CompileAndVerify(compilation, expectedOutput:="42")
End Sub
<WorkItem(1108007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108007")>
<Fact>
Public Sub Bug1108007_2()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Class Color
Public Shared Sub M(x As Integer)
Console.WriteLine(x)
End Sub
Public Sub M(x As String)
End Sub
End Class
Class Program
Dim Color As Color
Shared Sub Main()
Try
Dim x As Object = ""
Color.M(x)
Catch e As Exception
Console.WriteLine(e.GetType())
End Try
End Sub
End Class
</file>
</compilation>, TestOptions.ReleaseExe)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim node = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Select(Function(e) e.Expression).Where(Function(e) e.ToString() = "Color").Single()
Dim symbol = model.GetSymbolInfo(node).Symbol
Assert.NotNull(symbol)
Assert.Equal("Color", symbol.Name)
Assert.Equal(SymbolKind.NamedType, symbol.Kind)
AssertTheseDiagnostics(compilation, <expected></expected>)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[System.NullReferenceException]]>)
End Sub
<WorkItem(1108007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108007")>
<Fact()>
Public Sub Bug1108007_3()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Class MyAttribute
Inherits System.Attribute
Public ReadOnly I As Integer
Public Sub New(i As Integer)
Me.I = i
End Sub
End Class
Class Color
Public Const I As Integer = 42
End Class
Class Program
Dim Color As Color
<MyAttribute(Color.I)>
Shared Sub Main()
End Sub
End Class
]]>
</file>
</compilation>, TestOptions.ReleaseExe)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim node = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Select(Function(e) e.Expression).Where(Function(e) e.ToString() = "Color").Single()
Dim symbol = model.GetSymbolInfo(node).Symbol
Assert.NotNull(symbol)
Assert.Equal("Color", symbol.Name)
Assert.Equal(SymbolKind.NamedType, symbol.Kind)
AssertTheseDiagnostics(compilation, <expected></expected>)
End Sub
<WorkItem(1108007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108007")>
<Fact()>
Public Sub Bug1108007_4()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Class Color
Public Shared Sub M(x As Integer)
Console.WriteLine(x)
End Sub
Public Sub M(x As String)
End Sub
Class Program
Dim Color As Color
Sub M()
Try
Dim x As Object = ""
Color.M(x)
Catch e As Exception
Console.WriteLine(e.GetType())
End Try
End Sub
Shared Sub Main()
Dim p = New Program()
p.M()
End Sub
End Class
End Class
</file>
</compilation>, TestOptions.ReleaseExe)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim node = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Select(Function(e) e.Expression).Where(Function(e) e.ToString() = "Color").Single()
Dim symbol = model.GetSymbolInfo(node).Symbol
Assert.NotNull(symbol)
Assert.Equal("Color", symbol.Name)
Assert.Equal(SymbolKind.Field, symbol.Kind)
AssertTheseDiagnostics(compilation, <expected></expected>)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[System.NullReferenceException]]>)
End Sub
<WorkItem(1108007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108007")>
<Fact()>
Public Sub Bug1108007_5()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Class Color
Public Shared Function M(x As Integer) As Integer
Return x
End Function
Public Function M(x As String) As Integer
Return x.Length
End Function
End Class
Class A
Public Sub New(x As Integer)
Console.WriteLine(x)
End Sub
End Class
Class B
Inherits A
Dim Color As Color
Public Sub New()
MyBase.New(Color.M(DirectCast(42, Object)))
End Sub
Shared Sub Main()
Dim b = New B()
End Sub
End Class
</file>
</compilation>, TestOptions.ReleaseExe)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim node = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Select(Function(e) e.Expression).Where(Function(e) e.ToString() = "Color").Single()
Dim symbol = model.GetSymbolInfo(node).Symbol
Assert.NotNull(symbol)
Assert.Equal("Color", symbol.Name)
Assert.Equal(SymbolKind.NamedType, symbol.Kind)
AssertTheseDiagnostics(compilation, <expected></expected>)
CompileAndVerify(compilation, expectedOutput:="42")
End Sub
<WorkItem(1108007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108007")>
<Fact()>
Public Sub Bug1108007_6()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Class Color
Public Shared Function M(x As Integer) As Integer
Console.WriteLine(x)
Return x
End Function
Public Function M(x As String) As Integer
Return x.Length
End Function
End Class
Class Program
Dim Color As Color
Dim I As Integer = Color.M(DirectCast(42, Object))
Shared Sub Main()
Try
Dim p = New Program()
Catch e As Exception
Console.WriteLine(e.GetType())
End Try
End Sub
End Class
</file>
</compilation>, TestOptions.ReleaseExe)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim node = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Select(Function(e) e.Expression).Where(Function(e) e.ToString() = "Color").Single()
Dim symbol = model.GetSymbolInfo(node).Symbol
Assert.NotNull(symbol)
Assert.Equal("Color", symbol.Name)
Assert.Equal(SymbolKind.Field, symbol.Kind)
AssertTheseDiagnostics(compilation, <expected></expected>)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[System.NullReferenceException]]>)
End Sub
<WorkItem(1108007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108007")>
<Fact()>
Public Sub Bug1108007_7()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Class Color
Public Shared Function M(x As Integer) As Integer
Console.WriteLine(x)
Return x
End Function
Public Function M(x As String) As Integer
Return x.Length
End Function
End Class
Class Program
Dim Color As Color
Shared Dim I As Integer = Color.M(DirectCast(42, Object))
Shared Sub Main()
Dim i = Program.I
End Sub
End Class
</file>
</compilation>, TestOptions.ReleaseExe)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim node = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Select(Function(e) e.Expression).Where(Function(e) e.ToString() = "Color").Single()
Dim symbol = model.GetSymbolInfo(node).Symbol
Assert.NotNull(symbol)
Assert.Equal("Color", symbol.Name)
Assert.Equal(SymbolKind.NamedType, symbol.Kind)
AssertTheseDiagnostics(compilation, <expected></expected>)
CompileAndVerify(compilation, expectedOutput:="42")
End Sub
<WorkItem(1108007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108007")>
<Fact>
Public Sub Bug1108007_8()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Class Color
Public Shared Sub M(x As Integer)
Console.WriteLine(x)
End Sub
Public Sub M(x As String)
End Sub
End Class
Class Outer
Dim Color As Color
Class Program
Sub M()
Try
Dim x As Object = ""
Color.M(x)
Catch e As Exception
Console.WriteLine(e.GetType())
End Try
End Sub
Shared Sub Main()
Dim p = New Program()
p.M()
End Sub
End Class
End Class
</file>
</compilation>, TestOptions.ReleaseExe)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim node = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Select(Function(e) e.Expression).Where(Function(e) e.ToString() = "Color").Single()
Dim symbol = model.GetSymbolInfo(node).Symbol
Assert.NotNull(symbol)
Assert.Equal("Color", symbol.Name)
Assert.Equal(SymbolKind.NamedType, symbol.Kind)
AssertTheseDiagnostics(compilation, <expected></expected>)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[System.NullReferenceException]]>)
End Sub
<WorkItem(1108007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108007")>
<Fact()>
Public Sub Bug1108007_9()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Class Color
Public Shared Sub M(x As Integer)
System.Console.WriteLine(x)
End Sub
Public Sub M(x As String)
End Sub
End Class
Class Outer
Shared Dim Color As Color = New Color()
Class Program
Sub M()
Dim x As Object = 42
Color.M(x)
End Sub
Shared Sub Main()
Dim p = New Program()
p.M()
End Sub
End Class
End Class </file>
</compilation>, TestOptions.ReleaseExe)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim node = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Select(Function(e) e.Expression).Where(Function(e) e.ToString() = "Color").Single()
Dim symbol = model.GetSymbolInfo(node).Symbol
Assert.NotNull(symbol)
Assert.Equal("Color", symbol.Name)
Assert.Equal(SymbolKind.Field, symbol.Kind)
AssertTheseDiagnostics(compilation, <expected></expected>)
CompileAndVerify(compilation, expectedOutput:="42")
End Sub
<WorkItem(1114969, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1114969")>
<Fact()>
Public Sub Bug1114969()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Class Color
Public Function M() As Integer
Return 42
End Function
End Class
Class Base
Protected Dim Color As Color = New Color()
End Class
Class Derived
Inherits Base
Sub M()
System.Console.WriteLine(Color.M())
End Sub
Shared Sub Main()
Dim d = New Derived()
d.M()
End Sub
End Class </file>
</compilation>, TestOptions.ReleaseExe)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim node = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Select(Function(e) e.Expression).Where(Function(e) e.ToString() = "Color").Single()
Dim symbol = model.GetSymbolInfo(node).Symbol
Assert.NotNull(symbol)
Assert.Equal("Color", symbol.Name)
Assert.Equal(SymbolKind.Field, symbol.Kind)
AssertTheseDiagnostics(compilation, <expected></expected>)
CompileAndVerify(compilation, expectedOutput:="42")
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
' This class tests binding of various expressions; i.e., the code in Binder_Expressions.vb
'
' Tests should be added here for every construct that can be bound
' correctly, with a test that compiles, verifies, and runs code for that construct.
' Tests should also be added here for every diagnostic that can be generated.
Public Class Binder_Expressions_Tests
Inherits BasicTestBase
' Test that BC30157 is generated for a member access off With when there is no containing With.
<Fact>
Public Sub MemberAccessNoContainingWith()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="MemberAccessNoContainingWith">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x as Integer
x = .goo
End Sub
End Module
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC30157: Leading '.' or '!' can only appear inside a 'With' statement.
x = .goo
~~~~
</expected>)
End Sub
' Test field access off a local variable of structure type.
<Fact>
Public Sub FieldAccessInLocalStruct()
CompileAndVerify(
<compilation name="FieldAccessInLocalStruct">
<file name="a.vb">
Imports System
Module M1
Structure S1
Public Field1 As Integer
End Structure
Sub Main()
Dim x as S1
x.Field1 = 123
Console.WriteLine(x.Field1)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="123")
End Sub
<WorkItem(679765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/679765")>
<ConditionalFact(GetType(NoIOperationValidation))>
Public Sub Bug679765()
CompileAndVerify(
<compilation>
<file name="a.vb">
<%= SemanticResourceUtil.T_68086 %>
</file>
</compilation>, references:={MsvbRef})
End Sub
<WorkItem(707924, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/707924")>
<Fact()>
Public Sub Bug707924a()
Dim source = SemanticResourceUtil.T_1247520
Dim result = VisualBasicSyntaxTree.ParseText(source).ToString()
Assert.Equal(source, result)
End Sub
' Test access to a local variable and assignment of them..
<Fact>
Public Sub LocalVariable1()
CompileAndVerify(
<compilation name="LocalVariable1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x as Integer
Dim y as Long
x = 143
y = x
Console.WriteLine(y)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="143")
End Sub
' Test access to a local variable, parameter, type parameter, namespace with arity.
<Fact>
Public Sub LocalVariableWrongArity()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="LocalVariable1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x, y as Integer
x = 143
y = x(Of Integer)
x = System.Collections(Of Decimal)
End Sub
Sub goo(y as string)
dim z as string
z = y(of Boolean)
End Sub
End Module
Class Q(Of T, U)
Sub a()
dim x as integer = U(Of T)
End Sub
End Class
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC32045: 'x' has no type parameters and so cannot have type arguments.
y = x(Of Integer)
~~~~~~~~~~~~
BC32045: 'System.Collections' has no type parameters and so cannot have type arguments.
x = System.Collections(Of Decimal)
~~~~~~~~~~~~
BC32045: 'y As String' has no type parameters and so cannot have type arguments.
z = y(of Boolean)
~~~~~~~~~~~~
BC32045: 'U' has no type parameters and so cannot have type arguments.
dim x as integer = U(Of T)
~~~~~~
</expected>)
End Sub
' Test access to a local variable and assignment of them..
<Fact>
Public Sub ArrayAssignment1()
CompileAndVerify(
<compilation name="ArrayAssignment1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
dim z(10) as string
dim i as integer
i = 2
z(i) = "hello"
Console.WriteLine(z(i))
End Sub
End Module
</file>
</compilation>,
expectedOutput:="hello")
End Sub
' Test access to a local variable and assignment of them..
<Fact>
Public Sub ArrayAssignmentError1()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ArrayAssignmentError1">
<file name="a.vb">
Imports System
Module M1
Sub Main()
dim z(10) as string
z(1,1) = "world"
z() = "world"
End Sub
End Module
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC30106: Number of indices exceeds the number of dimensions of the indexed array.
z(1,1) = "world"
~~~~~
BC30105: Number of indices is less than the number of dimensions of the indexed array.
z() = "world"
~~
</expected>)
End Sub
' Test array upper bound is correct
<WorkItem(4225, "DevDiv_Projects/Roslyn")>
<Fact>
Public Sub CheckArrayUpperBound()
Dim compilation = CompileAndVerify(
<compilation name="ArrayAssignmentError1">
<file name="a.vb">
Imports System
Module M
Sub Main()
dim a as integer() = New Integer(1) {}
Console.WriteLine(a.GetLength(0))
Console.WriteLine(New Integer(-1) {}.GetLength(0))
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
2
0
]]>)
End Sub
' Test access to a local variable and assignment of them..
<Fact()>
Public Sub ArrayAssignmentError2()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="ArrayAssignmentErrors2">
<file name="a.vb">
Option strict on
Imports System
Module M1
Sub Main()
dim z(10) as string
dim i as uinteger
' Should report an implicit conversion error, uinteger can't be converted to integer
z(i) = "world"
End Sub
End Module
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC30512: Option Strict On disallows implicit conversions from 'UInteger' to 'Integer'.
z(i) = "world"
~
</expected>)
End Sub
' Test access to a parameter (both simple and byref)
<Fact>
Public Sub Parameter1()
CompileAndVerify(
<compilation name="Parameter1">
<file name="a.vb">
Imports System
Module M1
Sub Goo(xParam as Integer, ByRef yParam As Long)
Console.WriteLine("xParam = {0}", xParam)
Console.WriteLine("yParam = {0}", yParam)
xParam = 17
yParam = 189
Console.WriteLine("xParam = {0}", xParam)
Console.WriteLine("yParam = {0}", yParam)
End Sub
Sub Main()
Dim x as Integer
Dim y as Long
x = 143
y = 16442
Console.WriteLine("x = {0}", x)
Console.WriteLine("y = {0}", y)
Goo(x,y)
Console.WriteLine("x = {0}", x)
Console.WriteLine("y = {0}", y)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
x = 143
y = 16442
xParam = 143
yParam = 16442
xParam = 17
yParam = 189
x = 143
y = 189
]]>)
End Sub
' Test object creation expression
<Fact>
Public Sub SimpleObjectCreation1()
CompileAndVerify(
<compilation name="SimpleObjectCreation">
<file name="a.vb">
Imports System
Class C1
Public Sub New()
End Sub
Sub Goo()
Console.WriteLine("Called C1.Goo")
End Sub
End Class
Module M1
Sub Main()
dim c as C1
c = new C1()
c.Goo()
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Called C1.Goo")
End Sub
' Test object creation expression
<Fact>
Public Sub MeReference()
CompileAndVerify(
<compilation name="MeReference">
<file name="a.vb">
Imports System
Class C1
private _i as integer
Public Sub New(i as integer)
Me._i = i
Console.WriteLine(Me._i)
End Sub
End Class
Module M1
Sub Main()
dim c as C1
c = new C1(1)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="1")
End Sub
' Test access to simple identifier that isn't found anywhere.
<Fact>
Public Sub SimpleNameNotFound()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="SimpleNameNotFound">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x as Integer
x = goo
End Sub
End Module
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC30451: 'goo' is not declared. It may be inaccessible due to its protection level.
x = goo
~~~
</expected>)
End Sub
<WorkItem(538871, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538871")>
<Fact>
Public Sub QualifiedNameBeforeDotNotFound()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="QualifiedNameBeforeDotNotFound">
<file name="a.vb">
Imports System
Module MainModule
Class A
End Class
Sub Main()
Rdim123.Rdim456()
A.B.Rdim456()
End Sub
End Module
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC30451: 'Rdim123' is not declared. It may be inaccessible due to its protection level.
Rdim123.Rdim456()
~~~~~~~
BC30456: 'B' is not a member of 'MainModule.A'.
A.B.Rdim456()
~~~
</expected>)
End Sub
' Test access to qualified identifier not found, in various scopes
<Fact>
Public Sub QualifiedNameNotFound()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="QualifiedNameNotFound">
<file name="a.vb">
Imports System
Namespace N
End Namespace
Class C
Public y as Integer
End Class
Module M1
Sub Main()
Dim x as Integer
Dim cInstance as C
cInstance = Nothing
x = N.goo
x = C.goo
x = cInstance.goo
x = M1.goo
End Sub
End Module
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC30456: 'goo' is not a member of 'N'.
x = N.goo
~~~~~
BC30456: 'goo' is not a member of 'C'.
x = C.goo
~~~~~
BC30456: 'goo' is not a member of 'C'.
x = cInstance.goo
~~~~~~~~~~~~~
BC30456: 'goo' is not a member of 'M1'.
x = M1.goo
~~~~~~
</expected>)
End Sub
' Test access qualified identifier off of type parameter
<Fact>
Public Sub TypeParamCantQualify()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation name="TypeParamCantQualify">
<file name="a.vb">
Imports System
Class C(Of T)
Public Sub f()
dim x as Integer
x = T.goo
End Sub
End Class
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC32098: Type parameters cannot be used as qualifiers.
x = T.goo
~~~~~
</expected>)
End Sub
' Test access to simple identifier that can be found, but has an error.
<Fact>
Public Sub BadSimpleName()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadSimpleName">
<file name="a.vb">
Imports System
Class Goo(Of T)
Shared Public x As Integer
End Class
Module Module1
Sub Main()
Dim y As Integer
y = Goo.x
End Sub
End Module
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC32042: Too few type arguments to 'Goo(Of T)'.
y = Goo.x
~~~
</expected>)
End Sub
' Test access to qualified identifier that can be found, but has an error.
<Fact>
Public Sub BadQualifiedName()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="BadQualifiedName">
<file name="a.vb">
Imports System
Namespace N
Class Goo(Of T)
Shared Public x As Integer
End Class
End Namespace
Class C
Class Goo(Of T)
Shared Public x As Integer
End Class
End Class
Module Module1
Sub Main()
Dim y As Integer
Dim cInstance as C
cInstance = Nothing
y = N.Goo.x
y = C.Goo.x
y = cInstance.Goo.x
y = cInstance.Goo(Of Integer).x
End Sub
End Module
</file>
</compilation>)
' Note that we produce different (but I think better) error messages than Dev10.
AssertTheseDiagnostics(compilation,
<expected>
BC32042: Too few type arguments to 'Goo(Of T)'.
y = N.Goo.x
~~~~~
BC32042: Too few type arguments to 'C.Goo(Of T)'.
y = C.Goo.x
~~~~~
BC32042: Too few type arguments to 'C.Goo(Of T)'.
y = cInstance.Goo.x
~~~~~~~~~~~~~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
y = cInstance.Goo(Of Integer).x
~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
' Test access to instance member in various ways to get various errors.
<Fact>
Public Sub AccessInstanceFromStatic()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation name="AccessInstanceFromStatic">
<file name="a.vb">
Class K
Public Sub y()
End Sub
Public x As Integer
Class Z
Public Sub yy()
End Sub
Public xx As Integer
Public Shared Sub goo()
Dim v As Integer
Dim zInstance As Z
zInstance = Nothing
y()
v = x
yy()
v = xx
zInstance.yy()
v = zInstance.xx
Z.yy()
v = Z.xx
End Sub
End Class
End Class
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC30469: Reference to a non-shared member requires an object reference.
y()
~
BC30469: Reference to a non-shared member requires an object reference.
v = x
~
BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.
yy()
~~
BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.
v = xx
~~
BC30469: Reference to a non-shared member requires an object reference.
Z.yy()
~~~~
BC30469: Reference to a non-shared member requires an object reference.
v = Z.xx
~~~~
</expected>)
End Sub
' Test access to static member in various ways to get various errors.
<Fact>
Public Sub AccessStaticViaInstance()
Dim compilation = CreateCompilationWithMscorlib40(
<compilation name="AccessStaticViaInstance">
<file name="a.vb">
Class K
Public Shared Sub y()
End Sub
Public Shared x As Integer
Class Z
Public Shared Sub yy()
End Sub
Public Shared xx As Integer
Public Sub goo()
Dim v As Integer
Dim zInstance As Z
zInstance = Nothing
y()
v = x
yy()
v = xx
zInstance.yy()
v = zInstance.xx
Z.yy()
v = Z.xx
End Sub
End Class
End Class
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
zInstance.yy()
~~~~~~~~~~~~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
v = zInstance.xx
~~~~~~~~~~~~
</expected>)
End Sub
<Fact(), WorkItem(531587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531587")>
Public Sub CircularSharedMemberAccessThroughInstance()
Dim source =
<compilation name="FieldsConst">
<file name="a.vb">
Option Strict On
Option Infer On
Class C1
Const i As Integer = j.MaxValue
Const j As Integer = i.MaxValue
Public shared Sub Main(args() as string)
End sub
End Class
</file>
</compilation>
Dim c1 = CreateCompilationWithMscorlib40AndVBRuntime(source)
c1.AssertTheseDiagnostics(
<expected>
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
Const i As Integer = j.MaxValue
~~~~~~~~~~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
Const j As Integer = i.MaxValue
~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub ConstantFields1()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="VBConstantFields1">
<file name="a.vb">
Module Module1
Sub Main()
System.Console.WriteLine("Int64Field: {0}", ConstFields.Int64Field)
System.Console.WriteLine("DateTimeField: {0}", ConstFields.DateTimeField.ToString("M/d/yyyy h:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture))
System.Console.WriteLine("DoubleField: {0}", ConstFields.DoubleField)
System.Console.WriteLine("SingleField: {0}", ConstFields.SingleField)
System.Console.WriteLine("StringField: {0}", ConstFields.StringField)
System.Console.WriteLine("StringNullField: [{0}]", ConstFields.StringNullField)
System.Console.WriteLine("ObjectNullField: [{0}]", ConstFields.ObjectNullField)
System.Console.WriteLine("ByteValue: {0}", ByteEnum.ByteValue)
System.Console.WriteLine("SByteValue: {0}", SByteEnum.SByteValue)
System.Console.WriteLine("UInt16Value: {0}", UInt16Enum.UInt16Value)
System.Console.WriteLine("Int16Value: {0}", Int16Enum.Int16Value)
System.Console.WriteLine("UInt32Value: {0}", UInt32Enum.UInt32Value)
System.Console.WriteLine("Int32Value: {0}", Int32Enum.Int32Value)
System.Console.WriteLine("UInt64Value: {0}", UInt64Enum.UInt64Value)
System.Console.WriteLine("Int64Value: {0}", Int64Enum.Int64Value)
End Sub
End Module
</file>
</compilation>, TestOptions.ReleaseExe)
compilation = compilation.AddReferences(TestReferences.SymbolsTests.Fields.ConstantFields)
CompileAndVerify(compilation, <![CDATA[
Int64Field: 634315546432909307
DateTimeField: 1/25/2011 12:17:23 PM
DoubleField: -10
SingleField: 9
StringField: 11
StringNullField: []
ObjectNullField: []
ByteValue: ByteValue
SByteValue: SByteValue
UInt16Value: UInt16Value
Int16Value: Int16Value
UInt32Value: UInt32Value
Int32Value: Int32Value
UInt64Value: UInt64Value
Int64Value: Int64Value
]]>)
End Sub
' Test member of built in type.
<Fact>
Public Sub MemberOfBuiltInType()
CompileAndVerify(
<compilation name="MeReference">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x as Integer
x = Integer.Parse("143")
Console.WriteLine(x)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="143")
End Sub
' Test member of nullable type.
<Fact>
Public Sub MemberOfNullableType()
CompileAndVerify(
<compilation name="MeReference">
<file name="a.vb">
Imports System
Module M1
Sub Main()
Dim x as boolean
x = Integer?.Equals("goo", "g" + "oo")
Console.WriteLine(x)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="True")
End Sub
<Fact>
Public Sub Bug4272()
Dim compilationDef =
<compilation name="Bug4272">
<file name="a.vb">
Option Strict On
Module M
Function Goo(x As Integer) As Integer()
Goo(1) = 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.
Goo(1) = Nothing
~~~~~~
BC42105: Function 'Goo' 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>)
compilationDef =
<compilation name="Bug4272">
<file name="a.vb">
Module Module1
Sub Main()
Goo()
End Sub
Private val As TestClass
Function Goo() As TestClass
If val Is Nothing Then
System.Console.WriteLine("Nothing")
val = New TestClass()
val.Field = 2
Else
System.Console.WriteLine("val")
Return val
End If
Dim x As TestClass = New TestClass()
x.Field = 1
Goo = x
System.Console.WriteLine(Goo.Field)
System.Console.WriteLine(Goo.GetField())
System.Console.WriteLine(Goo().Field)
System.Console.WriteLine(Goo(3))
End Function
Function Goo(x As Integer) As Integer
Return x
End Function
End Module
Class TestClass
Public Field As Integer
Public Function GetField() As Integer
Return Field
End Function
End Class
</file>
</compilation>
compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
Nothing
1
1
val
2
3
]]>)
compilationDef =
<compilation name="Bug4272">
<file name="a.vb">
Option Strict On
Module M
Function Goo(x As Integer) As Integer()
Dim y As Integer() = Goo(1)
End Function
End Module
Module M1
Function Goo(x As Object) As Integer
Return Goo(1)
End Function
Function Goo(x As Integer) As Integer
Return 1
End Function
End Module
</file>
</compilation>
compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertTheseDiagnostics(compilation,
<expected>
BC42105: Function 'Goo' 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
<WorkItem(538802, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538802")>
<Fact>
Public Sub MethodAccessibilityChecking()
CompileAndVerify(
<compilation name="MeReference">
<file name="a.vb">
Imports System
Public Class C1
Private Shared Sub goo(x as String)
Console.Writeline("Private")
End Sub
Public Shared Sub goo(x as Object)
Console.Writeline("Public")
End Sub
End class
Module Program
Sub Main()
'Below call should bind to public overload that takes object
c1.goo("")
End Sub
End Module
</file>
</compilation>,
expectedOutput:="Public")
End Sub
<Fact>
Public Sub Bug4249()
Dim compilationDef =
<compilation name="Bug4249">
<file name="a.vb">
Module Program
Sub Main()
Main().ToString
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertTheseDiagnostics(compilation,
<expected>
BC30491: Expression does not produce a value.
Main().ToString
~~~~~~
</expected>)
End Sub
<Fact>
Public Sub Bug4250()
Dim compilationDef =
<compilation name="Bug4250">
<file name="a.vb">
Module Program
Sub Main()
System.Console.WriteLine(Goo.ToString)
System.Console.WriteLine(Bar(Of Integer).ToString)
End Sub
Function Goo() as Integer
return 123
End Function
Function Bar(Of T)() as Integer
return 231
End Function
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
CompileAndVerify(compilation, <![CDATA[
123
231
]]>)
compilationDef =
<compilation name="Bug4250">
<file name="a.vb">
Module Program
Sub Main()
System.Console.WriteLine(Goo.ToString)
End Sub
Function Goo(x as Integer) as Integer
return 321
End Function
End Module
</file>
</compilation>
compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation,
<expected>
BC30455: Argument not specified for parameter 'x' of 'Public Function Goo(x As Integer) As Integer'.
System.Console.WriteLine(Goo.ToString)
~~~
</expected>)
End Sub
<Fact>
Public Sub Bug4277()
Dim compilationDef =
<compilation name="Bug4277">
<file name="a.vb">
Option Strict Off
Module M
Sub Main()
End Sub
End Module
Class B
Sub T()
End Sub
End Class
Class A(Of T)
Inherits B
Sub Goo()
T()
End Sub
End Class
Class C
Sub S()
End Sub
Class A(Of S)
Sub Goo()
S()
End Sub
End Class
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertTheseDiagnostics(compilation,
<expected>
BC30108: 'S' is a type and cannot be used as an expression.
S()
~
</expected>)
End Sub
<WorkItem(538438, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538438")>
<Fact>
Public Sub TestRangeExpressionAllowableLowerBounds()
Dim compilationDef =
<compilation name="TestRangeExpressionAllowableLowerBounds">
<file name="a.vb">
Friend Module ExpArrBounds0LowerBound
Sub ExpArrBounds0LowerBound()
Dim x0(0 To 2&)
Dim x1(0& To 2&)
Dim x2(0ul To 2&)
Dim x3(0l To 2&)
Dim x4(0us To 2&)
Dim x5(0s To 2&)
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertNoErrors(compilation)
End Sub
<WorkItem(537219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537219")>
<Fact>
Public Sub BC32059ERR_OnlyNullLowerBound()
Dim compilationDef =
<compilation name="BC32059ERR_OnlyNullLowerBound">
<file name="a.b">
Friend Module ExpArrBounds003Errmod
Sub ExpArrBounds003Err()
' COMPILEERROR: BC32059, "0!"
Dim x1(0! To 5) as Single
Dim x2(0.0 to 5) as Single
Dim x3(0d to 5) as Single
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertTheseDiagnostics(compilation,
<errors>
BC32059: Array lower bounds can be only '0'.
Dim x1(0! To 5) as Single
~~
BC32059: Array lower bounds can be only '0'.
Dim x2(0.0 to 5) as Single
~~~
BC32059: Array lower bounds can be only '0'.
Dim x3(0d to 5) as Single
~~
</errors>)
End Sub
<Fact>
Public Sub LocalShadowsGenericMethod()
Dim compilationDef =
<compilation name="LocalShadowsGenericMethod">
<file name="a.vb">
Class Y
Sub f()
Dim goo As Integer
goo(Of Integer)()
End Sub
Public Sub goo(Of T)()
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertTheseDiagnostics(compilation,
<errors>
BC42024: Unused local variable: 'goo'.
Dim goo As Integer
~~~
BC32045: 'goo' has no type parameters and so cannot have type arguments.
goo(Of Integer)()
~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub AccessingMemberOffOfNothing()
Dim compilationDef =
<compilation name="AccessingMemberOffOfNothing">
<file name="a.vb">
Class Y
Sub f()
Dim x As System.Type = Nothing.GetType()
End Sub
End Class
</file>
</compilation>
CompileAndVerify(compilationDef).
VerifyIL("Y.f",
<![CDATA[
{
// Code size 8 (0x8)
.maxstack 1
IL_0000: ldnull
IL_0001: callvirt "Function Object.GetType() As System.Type"
IL_0006: pop
IL_0007: ret
}
]]>)
End Sub
<Fact>
Public Sub ColorColor()
Dim compilationDef =
<compilation name="AccessingMemberOffOfNothing">
<file name="a.vb">
Option Strict On
Imports System
Module Module1
Sub main()
Dim o As New cls1
End Sub
End Module
Class cls1
Public Const s As Integer = 123
Shared o As Integer = cls1.s
Public ReadOnly Property cls1 As cls1
Get
Console.WriteLine("hi")
Return Me
End Get
End Property
Sub New()
' cls1 is a type here, no warnings needed, but colorizer should show it as a type
cls1.s.ToString()
End Sub
Shared Sub moo()
Console.WriteLine(cls1.s)
End Sub
End Class
Class Color
Public Shared Red As Color = Nothing
Public Shared Property Green As Color
Public Class TypeInColor
Public shared c as Color
End Class
Public Class GenericTypeInColor
Public shared c as Color
End Class
Public Class GenericTypeInColor(of T)
Public shared c as Color
End Class
End Class
Class Test
ReadOnly Property Color() As Color
Get
Return Color.Red
End Get
End Property
Shared Function DefaultColor() As Color
Dim c as Color = Color.Green ' Binds to the instance property!
c= Color.TypeInColor.c
c= Color.GenericTypeInColor.c
c= Color.GenericTypeInColor(of UShort).c
return c
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub FalseColorColor()
Dim compilationDef =
<compilation name="AccessingMemberOffOfNothing">
<file name="a.vb">
Imports Q = B
Class B
Public Shared Zip As Integer
Public ReadOnly Property Q As B
Get
Return Nothing
End Get
End Property
Shared Sub f()
Dim x As Integer = Q.Zip 'this should be an error
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertTheseDiagnostics(compilation,
<errors>
BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.
Dim x As Integer = Q.Zip 'this should be an error
~
</errors>)
End Sub
<Fact>
Public Sub ColorColor1()
Dim compilationDef =
<compilation name="AccessingMemberOffOfNothing">
<file name="a.vb">
Option Strict On
Imports System
Module Module1
Sub main()
Test.DefaultColor()
End Sub
End Module
Class Color
Public Shared Red As Color = Nothing
Public Shared Function G(Of T)(x As T) As Color
Return Red
End Function
End Class
Class Test
ReadOnly Property color(x as integer) As Color
Get
Console.WriteLine("evaluated")
Return Color.Red
End Get
End Property
Shared Function DefaultColor() As Color
dim a = color.G(1) ' error, missing parameter to color property
Return color.G(of Long)(1) ' error, missing parameter to color property
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertTheseDiagnostics(compilation, <expected>
BC30455: Argument not specified for parameter 'x' of 'Public ReadOnly Property color(x As Integer) As Color'.
dim a = color.G(1) ' error, missing parameter to color property
~~~~~
BC30455: Argument not specified for parameter 'x' of 'Public ReadOnly Property color(x As Integer) As Color'.
Return color.G(of Long)(1) ' error, missing parameter to color property
~~~~~
</expected>)
End Sub
<Fact>
Public Sub ColorColor2()
Dim compilationDef =
<compilation name="AccessingMemberOffOfNothing">
<file name="a.vb">
Option Strict On
Imports System
Module Module1
Sub main()
Test.DefaultColor()
End Sub
End Module
Class Color
Public Shared Red As Color = Nothing
Public Shared Function G(Of T)(x As T) As Color
Return Red
End Function
End Class
Class Test
ReadOnly Property color() As Color
Get
Console.WriteLine("evaluated")
Return Color.Red
End Get
End Property
Shared Function DefaultColor() As Color
Return color.G(1) ' Binds to the type
Return color.G(of Long)(1) ' Binds to the type
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub ColorColorOverloaded()
Dim compilationDef =
<compilation name="ColorColorOverloaded">
<file name="a.vb">
Option Strict On
Imports System
Module Module1
Public Sub Main()
Dim o as Test = New Test
o.DefaultColor()
End Sub
Class Color
Public Shared Red As Color = New Color
Public Shared Function G(x As Integer) As Color
Return Red
End Function
Public Function G() As Color
Return Red
End Function
End Class
Class Test
ReadOnly Property Color() As Color
Get
Console.Write("evaluated")
Return Color.Red
End Get
End Property
Function DefaultColor() As Color
Dim c1 As Color
c1 = Color.G(1) ' Binds to the type
c1 = Color.G() ' Binds to the member
Return c1
End Function
End Class
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertNoErrors(compilation)
CompileAndVerify(compilationDef, expectedOutput:="evaluated").
VerifyIL("Module1.Test.DefaultColor",
<![CDATA[
{
// Code size 19 (0x13)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: call "Function Module1.Color.G(Integer) As Module1.Color"
IL_0006: pop
IL_0007: ldarg.0
IL_0008: call "Function Module1.Test.get_Color() As Module1.Color"
IL_000d: callvirt "Function Module1.Color.G() As Module1.Color"
IL_0012: ret
}
]]>)
End Sub
<Fact()>
Public Sub ColorColorOverloadedOptional()
Dim compilationDef =
<compilation name="ColorColorOverloaded">
<file name="a.vb">
Option Strict On
Imports System
Module Module1
Public Sub Main()
Dim o as Test = New Test
o.DefaultColor()
End Sub
Class Color
Public Shared Red As Color = New Color
Public Shared Function G(x As Integer) As Color
Return Red
End Function
Public Function G() As Color
Return Red
End Function
End Class
Class Test
ReadOnly Property Color(optional x as integer = 1) As Color
Get
Console.Write("evaluated")
Return Color.Red
End Get
End Property
Function DefaultColor() As Color
Dim c1 As Color
c1 = Color.G(1) ' Binds to the type
c1 = Color.G() ' Binds to the member
Return c1
End Function
End Class
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertNoErrors(compilation)
CompileAndVerify(compilationDef, expectedOutput:="evaluated").
VerifyIL("Module1.Test.DefaultColor",
<![CDATA[
{
// Code size 20 (0x14)
.maxstack 2
IL_0000: ldc.i4.1
IL_0001: call "Function Module1.Color.G(Integer) As Module1.Color"
IL_0006: pop
IL_0007: ldarg.0
IL_0008: ldc.i4.1
IL_0009: call "Function Module1.Test.get_Color(Integer) As Module1.Color"
IL_000e: callvirt "Function Module1.Color.G() As Module1.Color"
IL_0013: ret
}
]]>)
End Sub
<Fact>
Public Sub ColorColorOverloadedErr()
Dim compilationDef =
<compilation name="ColorColorOverloaded">
<file name="a.vb">
Option Strict On
Imports System
Module Module1
Public Sub Main()
Dim o as Test = New Test
o.DefaultColor()
End Sub
Class Color
Public Shared Red As Color = New Color
Public Shared Function G(x As Integer) As Color
Return Red
End Function
Public Function G() As Color
Return Red
End Function
End Class
Class Test
ReadOnly Property Color(x as integer) As Color
Get
Console.Write("evaluated")
Return Color.Red
End Get
End Property
Function DefaultColor() As Color
Dim c1 As Color
c1 = Color.G(1) ' missing parameter x
c1 = Color.G() ' missing parameter x
Return c1
End Function
End Class
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertTheseDiagnostics(compilation,
<errors>
BC30455: Argument not specified for parameter 'x' of 'Public ReadOnly Property Color(x As Integer) As Module1.Color'.
c1 = Color.G(1) ' missing parameter x
~~~~~
BC30455: Argument not specified for parameter 'x' of 'Public ReadOnly Property Color(x As Integer) As Module1.Color'.
c1 = Color.G() ' missing parameter x
~~~~~
</errors>)
End Sub
<Fact>
Public Sub ColorColorOverloadedErr2()
Dim compilationDef =
<compilation name="ColorColorOverloaded">
<file name="a.vb">
Option Strict On
Imports System
Module Module1
Public Sub Main()
Dim o as Test = New Test
o.DefaultColor()
End Sub
Class Color
Public Shared Red As Color = New Color
Public Shared Function G(x As Integer) As Color
Return Red
End Function
Public Function G() As Color
Return Red
End Function
End Class
Class Test
ReadOnly Property Color As Color
Get
Console.Write("evaluated")
Return Color.Red
End Get
End Property
Function DefaultColor() As Color
Dim c1 As Color
c1 = Color.G(1) ' Binds to the type
c1 = Color.G() ' Binds to the member
Return c1
End Function
End Class
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertNoDiagnostics(compilation)
End Sub
<Fact>
Public Sub ColorColorOverloadedAddressOf()
Dim compilationDef =
<compilation name="ColorColorOverloadedAddressOf">
<file name="a.vb">
Option Strict On
Imports System
Module Module1
Public Sub Main()
Dim o as Test = New Test
o.DefaultColor()
End Sub
Class Color
Public Shared Red As Color = New Color
Public Shared Function G(x As Integer) As Color
Return Red
End Function
Public Function G() As Color
Return Red
End Function
End Class
Class Test
ReadOnly Property Color() As Color
Get
Console.Write("evaluated")
Return Color.Red
End Get
End Property
Function DefaultColor() As Color
Dim c1 As Color
Dim d1 As Func(Of Integer, Color) = AddressOf Color.G ' Binds to the type
c1 = d1(1)
Dim d2 As Func(Of Color) = AddressOf Color.G ' Binds to the member
c1 = d2()
Return c1
End Function
End Class
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertNoErrors(compilation)
CompileAndVerify(compilationDef, expectedOutput:="evaluated").
VerifyIL("Module1.Test.DefaultColor",
<![CDATA[
{
// Code size 42 (0x2a)
.maxstack 2
IL_0000: ldnull
IL_0001: ldftn "Function Module1.Color.G(Integer) As Module1.Color"
IL_0007: newobj "Sub System.Func(Of Integer, Module1.Color)..ctor(Object, System.IntPtr)"
IL_000c: ldc.i4.1
IL_000d: callvirt "Function System.Func(Of Integer, Module1.Color).Invoke(Integer) As Module1.Color"
IL_0012: pop
IL_0013: ldarg.0
IL_0014: call "Function Module1.Test.get_Color() As Module1.Color"
IL_0019: ldftn "Function Module1.Color.G() As Module1.Color"
IL_001f: newobj "Sub System.Func(Of Module1.Color)..ctor(Object, System.IntPtr)"
IL_0024: callvirt "Function System.Func(Of Module1.Color).Invoke() As Module1.Color"
IL_0029: ret
}
]]>)
End Sub
<Fact>
Public Sub ColorColorOverloadedAddressOfRelaxed()
Dim compilationDef =
<compilation name="ColorColorOverloadedAddressOfRelaxed">
<file name="a.vb">
Option Strict On
Imports System
Module Module1
Public Sub Main()
Dim o As Test = New Test
o.DefaultColor()
End Sub
Class Color
Public Shared Red As Color = New Color
Public Shared Function G(x As Integer) As Color
Return Red
End Function
Public Function G() As Color
Return Red
End Function
End Class
Class Test
ReadOnly Property Color() As Color
Get
Console.Write("evaluated")
Return Color.Red
End Get
End Property
Sub DefaultColor()
Dim d1 As Action(Of Integer) = AddressOf Color.G ' Binds to the type
d1(1)
Dim d2 As Action = AddressOf Color.G ' Binds to the member
d2()
End Sub
End Class
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertNoErrors(compilation)
CompileAndVerify(compilationDef, expectedOutput:="evaluated").
VerifyIL("Module1.Test.DefaultColor",
<![CDATA[
{
// Code size 76 (0x4c)
.maxstack 3
IL_0000: ldsfld "Module1.Test._Closure$__.$IR3-2 As System.Action(Of Integer)"
IL_0005: brfalse.s IL_000e
IL_0007: ldsfld "Module1.Test._Closure$__.$IR3-2 As System.Action(Of Integer)"
IL_000c: br.s IL_0024
IL_000e: ldsfld "Module1.Test._Closure$__.$I As Module1.Test._Closure$__"
IL_0013: ldftn "Sub Module1.Test._Closure$__._Lambda$__R3-2(Integer)"
IL_0019: newobj "Sub System.Action(Of Integer)..ctor(Object, System.IntPtr)"
IL_001e: dup
IL_001f: stsfld "Module1.Test._Closure$__.$IR3-2 As System.Action(Of Integer)"
IL_0024: ldc.i4.1
IL_0025: callvirt "Sub System.Action(Of Integer).Invoke(Integer)"
IL_002a: newobj "Sub Module1.Test._Closure$__R3-0..ctor()"
IL_002f: dup
IL_0030: ldarg.0
IL_0031: call "Function Module1.Test.get_Color() As Module1.Color"
IL_0036: stfld "Module1.Test._Closure$__R3-0.$VB$NonLocal_2 As Module1.Color"
IL_003b: ldftn "Sub Module1.Test._Closure$__R3-0._Lambda$__R3()"
IL_0041: newobj "Sub System.Action..ctor(Object, System.IntPtr)"
IL_0046: callvirt "Sub System.Action.Invoke()"
IL_004b: ret
}
]]>)
End Sub
<Fact>
Public Sub ColorColorExtension()
Dim compilationDef =
<compilation name="ColorColorOverloaded">
<file name="a.vb">
Option Strict On
Imports System
Imports System.Runtime.CompilerServices
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
Module Module1
Public Sub Main()
Dim o As Test = New Test
o.DefaultColor()
End Sub
Structure S1
End Structure
<Extension()>
Public Function G(this As Color) As Color
Return Color.Red
End Function
Class Color
Public Shared Red As Color = New Color
Public Shared Function G(x As Integer) As Color
Return Red
End Function
End Class
Class Test
Shared ReadOnly Property Color() As Color
Get
Console.Write("evaluated")
Return Color.Red
End Get
End Property
Function DefaultColor() As Color
Dim c1 As Color
c1 = Color.G(1) ' Binds to the type
c1 = Color.G() ' Binds to the member + extension
Return c1
End Function
End Class
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertNoErrors(compilation)
CompileAndVerify(compilationDef, expectedOutput:="evaluated").
VerifyIL("Module1.Test.DefaultColor",
<![CDATA[
{
// Code size 18 (0x12)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: call "Function Module1.Color.G(Integer) As Module1.Color"
IL_0006: pop
IL_0007: call "Function Module1.Test.get_Color() As Module1.Color"
IL_000c: call "Function Module1.G(Module1.Color) As Module1.Color"
IL_0011: ret
}
]]>)
End Sub
<Fact()>
Public Sub ColorColorAlias()
Dim compilationDef =
<compilation name="ColorColorAlias">
<file name="a.vb">
Option Strict On
Imports System
Imports Bar = NS1.Bar
Module Module1
Public Sub Main()
Dim o as Goo = New Goo()
Console.WriteLine(o.M())
End Sub
End Module
Namespace NS1
Public Class Bar
Public Shared c as Integer = 48
End Class
End Namespace
Class Goo
ReadOnly Property Bar As Bar
Get
Console.WriteLine("property called")
Return Nothing
End Get
End Property
Function M() As Integer
return Bar.c
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertNoDiagnostics(compilation)
CompileAndVerify(compilationDef, expectedOutput:="48").
VerifyIL("Goo.M",
<![CDATA[
{
// Code size 6 (0x6)
.maxstack 1
IL_0000: ldsfld "NS1.Bar.c As Integer"
IL_0005: ret
}
]]>)
End Sub
<Fact()>
Public Sub ColorColorWrongAlias()
Dim compilationDef =
<compilation name="ColorColorWrongAlias">
<file name="a.vb">
Option Strict On
Imports System
Imports Bar2 = NS1.Bar
Module Module1
Public Sub Main()
Dim o As Goo = New Goo()
Console.WriteLine(Goo.M())
End Sub
End Module
Namespace NS1
Public Class Bar
Public Shared c As Integer = 48
End Class
End Namespace
Class Goo
ReadOnly Property Bar2 As Bar2
Get
Console.WriteLine("property called")
Return Nothing
End Get
End Property
Public Shared Function M() As Integer
Return Bar2.c
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef)
AssertTheseDiagnostics(compilation, <expected>
BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.
Return Bar2.c
~~~~
</expected>)
End Sub
<Fact>
Public Sub ModulesWhereTypesShouldBe()
Dim text =
<compilation name="ModulesWhereTypesShouldBe">
<file name="a.vb">
Module M
Sub GG()
Dim y As System.Collections.Generic.List(Of M)
Dim z As Object = Nothing
Dim q = TryCast(z, M)
Dim p = CType(z, M)
Dim r As M()
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(text)
AssertTheseDiagnostics(compilation,
<errors>
BC42024: Unused local variable: 'y'.
Dim y As System.Collections.Generic.List(Of M)
~
BC30371: Module 'M' cannot be used as a type.
Dim y As System.Collections.Generic.List(Of M)
~
BC30371: Module 'M' cannot be used as a type.
Dim q = TryCast(z, M)
~
BC30371: Module 'M' cannot be used as a type.
Dim p = CType(z, M)
~
BC42024: Unused local variable: 'r'.
Dim r As M()
~
BC30371: Module 'M' cannot be used as a type.
Dim r As M()
~
</errors>)
End Sub
<Fact>
Public Sub GetTypeOnNSAlias()
Dim text =
<compilation name="GetTypeOnNSAlias">
<file name="a.vb">
Imports NS=System.Collections
Module M
Sub S()
Dim x = GetType(NS)
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(text)
AssertTheseDiagnostics(compilation,
<errors>
BC30182: Type expected.
Dim x = GetType(NS)
~~
</errors>)
End Sub
<WorkItem(542383, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542383")>
<Fact>
Public Sub GetTypeOnModuleName()
Dim text =
<compilation name="GetTypeForModuleName">
<file name="a.vb">
Imports System
Namespace AttrUseCust011
Friend Module AttrUseCust011mod
Sub GG()
Dim x = GetType(AttrUseCust011mod)
End Sub
End Module
End Namespace
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(text)
AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub GetTypeOnAlias()
Dim text =
<compilation name="GetTypeOnAlias">
<file name="a.vb">
Imports System
Imports Con = System.Console
Module M
Sub GG()
Dim x = GetType(Con)
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(text)
AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub Bug9300_1()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="NotYetImplementedInRoslyn">
<file name="a.vb">
Imports System.Runtime.CompilerServices
Imports System.Collections
Imports System
Module M
Sub Main()
Goo(Sub(x) x.New())
End Sub
Sub Goo(x As Action(Of Object()))
System.Console.WriteLine("Action(Of Object())")
x(New Object() {})
End Sub
<Extension()>
Sub [New](Of T)(ByVal x As T)
System.Console.WriteLine("[New]")
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>)
Dim expectedErrors1 = <errors>
BC30251: Type 'Object()' has no constructors.
Goo(Sub(x) x.New())
~~~~~
</errors>
AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub Bug9300_2()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="NotYetImplementedInRoslyn">
<file name="a.vb">
Imports System.Runtime.CompilerServices
Imports System.Collections
Imports System
Module M
Sub Main()
Goo(Sub(x) x.New())
End Sub
Class TC1
End Class
Sub Goo(x As Action(Of TC1))
End Sub
<Extension()>
Sub [New](Of T)(ByVal x As T)
System.Console.WriteLine("[New]")
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>)
Dim expectedErrors1 = <errors>
BC30282: Constructor call is valid only as the first statement in an instance constructor.
Goo(Sub(x) x.New())
~~~~~
</errors>
AssertTheseDiagnostics(compilation1, expectedErrors1)
End Sub
<Fact>
Public Sub Bug9300_3()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="NotYetImplementedInRoslyn">
<file name="a.vb">
Imports System.Runtime.CompilerServices
Imports System.Collections
Imports System
Module M
Sub Main()
Goo(Sub(x) x.New())
End Sub
Sub Goo(x As Action(Of IEnumerable))
System.Console.WriteLine("Action(Of IEnumerable)")
x(New Object() {})
End Sub
Sub Goo(x As Action(Of Object()))
System.Console.WriteLine("Action(Of Object())")
x(New Object() {})
End Sub
<Extension()>
Sub [New](Of T)(ByVal x As T)
System.Console.WriteLine("[New]")
End Sub
End Module
Namespace System.Runtime.CompilerServices
<AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)>
Class ExtensionAttribute
Inherits Attribute
End Class
End Namespace
</file>
</compilation>, TestOptions.ReleaseExe)
CompileAndVerify(compilation1, <![CDATA[
Action(Of IEnumerable)
[New]
]]>)
End Sub
<Fact>
Public Sub IllegalTypeExpressionsFromParserShouldNotBlowUpBinding()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="IllegalTypeExpressionsFromParserShouldNotBlowUpBinding">
<file name="a.vb">
Class Outer(Of T)
Public Shared Sub Print()
System.Console.WriteLine(GetType(Outer(Of ).Inner(Of T))) ' BC32099: Comma or ')' expected.
System.Console.WriteLine(GetType(Outer(Of ).Inner(Of Integer))) ' BC32099: Comma or ')' expected.
System.Console.WriteLine(GetType(Outer(Of T).Inner(Of ))) ' BC30182: Type expected.
System.Console.WriteLine(GetType(Outer(Of Integer).Inner(Of ))) ' BC30182: Type expected.
End Sub
Class Inner(Of U)
End Class
End Class
</file>
</compilation>)
AssertTheseDiagnostics(compilation1, <expected>
BC32099: Comma or ')' expected.
System.Console.WriteLine(GetType(Outer(Of ).Inner(Of T))) ' BC32099: Comma or ')' expected.
~
BC32099: Comma or ')' expected.
System.Console.WriteLine(GetType(Outer(Of ).Inner(Of Integer))) ' BC32099: Comma or ')' expected.
~~~~~~~
BC30182: Type expected.
System.Console.WriteLine(GetType(Outer(Of T).Inner(Of ))) ' BC30182: Type expected.
~
BC30182: Type expected.
System.Console.WriteLine(GetType(Outer(Of Integer).Inner(Of ))) ' BC30182: Type expected.
~
</expected>)
End Sub
<Fact()>
Public Sub Bug10335_1()
Dim source1_with =
<compilation name="Unavailable">
<file name="a.vb">
Public Interface IUnavailable
ReadOnly Default Property Item(p as Integer) as Integer
End Interface
</file>
</compilation>
Dim c1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source1_with)
Dim baseBuffer = CompileAndVerify(c1).EmittedAssemblyData
Dim source2 =
<compilation>
<file name="a.vb">
Public Class Class1
Implements IUnavailable
Public Default ReadOnly Property Item(p as Integer) as Integer implements IUnavailable.Item
Get
Return p
End Get
End Property
End Class
Public Class Class2
Public ReadOnly Property AProperty() as Class1
Get
Return new Class1()
End Get
End Property
End Class
</file>
</compilation>
Dim c2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source2, {MetadataReference.CreateFromImage(baseBuffer)})
Dim derivedBuffer = CompileAndVerify(c2).EmittedAssemblyData
Dim source3 =
<compilation>
<file name="a.vb">
Module M1
Sub Main()
Dim x as new Class2()
dim y = x.AProperty(23)
Dim z as Object = x.AProperty()
x.AProperty()
End Sub
End Module
</file>
</compilation>
Dim source1_without =
<compilation name="Unavailable">
<file name="a.vb">
Class Unused
End Class
</file>
</compilation>
Dim c1_without = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source1_without)
Dim image = CompileAndVerify(c1_without).EmittedAssemblyData
Dim c3 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source3, {MetadataReference.CreateFromImage(derivedBuffer), MetadataReference.CreateFromImage(image)})
AssertTheseDiagnostics(c3, <expected>
BC30545: Property access must assign to the property or use its value.
x.AProperty()
~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub ColorColorOverriddenProperty()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug12687">
<file name="a.vb">
Class TypeSubstitution
Shared Function Create() As Integer
Return 1
End Function
End Class
Class InstanceTypeSymbol
ReadOnly Property TypeSubstitution(a as Integer) As TypeSubstitution
Get
Return Nothing
End Get
End Property
End Class
Class Frame
Inherits InstanceTypeSymbol
Overloads ReadOnly Property TypeSubstitution As TypeSubstitution
Get
Return Nothing
End Get
End Property
Function Goo() As Integer
Return TypeSubstitution.Create()
End Function
End Class
</file>
</compilation>)
AssertNoDiagnostics(compilation)
End Sub
<Fact>
Public Sub ColorColorPropertyWithParam()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug12687">
<file name="a.vb">
Class TypeSubstitution
Shared Function Create() As Integer
Return 1
End Function
End Class
Class InstanceTypeSymbol
Overridable ReadOnly Property TypeSubstitution(a as Integer) As TypeSubstitution
Get
Return Nothing
End Get
End Property
End Class
Class Frame
Inherits InstanceTypeSymbol
Function Goo() As Integer
Return TypeSubstitution.Create()
End Function
End Class
</file>
</compilation>)
AssertTheseDiagnostics(compilation, <expected>
BC30455: Argument not specified for parameter 'a' of 'Public Overridable ReadOnly Property TypeSubstitution(a As Integer) As TypeSubstitution'.
Return TypeSubstitution.Create()
~~~~~~~~~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub ColorColorPropertyWithOverloading()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="Bug12687">
<file name="a.vb">
Class TypeSubstitution
Shared Function Create() As Integer
Return 1
End Function
End Class
Class InstanceTypeSymbol
ReadOnly Property TypeSubstitution(a as Integer) As String
Get
Return Nothing
End Get
End Property
ReadOnly Property TypeSubstitution As TypeSubstitution
Get
Return Nothing
End Get
End Property
End Class
Class Frame
Inherits InstanceTypeSymbol
Function Goo() As Integer
Return TypeSubstitution.Create()
End Function
End Class
</file>
</compilation>)
AssertNoDiagnostics(compilation)
End Sub
' Tests IsValidAssignmentTarget for PropertyAccess
' and IsLValueFieldAccess for FieldAccess.
<Fact>
Public Sub IsValidAssignmentTarget()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Structure S
Public F As Object
Public Property P As Object
Sub M()
Me.F = Nothing ' IsLValue = False, IsMeReference = True
MyClass.F = Nothing ' IsLValue = False, IsMyClassReference = True
Me.P = Nothing ' IsLValue = False, IsMeReference = True
MyClass.P = Nothing ' IsLValue = False, IsMyClassReference = True
End Sub
End Structure
Class C
Private F1 As S
Private ReadOnly F2 As S
Sub M()
F1.F = Nothing ' IsLValue = True
F2.F = Nothing ' IsLValue = False
F1.P = Nothing ' IsLValue = True
F2.P = Nothing ' IsLValue = False
End Sub
End Class
</file>
</compilation>)
compilation.AssertTheseDiagnostics(<expected>
BC30064: 'ReadOnly' variable cannot be the target of an assignment.
F2.F = Nothing ' IsLValue = False
~~~~
BC30068: Expression is a value and therefore cannot be the target of an assignment.
F2.P = Nothing ' IsLValue = False
~~~~
</expected>)
End Sub
<Fact>
Public Sub Bug12900()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="MemberAccessNoContainingWith">
<file name="a.vb">
Imports System
Module Program
Sub Main(args As String())
Const local _? As Integer
End Sub
End Module
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC30438: Constants must have a value.
Const local _? As Integer
~~~~~
BC30203: Identifier expected.
Const local _? As Integer
~
</expected>)
End Sub
<Fact>
Public Sub Bug13080()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Module Program
Sub Main(args As String())
Const '
End Sub
End Module
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC30203: Identifier expected.
Const '
~
BC30438: Constants must have a value.
Const '
~
</expected>)
End Sub
<WorkItem(546469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546469")>
<Fact>
Public Sub GetTypeAllowsArrayOfModules()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Imports VoidAlias = System.Void
Namespace Bar
Module Test
Sub Main()
' Array of types
Dim x As Type = GetType(Test()) 'ok
x = GetType(Void()) ' error
' types direct
x = GetType(Test) ' ok
x = GetType(Void) ' ok
' nullable
x = GetType(Test?) ' error
x = GetType(Void?) ' error
x = GetType(List(Of Test)) ' error
x = GetType(List(Of Void)) ' error
x = GetType(Bar.Test) ' ok
x = GetType(System.Void) ' ok
x = GetType(VoidAlias) ' ok
End Sub
End Module
End Namespace
</file>
</compilation>)
AssertTheseDiagnostics(compilation, <expected>
BC31428: Arrays of type 'System.Void' are not allowed in this expression.
x = GetType(Void()) ' error
~~~~~~
BC30371: Module 'Test' cannot be used as a type.
x = GetType(Test?) ' error
~~~~
BC33101: Type 'Test' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'.
x = GetType(Test?) ' error
~~~~
BC31422: 'System.Void' can only be used in a GetType expression.
x = GetType(Void?) ' error
~~~~
BC30371: Module 'Test' cannot be used as a type.
x = GetType(List(Of Test)) ' error
~~~~
BC31422: 'System.Void' can only be used in a GetType expression.
x = GetType(List(Of Void)) ' error
~~~~
</expected>)
End Sub
<WorkItem(530438, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530438")>
<WorkItem(546469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546469")>
<Fact()>
Public Sub GetTypeAllowsModuleAlias()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports ModuleAlias = Bar.Test
Imports System
Namespace Bar
Module Test
Sub Main()
Dim x As Type = GetType(ModuleAlias) ' ok
End Sub
End Module
End Namespace
</file>
</compilation>)
AssertTheseDiagnostics(compilation, <expected></expected>)
End Sub
<Fact()>
Public Sub RangeVariableColorColor()
Dim source = _
<compilation>
<file name="a.vb">
Imports System.Linq
Class Program
Shared Sub Main()
Dim q = From X As X In New X() { New X() }
Where X.S()
Where X.I()
Select 42
System.Console.Write(q.Single())
End Sub
End Class
Class X
Public Shared Function S() As Boolean
Return True
End Function
Public Shared Function I() As Boolean
Return True
End Function
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, options:=TestOptions.ReleaseExe)
AssertTheseDiagnostics(compilation, <expected></expected>)
CompileAndVerify(compilation, expectedOutput:="42")
End Sub
<WorkItem(1108036, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108036")>
<Fact()>
Public Sub Bug1108036()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Class Color
Public Shared Sub Cat()
End Sub
End Class
Class Program
Shared Sub Main()
Color.Cat()
End Sub
ReadOnly Property Color(Optional x As Integer = 0) As Color
Get
Return Nothing
End Get
End Property
ReadOnly Property Color(Optional x As String = "") As Integer
Get
Return 0
End Get
End Property
End Class
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC30521: Overload resolution failed because no accessible 'Color' is most specific for these arguments:
'Public ReadOnly Property Color([x As Integer = 0]) As Color': Not most specific.
'Public ReadOnly Property Color([x As String = ""]) As Integer': Not most specific.
Color.Cat()
~~~~~
</expected>)
End Sub
<WorkItem(1108036, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108036")>
<Fact()>
Public Sub Bug1108036_2()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Class Color
Public Shared Sub Cat()
End Sub
End Class
Class Program
Shared Sub Main()
Color.Cat()
End Sub
ReadOnly Property Color(Optional x As Integer = 0) As Integer
Get
Return 0
End Get
End Property
ReadOnly Property Color(Optional x As String = "") As Color
Get
Return Nothing
End Get
End Property
End Class
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC30521: Overload resolution failed because no accessible 'Color' is most specific for these arguments:
'Public ReadOnly Property Color([x As Integer = 0]) As Integer': Not most specific.
'Public ReadOnly Property Color([x As String = ""]) As Color': Not most specific.
Color.Cat()
~~~~~
</expected>)
End Sub
<WorkItem(969006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/969006")>
<Fact()>
Public Sub Bug969006_1()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Enum E
A
End Enum
Class C
Sub M()
Const e As E = E.A
Dim z = e
End Sub
End Class
</file>
</compilation>)
Dim tree = compilation.SyntaxTrees(0)
Dim model1 = compilation.GetSemanticModel(tree)
Dim node1 = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Single()
Assert.Equal("E.A", node1.ToString())
Assert.Equal("E", node1.Expression.ToString())
Dim symbolInfo = model1.GetSymbolInfo(node1.Expression)
Assert.Equal("E", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.NamedType, symbolInfo.Symbol.Kind)
Dim model2 = compilation.GetSemanticModel(tree)
Dim node2 = tree.GetRoot().DescendantNodes.OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "e").Single()
Assert.Equal("= e", node2.Parent.ToString())
symbolInfo = model2.GetSymbolInfo(node2)
Assert.Equal("e As E", symbolInfo.Symbol.ToTestDisplayString())
symbolInfo = model2.GetSymbolInfo(node1.Expression)
Assert.Equal("E", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.NamedType, symbolInfo.Symbol.Kind)
AssertTheseDiagnostics(compilation)
End Sub
<WorkItem(969006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/969006")>
<Fact()>
Public Sub Bug969006_2()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Enum E
A
End Enum
Class C
Sub M()
Dim e As E = E.A
Dim z = e
End Sub
End Class
</file>
</compilation>)
Dim tree = compilation.SyntaxTrees(0)
Dim model1 = compilation.GetSemanticModel(tree)
Dim node1 = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Single()
Assert.Equal("E.A", node1.ToString())
Assert.Equal("E", node1.Expression.ToString())
Dim symbolInfo = model1.GetSymbolInfo(node1.Expression)
Assert.Equal("E", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.NamedType, symbolInfo.Symbol.Kind)
Dim model2 = compilation.GetSemanticModel(tree)
Dim node2 = tree.GetRoot().DescendantNodes.OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "e").Single()
Assert.Equal("= e", node2.Parent.ToString())
symbolInfo = model2.GetSymbolInfo(node2)
Assert.Equal("e As E", symbolInfo.Symbol.ToTestDisplayString())
symbolInfo = model2.GetSymbolInfo(node1.Expression)
Assert.Equal("E", symbolInfo.Symbol.ToTestDisplayString())
Assert.Equal(SymbolKind.NamedType, symbolInfo.Symbol.Kind)
AssertTheseDiagnostics(compilation)
End Sub
<WorkItem(969006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/969006")>
<Fact()>
Public Sub Bug969006_3()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Enum E
A
End Enum
Class C
Sub M()
Const e = E.A
Dim z = e
End Sub
End Class
</file>
</compilation>)
Dim tree = compilation.SyntaxTrees(0)
Dim model1 = compilation.GetSemanticModel(tree)
Dim node1 = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Single()
Assert.Equal("E.A", node1.ToString())
Assert.Equal("E", node1.Expression.ToString())
Dim symbolInfo = model1.GetSymbolInfo(node1.Expression)
Assert.Equal("e As System.Object", symbolInfo.Symbol.ToTestDisplayString())
Dim model2 = compilation.GetSemanticModel(tree)
Dim node2 = tree.GetRoot().DescendantNodes.OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "e").Single()
Assert.Equal("= e", node2.Parent.ToString())
symbolInfo = model2.GetSymbolInfo(node2)
Assert.Equal("e As System.Object", symbolInfo.Symbol.ToTestDisplayString())
symbolInfo = model2.GetSymbolInfo(node1.Expression)
Assert.Equal("e As System.Object", symbolInfo.Symbol.ToTestDisplayString())
AssertTheseDiagnostics(compilation, <expected>
BC30500: Constant 'e' cannot depend on its own value.
Const e = E.A
~
BC42104: Variable 'e' is used before it has been assigned a value. A null reference exception could result at runtime.
Const e = E.A
~
</expected>)
End Sub
<WorkItem(969006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/969006")>
<Fact()>
Public Sub Bug969006_4()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Enum E
A
End Enum
Class C
Sub M()
Dim e = E.A
Dim z = e
End Sub
End Class
</file>
</compilation>)
Dim tree = compilation.SyntaxTrees(0)
Dim model1 = compilation.GetSemanticModel(tree)
Dim node1 = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Single()
Assert.Equal("E.A", node1.ToString())
Assert.Equal("E", node1.Expression.ToString())
Dim symbolInfo = model1.GetSymbolInfo(node1.Expression)
Assert.Equal("e As ?", symbolInfo.Symbol.ToTestDisplayString())
Dim model2 = compilation.GetSemanticModel(tree)
Dim node2 = tree.GetRoot().DescendantNodes.OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "e").Single()
Assert.Equal("= e", node2.Parent.ToString())
symbolInfo = model2.GetSymbolInfo(node2)
Assert.Equal("e As ?", symbolInfo.Symbol.ToTestDisplayString())
symbolInfo = model2.GetSymbolInfo(node1.Expression)
Assert.Equal("e As ?", symbolInfo.Symbol.ToTestDisplayString())
AssertTheseDiagnostics(compilation, <expected>
BC30980: Type of 'e' cannot be inferred from an expression containing 'e'.
Dim e = E.A
~
BC42104: Variable 'e' is used before it has been assigned a value. A null reference exception could result at runtime.
Dim e = E.A
~
</expected>)
End Sub
<WorkItem(1108007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108007")>
<Fact()>
Public Sub Bug1108007_1()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Class Color
Public Shared Sub M(x As Integer)
System.Console.WriteLine(x)
End Sub
Public Sub M(x As String)
End Sub
End Class
Class Program
Dim Color As Color
Shared Sub Main()
Dim x As Object = 42
Color.M(x)
End Sub
End Class
</file>
</compilation>, TestOptions.ReleaseExe)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim node = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Select(Function(e) e.Expression).Where(Function(e) e.ToString() = "Color").Single()
Dim symbol = model.GetSymbolInfo(node).Symbol
Assert.NotNull(symbol)
Assert.Equal("Color", symbol.Name)
Assert.Equal(SymbolKind.NamedType, symbol.Kind)
AssertTheseDiagnostics(compilation, <expected></expected>)
CompileAndVerify(compilation, expectedOutput:="42")
End Sub
<WorkItem(1108007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108007")>
<Fact>
Public Sub Bug1108007_2()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Class Color
Public Shared Sub M(x As Integer)
Console.WriteLine(x)
End Sub
Public Sub M(x As String)
End Sub
End Class
Class Program
Dim Color As Color
Shared Sub Main()
Try
Dim x As Object = ""
Color.M(x)
Catch e As Exception
Console.WriteLine(e.GetType())
End Try
End Sub
End Class
</file>
</compilation>, TestOptions.ReleaseExe)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim node = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Select(Function(e) e.Expression).Where(Function(e) e.ToString() = "Color").Single()
Dim symbol = model.GetSymbolInfo(node).Symbol
Assert.NotNull(symbol)
Assert.Equal("Color", symbol.Name)
Assert.Equal(SymbolKind.NamedType, symbol.Kind)
AssertTheseDiagnostics(compilation, <expected></expected>)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[System.NullReferenceException]]>)
End Sub
<WorkItem(1108007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108007")>
<Fact()>
Public Sub Bug1108007_3()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Class MyAttribute
Inherits System.Attribute
Public ReadOnly I As Integer
Public Sub New(i As Integer)
Me.I = i
End Sub
End Class
Class Color
Public Const I As Integer = 42
End Class
Class Program
Dim Color As Color
<MyAttribute(Color.I)>
Shared Sub Main()
End Sub
End Class
]]>
</file>
</compilation>, TestOptions.ReleaseExe)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim node = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Select(Function(e) e.Expression).Where(Function(e) e.ToString() = "Color").Single()
Dim symbol = model.GetSymbolInfo(node).Symbol
Assert.NotNull(symbol)
Assert.Equal("Color", symbol.Name)
Assert.Equal(SymbolKind.NamedType, symbol.Kind)
AssertTheseDiagnostics(compilation, <expected></expected>)
End Sub
<WorkItem(1108007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108007")>
<Fact()>
Public Sub Bug1108007_4()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Class Color
Public Shared Sub M(x As Integer)
Console.WriteLine(x)
End Sub
Public Sub M(x As String)
End Sub
Class Program
Dim Color As Color
Sub M()
Try
Dim x As Object = ""
Color.M(x)
Catch e As Exception
Console.WriteLine(e.GetType())
End Try
End Sub
Shared Sub Main()
Dim p = New Program()
p.M()
End Sub
End Class
End Class
</file>
</compilation>, TestOptions.ReleaseExe)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim node = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Select(Function(e) e.Expression).Where(Function(e) e.ToString() = "Color").Single()
Dim symbol = model.GetSymbolInfo(node).Symbol
Assert.NotNull(symbol)
Assert.Equal("Color", symbol.Name)
Assert.Equal(SymbolKind.Field, symbol.Kind)
AssertTheseDiagnostics(compilation, <expected></expected>)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[System.NullReferenceException]]>)
End Sub
<WorkItem(1108007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108007")>
<Fact()>
Public Sub Bug1108007_5()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Class Color
Public Shared Function M(x As Integer) As Integer
Return x
End Function
Public Function M(x As String) As Integer
Return x.Length
End Function
End Class
Class A
Public Sub New(x As Integer)
Console.WriteLine(x)
End Sub
End Class
Class B
Inherits A
Dim Color As Color
Public Sub New()
MyBase.New(Color.M(DirectCast(42, Object)))
End Sub
Shared Sub Main()
Dim b = New B()
End Sub
End Class
</file>
</compilation>, TestOptions.ReleaseExe)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim node = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Select(Function(e) e.Expression).Where(Function(e) e.ToString() = "Color").Single()
Dim symbol = model.GetSymbolInfo(node).Symbol
Assert.NotNull(symbol)
Assert.Equal("Color", symbol.Name)
Assert.Equal(SymbolKind.NamedType, symbol.Kind)
AssertTheseDiagnostics(compilation, <expected></expected>)
CompileAndVerify(compilation, expectedOutput:="42")
End Sub
<WorkItem(1108007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108007")>
<Fact()>
Public Sub Bug1108007_6()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Class Color
Public Shared Function M(x As Integer) As Integer
Console.WriteLine(x)
Return x
End Function
Public Function M(x As String) As Integer
Return x.Length
End Function
End Class
Class Program
Dim Color As Color
Dim I As Integer = Color.M(DirectCast(42, Object))
Shared Sub Main()
Try
Dim p = New Program()
Catch e As Exception
Console.WriteLine(e.GetType())
End Try
End Sub
End Class
</file>
</compilation>, TestOptions.ReleaseExe)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim node = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Select(Function(e) e.Expression).Where(Function(e) e.ToString() = "Color").Single()
Dim symbol = model.GetSymbolInfo(node).Symbol
Assert.NotNull(symbol)
Assert.Equal("Color", symbol.Name)
Assert.Equal(SymbolKind.Field, symbol.Kind)
AssertTheseDiagnostics(compilation, <expected></expected>)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[System.NullReferenceException]]>)
End Sub
<WorkItem(1108007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108007")>
<Fact()>
Public Sub Bug1108007_7()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Class Color
Public Shared Function M(x As Integer) As Integer
Console.WriteLine(x)
Return x
End Function
Public Function M(x As String) As Integer
Return x.Length
End Function
End Class
Class Program
Dim Color As Color
Shared Dim I As Integer = Color.M(DirectCast(42, Object))
Shared Sub Main()
Dim i = Program.I
End Sub
End Class
</file>
</compilation>, TestOptions.ReleaseExe)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim node = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Select(Function(e) e.Expression).Where(Function(e) e.ToString() = "Color").Single()
Dim symbol = model.GetSymbolInfo(node).Symbol
Assert.NotNull(symbol)
Assert.Equal("Color", symbol.Name)
Assert.Equal(SymbolKind.NamedType, symbol.Kind)
AssertTheseDiagnostics(compilation, <expected></expected>)
CompileAndVerify(compilation, expectedOutput:="42")
End Sub
<WorkItem(1108007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108007")>
<Fact>
Public Sub Bug1108007_8()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Class Color
Public Shared Sub M(x As Integer)
Console.WriteLine(x)
End Sub
Public Sub M(x As String)
End Sub
End Class
Class Outer
Dim Color As Color
Class Program
Sub M()
Try
Dim x As Object = ""
Color.M(x)
Catch e As Exception
Console.WriteLine(e.GetType())
End Try
End Sub
Shared Sub Main()
Dim p = New Program()
p.M()
End Sub
End Class
End Class
</file>
</compilation>, TestOptions.ReleaseExe)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim node = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Select(Function(e) e.Expression).Where(Function(e) e.ToString() = "Color").Single()
Dim symbol = model.GetSymbolInfo(node).Symbol
Assert.NotNull(symbol)
Assert.Equal("Color", symbol.Name)
Assert.Equal(SymbolKind.NamedType, symbol.Kind)
AssertTheseDiagnostics(compilation, <expected></expected>)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[System.NullReferenceException]]>)
End Sub
<WorkItem(1108007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108007")>
<Fact()>
Public Sub Bug1108007_9()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Class Color
Public Shared Sub M(x As Integer)
System.Console.WriteLine(x)
End Sub
Public Sub M(x As String)
End Sub
End Class
Class Outer
Shared Dim Color As Color = New Color()
Class Program
Sub M()
Dim x As Object = 42
Color.M(x)
End Sub
Shared Sub Main()
Dim p = New Program()
p.M()
End Sub
End Class
End Class </file>
</compilation>, TestOptions.ReleaseExe)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim node = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Select(Function(e) e.Expression).Where(Function(e) e.ToString() = "Color").Single()
Dim symbol = model.GetSymbolInfo(node).Symbol
Assert.NotNull(symbol)
Assert.Equal("Color", symbol.Name)
Assert.Equal(SymbolKind.Field, symbol.Kind)
AssertTheseDiagnostics(compilation, <expected></expected>)
CompileAndVerify(compilation, expectedOutput:="42")
End Sub
<WorkItem(1114969, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1114969")>
<Fact()>
Public Sub Bug1114969()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Class Color
Public Function M() As Integer
Return 42
End Function
End Class
Class Base
Protected Dim Color As Color = New Color()
End Class
Class Derived
Inherits Base
Sub M()
System.Console.WriteLine(Color.M())
End Sub
Shared Sub Main()
Dim d = New Derived()
d.M()
End Sub
End Class </file>
</compilation>, TestOptions.ReleaseExe)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim node = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Select(Function(e) e.Expression).Where(Function(e) e.ToString() = "Color").Single()
Dim symbol = model.GetSymbolInfo(node).Symbol
Assert.NotNull(symbol)
Assert.Equal("Color", symbol.Name)
Assert.Equal(SymbolKind.Field, symbol.Kind)
AssertTheseDiagnostics(compilation, <expected></expected>)
CompileAndVerify(compilation, expectedOutput:="42")
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Tools/ExternalAccess/FSharp/Editor/Implementation/Debugging/FSharpDebugLocationInfo.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Debugging;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor.Implementation.Debugging
{
internal readonly struct FSharpDebugLocationInfo
{
internal readonly DebugLocationInfo UnderlyingObject;
public FSharpDebugLocationInfo(string name, int lineOffset)
=> UnderlyingObject = new DebugLocationInfo(name, lineOffset);
public readonly string Name => UnderlyingObject.Name;
public readonly int LineOffset => UnderlyingObject.LineOffset;
internal bool IsDefault => UnderlyingObject.IsDefault;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Debugging;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor.Implementation.Debugging
{
internal readonly struct FSharpDebugLocationInfo
{
internal readonly DebugLocationInfo UnderlyingObject;
public FSharpDebugLocationInfo(string name, int lineOffset)
=> UnderlyingObject = new DebugLocationInfo(name, lineOffset);
public readonly string Name => UnderlyingObject.Name;
public readonly int LineOffset => UnderlyingObject.LineOffset;
internal bool IsDefault => UnderlyingObject.IsDefault;
}
}
| -1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Analyzers/VisualBasic/Tests/AddAccessibilityModifiers/AddAccessibilityModifiersTests.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.CodeStyle
Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions
Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeFixVerifier(Of
Microsoft.CodeAnalysis.VisualBasic.AddAccessibilityModifiers.VisualBasicAddAccessibilityModifiersDiagnosticAnalyzer,
Microsoft.CodeAnalysis.VisualBasic.AddAccessibilityModifiers.VisualBasicAddAccessibilityModifiersCodeFixProvider)
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.AddAccessibilityModifiers
Public Class AddAccessibilityModifiersTests
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)>
Public Sub TestStandardProperty([property] As AnalyzerProperty)
VerifyVB.VerifyStandardProperty([property])
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)>
Public Async Function TestAllConstructs() As Task
Await VerifyVB.VerifyCodeFixAsync(
"
namespace N
namespace Outer.Inner
class [|C|]
class [|NestedClass|]
end class
structure [|NestedStruct|]
end structure
dim [|f1|] as integer
dim [|f2|], f3 as integer
dim [|f4|], f5 as integer, f6, f7 as boolean
public {|BC30260:f4|} as integer
event [|e1|] as {|BC31044:{|BC30002:Action|}|}
public event e2 as {|BC31044:{|BC30002:Action|}|}
custom event {|BC31130:{|BC31131:{|BC31132:[|e4|]|}|}|} as {|BC31044:{|BC30002:Action|}|}
end event
shared sub new()
end sub
sub [|new|]()
end sub
public sub new(i as integer)
end sub
sub [|M1|]()
end sub
public sub M2()
end sub
function [|M3|]() as integer
end function
{|BC30027:function [|M4|]() as integer|}
{|BC30289:public function M5() as integer|}
end function
{|BC31432:partial|} sub [|M6|]()
end sub
property [|P1|] as integer
property {|BC30124:[|P2|]|} as integer
get
end get
end property
public property P3 as integer
shared operator [|&|](c1 as C, c2 as C) as integer
end operator
end class
interface [|I|]
event e6 as {|BC31044:{|BC30002:Action|}|}
sub M3()
function M4() as integer
property P3 as integer
end interface
delegate sub [|D1|]()
delegate function [|D2|]() as integer
enum [|E|]
EMember
end enum
structure [|S|]
dim [|f|] as integer
sub [|M|]()
end sub
shared operator [|&|](c1 as S, c2 as S) as integer
end operator
end structure
module [|M|]
dim [|f|] as integer
sub [|M|]()
end sub
end module
end namespace
end namespace",
"
namespace N
namespace Outer.Inner
Friend class C
Public class NestedClass
end class
Public structure NestedStruct
end structure
Private f1 as integer
Private f2, f3 as integer
Private f4, f5 as integer, f6, f7 as boolean
public {|BC30260:f4|} as integer
Public event e1 as {|BC31044:{|BC30002:Action|}|}
public event e2 as {|BC31044:{|BC30002:Action|}|}
Public custom event {|BC31130:{|BC31131:{|BC31132:e4|}|}|} as {|BC31044:{|BC30002:Action|}|}
end event
shared sub new()
end sub
Public sub new()
end sub
public sub new(i as integer)
end sub
Public sub M1()
end sub
public sub M2()
end sub
Public function M3() as integer
end function
{|BC30027:Public function M4() as integer|}
{|BC30289:public function M5() as integer|}
end function
partial {|BC31431:Public|} sub M6()
end sub
Public property P1 as integer
Public property {|BC30124:P2|} as integer
get
end get
end property
public property P3 as integer
Public shared operator &(c1 as C, c2 as C) as integer
end operator
end class
Friend interface I
event e6 as {|BC31044:{|BC30002:Action|}|}
sub M3()
function M4() as integer
property P3 as integer
end interface
Friend delegate sub D1()
Friend delegate function D2() as integer
Friend enum E
EMember
end enum
Friend structure S
Public f as integer
Public sub M()
end sub
Public shared operator &(c1 as S, c2 as S) as integer
end operator
end structure
Friend module M
Private f as integer
Public sub M()
end sub
end module
end namespace
end namespace")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)>
Public Async Function TestAllConstructsWithOmit() As Task
Dim source = "
namespace N
namespace Outer.Inner
Friend class [|C|]
Public class [|NestedClass|]
end class
Public structure [|NestedStruct|]
end structure
Private [|f1|] as integer
Private [|f2|], f3 as integer
Private [|f4|], f5 as integer, f6, f7 as boolean
public {|BC30260:f4|} as integer
Private Const [|foo|] As long = 3
private const [|bar|] = 4, barbar = 5
public Const pfoo As long = 3
public Const pbar = 4, pbarbar As ULong = 5
Private Shared [|sfoo|] = 4
private shared [|sbar|] as Long = 5, sbarbar = 0
public Shared spfoo = 4
public Shared spbar = 4, spbarbar as Long = 4
Public event [|e1|] as {|BC31044:{|BC30002:Action|}|}
public event [|e2|] as {|BC31044:{|BC30002:Action|}|}
Public custom event {|BC31130:{|BC31131:{|BC31132:[|e4|]|}|}|} as {|BC31044:{|BC30002:Action|}|}
end event
shared sub new()
end sub
Public sub [|new|]()
end sub
public sub [|new|](i as integer)
end sub
Public sub [|M1|]()
end sub
public sub [|M2|]()
end sub
Public function [|M3|]() as integer
end function
{|BC30027:Public function [|M4|]() as integer|}
{|BC30289:public function [|M5|]() as integer|}
end function
Private partial sub M6()
end sub
Public property [|P1|] as integer
Public property {|BC30124:[|P2|]|} as integer
get
end get
end property
public property [|P3|] as integer
Public shared operator [|&|](c1 as C, c2 as C) as integer
end operator
end class
Friend interface [|I|]
event e6 as {|BC31044:{|BC30002:Action|}|}
sub M3()
function M4() as integer
property P3 as integer
end interface
Friend delegate sub [|D1|]()
Friend delegate function [|D2|]() as integer
Friend enum [|E|]
EMember
end enum
Friend structure [|S|]
Public [|f|] as integer
Public sub [|M|]()
end sub
Public shared operator [|&|](c1 as S, c2 as S) as integer
end operator
end structure
Friend module [|M|]
Private [|f|] as integer
Public sub [|M|]()
end sub
end module
end namespace
end namespace"
Dim fixedSource = "
namespace N
namespace Outer.Inner
class C
class NestedClass
end class
structure NestedStruct
end structure
Dim f1 as integer
Dim f2, f3 as integer
Dim f4, f5 as integer, f6, f7 as boolean
public {|BC30260:f4|} as integer
Const foo As long = 3
const bar = 4, barbar = 5
public Const pfoo As long = 3
public Const pbar = 4, pbarbar As ULong = 5
Shared sfoo = 4
shared sbar as Long = 5, sbarbar = 0
public Shared spfoo = 4
public Shared spbar = 4, spbarbar as Long = 4
event e1 as {|BC31044:{|BC30002:Action|}|}
event e2 as {|BC31044:{|BC30002:Action|}|}
custom event {|BC31130:{|BC31131:{|BC31132:e4|}|}|} as {|BC31044:{|BC30002:Action|}|}
end event
shared sub new()
end sub
sub new()
end sub
sub new(i as integer)
end sub
sub M1()
end sub
sub M2()
end sub
function M3() as integer
end function
{|BC30027:function M4() as integer|}
{|BC30289:function M5() as integer|}
end function
Private partial sub M6()
end sub
property P1 as integer
property {|BC30124:P2|} as integer
get
end get
end property
property P3 as integer
shared operator &(c1 as C, c2 as C) as integer
end operator
end class
interface I
event e6 as {|BC31044:{|BC30002:Action|}|}
sub M3()
function M4() as integer
property P3 as integer
end interface
delegate sub D1()
delegate function D2() as integer
enum E
EMember
end enum
structure S
Dim f as integer
sub M()
end sub
shared operator &(c1 as S, c2 as S) as integer
end operator
end structure
module M
Dim f as integer
sub M()
end sub
end module
end namespace
end namespace"
Dim test As New VerifyVB.Test()
test.TestCode = source
test.FixedCode = fixedSource
test.Options.Add(CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.OmitIfDefault)
Await test.RunAsync()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)>
<WorkItem(44076, "https://github.com/dotnet/roslyn/issues/44076")>
Public Async Function TestModuleConstructor() As Task
Dim source = "
Friend Module Example
Sub New()
End Sub
End Module
"
Await VerifyVB.VerifyCodeFixAsync(source, source)
End Function
<WorkItem(48899, "https://github.com/dotnet/roslyn/issues/48899")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)>
Public Async Function TestAbstractMethod() As Task
Await VerifyVB.VerifyCodeFixAsync("
public mustinherit class TestClass
mustoverride sub [|Test|]()
end class
",
"
public mustinherit class TestClass
Protected mustoverride sub Test()
end class
")
End Function
<WorkItem(48899, "https://github.com/dotnet/roslyn/issues/48899")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)>
Public Async Function TestOverriddenMethod() As Task
Await VerifyVB.VerifyCodeFixAsync("
public mustinherit class TestClass
public mustoverride sub Test()
end class
public class Derived
inherits TestClass
overrides sub [|Test|]()
end sub
end class
",
"
public mustinherit class TestClass
public mustoverride sub Test()
end class
public class Derived
inherits TestClass
Public overrides sub Test()
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.CodeStyle
Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions
Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeFixVerifier(Of
Microsoft.CodeAnalysis.VisualBasic.AddAccessibilityModifiers.VisualBasicAddAccessibilityModifiersDiagnosticAnalyzer,
Microsoft.CodeAnalysis.VisualBasic.AddAccessibilityModifiers.VisualBasicAddAccessibilityModifiersCodeFixProvider)
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.AddAccessibilityModifiers
Public Class AddAccessibilityModifiersTests
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)>
Public Sub TestStandardProperty([property] As AnalyzerProperty)
VerifyVB.VerifyStandardProperty([property])
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)>
Public Async Function TestAllConstructs() As Task
Await VerifyVB.VerifyCodeFixAsync(
"
namespace N
namespace Outer.Inner
class [|C|]
class [|NestedClass|]
end class
structure [|NestedStruct|]
end structure
dim [|f1|] as integer
dim [|f2|], f3 as integer
dim [|f4|], f5 as integer, f6, f7 as boolean
public {|BC30260:f4|} as integer
event [|e1|] as {|BC31044:{|BC30002:Action|}|}
public event e2 as {|BC31044:{|BC30002:Action|}|}
custom event {|BC31130:{|BC31131:{|BC31132:[|e4|]|}|}|} as {|BC31044:{|BC30002:Action|}|}
end event
shared sub new()
end sub
sub [|new|]()
end sub
public sub new(i as integer)
end sub
sub [|M1|]()
end sub
public sub M2()
end sub
function [|M3|]() as integer
end function
{|BC30027:function [|M4|]() as integer|}
{|BC30289:public function M5() as integer|}
end function
{|BC31432:partial|} sub [|M6|]()
end sub
property [|P1|] as integer
property {|BC30124:[|P2|]|} as integer
get
end get
end property
public property P3 as integer
shared operator [|&|](c1 as C, c2 as C) as integer
end operator
end class
interface [|I|]
event e6 as {|BC31044:{|BC30002:Action|}|}
sub M3()
function M4() as integer
property P3 as integer
end interface
delegate sub [|D1|]()
delegate function [|D2|]() as integer
enum [|E|]
EMember
end enum
structure [|S|]
dim [|f|] as integer
sub [|M|]()
end sub
shared operator [|&|](c1 as S, c2 as S) as integer
end operator
end structure
module [|M|]
dim [|f|] as integer
sub [|M|]()
end sub
end module
end namespace
end namespace",
"
namespace N
namespace Outer.Inner
Friend class C
Public class NestedClass
end class
Public structure NestedStruct
end structure
Private f1 as integer
Private f2, f3 as integer
Private f4, f5 as integer, f6, f7 as boolean
public {|BC30260:f4|} as integer
Public event e1 as {|BC31044:{|BC30002:Action|}|}
public event e2 as {|BC31044:{|BC30002:Action|}|}
Public custom event {|BC31130:{|BC31131:{|BC31132:e4|}|}|} as {|BC31044:{|BC30002:Action|}|}
end event
shared sub new()
end sub
Public sub new()
end sub
public sub new(i as integer)
end sub
Public sub M1()
end sub
public sub M2()
end sub
Public function M3() as integer
end function
{|BC30027:Public function M4() as integer|}
{|BC30289:public function M5() as integer|}
end function
partial {|BC31431:Public|} sub M6()
end sub
Public property P1 as integer
Public property {|BC30124:P2|} as integer
get
end get
end property
public property P3 as integer
Public shared operator &(c1 as C, c2 as C) as integer
end operator
end class
Friend interface I
event e6 as {|BC31044:{|BC30002:Action|}|}
sub M3()
function M4() as integer
property P3 as integer
end interface
Friend delegate sub D1()
Friend delegate function D2() as integer
Friend enum E
EMember
end enum
Friend structure S
Public f as integer
Public sub M()
end sub
Public shared operator &(c1 as S, c2 as S) as integer
end operator
end structure
Friend module M
Private f as integer
Public sub M()
end sub
end module
end namespace
end namespace")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)>
Public Async Function TestAllConstructsWithOmit() As Task
Dim source = "
namespace N
namespace Outer.Inner
Friend class [|C|]
Public class [|NestedClass|]
end class
Public structure [|NestedStruct|]
end structure
Private [|f1|] as integer
Private [|f2|], f3 as integer
Private [|f4|], f5 as integer, f6, f7 as boolean
public {|BC30260:f4|} as integer
Private Const [|foo|] As long = 3
private const [|bar|] = 4, barbar = 5
public Const pfoo As long = 3
public Const pbar = 4, pbarbar As ULong = 5
Private Shared [|sfoo|] = 4
private shared [|sbar|] as Long = 5, sbarbar = 0
public Shared spfoo = 4
public Shared spbar = 4, spbarbar as Long = 4
Public event [|e1|] as {|BC31044:{|BC30002:Action|}|}
public event [|e2|] as {|BC31044:{|BC30002:Action|}|}
Public custom event {|BC31130:{|BC31131:{|BC31132:[|e4|]|}|}|} as {|BC31044:{|BC30002:Action|}|}
end event
shared sub new()
end sub
Public sub [|new|]()
end sub
public sub [|new|](i as integer)
end sub
Public sub [|M1|]()
end sub
public sub [|M2|]()
end sub
Public function [|M3|]() as integer
end function
{|BC30027:Public function [|M4|]() as integer|}
{|BC30289:public function [|M5|]() as integer|}
end function
Private partial sub M6()
end sub
Public property [|P1|] as integer
Public property {|BC30124:[|P2|]|} as integer
get
end get
end property
public property [|P3|] as integer
Public shared operator [|&|](c1 as C, c2 as C) as integer
end operator
end class
Friend interface [|I|]
event e6 as {|BC31044:{|BC30002:Action|}|}
sub M3()
function M4() as integer
property P3 as integer
end interface
Friend delegate sub [|D1|]()
Friend delegate function [|D2|]() as integer
Friend enum [|E|]
EMember
end enum
Friend structure [|S|]
Public [|f|] as integer
Public sub [|M|]()
end sub
Public shared operator [|&|](c1 as S, c2 as S) as integer
end operator
end structure
Friend module [|M|]
Private [|f|] as integer
Public sub [|M|]()
end sub
end module
end namespace
end namespace"
Dim fixedSource = "
namespace N
namespace Outer.Inner
class C
class NestedClass
end class
structure NestedStruct
end structure
Dim f1 as integer
Dim f2, f3 as integer
Dim f4, f5 as integer, f6, f7 as boolean
public {|BC30260:f4|} as integer
Const foo As long = 3
const bar = 4, barbar = 5
public Const pfoo As long = 3
public Const pbar = 4, pbarbar As ULong = 5
Shared sfoo = 4
shared sbar as Long = 5, sbarbar = 0
public Shared spfoo = 4
public Shared spbar = 4, spbarbar as Long = 4
event e1 as {|BC31044:{|BC30002:Action|}|}
event e2 as {|BC31044:{|BC30002:Action|}|}
custom event {|BC31130:{|BC31131:{|BC31132:e4|}|}|} as {|BC31044:{|BC30002:Action|}|}
end event
shared sub new()
end sub
sub new()
end sub
sub new(i as integer)
end sub
sub M1()
end sub
sub M2()
end sub
function M3() as integer
end function
{|BC30027:function M4() as integer|}
{|BC30289:function M5() as integer|}
end function
Private partial sub M6()
end sub
property P1 as integer
property {|BC30124:P2|} as integer
get
end get
end property
property P3 as integer
shared operator &(c1 as C, c2 as C) as integer
end operator
end class
interface I
event e6 as {|BC31044:{|BC30002:Action|}|}
sub M3()
function M4() as integer
property P3 as integer
end interface
delegate sub D1()
delegate function D2() as integer
enum E
EMember
end enum
structure S
Dim f as integer
sub M()
end sub
shared operator &(c1 as S, c2 as S) as integer
end operator
end structure
module M
Dim f as integer
sub M()
end sub
end module
end namespace
end namespace"
Dim test As New VerifyVB.Test()
test.TestCode = source
test.FixedCode = fixedSource
test.Options.Add(CodeStyleOptions2.RequireAccessibilityModifiers, AccessibilityModifiersRequired.OmitIfDefault)
Await test.RunAsync()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)>
<WorkItem(44076, "https://github.com/dotnet/roslyn/issues/44076")>
Public Async Function TestModuleConstructor() As Task
Dim source = "
Friend Module Example
Sub New()
End Sub
End Module
"
Await VerifyVB.VerifyCodeFixAsync(source, source)
End Function
<WorkItem(48899, "https://github.com/dotnet/roslyn/issues/48899")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)>
Public Async Function TestAbstractMethod() As Task
Await VerifyVB.VerifyCodeFixAsync("
public mustinherit class TestClass
mustoverride sub [|Test|]()
end class
",
"
public mustinherit class TestClass
Protected mustoverride sub Test()
end class
")
End Function
<WorkItem(48899, "https://github.com/dotnet/roslyn/issues/48899")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAccessibilityModifiers)>
Public Async Function TestOverriddenMethod() As Task
Await VerifyVB.VerifyCodeFixAsync("
public mustinherit class TestClass
public mustoverride sub Test()
end class
public class Derived
inherits TestClass
overrides sub [|Test|]()
end sub
end class
",
"
public mustinherit class TestClass
public mustoverride sub Test()
end class
public class Derived
inherits TestClass
Public overrides sub Test()
end sub
end class
")
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Features/Core/Portable/AddImport/AbstractAddImportCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Packaging;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.SymbolSearch;
namespace Microsoft.CodeAnalysis.AddImport
{
internal abstract partial class AbstractAddImportCodeFixProvider : CodeFixProvider
{
private const int MaxResults = 5;
private readonly IPackageInstallerService _packageInstallerService;
private readonly ISymbolSearchService _symbolSearchService;
/// <summary>
/// Values for these parameters can be provided (during testing) for mocking purposes.
/// </summary>
protected AbstractAddImportCodeFixProvider(
IPackageInstallerService packageInstallerService = null,
ISymbolSearchService symbolSearchService = null)
{
_packageInstallerService = packageInstallerService;
_symbolSearchService = symbolSearchService;
}
public sealed override FixAllProvider GetFixAllProvider()
{
// Currently Fix All is not supported for this provider
// https://github.com/dotnet/roslyn/issues/34457
return null;
}
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var document = context.Document;
var span = context.Span;
var cancellationToken = context.CancellationToken;
var diagnostics = context.Diagnostics;
var addImportService = document.GetLanguageService<IAddImportFeatureService>();
var solution = document.Project.Solution;
var options = solution.Options;
var searchReferenceAssemblies = options.GetOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, document.Project.Language);
var searchNuGetPackages = options.GetOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages, document.Project.Language);
var symbolSearchService = searchReferenceAssemblies || searchNuGetPackages
? _symbolSearchService ?? solution.Workspace.Services.GetService<ISymbolSearchService>()
: null;
var installerService = GetPackageInstallerService(document);
var packageSources = searchNuGetPackages && symbolSearchService != null && installerService?.IsEnabled(document.Project.Id) == true
? installerService.TryGetPackageSources()
: ImmutableArray<PackageSource>.Empty;
var fixesForDiagnostic = await addImportService.GetFixesForDiagnosticsAsync(
document, span, diagnostics, MaxResults, symbolSearchService, searchReferenceAssemblies, packageSources, cancellationToken).ConfigureAwait(false);
foreach (var (diagnostic, fixes) in fixesForDiagnostic)
{
// Limit the results returned since this will be displayed to the user
var codeActions = addImportService.GetCodeActionsForFixes(document, fixes, installerService, MaxResults);
context.RegisterFixes(codeActions, diagnostic);
}
}
private IPackageInstallerService GetPackageInstallerService(Document document)
=> _packageInstallerService ?? document.Project.Solution.Workspace.Services.GetService<IPackageInstallerService>();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Packaging;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.SymbolSearch;
namespace Microsoft.CodeAnalysis.AddImport
{
internal abstract partial class AbstractAddImportCodeFixProvider : CodeFixProvider
{
private const int MaxResults = 5;
private readonly IPackageInstallerService _packageInstallerService;
private readonly ISymbolSearchService _symbolSearchService;
/// <summary>
/// Values for these parameters can be provided (during testing) for mocking purposes.
/// </summary>
protected AbstractAddImportCodeFixProvider(
IPackageInstallerService packageInstallerService = null,
ISymbolSearchService symbolSearchService = null)
{
_packageInstallerService = packageInstallerService;
_symbolSearchService = symbolSearchService;
}
public sealed override FixAllProvider GetFixAllProvider()
{
// Currently Fix All is not supported for this provider
// https://github.com/dotnet/roslyn/issues/34457
return null;
}
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var document = context.Document;
var span = context.Span;
var cancellationToken = context.CancellationToken;
var diagnostics = context.Diagnostics;
var addImportService = document.GetLanguageService<IAddImportFeatureService>();
var solution = document.Project.Solution;
var options = solution.Options;
var searchReferenceAssemblies = options.GetOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, document.Project.Language);
var searchNuGetPackages = options.GetOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages, document.Project.Language);
var symbolSearchService = searchReferenceAssemblies || searchNuGetPackages
? _symbolSearchService ?? solution.Workspace.Services.GetService<ISymbolSearchService>()
: null;
var installerService = GetPackageInstallerService(document);
var packageSources = searchNuGetPackages && symbolSearchService != null && installerService?.IsEnabled(document.Project.Id) == true
? installerService.TryGetPackageSources()
: ImmutableArray<PackageSource>.Empty;
var fixesForDiagnostic = await addImportService.GetFixesForDiagnosticsAsync(
document, span, diagnostics, MaxResults, symbolSearchService, searchReferenceAssemblies, packageSources, cancellationToken).ConfigureAwait(false);
foreach (var (diagnostic, fixes) in fixesForDiagnostic)
{
// Limit the results returned since this will be displayed to the user
var codeActions = addImportService.GetCodeActionsForFixes(document, fixes, installerService, MaxResults);
context.RegisterFixes(codeActions, diagnostic);
}
}
private IPackageInstallerService GetPackageInstallerService(Document document)
=> _packageInstallerService ?? document.Project.Solution.Workspace.Services.GetService<IPackageInstallerService>();
}
}
| -1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/EditorFeatures/VisualBasicTest/Recommendations/Declarations/ModifierKeywordRecommenderTests.InsideStructureDeclaration.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations.ModifierKeywordRecommenderTests
Public Class InsideStructureDeclaration
#Region "Scope Keywords"
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PublicExistsTest()
VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "Public")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ProtectedMissingTest()
VerifyRecommendationsMissing(<StructureDeclaration>|</StructureDeclaration>, "Protected")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PrivateExistsTest()
VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "Private")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub FriendExistsTest()
VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "Friend")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ProtectedFriendMissingTest()
VerifyRecommendationsMissing(<StructureDeclaration>|</StructureDeclaration>, "Protected Friend")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PublicNotAfterPublicTest()
VerifyRecommendationsMissing(<StructureDeclaration>Public |</StructureDeclaration>, "Public")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ProtectedNotAfterPublicTest()
VerifyRecommendationsMissing(<StructureDeclaration>Public |</StructureDeclaration>, "Protected")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PrivateNotAfterPublicTest()
VerifyRecommendationsMissing(<StructureDeclaration>Public |</StructureDeclaration>, "Private")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub FriendNotAfterPublicTest()
VerifyRecommendationsMissing(<StructureDeclaration>Public |</StructureDeclaration>, "Friend")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ProtectedFriendNotAfterPublicTest()
VerifyRecommendationsMissing(<StructureDeclaration>Public |</StructureDeclaration>, "Protected Friend")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub FriendNotAfterProtectedTest()
VerifyRecommendationsMissing(<StructureDeclaration>Protected |</StructureDeclaration>, "Friend")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub FriendNotAfterProtectedFriendTest()
VerifyRecommendationsMissing(<StructureDeclaration>Protected Friend |</StructureDeclaration>, "Friend")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ProtectedNotAfterFriendTest()
VerifyRecommendationsMissing(<StructureDeclaration>Friend |</StructureDeclaration>, "Protected")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ProtectedNotAfterProtectedFriendTest()
VerifyRecommendationsMissing(<StructureDeclaration>Protected Friend |</StructureDeclaration>, "Protected")
End Sub
#End Region
#Region "Narrowing and Widening Keywords"
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NarrowingExistsTest()
VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "Narrowing")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WideningExistsTest()
VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "Widening")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NarrowingNotAfterWideningTest()
VerifyRecommendationsMissing(<StructureDeclaration>Widening |</StructureDeclaration>, "Narrowing")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WideningNotAfterNarrowingTest()
VerifyRecommendationsMissing(<StructureDeclaration>Narrowing |</StructureDeclaration>, "Widening")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NarrowingNotAfterProtectedTest()
VerifyRecommendationsMissing(<StructureDeclaration>Protected |</StructureDeclaration>, "Narrowing")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WideningNotAfterProtectedTest()
VerifyRecommendationsMissing(<StructureDeclaration>Protected |</StructureDeclaration>, "Widening")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NarrowingNotAfterPrivateTest()
VerifyRecommendationsMissing(<StructureDeclaration>Private |</StructureDeclaration>, "Narrowing")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WideningNotAfterPrivateTest()
VerifyRecommendationsMissing(<StructureDeclaration>Private |</StructureDeclaration>, "Widening")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NarrowingNotAfterProtectedFriendTest()
VerifyRecommendationsMissing(<StructureDeclaration>Protected Friend |</StructureDeclaration>, "Narrowing")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WideningNotAfterProtectedFriendTest()
VerifyRecommendationsMissing(<StructureDeclaration>Protected Friend |</StructureDeclaration>, "Widening")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NarrowingNotAfterMustOverrideTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustOverride |</StructureDeclaration>, "Narrowing")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WideningNotAfterMustOverrideTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustOverride |</StructureDeclaration>, "Widening")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NarrowingNotAfterMustInheritTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustInherit |</StructureDeclaration>, "Narrowing")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WideningNotAfterNotInheritableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotInheritable |</StructureDeclaration>, "Widening")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NarrowingNotAfterNotInheritableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotInheritable |</StructureDeclaration>, "Narrowing")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WideningNotAfterMustInheritTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustInherit |</StructureDeclaration>, "Widening")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NarrowingNotAfterNotOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotOverridable |</StructureDeclaration>, "Narrowing")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WideningNotAfterNotOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotOverridable |</StructureDeclaration>, "Widening")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NarrowingAfterOverloadsTest()
VerifyRecommendationsContain(<StructureDeclaration>Overloads |</StructureDeclaration>, "Narrowing")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WideningAfterOverloadsTest()
VerifyRecommendationsContain(<StructureDeclaration>Overloads |</StructureDeclaration>, "Widening")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NarrowingNotAfterOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overridable |</StructureDeclaration>, "Narrowing")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WideningNotAfterOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overridable |</StructureDeclaration>, "Widening")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NarrowingNotAfterPartialTest()
VerifyRecommendationsMissing(<StructureDeclaration>Partial |</StructureDeclaration>, "Narrowing")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WideningNotAfterPartialTest()
VerifyRecommendationsMissing(<StructureDeclaration>Partial |</StructureDeclaration>, "Widening")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NarrowingAfterSharedTest()
VerifyRecommendationsContain(<StructureDeclaration>Shared |</StructureDeclaration>, "Narrowing")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WideningAfterSharedTest()
VerifyRecommendationsContain(<StructureDeclaration>Shared |</StructureDeclaration>, "Widening")
End Sub
#End Region
#Region "MustInherit and NotInheritable Keywords"
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustInheritExistsTest()
VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "MustInherit")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotInheritableExistsTest()
VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "NotInheritable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustInheritNotAfterNotInheritableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotInheritable |</StructureDeclaration>, "MustInherit")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotInheritableNotAfterMustInheritTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustInherit |</StructureDeclaration>, "NotInheritable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustInheritNotAfterNarrowingTest()
VerifyRecommendationsMissing(<StructureDeclaration>Narrowing |</StructureDeclaration>, "MustInherit")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotInheritableNotAfterNarrowingTest()
VerifyRecommendationsMissing(<StructureDeclaration>Narrowing |</StructureDeclaration>, "NotInheritable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustInheritNotAfterWideningTest()
VerifyRecommendationsMissing(<StructureDeclaration>Widening |</StructureDeclaration>, "MustInherit")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotInheritableNotAfterWideningTest()
VerifyRecommendationsMissing(<StructureDeclaration>Widening |</StructureDeclaration>, "NotInheritable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustInheritNotAfterMustOverrideTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustOverride |</StructureDeclaration>, "MustInherit")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotInheritableNotAfterMustOverrideTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustOverride |</StructureDeclaration>, "NotInheritable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustInheritNotAfterNotOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotOverridable |</StructureDeclaration>, "MustInherit")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotInheritableNotAfterNotOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotOverridable |</StructureDeclaration>, "NotInheritable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustInheritNotAfterOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overridable |</StructureDeclaration>, "MustInherit")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotInheritableNotAfterOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overridable |</StructureDeclaration>, "NotInheritable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustInheritAfterPartialTest()
VerifyRecommendationsContain(<StructureDeclaration>Partial |</StructureDeclaration>, "MustInherit")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotInheritableAfterPartialTest()
VerifyRecommendationsContain(<StructureDeclaration>Partial |</StructureDeclaration>, "NotInheritable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustInheritNotAfterReadOnlyTest()
VerifyRecommendationsMissing(<StructureDeclaration>ReadOnly |</StructureDeclaration>, "MustInherit")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotInheritableNotAfterReadOnlyTest()
VerifyRecommendationsMissing(<StructureDeclaration>ReadOnly |</StructureDeclaration>, "NotInheritable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustInheritNotAfterSharedTest()
VerifyRecommendationsMissing(<StructureDeclaration>Shared |</StructureDeclaration>, "MustInherit")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotInheritableNotAfterSharedTest()
VerifyRecommendationsMissing(<StructureDeclaration>Shared |</StructureDeclaration>, "NotInheritable")
End Sub
#End Region
#Region "Overrides and Overridable Set of Keywords"
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverridesExistsTest()
VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "Overrides")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverridesNotAfterOverridesTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overrides |</StructureDeclaration>, "Overrides")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverridesNotAfterMustOverrideTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustOverride |</StructureDeclaration>, "Overrides")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverridesNotAfterOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overridable |</StructureDeclaration>, "Overrides")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverridesNotAfterNotOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotOverridable |</StructureDeclaration>, "Overrides")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverridesNotAfterShadowsTest()
VerifyRecommendationsMissing(<StructureDeclaration>Shadows |</StructureDeclaration>, "Overrides")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverridesAfterOverloadsTest()
VerifyRecommendationsContain(<StructureDeclaration>Overloads |</StructureDeclaration>, "Overrides")
End Sub
' ---------
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustOverrideMissingTest()
VerifyRecommendationsMissing(<StructureDeclaration>|</StructureDeclaration>, "MustOverride")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustOverrideNotAfterOverridesTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overrides |</StructureDeclaration>, "MustOverride")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustOverrideNotAfterMustOverrideTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustOverride |</StructureDeclaration>, "MustOverride")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustOverrideNotAfterOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overridable |</StructureDeclaration>, "MustOverride")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustOverrideNotAfterNotOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotOverridable |</StructureDeclaration>, "MustOverride")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustOverrideNotAfterShadowsTest()
VerifyRecommendationsMissing(<StructureDeclaration>Shadows |</StructureDeclaration>, "MustOverride")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustOverrideNotAfterOverloadsTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overloads |</StructureDeclaration>, "MustOverride")
End Sub
' ---------
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverridableMissingTest()
VerifyRecommendationsMissing(<StructureDeclaration>|</StructureDeclaration>, "Overridable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverridableNotAfterOverridesTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overrides |</StructureDeclaration>, "Overridable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverridableNotAfterMustOverrideTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustOverride |</StructureDeclaration>, "Overridable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverridableNotAfterOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overridable |</StructureDeclaration>, "Overridable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverridableNotAfterNotOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotOverridable |</StructureDeclaration>, "Overridable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverridableNotAfterShadowsTest()
VerifyRecommendationsMissing(<StructureDeclaration>Shadows |</StructureDeclaration>, "Overridable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverridableNotAfterOverloadsTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overloads |</StructureDeclaration>, "Overridable")
End Sub
' ---------
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotOverridableMissingTest()
VerifyRecommendationsMissing(<StructureDeclaration>|</StructureDeclaration>, "NotOverridable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotOverridableAfterOverridesTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overrides |</StructureDeclaration>, "NotOverridable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotOverridableNotAfterMustOverrideTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustOverride |</StructureDeclaration>, "NotOverridable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotOverridableNotAfterOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overridable |</StructureDeclaration>, "NotOverridable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotOverridableNotAfterNotOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotOverridable |</StructureDeclaration>, "NotOverridable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotOverridableNotAfterShadowsTest()
VerifyRecommendationsMissing(<StructureDeclaration>Shadows |</StructureDeclaration>, "NotOverridable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotOverridableNotAfterOverloadsTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overloads |</StructureDeclaration>, "NotOverridable")
End Sub
' ---------
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverloadsExistsTest()
VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "Overloads")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverloadsAfterOverridesTest()
VerifyRecommendationsContain(<StructureDeclaration>Overrides |</StructureDeclaration>, "Overloads")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverloadsNotAfterMustOverrideTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustOverride |</StructureDeclaration>, "Overloads")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverloadsNotAfterOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overridable |</StructureDeclaration>, "Overloads")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverloadsNotAfterNotOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotOverridable |</StructureDeclaration>, "Overloads")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverloadsNotAfterShadowsTest()
VerifyRecommendationsMissing(<StructureDeclaration>Shadows |</StructureDeclaration>, "Overloads")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverloadsNotAfterOverloadsTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overloads |</StructureDeclaration>, "Overloads")
End Sub
#End Region
#Region "ReadOnly and WriteOnly Keywords"
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ReadOnlyExistsTest()
VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "ReadOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WriteOnlyExistsTest()
VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "WriteOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ReadOnlyAfterSharedTest()
VerifyRecommendationsContain(<StructureDeclaration>Shared |</StructureDeclaration>, "ReadOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WriteOnlyAfterSharedTest()
VerifyRecommendationsContain(<StructureDeclaration>Shared |</StructureDeclaration>, "WriteOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ReadOnlyAfterDefaultTest()
VerifyRecommendationsContain(<StructureDeclaration>Default |</StructureDeclaration>, "ReadOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WriteOnlyAfterDefaultTest()
VerifyRecommendationsContain(<StructureDeclaration>Default |</StructureDeclaration>, "WriteOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ReadOnlyNotAfterMustInheritTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustInherit |</StructureDeclaration>, "ReadOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WriteOnlyNotAfterMustInheritTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustInherit |</StructureDeclaration>, "WriteOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ReadOnlyAfterOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overridable |</StructureDeclaration>, "ReadOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WriteOnlyAfterOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overridable |</StructureDeclaration>, "WriteOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ReadOnlyNotAfterNotOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotOverridable |</StructureDeclaration>, "ReadOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WriteOnlyAfterNotOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotOverridable |</StructureDeclaration>, "WriteOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ReadOnlyAfterOverloadsTest()
VerifyRecommendationsContain(<StructureDeclaration>Overloads |</StructureDeclaration>, "ReadOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WriteOnlyAfterOverloadsTest()
VerifyRecommendationsContain(<StructureDeclaration>Overloads |</StructureDeclaration>, "WriteOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ReadOnlyNotAfterMustOverrideTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustOverride |</StructureDeclaration>, "ReadOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WriteOnlyNotAfterMustOverrideTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustOverride |</StructureDeclaration>, "WriteOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ReadOnlyNotAfterNarrowingTest()
VerifyRecommendationsMissing(<StructureDeclaration>Narrowing |</StructureDeclaration>, "ReadOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WriteOnlyNotAfterNarrowingTest()
VerifyRecommendationsMissing(<StructureDeclaration>Narrowing |</StructureDeclaration>, "WriteOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ReadOnlyNotAfterPartialTest()
VerifyRecommendationsMissing(<StructureDeclaration>Partial |</StructureDeclaration>, "ReadOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WriteOnlyNotAfterPartialTest()
VerifyRecommendationsMissing(<StructureDeclaration>Partial |</StructureDeclaration>, "WriteOnly")
End Sub
#End Region
#Region "Partial Keyword"
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PartialExistsTest()
VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "Partial")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PartialNotAfterMustOverrideTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustOverride |</StructureDeclaration>, "Partial")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PartialNotAfterPartialTest()
VerifyRecommendationsMissing(<StructureDeclaration>Partial |</StructureDeclaration>, "Partial")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PartialAfterMustInheritTest()
VerifyRecommendationsContain(<StructureDeclaration>MustInherit |</StructureDeclaration>, "Partial")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PartialAfterNotInheritableTest()
VerifyRecommendationsContain(<StructureDeclaration>NotInheritable |</StructureDeclaration>, "Partial")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PartialNotAfterNotOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotOverridable |</StructureDeclaration>, "Partial")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PartialNotAfterOverloadsTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overloads |</StructureDeclaration>, "Partial")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PartialNotAfterOverridesTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overrides |</StructureDeclaration>, "Partial")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PartialNotAfterOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overridable |</StructureDeclaration>, "Partial")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PartialNotAfterReadOnlyTest()
VerifyRecommendationsMissing(<StructureDeclaration>ReadOnly |</StructureDeclaration>, "Partial")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PartialNotAfterWriteOnlyTest()
VerifyRecommendationsMissing(<StructureDeclaration>WriteOnly |</StructureDeclaration>, "Partial")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PartialNotAfterNarrowingTest()
VerifyRecommendationsMissing(<StructureDeclaration>Narrowing |</StructureDeclaration>, "Partial")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PartialNotAfterWideningTest()
VerifyRecommendationsMissing(<StructureDeclaration>Widening |</StructureDeclaration>, "Partial")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PartialNotAfterShadowsTest()
VerifyRecommendationsMissing(<StructureDeclaration>Shadows |</StructureDeclaration>, "Partial")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PartialNotAfterDefaultTest()
VerifyRecommendationsMissing(<StructureDeclaration>Default |</StructureDeclaration>, "Partial")
End Sub
#End Region
#Region "Shadows Keyword"
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ShadowsExistsTest()
VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "Shadows")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ShadowsNotAfterMustOverrideTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustOverride |</StructureDeclaration>, "Shadows")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ShadowsNotAfterMustInheritTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustInherit |</StructureDeclaration>, "Shadows")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ShadowsNotAfterNotInheritableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotInheritable |</StructureDeclaration>, "Shadows")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ShadowsAfterNotOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotOverridable |</StructureDeclaration>, "Shadows")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ShadowsNotAfterOverloadsTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overloads |</StructureDeclaration>, "Shadows")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ShadowsNotAfterOverridesTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overrides |</StructureDeclaration>, "Shadows")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ShadowsNotAfterOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overridable |</StructureDeclaration>, "Shadows")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ShadowsAfterReadOnlyTest()
VerifyRecommendationsContain(<StructureDeclaration>ReadOnly |</StructureDeclaration>, "Shadows")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ShadowsAfterWriteOnlyTest()
VerifyRecommendationsContain(<StructureDeclaration>WriteOnly |</StructureDeclaration>, "Shadows")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ShadowsAfterNarrowingTest()
VerifyRecommendationsContain(<StructureDeclaration>Narrowing |</StructureDeclaration>, "Shadows")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ShadowsAfterWideningTest()
VerifyRecommendationsContain(<StructureDeclaration>Widening |</StructureDeclaration>, "Shadows")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ShadowsNotAfterShadowsTest()
VerifyRecommendationsMissing(<StructureDeclaration>Shadows |</StructureDeclaration>, "Shadows")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ShadowsAfterDefaultTest()
VerifyRecommendationsContain(<StructureDeclaration>Default |</StructureDeclaration>, "Shadows")
End Sub
#End Region
#Region "Shared Keyword"
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub SharedDoesExistTest()
VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "Shared")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub SharedDoesNotExistAfterSharedTest()
VerifyRecommendationsMissing(<StructureDeclaration>Shared |</StructureDeclaration>, "Shared")
End Sub
#End Region
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations.ModifierKeywordRecommenderTests
Public Class InsideStructureDeclaration
#Region "Scope Keywords"
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PublicExistsTest()
VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "Public")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ProtectedMissingTest()
VerifyRecommendationsMissing(<StructureDeclaration>|</StructureDeclaration>, "Protected")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PrivateExistsTest()
VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "Private")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub FriendExistsTest()
VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "Friend")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ProtectedFriendMissingTest()
VerifyRecommendationsMissing(<StructureDeclaration>|</StructureDeclaration>, "Protected Friend")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PublicNotAfterPublicTest()
VerifyRecommendationsMissing(<StructureDeclaration>Public |</StructureDeclaration>, "Public")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ProtectedNotAfterPublicTest()
VerifyRecommendationsMissing(<StructureDeclaration>Public |</StructureDeclaration>, "Protected")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PrivateNotAfterPublicTest()
VerifyRecommendationsMissing(<StructureDeclaration>Public |</StructureDeclaration>, "Private")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub FriendNotAfterPublicTest()
VerifyRecommendationsMissing(<StructureDeclaration>Public |</StructureDeclaration>, "Friend")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ProtectedFriendNotAfterPublicTest()
VerifyRecommendationsMissing(<StructureDeclaration>Public |</StructureDeclaration>, "Protected Friend")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub FriendNotAfterProtectedTest()
VerifyRecommendationsMissing(<StructureDeclaration>Protected |</StructureDeclaration>, "Friend")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub FriendNotAfterProtectedFriendTest()
VerifyRecommendationsMissing(<StructureDeclaration>Protected Friend |</StructureDeclaration>, "Friend")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ProtectedNotAfterFriendTest()
VerifyRecommendationsMissing(<StructureDeclaration>Friend |</StructureDeclaration>, "Protected")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ProtectedNotAfterProtectedFriendTest()
VerifyRecommendationsMissing(<StructureDeclaration>Protected Friend |</StructureDeclaration>, "Protected")
End Sub
#End Region
#Region "Narrowing and Widening Keywords"
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NarrowingExistsTest()
VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "Narrowing")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WideningExistsTest()
VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "Widening")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NarrowingNotAfterWideningTest()
VerifyRecommendationsMissing(<StructureDeclaration>Widening |</StructureDeclaration>, "Narrowing")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WideningNotAfterNarrowingTest()
VerifyRecommendationsMissing(<StructureDeclaration>Narrowing |</StructureDeclaration>, "Widening")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NarrowingNotAfterProtectedTest()
VerifyRecommendationsMissing(<StructureDeclaration>Protected |</StructureDeclaration>, "Narrowing")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WideningNotAfterProtectedTest()
VerifyRecommendationsMissing(<StructureDeclaration>Protected |</StructureDeclaration>, "Widening")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NarrowingNotAfterPrivateTest()
VerifyRecommendationsMissing(<StructureDeclaration>Private |</StructureDeclaration>, "Narrowing")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WideningNotAfterPrivateTest()
VerifyRecommendationsMissing(<StructureDeclaration>Private |</StructureDeclaration>, "Widening")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NarrowingNotAfterProtectedFriendTest()
VerifyRecommendationsMissing(<StructureDeclaration>Protected Friend |</StructureDeclaration>, "Narrowing")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WideningNotAfterProtectedFriendTest()
VerifyRecommendationsMissing(<StructureDeclaration>Protected Friend |</StructureDeclaration>, "Widening")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NarrowingNotAfterMustOverrideTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustOverride |</StructureDeclaration>, "Narrowing")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WideningNotAfterMustOverrideTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustOverride |</StructureDeclaration>, "Widening")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NarrowingNotAfterMustInheritTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustInherit |</StructureDeclaration>, "Narrowing")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WideningNotAfterNotInheritableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotInheritable |</StructureDeclaration>, "Widening")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NarrowingNotAfterNotInheritableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotInheritable |</StructureDeclaration>, "Narrowing")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WideningNotAfterMustInheritTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustInherit |</StructureDeclaration>, "Widening")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NarrowingNotAfterNotOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotOverridable |</StructureDeclaration>, "Narrowing")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WideningNotAfterNotOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotOverridable |</StructureDeclaration>, "Widening")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NarrowingAfterOverloadsTest()
VerifyRecommendationsContain(<StructureDeclaration>Overloads |</StructureDeclaration>, "Narrowing")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WideningAfterOverloadsTest()
VerifyRecommendationsContain(<StructureDeclaration>Overloads |</StructureDeclaration>, "Widening")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NarrowingNotAfterOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overridable |</StructureDeclaration>, "Narrowing")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WideningNotAfterOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overridable |</StructureDeclaration>, "Widening")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NarrowingNotAfterPartialTest()
VerifyRecommendationsMissing(<StructureDeclaration>Partial |</StructureDeclaration>, "Narrowing")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WideningNotAfterPartialTest()
VerifyRecommendationsMissing(<StructureDeclaration>Partial |</StructureDeclaration>, "Widening")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NarrowingAfterSharedTest()
VerifyRecommendationsContain(<StructureDeclaration>Shared |</StructureDeclaration>, "Narrowing")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WideningAfterSharedTest()
VerifyRecommendationsContain(<StructureDeclaration>Shared |</StructureDeclaration>, "Widening")
End Sub
#End Region
#Region "MustInherit and NotInheritable Keywords"
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustInheritExistsTest()
VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "MustInherit")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotInheritableExistsTest()
VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "NotInheritable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustInheritNotAfterNotInheritableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotInheritable |</StructureDeclaration>, "MustInherit")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotInheritableNotAfterMustInheritTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustInherit |</StructureDeclaration>, "NotInheritable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustInheritNotAfterNarrowingTest()
VerifyRecommendationsMissing(<StructureDeclaration>Narrowing |</StructureDeclaration>, "MustInherit")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotInheritableNotAfterNarrowingTest()
VerifyRecommendationsMissing(<StructureDeclaration>Narrowing |</StructureDeclaration>, "NotInheritable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustInheritNotAfterWideningTest()
VerifyRecommendationsMissing(<StructureDeclaration>Widening |</StructureDeclaration>, "MustInherit")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotInheritableNotAfterWideningTest()
VerifyRecommendationsMissing(<StructureDeclaration>Widening |</StructureDeclaration>, "NotInheritable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustInheritNotAfterMustOverrideTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustOverride |</StructureDeclaration>, "MustInherit")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotInheritableNotAfterMustOverrideTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustOverride |</StructureDeclaration>, "NotInheritable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustInheritNotAfterNotOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotOverridable |</StructureDeclaration>, "MustInherit")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotInheritableNotAfterNotOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotOverridable |</StructureDeclaration>, "NotInheritable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustInheritNotAfterOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overridable |</StructureDeclaration>, "MustInherit")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotInheritableNotAfterOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overridable |</StructureDeclaration>, "NotInheritable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustInheritAfterPartialTest()
VerifyRecommendationsContain(<StructureDeclaration>Partial |</StructureDeclaration>, "MustInherit")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotInheritableAfterPartialTest()
VerifyRecommendationsContain(<StructureDeclaration>Partial |</StructureDeclaration>, "NotInheritable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustInheritNotAfterReadOnlyTest()
VerifyRecommendationsMissing(<StructureDeclaration>ReadOnly |</StructureDeclaration>, "MustInherit")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotInheritableNotAfterReadOnlyTest()
VerifyRecommendationsMissing(<StructureDeclaration>ReadOnly |</StructureDeclaration>, "NotInheritable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustInheritNotAfterSharedTest()
VerifyRecommendationsMissing(<StructureDeclaration>Shared |</StructureDeclaration>, "MustInherit")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotInheritableNotAfterSharedTest()
VerifyRecommendationsMissing(<StructureDeclaration>Shared |</StructureDeclaration>, "NotInheritable")
End Sub
#End Region
#Region "Overrides and Overridable Set of Keywords"
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverridesExistsTest()
VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "Overrides")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverridesNotAfterOverridesTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overrides |</StructureDeclaration>, "Overrides")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverridesNotAfterMustOverrideTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustOverride |</StructureDeclaration>, "Overrides")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverridesNotAfterOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overridable |</StructureDeclaration>, "Overrides")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverridesNotAfterNotOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotOverridable |</StructureDeclaration>, "Overrides")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverridesNotAfterShadowsTest()
VerifyRecommendationsMissing(<StructureDeclaration>Shadows |</StructureDeclaration>, "Overrides")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverridesAfterOverloadsTest()
VerifyRecommendationsContain(<StructureDeclaration>Overloads |</StructureDeclaration>, "Overrides")
End Sub
' ---------
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustOverrideMissingTest()
VerifyRecommendationsMissing(<StructureDeclaration>|</StructureDeclaration>, "MustOverride")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustOverrideNotAfterOverridesTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overrides |</StructureDeclaration>, "MustOverride")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustOverrideNotAfterMustOverrideTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustOverride |</StructureDeclaration>, "MustOverride")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustOverrideNotAfterOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overridable |</StructureDeclaration>, "MustOverride")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustOverrideNotAfterNotOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotOverridable |</StructureDeclaration>, "MustOverride")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustOverrideNotAfterShadowsTest()
VerifyRecommendationsMissing(<StructureDeclaration>Shadows |</StructureDeclaration>, "MustOverride")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub MustOverrideNotAfterOverloadsTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overloads |</StructureDeclaration>, "MustOverride")
End Sub
' ---------
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverridableMissingTest()
VerifyRecommendationsMissing(<StructureDeclaration>|</StructureDeclaration>, "Overridable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverridableNotAfterOverridesTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overrides |</StructureDeclaration>, "Overridable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverridableNotAfterMustOverrideTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustOverride |</StructureDeclaration>, "Overridable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverridableNotAfterOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overridable |</StructureDeclaration>, "Overridable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverridableNotAfterNotOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotOverridable |</StructureDeclaration>, "Overridable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverridableNotAfterShadowsTest()
VerifyRecommendationsMissing(<StructureDeclaration>Shadows |</StructureDeclaration>, "Overridable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverridableNotAfterOverloadsTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overloads |</StructureDeclaration>, "Overridable")
End Sub
' ---------
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotOverridableMissingTest()
VerifyRecommendationsMissing(<StructureDeclaration>|</StructureDeclaration>, "NotOverridable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotOverridableAfterOverridesTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overrides |</StructureDeclaration>, "NotOverridable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotOverridableNotAfterMustOverrideTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustOverride |</StructureDeclaration>, "NotOverridable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotOverridableNotAfterOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overridable |</StructureDeclaration>, "NotOverridable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotOverridableNotAfterNotOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotOverridable |</StructureDeclaration>, "NotOverridable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotOverridableNotAfterShadowsTest()
VerifyRecommendationsMissing(<StructureDeclaration>Shadows |</StructureDeclaration>, "NotOverridable")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotOverridableNotAfterOverloadsTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overloads |</StructureDeclaration>, "NotOverridable")
End Sub
' ---------
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverloadsExistsTest()
VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "Overloads")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverloadsAfterOverridesTest()
VerifyRecommendationsContain(<StructureDeclaration>Overrides |</StructureDeclaration>, "Overloads")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverloadsNotAfterMustOverrideTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustOverride |</StructureDeclaration>, "Overloads")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverloadsNotAfterOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overridable |</StructureDeclaration>, "Overloads")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverloadsNotAfterNotOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotOverridable |</StructureDeclaration>, "Overloads")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverloadsNotAfterShadowsTest()
VerifyRecommendationsMissing(<StructureDeclaration>Shadows |</StructureDeclaration>, "Overloads")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OverloadsNotAfterOverloadsTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overloads |</StructureDeclaration>, "Overloads")
End Sub
#End Region
#Region "ReadOnly and WriteOnly Keywords"
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ReadOnlyExistsTest()
VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "ReadOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WriteOnlyExistsTest()
VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "WriteOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ReadOnlyAfterSharedTest()
VerifyRecommendationsContain(<StructureDeclaration>Shared |</StructureDeclaration>, "ReadOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WriteOnlyAfterSharedTest()
VerifyRecommendationsContain(<StructureDeclaration>Shared |</StructureDeclaration>, "WriteOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ReadOnlyAfterDefaultTest()
VerifyRecommendationsContain(<StructureDeclaration>Default |</StructureDeclaration>, "ReadOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WriteOnlyAfterDefaultTest()
VerifyRecommendationsContain(<StructureDeclaration>Default |</StructureDeclaration>, "WriteOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ReadOnlyNotAfterMustInheritTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustInherit |</StructureDeclaration>, "ReadOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WriteOnlyNotAfterMustInheritTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustInherit |</StructureDeclaration>, "WriteOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ReadOnlyAfterOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overridable |</StructureDeclaration>, "ReadOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WriteOnlyAfterOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overridable |</StructureDeclaration>, "WriteOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ReadOnlyNotAfterNotOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotOverridable |</StructureDeclaration>, "ReadOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WriteOnlyAfterNotOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotOverridable |</StructureDeclaration>, "WriteOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ReadOnlyAfterOverloadsTest()
VerifyRecommendationsContain(<StructureDeclaration>Overloads |</StructureDeclaration>, "ReadOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WriteOnlyAfterOverloadsTest()
VerifyRecommendationsContain(<StructureDeclaration>Overloads |</StructureDeclaration>, "WriteOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ReadOnlyNotAfterMustOverrideTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustOverride |</StructureDeclaration>, "ReadOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WriteOnlyNotAfterMustOverrideTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustOverride |</StructureDeclaration>, "WriteOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ReadOnlyNotAfterNarrowingTest()
VerifyRecommendationsMissing(<StructureDeclaration>Narrowing |</StructureDeclaration>, "ReadOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WriteOnlyNotAfterNarrowingTest()
VerifyRecommendationsMissing(<StructureDeclaration>Narrowing |</StructureDeclaration>, "WriteOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ReadOnlyNotAfterPartialTest()
VerifyRecommendationsMissing(<StructureDeclaration>Partial |</StructureDeclaration>, "ReadOnly")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub WriteOnlyNotAfterPartialTest()
VerifyRecommendationsMissing(<StructureDeclaration>Partial |</StructureDeclaration>, "WriteOnly")
End Sub
#End Region
#Region "Partial Keyword"
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PartialExistsTest()
VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "Partial")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PartialNotAfterMustOverrideTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustOverride |</StructureDeclaration>, "Partial")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PartialNotAfterPartialTest()
VerifyRecommendationsMissing(<StructureDeclaration>Partial |</StructureDeclaration>, "Partial")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PartialAfterMustInheritTest()
VerifyRecommendationsContain(<StructureDeclaration>MustInherit |</StructureDeclaration>, "Partial")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PartialAfterNotInheritableTest()
VerifyRecommendationsContain(<StructureDeclaration>NotInheritable |</StructureDeclaration>, "Partial")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PartialNotAfterNotOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotOverridable |</StructureDeclaration>, "Partial")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PartialNotAfterOverloadsTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overloads |</StructureDeclaration>, "Partial")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PartialNotAfterOverridesTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overrides |</StructureDeclaration>, "Partial")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PartialNotAfterOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overridable |</StructureDeclaration>, "Partial")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PartialNotAfterReadOnlyTest()
VerifyRecommendationsMissing(<StructureDeclaration>ReadOnly |</StructureDeclaration>, "Partial")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PartialNotAfterWriteOnlyTest()
VerifyRecommendationsMissing(<StructureDeclaration>WriteOnly |</StructureDeclaration>, "Partial")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PartialNotAfterNarrowingTest()
VerifyRecommendationsMissing(<StructureDeclaration>Narrowing |</StructureDeclaration>, "Partial")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PartialNotAfterWideningTest()
VerifyRecommendationsMissing(<StructureDeclaration>Widening |</StructureDeclaration>, "Partial")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PartialNotAfterShadowsTest()
VerifyRecommendationsMissing(<StructureDeclaration>Shadows |</StructureDeclaration>, "Partial")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub PartialNotAfterDefaultTest()
VerifyRecommendationsMissing(<StructureDeclaration>Default |</StructureDeclaration>, "Partial")
End Sub
#End Region
#Region "Shadows Keyword"
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ShadowsExistsTest()
VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "Shadows")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ShadowsNotAfterMustOverrideTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustOverride |</StructureDeclaration>, "Shadows")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ShadowsNotAfterMustInheritTest()
VerifyRecommendationsMissing(<StructureDeclaration>MustInherit |</StructureDeclaration>, "Shadows")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ShadowsNotAfterNotInheritableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotInheritable |</StructureDeclaration>, "Shadows")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ShadowsAfterNotOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>NotOverridable |</StructureDeclaration>, "Shadows")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ShadowsNotAfterOverloadsTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overloads |</StructureDeclaration>, "Shadows")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ShadowsNotAfterOverridesTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overrides |</StructureDeclaration>, "Shadows")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ShadowsNotAfterOverridableTest()
VerifyRecommendationsMissing(<StructureDeclaration>Overridable |</StructureDeclaration>, "Shadows")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ShadowsAfterReadOnlyTest()
VerifyRecommendationsContain(<StructureDeclaration>ReadOnly |</StructureDeclaration>, "Shadows")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ShadowsAfterWriteOnlyTest()
VerifyRecommendationsContain(<StructureDeclaration>WriteOnly |</StructureDeclaration>, "Shadows")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ShadowsAfterNarrowingTest()
VerifyRecommendationsContain(<StructureDeclaration>Narrowing |</StructureDeclaration>, "Shadows")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ShadowsAfterWideningTest()
VerifyRecommendationsContain(<StructureDeclaration>Widening |</StructureDeclaration>, "Shadows")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ShadowsNotAfterShadowsTest()
VerifyRecommendationsMissing(<StructureDeclaration>Shadows |</StructureDeclaration>, "Shadows")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ShadowsAfterDefaultTest()
VerifyRecommendationsContain(<StructureDeclaration>Default |</StructureDeclaration>, "Shadows")
End Sub
#End Region
#Region "Shared Keyword"
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub SharedDoesExistTest()
VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "Shared")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub SharedDoesNotExistAfterSharedTest()
VerifyRecommendationsMissing(<StructureDeclaration>Shared |</StructureDeclaration>, "Shared")
End Sub
#End Region
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Compilers/CSharp/Portable/Utilities/ValueSetFactory.StringTC.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp
{
internal static partial class ValueSetFactory
{
private struct StringTC : IEquatableValueTC<string>
{
string IEquatableValueTC<string>.FromConstantValue(ConstantValue constantValue)
{
var result = constantValue.IsBad ? string.Empty : constantValue.StringValue;
Debug.Assert(result != null);
return result;
}
string[] IEquatableValueTC<string>.RandomValues(int count, Random random, int scope)
{
Debug.Assert(count > 0);
Debug.Assert(scope >= count);
string[] result = new string[count];
int next = 0;
for (int i = 0; i < scope; i++)
{
int need = count - next;
int remain = scope - i;
if (random.NextDouble() * remain < need)
{
result[next++] = i.ToString();
}
}
Debug.Assert(next == count);
return result;
}
ConstantValue IEquatableValueTC<string>.ToConstantValue(string value) => ConstantValue.Create(value);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp
{
internal static partial class ValueSetFactory
{
private struct StringTC : IEquatableValueTC<string>
{
string IEquatableValueTC<string>.FromConstantValue(ConstantValue constantValue)
{
var result = constantValue.IsBad ? string.Empty : constantValue.StringValue;
Debug.Assert(result != null);
return result;
}
string[] IEquatableValueTC<string>.RandomValues(int count, Random random, int scope)
{
Debug.Assert(count > 0);
Debug.Assert(scope >= count);
string[] result = new string[count];
int next = 0;
for (int i = 0; i < scope; i++)
{
int need = count - next;
int remain = scope - i;
if (random.NextDouble() * remain < need)
{
result[next++] = i.ToString();
}
}
Debug.Assert(next == count);
return result;
}
ConstantValue IEquatableValueTC<string>.ToConstantValue(string value) => ConstantValue.Create(value);
}
}
}
| -1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Compilers/Test/Core/FX/MonoHelpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public static class MonoHelpers
{
public static bool IsRunningOnMono() => Roslyn.Test.Utilities.ExecutionConditionUtil.IsMonoDesktop;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public static class MonoHelpers
{
public static bool IsRunningOnMono() => Roslyn.Test.Utilities.ExecutionConditionUtil.IsMonoDesktop;
}
}
| -1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/EditorFeatures/CSharpTest/SignatureHelp/TupleConstructionSignatureHelpProviderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp
{
public class TupleConstructionSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests
{
internal override Type GetSignatureHelpProviderType()
=> typeof(TupleConstructionSignatureHelpProvider);
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InvocationAfterOpenParen()
{
var markup = @"
class C
{
(int, int) y = [|($$
|]}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("(int, int)", currentParameterIndex: 0, parameterDocumentation: ""));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InvocationWithNullableReferenceTypes()
{
var markup = @"
class C
{
(string?, string) y = [|($$
|]}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("(string?, string)", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[WorkItem(655607, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/655607")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestMissingTupleElement()
{
var markup = @"
class C
{
void M()
{
(a, ) = [|($$
|] }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("(object a, object)", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InvocationAfterOpenParen2()
{
var markup = @"
class C
{
(int, int) y = [|($$)|]
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("(int, int)", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InvocationAfterComma1()
{
var markup = @"
class C
{
(int, int) y = [|(1,$$
|]}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("(int, int)", currentParameterIndex: 1, parameterDocumentation: ""));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InvocationAfterComma2()
{
var markup = @"
class C
{
(int, int) y = [|(1,$$)|]
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("(int, int)", currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task ParameterIndexWithNameTyped()
{
var markup = @"
class C
{
(int a, int b) y = [|(b: $$
|]}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
// currentParameterIndex only considers the position in the argument list
// and not names, hence passing 0 even though the controller will highlight
// "int b" in the actual display
expectedOrderedItems.Add(new SignatureHelpTestItem("(int a, int b)", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/14277"), Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task NestedTuple()
{
var markup = @"
class C
{
(int a, (int b, int c)) y = [|(1, ($$
|]}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("(int b, int c)", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task NestedTupleWhenNotInferred()
{
var markup = @"
class C
{
(int, object) y = [|(1, ($$
|]}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("(int, object)", currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task NestedTupleWhenNotInferred2()
{
var markup = @"
class C
{
(int, object) y = [|(1, (2,$$
|]}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("(int, object)", currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task NestedTupleWhenNotInferred3()
{
var markup = @"
class C
{
(int, object) y = [|(1, ($$
|]}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("(int, object)", currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task NestedTupleWhenNotInferred4()
{
var markup = @"
class C
{
(object, object) y = [|(($$
|]}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("(object, object)", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task MultipleOverloads()
{
var markup = @"
class Program
{
static void Main(string[] args)
{
Do1([|($$)|])
}
static void Do1((int, int) i) { }
static void Do1((string, string) s) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("(int, int)", currentParameterIndex: 0));
expectedOrderedItems.Add(new SignatureHelpTestItem("(string, string)", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[WorkItem(14793, "https://github.com/dotnet/roslyn/issues/14793")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task DoNotCrashInLinkedFile()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if GOO
void bar()
{
}
#endif
void goo()
{
(int, string) x = ($$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"(int, string)", currentParameterIndex: 0);
await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, 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.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp
{
public class TupleConstructionSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests
{
internal override Type GetSignatureHelpProviderType()
=> typeof(TupleConstructionSignatureHelpProvider);
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InvocationAfterOpenParen()
{
var markup = @"
class C
{
(int, int) y = [|($$
|]}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("(int, int)", currentParameterIndex: 0, parameterDocumentation: ""));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InvocationWithNullableReferenceTypes()
{
var markup = @"
class C
{
(string?, string) y = [|($$
|]}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("(string?, string)", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[WorkItem(655607, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/655607")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestMissingTupleElement()
{
var markup = @"
class C
{
void M()
{
(a, ) = [|($$
|] }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("(object a, object)", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InvocationAfterOpenParen2()
{
var markup = @"
class C
{
(int, int) y = [|($$)|]
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("(int, int)", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InvocationAfterComma1()
{
var markup = @"
class C
{
(int, int) y = [|(1,$$
|]}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("(int, int)", currentParameterIndex: 1, parameterDocumentation: ""));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InvocationAfterComma2()
{
var markup = @"
class C
{
(int, int) y = [|(1,$$)|]
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("(int, int)", currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task ParameterIndexWithNameTyped()
{
var markup = @"
class C
{
(int a, int b) y = [|(b: $$
|]}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
// currentParameterIndex only considers the position in the argument list
// and not names, hence passing 0 even though the controller will highlight
// "int b" in the actual display
expectedOrderedItems.Add(new SignatureHelpTestItem("(int a, int b)", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/14277"), Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task NestedTuple()
{
var markup = @"
class C
{
(int a, (int b, int c)) y = [|(1, ($$
|]}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("(int b, int c)", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task NestedTupleWhenNotInferred()
{
var markup = @"
class C
{
(int, object) y = [|(1, ($$
|]}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("(int, object)", currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task NestedTupleWhenNotInferred2()
{
var markup = @"
class C
{
(int, object) y = [|(1, (2,$$
|]}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("(int, object)", currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task NestedTupleWhenNotInferred3()
{
var markup = @"
class C
{
(int, object) y = [|(1, ($$
|]}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("(int, object)", currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task NestedTupleWhenNotInferred4()
{
var markup = @"
class C
{
(object, object) y = [|(($$
|]}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("(object, object)", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task MultipleOverloads()
{
var markup = @"
class Program
{
static void Main(string[] args)
{
Do1([|($$)|])
}
static void Do1((int, int) i) { }
static void Do1((string, string) s) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("(int, int)", currentParameterIndex: 0));
expectedOrderedItems.Add(new SignatureHelpTestItem("(string, string)", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[WorkItem(14793, "https://github.com/dotnet/roslyn/issues/14793")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task DoNotCrashInLinkedFile()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if GOO
void bar()
{
}
#endif
void goo()
{
(int, string) x = ($$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"(int, string)", currentParameterIndex: 0);
await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false);
}
}
}
| -1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ConstKeywordRecommender.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class ConstKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
private static readonly ISet<SyntaxKind> s_validModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
{
SyntaxKind.NewKeyword,
SyntaxKind.PublicKeyword,
SyntaxKind.ProtectedKeyword,
SyntaxKind.InternalKeyword,
SyntaxKind.PrivateKeyword,
};
private static readonly ISet<SyntaxKind> s_validGlobalModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
{
SyntaxKind.NewKeyword,
SyntaxKind.PublicKeyword,
SyntaxKind.InternalKeyword,
SyntaxKind.PrivateKeyword,
};
public ConstKeywordRecommender()
: base(SyntaxKind.ConstKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return
IsMemberDeclarationContext(context, cancellationToken) ||
IsLocalVariableDeclaration(context);
}
private static bool IsMemberDeclarationContext(CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return
context.SyntaxTree.IsGlobalMemberDeclarationContext(context.Position, s_validGlobalModifiers, cancellationToken) ||
context.IsMemberDeclarationContext(
validModifiers: s_validModifiers,
validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations,
canBePartial: false,
cancellationToken: cancellationToken);
}
private static bool IsLocalVariableDeclaration(CSharpSyntaxContext context)
{
// cases:
// void Goo() {
// |
//
// |
return
context.IsStatementContext ||
context.IsGlobalStatementContext;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class ConstKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
private static readonly ISet<SyntaxKind> s_validModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
{
SyntaxKind.NewKeyword,
SyntaxKind.PublicKeyword,
SyntaxKind.ProtectedKeyword,
SyntaxKind.InternalKeyword,
SyntaxKind.PrivateKeyword,
};
private static readonly ISet<SyntaxKind> s_validGlobalModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
{
SyntaxKind.NewKeyword,
SyntaxKind.PublicKeyword,
SyntaxKind.InternalKeyword,
SyntaxKind.PrivateKeyword,
};
public ConstKeywordRecommender()
: base(SyntaxKind.ConstKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return
IsMemberDeclarationContext(context, cancellationToken) ||
IsLocalVariableDeclaration(context);
}
private static bool IsMemberDeclarationContext(CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return
context.SyntaxTree.IsGlobalMemberDeclarationContext(context.Position, s_validGlobalModifiers, cancellationToken) ||
context.IsMemberDeclarationContext(
validModifiers: s_validModifiers,
validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations,
canBePartial: false,
cancellationToken: cancellationToken);
}
private static bool IsLocalVariableDeclaration(CSharpSyntaxContext context)
{
// cases:
// void Goo() {
// |
//
// |
return
context.IsStatementContext ||
context.IsGlobalStatementContext;
}
}
}
| -1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/EditorFeatures/Core.Wpf/Peek/PeekableItem.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using Microsoft.VisualStudio.Language.Intellisense;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Peek
{
internal abstract class PeekableItem : IPeekableItem
{
protected readonly IPeekResultFactory PeekResultFactory;
protected PeekableItem(IPeekResultFactory peekResultFactory)
=> this.PeekResultFactory = peekResultFactory;
public string DisplayName =>
// This is unused, and was supposed to have been removed from IPeekableItem.
null;
public abstract IEnumerable<IPeekRelationship> Relationships { get; }
public abstract IPeekResultSource GetOrCreateResultSource(string relationshipName);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using Microsoft.VisualStudio.Language.Intellisense;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Peek
{
internal abstract class PeekableItem : IPeekableItem
{
protected readonly IPeekResultFactory PeekResultFactory;
protected PeekableItem(IPeekResultFactory peekResultFactory)
=> this.PeekResultFactory = peekResultFactory;
public string DisplayName =>
// This is unused, and was supposed to have been removed from IPeekableItem.
null;
public abstract IEnumerable<IPeekRelationship> Relationships { get; }
public abstract IPeekResultSource GetOrCreateResultSource(string relationshipName);
}
}
| -1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Features/Core/Portable/ImplementInterface/AbstractImplementInterfaceService.CodeAction_Method.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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 Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.ImplementInterface
{
internal abstract partial class AbstractImplementInterfaceService
{
internal partial class ImplementInterfaceCodeAction
{
private ISymbol GenerateMethod(
Compilation compilation,
IMethodSymbol method,
Accessibility accessibility,
DeclarationModifiers modifiers,
bool generateAbstractly,
bool useExplicitInterfaceSymbol,
string memberName)
{
var syntaxFacts = Document.GetRequiredLanguageService<ISyntaxFactsService>();
var updatedMethod = method.EnsureNonConflictingNames(State.ClassOrStructType, syntaxFacts);
updatedMethod = updatedMethod.RemoveInaccessibleAttributesAndAttributesOfTypes(
State.ClassOrStructType,
AttributesToRemove(compilation));
return CodeGenerationSymbolFactory.CreateMethodSymbol(
updatedMethod,
accessibility: accessibility,
modifiers: modifiers,
explicitInterfaceImplementations: useExplicitInterfaceSymbol ? ImmutableArray.Create(updatedMethod) : default,
name: memberName,
statements: generateAbstractly
? default
: ImmutableArray.Create(CreateStatement(compilation, updatedMethod)));
}
private SyntaxNode CreateStatement(Compilation compilation, IMethodSymbol method)
{
var factory = Document.GetLanguageService<SyntaxGenerator>();
return ThroughMember == null
? factory.CreateThrowNotImplementedStatement(compilation)
: factory.GenerateDelegateThroughMemberStatement(method, ThroughMember);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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 Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.ImplementInterface
{
internal abstract partial class AbstractImplementInterfaceService
{
internal partial class ImplementInterfaceCodeAction
{
private ISymbol GenerateMethod(
Compilation compilation,
IMethodSymbol method,
Accessibility accessibility,
DeclarationModifiers modifiers,
bool generateAbstractly,
bool useExplicitInterfaceSymbol,
string memberName)
{
var syntaxFacts = Document.GetRequiredLanguageService<ISyntaxFactsService>();
var updatedMethod = method.EnsureNonConflictingNames(State.ClassOrStructType, syntaxFacts);
updatedMethod = updatedMethod.RemoveInaccessibleAttributesAndAttributesOfTypes(
State.ClassOrStructType,
AttributesToRemove(compilation));
return CodeGenerationSymbolFactory.CreateMethodSymbol(
updatedMethod,
accessibility: accessibility,
modifiers: modifiers,
explicitInterfaceImplementations: useExplicitInterfaceSymbol ? ImmutableArray.Create(updatedMethod) : default,
name: memberName,
statements: generateAbstractly
? default
: ImmutableArray.Create(CreateStatement(compilation, updatedMethod)));
}
private SyntaxNode CreateStatement(Compilation compilation, IMethodSymbol method)
{
var factory = Document.GetLanguageService<SyntaxGenerator>();
return ThroughMember == null
? factory.CreateThrowNotImplementedStatement(compilation)
: factory.GenerateDelegateThroughMemberStatement(method, ThroughMember);
}
}
}
}
| -1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/EditorFeatures/CSharpTest2/Recommendations/FloatKeywordRecommenderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Completion.Providers;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class FloatKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClass_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalStatement_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalVariableDeclaration_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStackAlloc()
{
await VerifyKeywordAsync(
@"class C {
int* goo = stackalloc $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFixedStatement()
{
await VerifyKeywordAsync(
@"fixed ($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDelegateReturnType()
{
await VerifyKeywordAsync(
@"public delegate $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCastType()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var str = (($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCastType2()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var str = (($$)items) as string;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstInMemberContext()
{
await VerifyKeywordAsync(
@"class C {
const $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefInMemberContext()
{
await VerifyKeywordAsync(
@"class C {
ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefReadonlyInMemberContext()
{
await VerifyKeywordAsync(
@"class C {
ref readonly $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstInStatementContext()
{
await VerifyKeywordAsync(AddInsideMethod(
@"const $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefInStatementContext()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefReadonlyInStatementContext()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref readonly $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstLocalDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"const $$ int local;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefLocalDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref $$ int local;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefReadonlyLocalDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref readonly $$ int local;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefLocalFunction()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref $$ int Function();"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefReadonlyLocalFunction()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref readonly $$ int Function();"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefExpression()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref int x = ref $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInEmptyStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEnumBaseTypes()
{
await VerifyAbsenceAsync(
@"enum E : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType1()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType2()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<int,$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType3()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<int[],$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType4()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<IGoo<int?,byte*>,$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInBaseList()
{
await VerifyAbsenceAsync(
@"class C : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType_InBaseList()
{
await VerifyKeywordAsync(
@"class C : IList<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIs()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var v = goo is $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAs()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var v = goo as $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethod()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterField()
{
await VerifyKeywordAsync(
@"class C {
int i;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProperty()
{
await VerifyKeywordAsync(
@"class C {
int i { get; }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAttribute()
{
await VerifyKeywordAsync(
@"class C {
[goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideStruct()
{
await VerifyKeywordAsync(
@"struct S {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideInterface()
{
await VerifyKeywordAsync(
@"interface I {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideClass()
{
await VerifyKeywordAsync(
@"class C {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterPartial()
=> await VerifyAbsenceAsync(@"partial $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterNestedPartial()
{
await VerifyAbsenceAsync(
@"class C {
partial $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAbstract()
{
await VerifyKeywordAsync(
@"class C {
abstract $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedInternal()
{
await VerifyKeywordAsync(
@"class C {
internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedStaticPublic()
{
await VerifyKeywordAsync(
@"class C {
static public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPublicStatic()
{
await VerifyKeywordAsync(
@"class C {
public static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterVirtualPublic()
{
await VerifyKeywordAsync(
@"class C {
virtual public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPublic()
{
await VerifyKeywordAsync(
@"class C {
public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPrivate()
{
await VerifyKeywordAsync(
@"class C {
private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedProtected()
{
await VerifyKeywordAsync(
@"class C {
protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedSealed()
{
await VerifyKeywordAsync(
@"class C {
sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedStatic()
{
await VerifyKeywordAsync(
@"class C {
static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodOpenParen()
{
await VerifyKeywordAsync(
@"class C {
void Goo($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodComma()
{
await VerifyKeywordAsync(
@"class C {
void Goo(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodAttribute()
{
await VerifyKeywordAsync(
@"class C {
void Goo(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorOpenParen()
{
await VerifyKeywordAsync(
@"class C {
public C($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorComma()
{
await VerifyKeywordAsync(
@"class C {
public C(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorAttribute()
{
await VerifyKeywordAsync(
@"class C {
public C(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateOpenParen()
{
await VerifyKeywordAsync(
@"delegate void D($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateComma()
{
await VerifyKeywordAsync(
@"delegate void D(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateAttribute()
{
await VerifyKeywordAsync(
@"delegate void D(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterThis()
{
await VerifyKeywordAsync(
@"static class C {
public static void Goo(this $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRef()
{
await VerifyKeywordAsync(
@"class C {
void Goo(ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterOut()
{
await VerifyKeywordAsync(
@"class C {
void Goo(out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLambdaRef()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
System.Func<int, int> f = (ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLambdaOut()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
System.Func<int, int> f = (out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterParams()
{
await VerifyKeywordAsync(
@"class C {
void Goo(params $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInImplicitOperator()
{
await VerifyKeywordAsync(
@"class C {
public static implicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInExplicitOperator()
{
await VerifyKeywordAsync(
@"class C {
public static explicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerBracket()
{
await VerifyKeywordAsync(
@"class C {
int this[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerBracketComma()
{
await VerifyKeywordAsync(
@"class C {
int this[int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNewInExpression()
{
await VerifyKeywordAsync(AddInsideMethod(
@"new $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterOut2()
{
await VerifyKeywordAsync(
@"class C {
private static void RoundToFloat(double d, out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterOut3()
{
await VerifyKeywordAsync(
@"class C {
private static void RoundToFloat(double d, out $$ float f)");
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInTypeOf()
{
await VerifyKeywordAsync(AddInsideMethod(
@"typeof($$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDefault()
{
await VerifyKeywordAsync(AddInsideMethod(
@"default($$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInSizeOf()
{
await VerifyKeywordAsync(AddInsideMethod(
@"sizeof($$"));
}
[WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInObjectInitializerMemberContext()
{
await VerifyAbsenceAsync(@"
class C
{
public int x, y;
void M()
{
var c = new C { x = 2, y = 3, $$");
}
[WorkItem(546938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCrefContext()
{
await VerifyKeywordAsync(@"
class Program
{
/// <see cref=""$$"">
static void Main(string[] args)
{
}
}");
}
[WorkItem(546955, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCrefContextNotAfterDot()
{
await VerifyAbsenceAsync(@"
/// <see cref=""System.$$"" />
class C { }
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAsync()
=> await VerifyKeywordAsync(@"class c { async $$ }");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAsyncAsType()
=> await VerifyAbsenceAsync(@"class c { async async $$ }");
[WorkItem(1468, "https://github.com/dotnet/roslyn/issues/1468")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInCrefTypeParameter()
{
await VerifyAbsenceAsync(@"
using System;
/// <see cref=""List{$$}"" />
class C { }
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task Preselection()
{
await VerifyKeywordAsync(@"
class Program
{
static void Main(string[] args)
{
Helper($$)
}
static void Helper(float x) { }
}
");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInTupleWithinType()
{
await VerifyKeywordAsync(@"
class Program
{
($$
}");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInTupleWithinMember()
{
await VerifyKeywordAsync(@"
class Program
{
void Method()
{
($$
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerType()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerTypeAfterComma()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<int, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerTypeAfterModifier()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterDelegateAsterisk()
{
await VerifyAbsenceAsync(@"
class C
{
delegate*$$");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Completion.Providers;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class FloatKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClass_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalStatement_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalVariableDeclaration_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStackAlloc()
{
await VerifyKeywordAsync(
@"class C {
int* goo = stackalloc $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFixedStatement()
{
await VerifyKeywordAsync(
@"fixed ($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDelegateReturnType()
{
await VerifyKeywordAsync(
@"public delegate $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCastType()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var str = (($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCastType2()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var str = (($$)items) as string;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstInMemberContext()
{
await VerifyKeywordAsync(
@"class C {
const $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefInMemberContext()
{
await VerifyKeywordAsync(
@"class C {
ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefReadonlyInMemberContext()
{
await VerifyKeywordAsync(
@"class C {
ref readonly $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstInStatementContext()
{
await VerifyKeywordAsync(AddInsideMethod(
@"const $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefInStatementContext()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefReadonlyInStatementContext()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref readonly $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstLocalDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"const $$ int local;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefLocalDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref $$ int local;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefReadonlyLocalDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref readonly $$ int local;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefLocalFunction()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref $$ int Function();"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefReadonlyLocalFunction()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref readonly $$ int Function();"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRefExpression()
{
await VerifyKeywordAsync(AddInsideMethod(
@"ref int x = ref $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInEmptyStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEnumBaseTypes()
{
await VerifyAbsenceAsync(
@"enum E : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType1()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType2()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<int,$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType3()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<int[],$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType4()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<IGoo<int?,byte*>,$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInBaseList()
{
await VerifyAbsenceAsync(
@"class C : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType_InBaseList()
{
await VerifyKeywordAsync(
@"class C : IList<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIs()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var v = goo is $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAs()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var v = goo as $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethod()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterField()
{
await VerifyKeywordAsync(
@"class C {
int i;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProperty()
{
await VerifyKeywordAsync(
@"class C {
int i { get; }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAttribute()
{
await VerifyKeywordAsync(
@"class C {
[goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideStruct()
{
await VerifyKeywordAsync(
@"struct S {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideInterface()
{
await VerifyKeywordAsync(
@"interface I {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideClass()
{
await VerifyKeywordAsync(
@"class C {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterPartial()
=> await VerifyAbsenceAsync(@"partial $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterNestedPartial()
{
await VerifyAbsenceAsync(
@"class C {
partial $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAbstract()
{
await VerifyKeywordAsync(
@"class C {
abstract $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedInternal()
{
await VerifyKeywordAsync(
@"class C {
internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedStaticPublic()
{
await VerifyKeywordAsync(
@"class C {
static public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPublicStatic()
{
await VerifyKeywordAsync(
@"class C {
public static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterVirtualPublic()
{
await VerifyKeywordAsync(
@"class C {
virtual public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPublic()
{
await VerifyKeywordAsync(
@"class C {
public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPrivate()
{
await VerifyKeywordAsync(
@"class C {
private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedProtected()
{
await VerifyKeywordAsync(
@"class C {
protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedSealed()
{
await VerifyKeywordAsync(
@"class C {
sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedStatic()
{
await VerifyKeywordAsync(
@"class C {
static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodOpenParen()
{
await VerifyKeywordAsync(
@"class C {
void Goo($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodComma()
{
await VerifyKeywordAsync(
@"class C {
void Goo(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodAttribute()
{
await VerifyKeywordAsync(
@"class C {
void Goo(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorOpenParen()
{
await VerifyKeywordAsync(
@"class C {
public C($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorComma()
{
await VerifyKeywordAsync(
@"class C {
public C(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorAttribute()
{
await VerifyKeywordAsync(
@"class C {
public C(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateOpenParen()
{
await VerifyKeywordAsync(
@"delegate void D($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateComma()
{
await VerifyKeywordAsync(
@"delegate void D(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateAttribute()
{
await VerifyKeywordAsync(
@"delegate void D(int i, [Goo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterThis()
{
await VerifyKeywordAsync(
@"static class C {
public static void Goo(this $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRef()
{
await VerifyKeywordAsync(
@"class C {
void Goo(ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterOut()
{
await VerifyKeywordAsync(
@"class C {
void Goo(out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLambdaRef()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
System.Func<int, int> f = (ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLambdaOut()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {
System.Func<int, int> f = (out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterParams()
{
await VerifyKeywordAsync(
@"class C {
void Goo(params $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInImplicitOperator()
{
await VerifyKeywordAsync(
@"class C {
public static implicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInExplicitOperator()
{
await VerifyKeywordAsync(
@"class C {
public static explicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerBracket()
{
await VerifyKeywordAsync(
@"class C {
int this[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerBracketComma()
{
await VerifyKeywordAsync(
@"class C {
int this[int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNewInExpression()
{
await VerifyKeywordAsync(AddInsideMethod(
@"new $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterOut2()
{
await VerifyKeywordAsync(
@"class C {
private static void RoundToFloat(double d, out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterOut3()
{
await VerifyKeywordAsync(
@"class C {
private static void RoundToFloat(double d, out $$ float f)");
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInTypeOf()
{
await VerifyKeywordAsync(AddInsideMethod(
@"typeof($$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDefault()
{
await VerifyKeywordAsync(AddInsideMethod(
@"default($$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInSizeOf()
{
await VerifyKeywordAsync(AddInsideMethod(
@"sizeof($$"));
}
[WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInObjectInitializerMemberContext()
{
await VerifyAbsenceAsync(@"
class C
{
public int x, y;
void M()
{
var c = new C { x = 2, y = 3, $$");
}
[WorkItem(546938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCrefContext()
{
await VerifyKeywordAsync(@"
class Program
{
/// <see cref=""$$"">
static void Main(string[] args)
{
}
}");
}
[WorkItem(546955, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCrefContextNotAfterDot()
{
await VerifyAbsenceAsync(@"
/// <see cref=""System.$$"" />
class C { }
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAsync()
=> await VerifyKeywordAsync(@"class c { async $$ }");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAsyncAsType()
=> await VerifyAbsenceAsync(@"class c { async async $$ }");
[WorkItem(1468, "https://github.com/dotnet/roslyn/issues/1468")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInCrefTypeParameter()
{
await VerifyAbsenceAsync(@"
using System;
/// <see cref=""List{$$}"" />
class C { }
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task Preselection()
{
await VerifyKeywordAsync(@"
class Program
{
static void Main(string[] args)
{
Helper($$)
}
static void Helper(float x) { }
}
");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInTupleWithinType()
{
await VerifyKeywordAsync(@"
class Program
{
($$
}");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInTupleWithinMember()
{
await VerifyKeywordAsync(@"
class Program
{
void Method()
{
($$
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerType()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerTypeAfterComma()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<int, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFunctionPointerTypeAfterModifier()
{
await VerifyKeywordAsync(@"
class C
{
delegate*<ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterDelegateAsterisk()
{
await VerifyAbsenceAsync(@"
class C
{
delegate*$$");
}
}
}
| -1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Features/Core/Portable/GenerateType/GenerateTypeOptionsResult.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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;
namespace Microsoft.CodeAnalysis.GenerateType
{
internal class GenerateTypeOptionsResult
{
public static readonly GenerateTypeOptionsResult Cancelled = new(isCancelled: true);
public Accessibility Accessibility { get; }
public Document ExistingDocument { get; }
public bool IsCancelled { get; }
public bool IsNewFile { get; }
public IList<string> Folders { get; }
public string NewFileName { get; }
public Project Project { get; }
public TypeKind TypeKind { get; }
public string FullFilePath { get; }
public string TypeName { get; }
public string DefaultNamespace { get; }
public bool AreFoldersValidIdentifiers { get; }
public GenerateTypeOptionsResult(
Accessibility accessibility,
TypeKind typeKind,
string typeName,
Project project,
bool isNewFile,
string newFileName,
IList<string> folders,
string fullFilePath,
Document existingDocument,
bool areFoldersValidIdentifiers,
string defaultNamespace,
bool isCancelled = false)
{
Accessibility = accessibility;
TypeKind = typeKind;
TypeName = typeName;
Project = project;
IsNewFile = isNewFile;
NewFileName = newFileName;
Folders = folders;
FullFilePath = fullFilePath;
ExistingDocument = existingDocument;
AreFoldersValidIdentifiers = areFoldersValidIdentifiers;
DefaultNamespace = defaultNamespace;
IsCancelled = isCancelled;
}
private GenerateTypeOptionsResult(bool isCancelled)
=> IsCancelled = isCancelled;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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;
namespace Microsoft.CodeAnalysis.GenerateType
{
internal class GenerateTypeOptionsResult
{
public static readonly GenerateTypeOptionsResult Cancelled = new(isCancelled: true);
public Accessibility Accessibility { get; }
public Document ExistingDocument { get; }
public bool IsCancelled { get; }
public bool IsNewFile { get; }
public IList<string> Folders { get; }
public string NewFileName { get; }
public Project Project { get; }
public TypeKind TypeKind { get; }
public string FullFilePath { get; }
public string TypeName { get; }
public string DefaultNamespace { get; }
public bool AreFoldersValidIdentifiers { get; }
public GenerateTypeOptionsResult(
Accessibility accessibility,
TypeKind typeKind,
string typeName,
Project project,
bool isNewFile,
string newFileName,
IList<string> folders,
string fullFilePath,
Document existingDocument,
bool areFoldersValidIdentifiers,
string defaultNamespace,
bool isCancelled = false)
{
Accessibility = accessibility;
TypeKind = typeKind;
TypeName = typeName;
Project = project;
IsNewFile = isNewFile;
NewFileName = newFileName;
Folders = folders;
FullFilePath = fullFilePath;
ExistingDocument = existingDocument;
AreFoldersValidIdentifiers = areFoldersValidIdentifiers;
DefaultNamespace = defaultNamespace;
IsCancelled = isCancelled;
}
private GenerateTypeOptionsResult(bool isCancelled)
=> IsCancelled = isCancelled;
}
}
| -1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Compilers/Core/Portable/InternalUtilities/ThreadSafeFlagOperations.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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;
namespace Roslyn.Utilities
{
internal static class ThreadSafeFlagOperations
{
public static bool Set(ref int flags, int toSet)
{
int oldState, newState;
do
{
oldState = flags;
newState = oldState | toSet;
if (newState == oldState)
{
return false;
}
}
while (Interlocked.CompareExchange(ref flags, newState, oldState) != oldState);
return true;
}
public static bool Clear(ref int flags, int toClear)
{
int oldState, newState;
do
{
oldState = flags;
newState = oldState & ~toClear;
if (newState == oldState)
{
return false;
}
}
while (Interlocked.CompareExchange(ref flags, newState, oldState) != oldState);
return true;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
namespace Roslyn.Utilities
{
internal static class ThreadSafeFlagOperations
{
public static bool Set(ref int flags, int toSet)
{
int oldState, newState;
do
{
oldState = flags;
newState = oldState | toSet;
if (newState == oldState)
{
return false;
}
}
while (Interlocked.CompareExchange(ref flags, newState, oldState) != oldState);
return true;
}
public static bool Clear(ref int flags, int toClear)
{
int oldState, newState;
do
{
oldState = flags;
newState = oldState & ~toClear;
if (newState == oldState)
{
return false;
}
}
while (Interlocked.CompareExchange(ref flags, newState, oldState) != oldState);
return true;
}
}
}
| -1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/VisualStudio/Core/Impl/SolutionExplorer/SourceGeneratedFileItems/SourceGeneratedFileItem.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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 Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.Internal.VisualStudio.PlatformUI;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer
{
internal sealed partial class SourceGeneratedFileItem : BaseItem
{
private readonly string _languageName;
public SourceGeneratedFileItem(DocumentId documentId, string hintName, string languageName, Workspace workspace)
: base(name: hintName)
{
DocumentId = documentId;
HintName = hintName;
_languageName = languageName;
Workspace = workspace;
}
public DocumentId DocumentId { get; }
public string HintName { get; }
public Workspace Workspace { get; }
public override ImageMoniker IconMoniker =>
_languageName switch
{
LanguageNames.CSharp => KnownMonikers.CSFileNode,
LanguageNames.VisualBasic => KnownMonikers.VBFileNode,
_ => KnownMonikers.Document
};
public override object GetBrowseObject()
{
return new BrowseObject(this);
}
public override IInvocationController InvocationController => InvocationControllerImpl.Instance;
private sealed class InvocationControllerImpl : IInvocationController
{
public static IInvocationController Instance = new InvocationControllerImpl();
public bool Invoke(IEnumerable<object> items, InputSource inputSource, bool preview)
{
var didNavigate = false;
foreach (var item in items.OfType<SourceGeneratedFileItem>())
{
var documentNavigationService = item.Workspace.Services.GetService<IDocumentNavigationService>();
if (documentNavigationService != null)
{
// TODO: we're navigating back to the top of the file, do we have a way to just bring it to the focus and that's it?
// TODO: Use a threaded-wait-dialog here so we can cancel navigation.
didNavigate |= documentNavigationService.TryNavigateToPosition(item.Workspace, item.DocumentId, position: 0, CancellationToken.None);
}
}
return didNavigate;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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 Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.Internal.VisualStudio.PlatformUI;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer
{
internal sealed partial class SourceGeneratedFileItem : BaseItem
{
private readonly string _languageName;
public SourceGeneratedFileItem(DocumentId documentId, string hintName, string languageName, Workspace workspace)
: base(name: hintName)
{
DocumentId = documentId;
HintName = hintName;
_languageName = languageName;
Workspace = workspace;
}
public DocumentId DocumentId { get; }
public string HintName { get; }
public Workspace Workspace { get; }
public override ImageMoniker IconMoniker =>
_languageName switch
{
LanguageNames.CSharp => KnownMonikers.CSFileNode,
LanguageNames.VisualBasic => KnownMonikers.VBFileNode,
_ => KnownMonikers.Document
};
public override object GetBrowseObject()
{
return new BrowseObject(this);
}
public override IInvocationController InvocationController => InvocationControllerImpl.Instance;
private sealed class InvocationControllerImpl : IInvocationController
{
public static IInvocationController Instance = new InvocationControllerImpl();
public bool Invoke(IEnumerable<object> items, InputSource inputSource, bool preview)
{
var didNavigate = false;
foreach (var item in items.OfType<SourceGeneratedFileItem>())
{
var documentNavigationService = item.Workspace.Services.GetService<IDocumentNavigationService>();
if (documentNavigationService != null)
{
// TODO: we're navigating back to the top of the file, do we have a way to just bring it to the focus and that's it?
// TODO: Use a threaded-wait-dialog here so we can cancel navigation.
didNavigate |= documentNavigationService.TryNavigateToPosition(item.Workspace, item.DocumentId, position: 0, CancellationToken.None);
}
}
return didNavigate;
}
}
}
}
| -1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Analyzers/VisualBasic/CodeFixes/SimplifyLinqExpression/VisualBasicSimplifyLinqExpressionCodeFixProvider.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.LanguageServices
Imports Microsoft.CodeAnalysis.SimplifyLinqExpression
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.SimplifyLinqExpression
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.SimplifyLinqExpression), [Shared]>
Friend Class VisualBasicSimplifyLinqExpressionCodeFixProvider
Inherits AbstractSimplifyLinqExpressionCodeFixProvider(Of
InvocationExpressionSyntax, SimpleNameSyntax, 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()
End Sub
Protected Overrides ReadOnly Property SyntaxFacts As ISyntaxFacts = VisualBasicSyntaxFacts.Instance
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.LanguageServices
Imports Microsoft.CodeAnalysis.SimplifyLinqExpression
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.SimplifyLinqExpression
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.SimplifyLinqExpression), [Shared]>
Friend Class VisualBasicSimplifyLinqExpressionCodeFixProvider
Inherits AbstractSimplifyLinqExpressionCodeFixProvider(Of
InvocationExpressionSyntax, SimpleNameSyntax, 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()
End Sub
Protected Overrides ReadOnly Property SyntaxFacts As ISyntaxFacts = VisualBasicSyntaxFacts.Instance
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Extensions/ContextQuery/IsStatementTerminatingTokenVisitor.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
''' <summary>
''' A visitor that determines if the targetToken passed in the constructor can be considered
''' the end of the visited statement. Tokens in the token stream of the file after
''' targetToken are ignored. This means that in some cases, say "Throw" vs. "Throw x" there
''' is more than one keyword that could terminate the statement.
''' </summary>
Friend Class IsStatementTerminatingTokenVisitor
Inherits VisualBasicSyntaxVisitor(Of Boolean)
Private ReadOnly _targetToken As SyntaxToken
Public Sub New(targetToken As SyntaxToken)
_targetToken = targetToken
End Sub
Public Overrides Function DefaultVisit(node As SyntaxNode) As Boolean
' By default, it doesn't terminate
Return False
End Function
Public Overrides Function VisitAddRemoveHandlerStatement(node As AddRemoveHandlerStatementSyntax) As Boolean
Return TargetTokenMatches(GetExpressionTerminatingToken(node.DelegateExpression))
End Function
Public Overrides Function VisitAssignmentStatement(node As AssignmentStatementSyntax) As Boolean
Return TargetTokenMatches(GetExpressionTerminatingToken(node.Right))
End Function
Public Overrides Function VisitCallStatement(node As CallStatementSyntax) As Boolean
Return TargetTokenMatches(GetExpressionTerminatingToken(node.Invocation))
End Function
Public Overrides Function VisitExpressionStatement(node As ExpressionStatementSyntax) As Boolean
Return TargetTokenMatches(GetExpressionTerminatingToken(node.Expression))
End Function
Public Overrides Function VisitContinueStatement(node As ContinueStatementSyntax) As Boolean
Return TargetTokenMatches(node.BlockKeyword)
End Function
Public Overrides Function VisitEraseStatement(node As EraseStatementSyntax) As Boolean
Return TargetTokenMatches(GetExpressionTerminatingToken(node.Expressions.Last()))
End Function
Public Overrides Function VisitErrorStatement(node As ErrorStatementSyntax) As Boolean
Return TargetTokenMatches(GetExpressionTerminatingToken(node.ErrorNumber))
End Function
Public Overrides Function VisitExitStatement(node As ExitStatementSyntax) As Boolean
Return TargetTokenMatches(node.BlockKeyword)
End Function
Public Overrides Function VisitGoToStatement(node As GoToStatementSyntax) As Boolean
Return TargetTokenMatches(node.Label.LabelToken)
End Function
Public Overrides Function VisitLocalDeclarationStatement(node As LocalDeclarationStatementSyntax) As Boolean
Dim lastDeclarator = node.Declarators.Last()
If lastDeclarator.Initializer IsNot Nothing Then
Return TargetTokenMatches(GetExpressionTerminatingToken(lastDeclarator.Initializer.Value))
ElseIf lastDeclarator.AsClause IsNot Nothing Then
Return TargetTokenMatches(GetExpressionTerminatingToken(lastDeclarator.AsClause.Type))
Else
Return TargetTokenMatches(lastDeclarator.Names.Last().Identifier)
End If
End Function
Public Overrides Function VisitRaiseEventStatement(node As RaiseEventStatementSyntax) As Boolean
Dim argumentList = node.ArgumentList
If argumentList IsNot Nothing Then
Return TargetTokenMatches(argumentList.CloseParenToken)
Else
Return TargetTokenMatches(node.Name.Identifier)
End If
End Function
Public Overrides Function VisitReDimStatement(node As ReDimStatementSyntax) As Boolean
Dim lastClause = node.Clauses.Last()
If lastClause.ArrayBounds IsNot Nothing Then
Return TargetTokenMatches(lastClause.ArrayBounds.CloseParenToken)
Else
Return TargetTokenMatches(GetExpressionTerminatingToken(lastClause.Expression))
End If
End Function
Public Overrides Function VisitResumeStatement(node As ResumeStatementSyntax) As Boolean
If node.Label IsNot Nothing AndAlso TargetTokenMatches(node.Label.LabelToken) Then
Return True
End If
Return TargetTokenMatches(node.ResumeKeyword)
End Function
Public Overrides Function VisitReturnStatement(node As Microsoft.CodeAnalysis.VisualBasic.Syntax.ReturnStatementSyntax) As Boolean
' Do we need a return value?
Dim methodBlock = node.ReturnKeyword.GetAncestor(Of MethodBlockBaseSyntax)
If methodBlock IsNot Nothing AndAlso methodBlock.IsKind(SyntaxKind.FunctionBlock, SyntaxKind.GetAccessorBlock) Then
If node.Expression IsNot Nothing Then
If TargetTokenMatches(GetExpressionTerminatingToken(node.Expression)) Then
' We are terminating the return value properly, so we're good
Return True
End If
End If
End If
Return TargetTokenMatches(node.ReturnKeyword)
End Function
Public Overrides Function VisitStopOrEndStatement(node As StopOrEndStatementSyntax) As Boolean
Return TargetTokenMatches(node.StopOrEndKeyword)
End Function
Public Overrides Function VisitThrowStatement(node As ThrowStatementSyntax) As Boolean
If node.ThrowKeyword.HasAncestor(Of TryBlockSyntax)() Then
If node.Expression IsNot Nothing Then
If TargetTokenMatches(GetExpressionTerminatingToken(node.Expression)) Then
Return True
End If
End If
End If
Return TargetTokenMatches(node.ThrowKeyword)
End Function
Private Function TargetTokenMatches(token As SyntaxToken) As Boolean
Return token.Kind <> SyntaxKind.None AndAlso Not token.IsMissing AndAlso _targetToken = token
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.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
''' <summary>
''' A visitor that determines if the targetToken passed in the constructor can be considered
''' the end of the visited statement. Tokens in the token stream of the file after
''' targetToken are ignored. This means that in some cases, say "Throw" vs. "Throw x" there
''' is more than one keyword that could terminate the statement.
''' </summary>
Friend Class IsStatementTerminatingTokenVisitor
Inherits VisualBasicSyntaxVisitor(Of Boolean)
Private ReadOnly _targetToken As SyntaxToken
Public Sub New(targetToken As SyntaxToken)
_targetToken = targetToken
End Sub
Public Overrides Function DefaultVisit(node As SyntaxNode) As Boolean
' By default, it doesn't terminate
Return False
End Function
Public Overrides Function VisitAddRemoveHandlerStatement(node As AddRemoveHandlerStatementSyntax) As Boolean
Return TargetTokenMatches(GetExpressionTerminatingToken(node.DelegateExpression))
End Function
Public Overrides Function VisitAssignmentStatement(node As AssignmentStatementSyntax) As Boolean
Return TargetTokenMatches(GetExpressionTerminatingToken(node.Right))
End Function
Public Overrides Function VisitCallStatement(node As CallStatementSyntax) As Boolean
Return TargetTokenMatches(GetExpressionTerminatingToken(node.Invocation))
End Function
Public Overrides Function VisitExpressionStatement(node As ExpressionStatementSyntax) As Boolean
Return TargetTokenMatches(GetExpressionTerminatingToken(node.Expression))
End Function
Public Overrides Function VisitContinueStatement(node As ContinueStatementSyntax) As Boolean
Return TargetTokenMatches(node.BlockKeyword)
End Function
Public Overrides Function VisitEraseStatement(node As EraseStatementSyntax) As Boolean
Return TargetTokenMatches(GetExpressionTerminatingToken(node.Expressions.Last()))
End Function
Public Overrides Function VisitErrorStatement(node As ErrorStatementSyntax) As Boolean
Return TargetTokenMatches(GetExpressionTerminatingToken(node.ErrorNumber))
End Function
Public Overrides Function VisitExitStatement(node As ExitStatementSyntax) As Boolean
Return TargetTokenMatches(node.BlockKeyword)
End Function
Public Overrides Function VisitGoToStatement(node As GoToStatementSyntax) As Boolean
Return TargetTokenMatches(node.Label.LabelToken)
End Function
Public Overrides Function VisitLocalDeclarationStatement(node As LocalDeclarationStatementSyntax) As Boolean
Dim lastDeclarator = node.Declarators.Last()
If lastDeclarator.Initializer IsNot Nothing Then
Return TargetTokenMatches(GetExpressionTerminatingToken(lastDeclarator.Initializer.Value))
ElseIf lastDeclarator.AsClause IsNot Nothing Then
Return TargetTokenMatches(GetExpressionTerminatingToken(lastDeclarator.AsClause.Type))
Else
Return TargetTokenMatches(lastDeclarator.Names.Last().Identifier)
End If
End Function
Public Overrides Function VisitRaiseEventStatement(node As RaiseEventStatementSyntax) As Boolean
Dim argumentList = node.ArgumentList
If argumentList IsNot Nothing Then
Return TargetTokenMatches(argumentList.CloseParenToken)
Else
Return TargetTokenMatches(node.Name.Identifier)
End If
End Function
Public Overrides Function VisitReDimStatement(node As ReDimStatementSyntax) As Boolean
Dim lastClause = node.Clauses.Last()
If lastClause.ArrayBounds IsNot Nothing Then
Return TargetTokenMatches(lastClause.ArrayBounds.CloseParenToken)
Else
Return TargetTokenMatches(GetExpressionTerminatingToken(lastClause.Expression))
End If
End Function
Public Overrides Function VisitResumeStatement(node As ResumeStatementSyntax) As Boolean
If node.Label IsNot Nothing AndAlso TargetTokenMatches(node.Label.LabelToken) Then
Return True
End If
Return TargetTokenMatches(node.ResumeKeyword)
End Function
Public Overrides Function VisitReturnStatement(node As Microsoft.CodeAnalysis.VisualBasic.Syntax.ReturnStatementSyntax) As Boolean
' Do we need a return value?
Dim methodBlock = node.ReturnKeyword.GetAncestor(Of MethodBlockBaseSyntax)
If methodBlock IsNot Nothing AndAlso methodBlock.IsKind(SyntaxKind.FunctionBlock, SyntaxKind.GetAccessorBlock) Then
If node.Expression IsNot Nothing Then
If TargetTokenMatches(GetExpressionTerminatingToken(node.Expression)) Then
' We are terminating the return value properly, so we're good
Return True
End If
End If
End If
Return TargetTokenMatches(node.ReturnKeyword)
End Function
Public Overrides Function VisitStopOrEndStatement(node As StopOrEndStatementSyntax) As Boolean
Return TargetTokenMatches(node.StopOrEndKeyword)
End Function
Public Overrides Function VisitThrowStatement(node As ThrowStatementSyntax) As Boolean
If node.ThrowKeyword.HasAncestor(Of TryBlockSyntax)() Then
If node.Expression IsNot Nothing Then
If TargetTokenMatches(GetExpressionTerminatingToken(node.Expression)) Then
Return True
End If
End If
End If
Return TargetTokenMatches(node.ThrowKeyword)
End Function
Private Function TargetTokenMatches(token As SyntaxToken) As Boolean
Return token.Kind <> SyntaxKind.None AndAlso Not token.IsMissing AndAlso _targetToken = token
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/EditorFeatures/Test2/IntelliSense/AbstractIntellisenseQuickInfoBuilderTests.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.Text
Imports System.Threading
Imports Microsoft.CodeAnalysis.Classification
Imports Microsoft.CodeAnalysis.Editor.Host
Imports Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo
Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.QuickInfo
Imports Microsoft.VisualStudio.Core.Imaging
Imports Microsoft.VisualStudio.Imaging
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Adornments
Imports Moq
Imports VSQuickInfoItem = Microsoft.VisualStudio.Language.Intellisense.QuickInfoItem
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense
<UseExportProvider>
Public MustInherit Class AbstractIntellisenseQuickInfoBuilderTests
Protected Shared Async Function GetQuickInfoItemAsync(quickInfoItem As QuickInfoItem) As Task(Of VSQuickInfoItem)
Dim workspaceDefinition =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
$$
</Document>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(workspaceDefinition)
Dim solution = workspace.CurrentSolution
Dim cursorDocument = workspace.Documents.First(Function(d) d.CursorPosition.HasValue)
Dim cursorBuffer = cursorDocument.GetTextBuffer()
Dim document = workspace.CurrentSolution.GetDocument(cursorDocument.Id)
Dim trackingSpan = New Mock(Of ITrackingSpan)(MockBehavior.Strict) With {
.DefaultValue = DefaultValue.Mock
}
Dim threadingContext = workspace.ExportProvider.GetExportedValue(Of IThreadingContext)()
Dim streamingPresenter = workspace.ExportProvider.GetExport(Of IStreamingFindUsagesPresenter)()
Return Await IntellisenseQuickInfoBuilder.BuildItemAsync(trackingSpan.Object, quickInfoItem, document, threadingContext, streamingPresenter, CancellationToken.None)
End Using
End Function
Protected Shared Async Function GetQuickInfoItemAsync(workspaceDefinition As XElement, language As String) As Task(Of VSQuickInfoItem)
Using workspace = TestWorkspace.Create(workspaceDefinition)
Dim solution = workspace.CurrentSolution
Dim cursorDocument = workspace.Documents.First(Function(d) d.CursorPosition.HasValue)
Dim cursorPosition = cursorDocument.CursorPosition.Value
Dim cursorBuffer = cursorDocument.GetTextBuffer()
Dim document = workspace.CurrentSolution.GetDocument(cursorDocument.Id)
Dim languageServiceProvider = workspace.Services.GetLanguageServices(language)
Dim quickInfoService = languageServiceProvider.GetRequiredService(Of QuickInfoService)
Dim codeAnalysisQuickInfoItem = Await quickInfoService.GetQuickInfoAsync(document, cursorPosition, CancellationToken.None).ConfigureAwait(False)
Dim trackingSpan = New Mock(Of ITrackingSpan)(MockBehavior.Strict) With {
.DefaultValue = DefaultValue.Mock
}
Dim threadingContext = workspace.ExportProvider.GetExportedValue(Of IThreadingContext)()
Dim streamingPresenter = workspace.ExportProvider.GetExport(Of IStreamingFindUsagesPresenter)()
Return Await IntellisenseQuickInfoBuilder.BuildItemAsync(trackingSpan.Object, codeAnalysisQuickInfoItem, document, threadingContext, streamingPresenter, CancellationToken.None)
End Using
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Text
Imports System.Threading
Imports Microsoft.CodeAnalysis.Classification
Imports Microsoft.CodeAnalysis.Editor.Host
Imports Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo
Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.QuickInfo
Imports Microsoft.VisualStudio.Core.Imaging
Imports Microsoft.VisualStudio.Imaging
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Adornments
Imports Moq
Imports VSQuickInfoItem = Microsoft.VisualStudio.Language.Intellisense.QuickInfoItem
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense
<UseExportProvider>
Public MustInherit Class AbstractIntellisenseQuickInfoBuilderTests
Protected Shared Async Function GetQuickInfoItemAsync(quickInfoItem As QuickInfoItem) As Task(Of VSQuickInfoItem)
Dim workspaceDefinition =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
$$
</Document>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(workspaceDefinition)
Dim solution = workspace.CurrentSolution
Dim cursorDocument = workspace.Documents.First(Function(d) d.CursorPosition.HasValue)
Dim cursorBuffer = cursorDocument.GetTextBuffer()
Dim document = workspace.CurrentSolution.GetDocument(cursorDocument.Id)
Dim trackingSpan = New Mock(Of ITrackingSpan)(MockBehavior.Strict) With {
.DefaultValue = DefaultValue.Mock
}
Dim threadingContext = workspace.ExportProvider.GetExportedValue(Of IThreadingContext)()
Dim streamingPresenter = workspace.ExportProvider.GetExport(Of IStreamingFindUsagesPresenter)()
Return Await IntellisenseQuickInfoBuilder.BuildItemAsync(trackingSpan.Object, quickInfoItem, document, threadingContext, streamingPresenter, CancellationToken.None)
End Using
End Function
Protected Shared Async Function GetQuickInfoItemAsync(workspaceDefinition As XElement, language As String) As Task(Of VSQuickInfoItem)
Using workspace = TestWorkspace.Create(workspaceDefinition)
Dim solution = workspace.CurrentSolution
Dim cursorDocument = workspace.Documents.First(Function(d) d.CursorPosition.HasValue)
Dim cursorPosition = cursorDocument.CursorPosition.Value
Dim cursorBuffer = cursorDocument.GetTextBuffer()
Dim document = workspace.CurrentSolution.GetDocument(cursorDocument.Id)
Dim languageServiceProvider = workspace.Services.GetLanguageServices(language)
Dim quickInfoService = languageServiceProvider.GetRequiredService(Of QuickInfoService)
Dim codeAnalysisQuickInfoItem = Await quickInfoService.GetQuickInfoAsync(document, cursorPosition, CancellationToken.None).ConfigureAwait(False)
Dim trackingSpan = New Mock(Of ITrackingSpan)(MockBehavior.Strict) With {
.DefaultValue = DefaultValue.Mock
}
Dim threadingContext = workspace.ExportProvider.GetExportedValue(Of IThreadingContext)()
Dim streamingPresenter = workspace.ExportProvider.GetExport(Of IStreamingFindUsagesPresenter)()
Return Await IntellisenseQuickInfoBuilder.BuildItemAsync(trackingSpan.Object, codeAnalysisQuickInfoItem, document, threadingContext, streamingPresenter, CancellationToken.None)
End Using
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Features/LanguageServer/Protocol/Handler/Completion/CompletionHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Experiments;
using Microsoft.CodeAnalysis.LanguageServer.Handler.Completion;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text.Adornments;
using Roslyn.Utilities;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
/// <summary>
/// Handle a completion request.
/// </summary>
internal class CompletionHandler : IRequestHandler<LSP.CompletionParams, LSP.CompletionList?>
{
private readonly ImmutableHashSet<char> _csharpTriggerCharacters;
private readonly ImmutableHashSet<char> _vbTriggerCharacters;
private readonly CompletionListCache _completionListCache;
public string Method => LSP.Methods.TextDocumentCompletionName;
public bool MutatesSolutionState => false;
public bool RequiresLSPSolution => true;
public CompletionHandler(
IEnumerable<Lazy<CompletionProvider, CompletionProviderMetadata>> completionProviders,
CompletionListCache completionListCache)
{
_csharpTriggerCharacters = completionProviders.Where(lz => lz.Metadata.Language == LanguageNames.CSharp).SelectMany(
lz => GetTriggerCharacters(lz.Value)).ToImmutableHashSet();
_vbTriggerCharacters = completionProviders.Where(lz => lz.Metadata.Language == LanguageNames.VisualBasic).SelectMany(
lz => GetTriggerCharacters(lz.Value)).ToImmutableHashSet();
_completionListCache = completionListCache;
}
public LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.CompletionParams request) => request.TextDocument;
public async Task<LSP.CompletionList?> HandleRequestAsync(LSP.CompletionParams request, RequestContext context, CancellationToken cancellationToken)
{
var document = context.Document;
if (document == null)
{
return null;
}
// C# and VB share the same LSP language server, and thus share the same default trigger characters.
// We need to ensure the trigger character is valid in the document's language. For example, the '{'
// character, while a trigger character in VB, is not a trigger character in C#.
if (request.Context != null &&
request.Context.TriggerKind == LSP.CompletionTriggerKind.TriggerCharacter &&
!char.TryParse(request.Context.TriggerCharacter, out var triggerCharacter) &&
!char.IsLetterOrDigit(triggerCharacter) &&
!IsValidTriggerCharacterForDocument(document, triggerCharacter))
{
return null;
}
var completionOptions = await GetCompletionOptionsAsync(document, cancellationToken).ConfigureAwait(false);
var completionService = document.GetRequiredLanguageService<CompletionService>();
var documentText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var completionListResult = await GetFilteredCompletionListAsync(request, documentText, document, completionOptions, completionService, cancellationToken).ConfigureAwait(false);
if (completionListResult == null)
{
return null;
}
var (list, isIncomplete, resultId) = completionListResult.Value;
var lspVSClientCapability = context.ClientCapabilities.HasVisualStudioLspCapability() == true;
var snippetsSupported = context.ClientCapabilities.TextDocument?.Completion?.CompletionItem?.SnippetSupport ?? false;
var commitCharactersRuleCache = new Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]>(CommitCharacterArrayComparer.Instance);
// Feature flag to enable the return of TextEdits instead of InsertTexts (will increase payload size).
// Flag is defined in VisualStudio\Core\Def\PackageRegistration.pkgdef.
// We also check against the CompletionOption for test purposes only.
Contract.ThrowIfNull(context.Solution);
var featureFlagService = context.Solution.Workspace.Services.GetRequiredService<IExperimentationService>();
var returnTextEdits = featureFlagService.IsExperimentEnabled(WellKnownExperimentNames.LSPCompletion) ||
completionOptions.GetOption(CompletionOptions.ForceRoslynLSPCompletionExperiment, document.Project.Language);
TextSpan? defaultSpan = null;
LSP.Range? defaultRange = null;
if (returnTextEdits)
{
// We want to compute the document's text just once.
documentText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
// We use the first item in the completion list as our comparison point for span
// and range for optimization when generating the TextEdits later on.
var completionChange = await completionService.GetChangeAsync(
document, list.Items.First(), cancellationToken: cancellationToken).ConfigureAwait(false);
// If possible, we want to compute the item's span and range just once.
// Individual items can override this range later.
defaultSpan = completionChange.TextChange.Span;
defaultRange = ProtocolConversions.TextSpanToRange(defaultSpan.Value, documentText);
}
var supportsCompletionListData = context.ClientCapabilities.HasCompletionListDataCapability();
var completionResolveData = new CompletionResolveData()
{
ResultId = resultId,
};
var stringBuilder = new StringBuilder();
using var _ = ArrayBuilder<LSP.CompletionItem>.GetInstance(out var lspCompletionItems);
foreach (var item in list.Items)
{
var completionItemResolveData = supportsCompletionListData ? null : completionResolveData;
var lspCompletionItem = await CreateLSPCompletionItemAsync(
request, document, item, completionItemResolveData, lspVSClientCapability, commitCharactersRuleCache,
completionService, context.ClientName, returnTextEdits, snippetsSupported, stringBuilder, documentText,
defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false);
lspCompletionItems.Add(lspCompletionItem);
}
var completionList = new LSP.VSCompletionList
{
Items = lspCompletionItems.ToArray(),
SuggestionMode = list.SuggestionModeItem != null,
IsIncomplete = isIncomplete,
};
if (supportsCompletionListData)
{
completionList.Data = completionResolveData;
}
if (context.ClientCapabilities.HasCompletionListCommitCharactersCapability())
{
PromoteCommonCommitCharactersOntoList(completionList);
}
var optimizedCompletionList = new LSP.OptimizedVSCompletionList(completionList);
return optimizedCompletionList;
// Local functions
bool IsValidTriggerCharacterForDocument(Document document, char triggerCharacter)
{
if (document.Project.Language == LanguageNames.CSharp)
{
return _csharpTriggerCharacters.Contains(triggerCharacter);
}
else if (document.Project.Language == LanguageNames.VisualBasic)
{
return _vbTriggerCharacters.Contains(triggerCharacter);
}
// Typescript still calls into this for completion.
// Since we don't know what their trigger characters are, just return true.
return true;
}
static async Task<LSP.CompletionItem> CreateLSPCompletionItemAsync(
LSP.CompletionParams request,
Document document,
CompletionItem item,
CompletionResolveData? completionResolveData,
bool supportsVSExtensions,
Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> commitCharacterRulesCache,
CompletionService completionService,
string? clientName,
bool returnTextEdits,
bool snippetsSupported,
StringBuilder stringBuilder,
SourceText? documentText,
TextSpan? defaultSpan,
LSP.Range? defaultRange,
CancellationToken cancellationToken)
{
if (supportsVSExtensions)
{
var vsCompletionItem = await CreateCompletionItemAsync<LSP.VSCompletionItem>(
request, document, item, completionResolveData, supportsVSExtensions, commitCharacterRulesCache,
completionService, clientName, returnTextEdits, snippetsSupported, stringBuilder,
documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false);
vsCompletionItem.Icon = new ImageElement(item.Tags.GetFirstGlyph().GetImageId());
return vsCompletionItem;
}
else
{
var roslynCompletionItem = await CreateCompletionItemAsync<LSP.CompletionItem>(
request, document, item, completionResolveData, supportsVSExtensions, commitCharacterRulesCache,
completionService, clientName, returnTextEdits, snippetsSupported, stringBuilder,
documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false);
return roslynCompletionItem;
}
}
static async Task<TCompletionItem> CreateCompletionItemAsync<TCompletionItem>(
LSP.CompletionParams request,
Document document,
CompletionItem item,
CompletionResolveData? completionResolveData,
bool supportsVSExtensions,
Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> commitCharacterRulesCache,
CompletionService completionService,
string? clientName,
bool returnTextEdits,
bool snippetsSupported,
StringBuilder stringBuilder,
SourceText? documentText,
TextSpan? defaultSpan,
LSP.Range? defaultRange,
CancellationToken cancellationToken) where TCompletionItem : LSP.CompletionItem, new()
{
// Generate display text
stringBuilder.Append(item.DisplayTextPrefix);
stringBuilder.Append(item.DisplayText);
stringBuilder.Append(item.DisplayTextSuffix);
var completeDisplayText = stringBuilder.ToString();
stringBuilder.Clear();
var completionItem = new TCompletionItem
{
Label = completeDisplayText,
SortText = item.SortText,
FilterText = item.FilterText,
Kind = GetCompletionKind(item.Tags),
Data = completionResolveData,
Preselect = ShouldItemBePreselected(item),
};
// Complex text edits (e.g. override and partial method completions) are always populated in the
// resolve handler, so we leave both TextEdit and InsertText unpopulated in these cases.
if (item.IsComplexTextEdit)
{
// Razor C# is currently the only language client that supports LSP.InsertTextFormat.Snippet.
// We can enable it for regular C# once LSP is used for local completion.
if (snippetsSupported)
{
completionItem.InsertTextFormat = LSP.InsertTextFormat.Snippet;
}
}
// If the feature flag is on, always return a TextEdit.
else if (returnTextEdits)
{
var textEdit = await GenerateTextEdit(
document, item, completionService, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false);
completionItem.TextEdit = textEdit;
}
// If the feature flag is off, return an InsertText.
else
{
completionItem.InsertText = item.Properties.ContainsKey("InsertionText") ? item.Properties["InsertionText"] : completeDisplayText;
}
var commitCharacters = GetCommitCharacters(item, commitCharacterRulesCache, supportsVSExtensions);
if (commitCharacters != null)
{
completionItem.CommitCharacters = commitCharacters;
}
return completionItem;
static async Task<LSP.TextEdit> GenerateTextEdit(
Document document,
CompletionItem item,
CompletionService completionService,
SourceText? documentText,
TextSpan? defaultSpan,
LSP.Range? defaultRange,
CancellationToken cancellationToken)
{
Contract.ThrowIfNull(documentText);
Contract.ThrowIfNull(defaultSpan);
Contract.ThrowIfNull(defaultRange);
var completionChange = await completionService.GetChangeAsync(
document, item, cancellationToken: cancellationToken).ConfigureAwait(false);
var completionChangeSpan = completionChange.TextChange.Span;
var textEdit = new LSP.TextEdit()
{
NewText = completionChange.TextChange.NewText ?? "",
Range = completionChangeSpan == defaultSpan.Value
? defaultRange
: ProtocolConversions.TextSpanToRange(completionChangeSpan, documentText),
};
return textEdit;
}
}
static string[]? GetCommitCharacters(
CompletionItem item,
Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> currentRuleCache,
bool supportsVSExtensions)
{
// VSCode does not have the concept of soft selection, the list is always hard selected.
// In order to emulate soft selection behavior for things like argument completion, regex completion, datetime completion, etc
// we create a completion item without any specific commit characters. This means only tab / enter will commit.
// VS supports soft selection, so we only do this for non-VS clients.
if (!supportsVSExtensions && item.Rules.SelectionBehavior == CompletionItemSelectionBehavior.SoftSelection)
{
return Array.Empty<string>();
}
var commitCharacterRules = item.Rules.CommitCharacterRules;
// VS will use the default commit characters if no items are specified on the completion item.
// However, other clients like VSCode do not support this behavior so we must specify
// commit characters on every completion item - https://github.com/microsoft/vscode/issues/90987
if (supportsVSExtensions && commitCharacterRules.IsEmpty)
{
return null;
}
if (currentRuleCache.TryGetValue(commitCharacterRules, out var cachedCommitCharacters))
{
return cachedCommitCharacters;
}
using var _ = PooledHashSet<char>.GetInstance(out var commitCharacters);
commitCharacters.AddAll(CompletionRules.Default.DefaultCommitCharacters);
foreach (var rule in commitCharacterRules)
{
switch (rule.Kind)
{
case CharacterSetModificationKind.Add:
commitCharacters.UnionWith(rule.Characters);
continue;
case CharacterSetModificationKind.Remove:
commitCharacters.ExceptWith(rule.Characters);
continue;
case CharacterSetModificationKind.Replace:
commitCharacters.Clear();
commitCharacters.AddRange(rule.Characters);
break;
}
}
var lspCommitCharacters = commitCharacters.Select(c => c.ToString()).ToArray();
currentRuleCache.Add(item.Rules.CommitCharacterRules, lspCommitCharacters);
return lspCommitCharacters;
}
static void PromoteCommonCommitCharactersOntoList(LSP.VSCompletionList completionList)
{
var commitCharacterReferences = new Dictionary<object, int>();
var mostUsedCount = 0;
string[]? mostUsedCommitCharacters = null;
for (var i = 0; i < completionList.Items.Length; i++)
{
var completionItem = completionList.Items[i];
var commitCharacters = completionItem.CommitCharacters;
if (commitCharacters == null)
{
continue;
}
commitCharacterReferences.TryGetValue(commitCharacters, out var existingCount);
existingCount++;
if (existingCount > mostUsedCount)
{
// Capture the most used commit character counts so we don't need to re-iterate the array later
mostUsedCommitCharacters = commitCharacters;
mostUsedCount = existingCount;
}
commitCharacterReferences[commitCharacters] = existingCount;
}
Contract.ThrowIfNull(mostUsedCommitCharacters);
// Promoted the most used commit characters onto the list and then remove these from child items.
completionList.CommitCharacters = mostUsedCommitCharacters;
for (var i = 0; i < completionList.Items.Length; i++)
{
var completionItem = completionList.Items[i];
if (completionItem.CommitCharacters == mostUsedCommitCharacters)
{
completionItem.CommitCharacters = null;
}
}
}
}
private async Task<(CompletionList CompletionList, bool IsIncomplete, long ResultId)?> GetFilteredCompletionListAsync(
LSP.CompletionParams request,
SourceText sourceText,
Document document,
OptionSet completionOptions,
CompletionService completionService,
CancellationToken cancellationToken)
{
var position = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(request.Position), cancellationToken).ConfigureAwait(false);
var completionListSpan = completionService.GetDefaultCompletionListSpan(sourceText, position);
var completionTrigger = await ProtocolConversions.LSPToRoslynCompletionTriggerAsync(request.Context, document, position, cancellationToken).ConfigureAwait(false);
var isTriggerForIncompleteCompletions = request.Context?.TriggerKind == LSP.CompletionTriggerKind.TriggerForIncompleteCompletions;
(CompletionList List, long ResultId)? result;
if (isTriggerForIncompleteCompletions)
{
// We don't have access to the original trigger, but we know the completion list is already present.
// It is safe to recompute with the invoked trigger as we will get all the items and filter down based on the current trigger.
var originalTrigger = new CompletionTrigger(CompletionTriggerKind.Invoke);
result = await CalculateListAsync(request, document, position, originalTrigger, completionOptions, completionService, _completionListCache, cancellationToken).ConfigureAwait(false);
}
else
{
// This is a new completion request, clear out the last result Id for incomplete results.
result = await CalculateListAsync(request, document, position, completionTrigger, completionOptions, completionService, _completionListCache, cancellationToken).ConfigureAwait(false);
}
if (result == null)
{
return null;
}
var resultId = result.Value.ResultId;
var completionListMaxSize = completionOptions.GetOption(LspOptions.MaxCompletionListSize);
var (completionList, isIncomplete) = FilterCompletionList(result.Value.List, completionListMaxSize, completionListSpan, completionTrigger, sourceText, document);
return (completionList, isIncomplete, resultId);
}
private static async Task<(CompletionList CompletionList, long ResultId)?> CalculateListAsync(
LSP.CompletionParams request,
Document document,
int position,
CompletionTrigger completionTrigger,
OptionSet completionOptions,
CompletionService completionService,
CompletionListCache completionListCache,
CancellationToken cancellationToken)
{
var completionList = await completionService.GetCompletionsAsync(document, position, completionTrigger, options: completionOptions, cancellationToken: cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
if (completionList == null || completionList.Items.IsEmpty)
{
return null;
}
// Cache the completion list so we can avoid recomputation in the resolve handler
var resultId = completionListCache.UpdateCache(request.TextDocument, completionList);
return (completionList, resultId);
}
private static (CompletionList CompletionList, bool IsIncomplete) FilterCompletionList(
CompletionList completionList,
int completionListMaxSize,
TextSpan completionListSpan,
CompletionTrigger completionTrigger,
SourceText sourceText,
Document document)
{
var filterText = sourceText.GetSubText(completionListSpan).ToString();
// Use pattern matching to determine which items are most relevant out of the calculated items.
using var _ = ArrayBuilder<MatchResult<CompletionItem?>>.GetInstance(out var matchResultsBuilder);
var index = 0;
var completionHelper = CompletionHelper.GetHelper(document);
foreach (var item in completionList.Items)
{
if (CompletionHelper.TryCreateMatchResult<CompletionItem?>(
completionHelper,
item,
editorCompletionItem: null,
filterText,
completionTrigger.Kind,
GetFilterReason(completionTrigger),
recentItems: ImmutableArray<string>.Empty,
includeMatchSpans: false,
index,
out var matchResult))
{
matchResultsBuilder.Add(matchResult);
index++;
}
}
// Next, we sort the list based on the pattern matching result.
matchResultsBuilder.Sort(MatchResult<CompletionItem?>.SortingComparer);
// Finally, truncate the list to 1000 items plus any preselected items that occur after the first 1000.
var filteredList = matchResultsBuilder
.Take(completionListMaxSize)
.Concat(matchResultsBuilder.Skip(completionListMaxSize).Where(match => ShouldItemBePreselected(match.RoslynCompletionItem)))
.Select(matchResult => matchResult.RoslynCompletionItem)
.ToImmutableArray();
var newCompletionList = completionList.WithItems(filteredList);
// Per the LSP spec, the completion list should be marked with isIncomplete = false when further insertions will
// not generate any more completion items. This means that we should be checking if the matchedResults is larger
// than the filteredList. However, the VS client has a bug where they do not properly re-trigger completion
// when a character is deleted to go from a complete list back to an incomplete list.
// For example, the following scenario.
// User types "So" -> server gives subset of items for "So" with isIncomplete = true
// User types "m" -> server gives entire set of items for "Som" with isIncomplete = false
// User deletes "m" -> client has to remember that "So" results were incomplete and re-request if the user types something else, like "n"
//
// Currently the VS client does not remember to re-request, so the completion list only ever shows items from "Som"
// so we always set the isIncomplete flag to true when the original list size (computed when no filter text was typed) is too large.
// VS bug here - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1335142
var isIncomplete = completionList.Items.Length > newCompletionList.Items.Length;
return (newCompletionList, isIncomplete);
static CompletionFilterReason GetFilterReason(CompletionTrigger trigger)
{
return trigger.Kind switch
{
CompletionTriggerKind.Insertion => CompletionFilterReason.Insertion,
CompletionTriggerKind.Deletion => CompletionFilterReason.Deletion,
_ => CompletionFilterReason.Other,
};
}
}
private static bool ShouldItemBePreselected(CompletionItem completionItem)
{
// An item should be preselcted for LSP when the match priority is preselect and the item is hard selected.
// LSP does not support soft preselection, so we do not preselect in that scenario to avoid interfering with typing.
return completionItem.Rules.MatchPriority == MatchPriority.Preselect && completionItem.Rules.SelectionBehavior == CompletionItemSelectionBehavior.HardSelection;
}
internal static ImmutableHashSet<char> GetTriggerCharacters(CompletionProvider provider)
{
if (provider is LSPCompletionProvider lspProvider)
{
return lspProvider.TriggerCharacters;
}
return ImmutableHashSet<char>.Empty;
}
internal static async Task<OptionSet> GetCompletionOptionsAsync(Document document, CancellationToken cancellationToken)
{
// Filter out snippets as they are not supported in the LSP client
// https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1139740
// Filter out unimported types for now as there are two issues with providing them:
// 1. LSP client does not currently provide a way to provide detail text on the completion item to show the namespace.
// https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1076759
// 2. We need to figure out how to provide the text edits along with the completion item or provide them in the resolve request.
// https://devdiv.visualstudio.com/DevDiv/_workitems/edit/985860/
// 3. LSP client should support completion filters / expanders
var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var completionOptions = documentOptions
.WithChangedOption(CompletionOptions.SnippetsBehavior, SnippetsRule.NeverInclude)
.WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, false)
.WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, false);
return completionOptions;
}
private static LSP.CompletionItemKind GetCompletionKind(ImmutableArray<string> tags)
{
foreach (var tag in tags)
{
if (ProtocolConversions.RoslynTagToCompletionItemKind.TryGetValue(tag, out var completionItemKind))
{
return completionItemKind;
}
}
return LSP.CompletionItemKind.Text;
}
internal TestAccessor GetTestAccessor()
=> new TestAccessor(this);
internal readonly struct TestAccessor
{
private readonly CompletionHandler _completionHandler;
public TestAccessor(CompletionHandler completionHandler)
=> _completionHandler = completionHandler;
public CompletionListCache GetCache()
=> _completionHandler._completionListCache;
}
private class CommitCharacterArrayComparer : IEqualityComparer<ImmutableArray<CharacterSetModificationRule>>
{
public static readonly CommitCharacterArrayComparer Instance = new();
private CommitCharacterArrayComparer()
{
}
public bool Equals([AllowNull] ImmutableArray<CharacterSetModificationRule> x, [AllowNull] ImmutableArray<CharacterSetModificationRule> y)
{
for (var i = 0; i < x.Length; i++)
{
var xKind = x[i].Kind;
var yKind = y[i].Kind;
if (xKind != yKind)
{
return false;
}
var xCharacters = x[i].Characters;
var yCharacters = y[i].Characters;
if (xCharacters.Length != yCharacters.Length)
{
return false;
}
for (var j = 0; j < xCharacters.Length; j++)
{
if (xCharacters[j] != yCharacters[j])
{
return false;
}
}
}
return true;
}
public int GetHashCode([DisallowNull] ImmutableArray<CharacterSetModificationRule> obj)
{
var combinedHash = Hash.CombineValues(obj);
return combinedHash;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Experiments;
using Microsoft.CodeAnalysis.LanguageServer.Handler.Completion;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text.Adornments;
using Roslyn.Utilities;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
/// <summary>
/// Handle a completion request.
/// </summary>
internal class CompletionHandler : IRequestHandler<LSP.CompletionParams, LSP.CompletionList?>
{
private readonly ImmutableHashSet<char> _csharpTriggerCharacters;
private readonly ImmutableHashSet<char> _vbTriggerCharacters;
private readonly CompletionListCache _completionListCache;
public string Method => LSP.Methods.TextDocumentCompletionName;
public bool MutatesSolutionState => false;
public bool RequiresLSPSolution => true;
public CompletionHandler(
IEnumerable<Lazy<CompletionProvider, CompletionProviderMetadata>> completionProviders,
CompletionListCache completionListCache)
{
_csharpTriggerCharacters = completionProviders.Where(lz => lz.Metadata.Language == LanguageNames.CSharp).SelectMany(
lz => GetTriggerCharacters(lz.Value)).ToImmutableHashSet();
_vbTriggerCharacters = completionProviders.Where(lz => lz.Metadata.Language == LanguageNames.VisualBasic).SelectMany(
lz => GetTriggerCharacters(lz.Value)).ToImmutableHashSet();
_completionListCache = completionListCache;
}
public LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.CompletionParams request) => request.TextDocument;
public async Task<LSP.CompletionList?> HandleRequestAsync(LSP.CompletionParams request, RequestContext context, CancellationToken cancellationToken)
{
var document = context.Document;
if (document == null)
{
return null;
}
// C# and VB share the same LSP language server, and thus share the same default trigger characters.
// We need to ensure the trigger character is valid in the document's language. For example, the '{'
// character, while a trigger character in VB, is not a trigger character in C#.
if (request.Context != null &&
request.Context.TriggerKind == LSP.CompletionTriggerKind.TriggerCharacter &&
!char.TryParse(request.Context.TriggerCharacter, out var triggerCharacter) &&
!char.IsLetterOrDigit(triggerCharacter) &&
!IsValidTriggerCharacterForDocument(document, triggerCharacter))
{
return null;
}
var completionOptions = await GetCompletionOptionsAsync(document, cancellationToken).ConfigureAwait(false);
var completionService = document.GetRequiredLanguageService<CompletionService>();
var documentText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var completionListResult = await GetFilteredCompletionListAsync(request, documentText, document, completionOptions, completionService, cancellationToken).ConfigureAwait(false);
if (completionListResult == null)
{
return null;
}
var (list, isIncomplete, resultId) = completionListResult.Value;
var lspVSClientCapability = context.ClientCapabilities.HasVisualStudioLspCapability() == true;
var snippetsSupported = context.ClientCapabilities.TextDocument?.Completion?.CompletionItem?.SnippetSupport ?? false;
var commitCharactersRuleCache = new Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]>(CommitCharacterArrayComparer.Instance);
// Feature flag to enable the return of TextEdits instead of InsertTexts (will increase payload size).
// Flag is defined in VisualStudio\Core\Def\PackageRegistration.pkgdef.
// We also check against the CompletionOption for test purposes only.
Contract.ThrowIfNull(context.Solution);
var featureFlagService = context.Solution.Workspace.Services.GetRequiredService<IExperimentationService>();
var returnTextEdits = featureFlagService.IsExperimentEnabled(WellKnownExperimentNames.LSPCompletion) ||
completionOptions.GetOption(CompletionOptions.ForceRoslynLSPCompletionExperiment, document.Project.Language);
TextSpan? defaultSpan = null;
LSP.Range? defaultRange = null;
if (returnTextEdits)
{
// We want to compute the document's text just once.
documentText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
// We use the first item in the completion list as our comparison point for span
// and range for optimization when generating the TextEdits later on.
var completionChange = await completionService.GetChangeAsync(
document, list.Items.First(), cancellationToken: cancellationToken).ConfigureAwait(false);
// If possible, we want to compute the item's span and range just once.
// Individual items can override this range later.
defaultSpan = completionChange.TextChange.Span;
defaultRange = ProtocolConversions.TextSpanToRange(defaultSpan.Value, documentText);
}
var supportsCompletionListData = context.ClientCapabilities.HasCompletionListDataCapability();
var completionResolveData = new CompletionResolveData()
{
ResultId = resultId,
};
var stringBuilder = new StringBuilder();
using var _ = ArrayBuilder<LSP.CompletionItem>.GetInstance(out var lspCompletionItems);
foreach (var item in list.Items)
{
var completionItemResolveData = supportsCompletionListData ? null : completionResolveData;
var lspCompletionItem = await CreateLSPCompletionItemAsync(
request, document, item, completionItemResolveData, lspVSClientCapability, commitCharactersRuleCache,
completionService, context.ClientName, returnTextEdits, snippetsSupported, stringBuilder, documentText,
defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false);
lspCompletionItems.Add(lspCompletionItem);
}
var completionList = new LSP.VSCompletionList
{
Items = lspCompletionItems.ToArray(),
SuggestionMode = list.SuggestionModeItem != null,
IsIncomplete = isIncomplete,
};
if (supportsCompletionListData)
{
completionList.Data = completionResolveData;
}
if (context.ClientCapabilities.HasCompletionListCommitCharactersCapability())
{
PromoteCommonCommitCharactersOntoList(completionList);
}
var optimizedCompletionList = new LSP.OptimizedVSCompletionList(completionList);
return optimizedCompletionList;
// Local functions
bool IsValidTriggerCharacterForDocument(Document document, char triggerCharacter)
{
if (document.Project.Language == LanguageNames.CSharp)
{
return _csharpTriggerCharacters.Contains(triggerCharacter);
}
else if (document.Project.Language == LanguageNames.VisualBasic)
{
return _vbTriggerCharacters.Contains(triggerCharacter);
}
// Typescript still calls into this for completion.
// Since we don't know what their trigger characters are, just return true.
return true;
}
static async Task<LSP.CompletionItem> CreateLSPCompletionItemAsync(
LSP.CompletionParams request,
Document document,
CompletionItem item,
CompletionResolveData? completionResolveData,
bool supportsVSExtensions,
Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> commitCharacterRulesCache,
CompletionService completionService,
string? clientName,
bool returnTextEdits,
bool snippetsSupported,
StringBuilder stringBuilder,
SourceText? documentText,
TextSpan? defaultSpan,
LSP.Range? defaultRange,
CancellationToken cancellationToken)
{
if (supportsVSExtensions)
{
var vsCompletionItem = await CreateCompletionItemAsync<LSP.VSCompletionItem>(
request, document, item, completionResolveData, supportsVSExtensions, commitCharacterRulesCache,
completionService, clientName, returnTextEdits, snippetsSupported, stringBuilder,
documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false);
vsCompletionItem.Icon = new ImageElement(item.Tags.GetFirstGlyph().GetImageId());
return vsCompletionItem;
}
else
{
var roslynCompletionItem = await CreateCompletionItemAsync<LSP.CompletionItem>(
request, document, item, completionResolveData, supportsVSExtensions, commitCharacterRulesCache,
completionService, clientName, returnTextEdits, snippetsSupported, stringBuilder,
documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false);
return roslynCompletionItem;
}
}
static async Task<TCompletionItem> CreateCompletionItemAsync<TCompletionItem>(
LSP.CompletionParams request,
Document document,
CompletionItem item,
CompletionResolveData? completionResolveData,
bool supportsVSExtensions,
Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> commitCharacterRulesCache,
CompletionService completionService,
string? clientName,
bool returnTextEdits,
bool snippetsSupported,
StringBuilder stringBuilder,
SourceText? documentText,
TextSpan? defaultSpan,
LSP.Range? defaultRange,
CancellationToken cancellationToken) where TCompletionItem : LSP.CompletionItem, new()
{
// Generate display text
stringBuilder.Append(item.DisplayTextPrefix);
stringBuilder.Append(item.DisplayText);
stringBuilder.Append(item.DisplayTextSuffix);
var completeDisplayText = stringBuilder.ToString();
stringBuilder.Clear();
var completionItem = new TCompletionItem
{
Label = completeDisplayText,
SortText = item.SortText,
FilterText = item.FilterText,
Kind = GetCompletionKind(item.Tags),
Data = completionResolveData,
Preselect = ShouldItemBePreselected(item),
};
// Complex text edits (e.g. override and partial method completions) are always populated in the
// resolve handler, so we leave both TextEdit and InsertText unpopulated in these cases.
if (item.IsComplexTextEdit)
{
// Razor C# is currently the only language client that supports LSP.InsertTextFormat.Snippet.
// We can enable it for regular C# once LSP is used for local completion.
if (snippetsSupported)
{
completionItem.InsertTextFormat = LSP.InsertTextFormat.Snippet;
}
}
// If the feature flag is on, always return a TextEdit.
else if (returnTextEdits)
{
var textEdit = await GenerateTextEdit(
document, item, completionService, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false);
completionItem.TextEdit = textEdit;
}
// If the feature flag is off, return an InsertText.
else
{
completionItem.InsertText = item.Properties.ContainsKey("InsertionText") ? item.Properties["InsertionText"] : completeDisplayText;
}
var commitCharacters = GetCommitCharacters(item, commitCharacterRulesCache, supportsVSExtensions);
if (commitCharacters != null)
{
completionItem.CommitCharacters = commitCharacters;
}
return completionItem;
static async Task<LSP.TextEdit> GenerateTextEdit(
Document document,
CompletionItem item,
CompletionService completionService,
SourceText? documentText,
TextSpan? defaultSpan,
LSP.Range? defaultRange,
CancellationToken cancellationToken)
{
Contract.ThrowIfNull(documentText);
Contract.ThrowIfNull(defaultSpan);
Contract.ThrowIfNull(defaultRange);
var completionChange = await completionService.GetChangeAsync(
document, item, cancellationToken: cancellationToken).ConfigureAwait(false);
var completionChangeSpan = completionChange.TextChange.Span;
var textEdit = new LSP.TextEdit()
{
NewText = completionChange.TextChange.NewText ?? "",
Range = completionChangeSpan == defaultSpan.Value
? defaultRange
: ProtocolConversions.TextSpanToRange(completionChangeSpan, documentText),
};
return textEdit;
}
}
static string[]? GetCommitCharacters(
CompletionItem item,
Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> currentRuleCache,
bool supportsVSExtensions)
{
// VSCode does not have the concept of soft selection, the list is always hard selected.
// In order to emulate soft selection behavior for things like argument completion, regex completion, datetime completion, etc
// we create a completion item without any specific commit characters. This means only tab / enter will commit.
// VS supports soft selection, so we only do this for non-VS clients.
if (!supportsVSExtensions && item.Rules.SelectionBehavior == CompletionItemSelectionBehavior.SoftSelection)
{
return Array.Empty<string>();
}
var commitCharacterRules = item.Rules.CommitCharacterRules;
// VS will use the default commit characters if no items are specified on the completion item.
// However, other clients like VSCode do not support this behavior so we must specify
// commit characters on every completion item - https://github.com/microsoft/vscode/issues/90987
if (supportsVSExtensions && commitCharacterRules.IsEmpty)
{
return null;
}
if (currentRuleCache.TryGetValue(commitCharacterRules, out var cachedCommitCharacters))
{
return cachedCommitCharacters;
}
using var _ = PooledHashSet<char>.GetInstance(out var commitCharacters);
commitCharacters.AddAll(CompletionRules.Default.DefaultCommitCharacters);
foreach (var rule in commitCharacterRules)
{
switch (rule.Kind)
{
case CharacterSetModificationKind.Add:
commitCharacters.UnionWith(rule.Characters);
continue;
case CharacterSetModificationKind.Remove:
commitCharacters.ExceptWith(rule.Characters);
continue;
case CharacterSetModificationKind.Replace:
commitCharacters.Clear();
commitCharacters.AddRange(rule.Characters);
break;
}
}
var lspCommitCharacters = commitCharacters.Select(c => c.ToString()).ToArray();
currentRuleCache.Add(item.Rules.CommitCharacterRules, lspCommitCharacters);
return lspCommitCharacters;
}
static void PromoteCommonCommitCharactersOntoList(LSP.VSCompletionList completionList)
{
var commitCharacterReferences = new Dictionary<object, int>();
var mostUsedCount = 0;
string[]? mostUsedCommitCharacters = null;
for (var i = 0; i < completionList.Items.Length; i++)
{
var completionItem = completionList.Items[i];
var commitCharacters = completionItem.CommitCharacters;
if (commitCharacters == null)
{
continue;
}
commitCharacterReferences.TryGetValue(commitCharacters, out var existingCount);
existingCount++;
if (existingCount > mostUsedCount)
{
// Capture the most used commit character counts so we don't need to re-iterate the array later
mostUsedCommitCharacters = commitCharacters;
mostUsedCount = existingCount;
}
commitCharacterReferences[commitCharacters] = existingCount;
}
Contract.ThrowIfNull(mostUsedCommitCharacters);
// Promoted the most used commit characters onto the list and then remove these from child items.
completionList.CommitCharacters = mostUsedCommitCharacters;
for (var i = 0; i < completionList.Items.Length; i++)
{
var completionItem = completionList.Items[i];
if (completionItem.CommitCharacters == mostUsedCommitCharacters)
{
completionItem.CommitCharacters = null;
}
}
}
}
private async Task<(CompletionList CompletionList, bool IsIncomplete, long ResultId)?> GetFilteredCompletionListAsync(
LSP.CompletionParams request,
SourceText sourceText,
Document document,
OptionSet completionOptions,
CompletionService completionService,
CancellationToken cancellationToken)
{
var position = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(request.Position), cancellationToken).ConfigureAwait(false);
var completionListSpan = completionService.GetDefaultCompletionListSpan(sourceText, position);
var completionTrigger = await ProtocolConversions.LSPToRoslynCompletionTriggerAsync(request.Context, document, position, cancellationToken).ConfigureAwait(false);
var isTriggerForIncompleteCompletions = request.Context?.TriggerKind == LSP.CompletionTriggerKind.TriggerForIncompleteCompletions;
(CompletionList List, long ResultId)? result;
if (isTriggerForIncompleteCompletions)
{
// We don't have access to the original trigger, but we know the completion list is already present.
// It is safe to recompute with the invoked trigger as we will get all the items and filter down based on the current trigger.
var originalTrigger = new CompletionTrigger(CompletionTriggerKind.Invoke);
result = await CalculateListAsync(request, document, position, originalTrigger, completionOptions, completionService, _completionListCache, cancellationToken).ConfigureAwait(false);
}
else
{
// This is a new completion request, clear out the last result Id for incomplete results.
result = await CalculateListAsync(request, document, position, completionTrigger, completionOptions, completionService, _completionListCache, cancellationToken).ConfigureAwait(false);
}
if (result == null)
{
return null;
}
var resultId = result.Value.ResultId;
var completionListMaxSize = completionOptions.GetOption(LspOptions.MaxCompletionListSize);
var (completionList, isIncomplete) = FilterCompletionList(result.Value.List, completionListMaxSize, completionListSpan, completionTrigger, sourceText, document);
return (completionList, isIncomplete, resultId);
}
private static async Task<(CompletionList CompletionList, long ResultId)?> CalculateListAsync(
LSP.CompletionParams request,
Document document,
int position,
CompletionTrigger completionTrigger,
OptionSet completionOptions,
CompletionService completionService,
CompletionListCache completionListCache,
CancellationToken cancellationToken)
{
var completionList = await completionService.GetCompletionsAsync(document, position, completionTrigger, options: completionOptions, cancellationToken: cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
if (completionList == null || completionList.Items.IsEmpty)
{
return null;
}
// Cache the completion list so we can avoid recomputation in the resolve handler
var resultId = completionListCache.UpdateCache(request.TextDocument, completionList);
return (completionList, resultId);
}
private static (CompletionList CompletionList, bool IsIncomplete) FilterCompletionList(
CompletionList completionList,
int completionListMaxSize,
TextSpan completionListSpan,
CompletionTrigger completionTrigger,
SourceText sourceText,
Document document)
{
var filterText = sourceText.GetSubText(completionListSpan).ToString();
// Use pattern matching to determine which items are most relevant out of the calculated items.
using var _ = ArrayBuilder<MatchResult<CompletionItem?>>.GetInstance(out var matchResultsBuilder);
var index = 0;
var completionHelper = CompletionHelper.GetHelper(document);
foreach (var item in completionList.Items)
{
if (CompletionHelper.TryCreateMatchResult<CompletionItem?>(
completionHelper,
item,
editorCompletionItem: null,
filterText,
completionTrigger.Kind,
GetFilterReason(completionTrigger),
recentItems: ImmutableArray<string>.Empty,
includeMatchSpans: false,
index,
out var matchResult))
{
matchResultsBuilder.Add(matchResult);
index++;
}
}
// Next, we sort the list based on the pattern matching result.
matchResultsBuilder.Sort(MatchResult<CompletionItem?>.SortingComparer);
// Finally, truncate the list to 1000 items plus any preselected items that occur after the first 1000.
var filteredList = matchResultsBuilder
.Take(completionListMaxSize)
.Concat(matchResultsBuilder.Skip(completionListMaxSize).Where(match => ShouldItemBePreselected(match.RoslynCompletionItem)))
.Select(matchResult => matchResult.RoslynCompletionItem)
.ToImmutableArray();
var newCompletionList = completionList.WithItems(filteredList);
// Per the LSP spec, the completion list should be marked with isIncomplete = false when further insertions will
// not generate any more completion items. This means that we should be checking if the matchedResults is larger
// than the filteredList. However, the VS client has a bug where they do not properly re-trigger completion
// when a character is deleted to go from a complete list back to an incomplete list.
// For example, the following scenario.
// User types "So" -> server gives subset of items for "So" with isIncomplete = true
// User types "m" -> server gives entire set of items for "Som" with isIncomplete = false
// User deletes "m" -> client has to remember that "So" results were incomplete and re-request if the user types something else, like "n"
//
// Currently the VS client does not remember to re-request, so the completion list only ever shows items from "Som"
// so we always set the isIncomplete flag to true when the original list size (computed when no filter text was typed) is too large.
// VS bug here - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1335142
var isIncomplete = completionList.Items.Length > newCompletionList.Items.Length;
return (newCompletionList, isIncomplete);
static CompletionFilterReason GetFilterReason(CompletionTrigger trigger)
{
return trigger.Kind switch
{
CompletionTriggerKind.Insertion => CompletionFilterReason.Insertion,
CompletionTriggerKind.Deletion => CompletionFilterReason.Deletion,
_ => CompletionFilterReason.Other,
};
}
}
private static bool ShouldItemBePreselected(CompletionItem completionItem)
{
// An item should be preselcted for LSP when the match priority is preselect and the item is hard selected.
// LSP does not support soft preselection, so we do not preselect in that scenario to avoid interfering with typing.
return completionItem.Rules.MatchPriority == MatchPriority.Preselect && completionItem.Rules.SelectionBehavior == CompletionItemSelectionBehavior.HardSelection;
}
internal static ImmutableHashSet<char> GetTriggerCharacters(CompletionProvider provider)
{
if (provider is LSPCompletionProvider lspProvider)
{
return lspProvider.TriggerCharacters;
}
return ImmutableHashSet<char>.Empty;
}
internal static async Task<OptionSet> GetCompletionOptionsAsync(Document document, CancellationToken cancellationToken)
{
// Filter out snippets as they are not supported in the LSP client
// https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1139740
// Filter out unimported types for now as there are two issues with providing them:
// 1. LSP client does not currently provide a way to provide detail text on the completion item to show the namespace.
// https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1076759
// 2. We need to figure out how to provide the text edits along with the completion item or provide them in the resolve request.
// https://devdiv.visualstudio.com/DevDiv/_workitems/edit/985860/
// 3. LSP client should support completion filters / expanders
var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var completionOptions = documentOptions
.WithChangedOption(CompletionOptions.SnippetsBehavior, SnippetsRule.NeverInclude)
.WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, false)
.WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, false);
return completionOptions;
}
private static LSP.CompletionItemKind GetCompletionKind(ImmutableArray<string> tags)
{
foreach (var tag in tags)
{
if (ProtocolConversions.RoslynTagToCompletionItemKind.TryGetValue(tag, out var completionItemKind))
{
return completionItemKind;
}
}
return LSP.CompletionItemKind.Text;
}
internal TestAccessor GetTestAccessor()
=> new TestAccessor(this);
internal readonly struct TestAccessor
{
private readonly CompletionHandler _completionHandler;
public TestAccessor(CompletionHandler completionHandler)
=> _completionHandler = completionHandler;
public CompletionListCache GetCache()
=> _completionHandler._completionListCache;
}
private class CommitCharacterArrayComparer : IEqualityComparer<ImmutableArray<CharacterSetModificationRule>>
{
public static readonly CommitCharacterArrayComparer Instance = new();
private CommitCharacterArrayComparer()
{
}
public bool Equals([AllowNull] ImmutableArray<CharacterSetModificationRule> x, [AllowNull] ImmutableArray<CharacterSetModificationRule> y)
{
for (var i = 0; i < x.Length; i++)
{
var xKind = x[i].Kind;
var yKind = y[i].Kind;
if (xKind != yKind)
{
return false;
}
var xCharacters = x[i].Characters;
var yCharacters = y[i].Characters;
if (xCharacters.Length != yCharacters.Length)
{
return false;
}
for (var j = 0; j < xCharacters.Length; j++)
{
if (xCharacters[j] != yCharacters[j])
{
return false;
}
}
}
return true;
}
public int GetHashCode([DisallowNull] ImmutableArray<CharacterSetModificationRule> obj)
{
var combinedHash = Hash.CombineValues(obj);
return combinedHash;
}
}
}
}
| -1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Tools/ExternalAccess/FSharp/Internal/GoToDefinition/FSharpFindDefinitionService.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ExternalAccess.FSharp.GoToDefinition;
using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Navigation;
using Microsoft.CodeAnalysis.GoToDefinition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Navigation;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.GoToDefinition
{
[ExportLanguageService(typeof(IFindDefinitionService), LanguageNames.FSharp), Shared]
internal class FSharpFindDefinitionService : IFindDefinitionService
{
private readonly IFSharpFindDefinitionService _service;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FSharpFindDefinitionService(IFSharpFindDefinitionService service)
{
_service = service;
}
public async Task<ImmutableArray<INavigableItem>> FindDefinitionsAsync(Document document, int position, CancellationToken cancellationToken)
{
var items = await _service.FindDefinitionsAsync(document, position, cancellationToken).ConfigureAwait(false);
return items.SelectAsArray(x => (INavigableItem)new InternalFSharpNavigableItem(x));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ExternalAccess.FSharp.GoToDefinition;
using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Navigation;
using Microsoft.CodeAnalysis.GoToDefinition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Navigation;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.GoToDefinition
{
[ExportLanguageService(typeof(IFindDefinitionService), LanguageNames.FSharp), Shared]
internal class FSharpFindDefinitionService : IFindDefinitionService
{
private readonly IFSharpFindDefinitionService _service;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public FSharpFindDefinitionService(IFSharpFindDefinitionService service)
{
_service = service;
}
public async Task<ImmutableArray<INavigableItem>> FindDefinitionsAsync(Document document, int position, CancellationToken cancellationToken)
{
var items = await _service.FindDefinitionsAsync(document, position, cancellationToken).ConfigureAwait(false);
return items.SelectAsArray(x => (INavigableItem)new InternalFSharpNavigableItem(x));
}
}
}
| -1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Scripting/Core/ScriptOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Reflection;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.Scripting.Hosting;
namespace Microsoft.CodeAnalysis.Scripting
{
using static ParameterValidationHelpers;
/// <summary>
/// Options for creating and running scripts.
/// </summary>
public sealed class ScriptOptions
{
public static ScriptOptions Default { get; } = new ScriptOptions(
filePath: string.Empty,
references: GetDefaultMetadataReferences(),
namespaces: ImmutableArray<string>.Empty,
metadataResolver: ScriptMetadataResolver.Default,
sourceResolver: SourceFileResolver.Default,
emitDebugInformation: false,
fileEncoding: null,
OptimizationLevel.Debug,
checkOverflow: false,
allowUnsafe: true,
warningLevel: 4,
parseOptions: null);
private static ImmutableArray<MetadataReference> GetDefaultMetadataReferences()
{
if (GacFileResolver.IsAvailable)
{
return ImmutableArray<MetadataReference>.Empty;
}
// These references are resolved lazily. Keep in sync with list in core csi.rsp.
var files = new[]
{
"System.Collections",
"System.Collections.Concurrent",
"System.Console",
"System.Diagnostics.Debug",
"System.Diagnostics.Process",
"System.Diagnostics.StackTrace",
"System.Globalization",
"System.IO",
"System.IO.FileSystem",
"System.IO.FileSystem.Primitives",
"System.Reflection",
"System.Reflection.Extensions",
"System.Reflection.Primitives",
"System.Runtime",
"System.Runtime.Extensions",
"System.Runtime.InteropServices",
"System.Text.Encoding",
"System.Text.Encoding.CodePages",
"System.Text.Encoding.Extensions",
"System.Text.RegularExpressions",
"System.Threading",
"System.Threading.Tasks",
"System.Threading.Tasks.Parallel",
"System.Threading.Thread",
"System.ValueTuple",
};
return ImmutableArray.CreateRange(files.Select(CreateUnresolvedReference));
}
/// <summary>
/// An array of <see cref="MetadataReference"/>s to be added to the script.
/// </summary>
/// <remarks>
/// The array may contain both resolved and unresolved references (<see cref="UnresolvedMetadataReference"/>).
/// Unresolved references are resolved when the script is about to be executed
/// (<see cref="Script.RunAsync(object, CancellationToken)"/>.
/// Any resolution errors are reported at that point through <see cref="CompilationErrorException"/>.
/// </remarks>
public ImmutableArray<MetadataReference> MetadataReferences { get; private set; }
/// <summary>
/// <see cref="MetadataReferenceResolver"/> to be used to resolve missing dependencies, unresolved metadata references and #r directives.
/// </summary>
public MetadataReferenceResolver MetadataResolver { get; private set; }
/// <summary>
/// <see cref="SourceReferenceResolver"/> to be used to resolve source of scripts referenced via #load directive.
/// </summary>
public SourceReferenceResolver SourceResolver { get; private set; }
/// <summary>
/// The namespaces, static classes and aliases imported by the script.
/// </summary>
public ImmutableArray<string> Imports { get; private set; }
/// <summary>
/// Specifies whether debugging symbols should be emitted.
/// </summary>
public bool EmitDebugInformation { get; private set; } = false;
/// <summary>
/// Specifies the encoding to be used when debugging scripts loaded from a file, or saved to a file for debugging purposes.
/// If it's null, the compiler will attempt to detect the necessary encoding for debugging
/// </summary>
public Encoding FileEncoding { get; private set; }
/// <summary>
/// The path to the script source if it originated from a file, empty otherwise.
/// </summary>
public string FilePath { get; private set; }
/// <summary>
/// Specifies whether or not optimizations should be performed on the output IL.
/// </summary>
public OptimizationLevel OptimizationLevel { get; private set; }
/// <summary>
/// Whether bounds checking on integer arithmetic is enforced by default or not.
/// </summary>
public bool CheckOverflow { get; private set; }
/// <summary>
/// Allow unsafe regions (i.e. unsafe modifiers on members and unsafe blocks).
/// </summary>
public bool AllowUnsafe { get; private set; }
/// <summary>
/// Global warning level (from 0 to 4).
/// </summary>
public int WarningLevel { get; private set; }
internal ParseOptions ParseOptions { get; private set; }
internal ScriptOptions(
string filePath,
ImmutableArray<MetadataReference> references,
ImmutableArray<string> namespaces,
MetadataReferenceResolver metadataResolver,
SourceReferenceResolver sourceResolver,
bool emitDebugInformation,
Encoding fileEncoding,
OptimizationLevel optimizationLevel,
bool checkOverflow,
bool allowUnsafe,
int warningLevel,
ParseOptions parseOptions)
{
Debug.Assert(filePath != null);
Debug.Assert(!references.IsDefault);
Debug.Assert(!namespaces.IsDefault);
Debug.Assert(metadataResolver != null);
Debug.Assert(sourceResolver != null);
FilePath = filePath;
MetadataReferences = references;
Imports = namespaces;
MetadataResolver = metadataResolver;
SourceResolver = sourceResolver;
EmitDebugInformation = emitDebugInformation;
FileEncoding = fileEncoding;
OptimizationLevel = optimizationLevel;
CheckOverflow = checkOverflow;
AllowUnsafe = allowUnsafe;
WarningLevel = warningLevel;
ParseOptions = parseOptions;
}
private ScriptOptions(ScriptOptions other)
: this(filePath: other.FilePath,
references: other.MetadataReferences,
namespaces: other.Imports,
metadataResolver: other.MetadataResolver,
sourceResolver: other.SourceResolver,
emitDebugInformation: other.EmitDebugInformation,
fileEncoding: other.FileEncoding,
optimizationLevel: other.OptimizationLevel,
checkOverflow: other.CheckOverflow,
allowUnsafe: other.AllowUnsafe,
warningLevel: other.WarningLevel,
parseOptions: other.ParseOptions)
{
}
// a reference to an assembly should by default be equivalent to #r, which applies recursive global alias:
private static readonly MetadataReferenceProperties s_assemblyReferenceProperties =
MetadataReferenceProperties.Assembly.WithRecursiveAliases(true);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the <see cref="FilePath"/> changed.
/// </summary>
public ScriptOptions WithFilePath(string filePath) =>
(FilePath == filePath) ? this : new ScriptOptions(this) { FilePath = filePath ?? "" };
private static MetadataReference CreateUnresolvedReference(string reference) =>
new UnresolvedMetadataReference(reference, s_assemblyReferenceProperties);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
private ScriptOptions WithReferences(ImmutableArray<MetadataReference> references) =>
MetadataReferences.Equals(references) ? this : new ScriptOptions(this) { MetadataReferences = CheckImmutableArray(references, nameof(references)) };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions WithReferences(IEnumerable<MetadataReference> references) =>
WithReferences(ToImmutableArrayChecked(references, nameof(references)));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions WithReferences(params MetadataReference[] references) =>
WithReferences((IEnumerable<MetadataReference>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions AddReferences(IEnumerable<MetadataReference> references) =>
WithReferences(ConcatChecked(MetadataReferences, references, nameof(references)));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
public ScriptOptions AddReferences(params MetadataReference[] references) =>
AddReferences((IEnumerable<MetadataReference>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
/// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception>
public ScriptOptions WithReferences(IEnumerable<Assembly> references) =>
WithReferences(SelectChecked(references, nameof(references), CreateReferenceFromAssembly));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
/// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception>
public ScriptOptions WithReferences(params Assembly[] references) =>
WithReferences((IEnumerable<Assembly>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
/// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception>
public ScriptOptions AddReferences(IEnumerable<Assembly> references) =>
AddReferences(SelectChecked(references, nameof(references), CreateReferenceFromAssembly));
private static MetadataReference CreateReferenceFromAssembly(Assembly assembly)
{
return MetadataReference.CreateFromAssemblyInternal(assembly, s_assemblyReferenceProperties);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
/// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception>
public ScriptOptions AddReferences(params Assembly[] references) =>
AddReferences((IEnumerable<Assembly>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions WithReferences(IEnumerable<string> references) =>
WithReferences(SelectChecked(references, nameof(references), CreateUnresolvedReference));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions WithReferences(params string[] references) =>
WithReferences((IEnumerable<string>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions AddReferences(IEnumerable<string> references) =>
AddReferences(SelectChecked(references, nameof(references), CreateUnresolvedReference));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
public ScriptOptions AddReferences(params string[] references) =>
AddReferences((IEnumerable<string>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with specified <see cref="MetadataResolver"/>.
/// </summary>
public ScriptOptions WithMetadataResolver(MetadataReferenceResolver resolver) =>
MetadataResolver == resolver ? this : new ScriptOptions(this) { MetadataResolver = resolver };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with specified <see cref="SourceResolver"/>.
/// </summary>
public ScriptOptions WithSourceResolver(SourceReferenceResolver resolver) =>
SourceResolver == resolver ? this : new ScriptOptions(this) { SourceResolver = resolver };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
private ScriptOptions WithImports(ImmutableArray<string> imports) =>
Imports.Equals(imports) ? this : new ScriptOptions(this) { Imports = CheckImmutableArray(imports, nameof(imports)) };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
public ScriptOptions WithImports(IEnumerable<string> imports) =>
WithImports(ToImmutableArrayChecked(imports, nameof(imports)));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
public ScriptOptions WithImports(params string[] imports) =>
WithImports((IEnumerable<string>)imports);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with <see cref="Imports"/> added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
public ScriptOptions AddImports(IEnumerable<string> imports) =>
WithImports(ConcatChecked(Imports, imports, nameof(imports)));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with <see cref="Imports"/> added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
public ScriptOptions AddImports(params string[] imports) =>
AddImports((IEnumerable<string>)imports);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with debugging information enabled.
/// </summary>
public ScriptOptions WithEmitDebugInformation(bool emitDebugInformation) =>
emitDebugInformation == EmitDebugInformation ? this : new ScriptOptions(this) { EmitDebugInformation = emitDebugInformation };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with specified <see cref="FileEncoding"/>.
/// </summary>
public ScriptOptions WithFileEncoding(Encoding encoding) =>
encoding == FileEncoding ? this : new ScriptOptions(this) { FileEncoding = encoding };
/// <summary>
/// Create a new <see cref="ScriptOptions"/> with the specified <see cref="OptimizationLevel"/>.
/// </summary>
/// <returns></returns>
public ScriptOptions WithOptimizationLevel(OptimizationLevel optimizationLevel) =>
optimizationLevel == OptimizationLevel ? this : new ScriptOptions(this) { OptimizationLevel = optimizationLevel };
/// <summary>
/// Create a new <see cref="ScriptOptions"/> with unsafe code regions allowed.
/// </summary>
public ScriptOptions WithAllowUnsafe(bool allowUnsafe) =>
allowUnsafe == AllowUnsafe ? this : new ScriptOptions(this) { AllowUnsafe = allowUnsafe };
/// <summary>
/// Create a new <see cref="ScriptOptions"/> with bounds checking on integer arithmetic enforced.
/// </summary>
public ScriptOptions WithCheckOverflow(bool checkOverflow) =>
checkOverflow == CheckOverflow ? this : new ScriptOptions(this) { CheckOverflow = checkOverflow };
/// <summary>
/// Create a new <see cref="ScriptOptions"/> with the specific <see cref="WarningLevel"/>.
/// </summary>
public ScriptOptions WithWarningLevel(int warningLevel) =>
warningLevel == WarningLevel ? this : new ScriptOptions(this) { WarningLevel = warningLevel };
internal ScriptOptions WithParseOptions(ParseOptions parseOptions) =>
parseOptions == ParseOptions ? this : new ScriptOptions(this) { ParseOptions = parseOptions };
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Reflection;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.Scripting.Hosting;
namespace Microsoft.CodeAnalysis.Scripting
{
using static ParameterValidationHelpers;
/// <summary>
/// Options for creating and running scripts.
/// </summary>
public sealed class ScriptOptions
{
public static ScriptOptions Default { get; } = new ScriptOptions(
filePath: string.Empty,
references: GetDefaultMetadataReferences(),
namespaces: ImmutableArray<string>.Empty,
metadataResolver: ScriptMetadataResolver.Default,
sourceResolver: SourceFileResolver.Default,
emitDebugInformation: false,
fileEncoding: null,
OptimizationLevel.Debug,
checkOverflow: false,
allowUnsafe: true,
warningLevel: 4,
parseOptions: null);
private static ImmutableArray<MetadataReference> GetDefaultMetadataReferences()
{
if (GacFileResolver.IsAvailable)
{
return ImmutableArray<MetadataReference>.Empty;
}
// These references are resolved lazily. Keep in sync with list in core csi.rsp.
var files = new[]
{
"System.Collections",
"System.Collections.Concurrent",
"System.Console",
"System.Diagnostics.Debug",
"System.Diagnostics.Process",
"System.Diagnostics.StackTrace",
"System.Globalization",
"System.IO",
"System.IO.FileSystem",
"System.IO.FileSystem.Primitives",
"System.Reflection",
"System.Reflection.Extensions",
"System.Reflection.Primitives",
"System.Runtime",
"System.Runtime.Extensions",
"System.Runtime.InteropServices",
"System.Text.Encoding",
"System.Text.Encoding.CodePages",
"System.Text.Encoding.Extensions",
"System.Text.RegularExpressions",
"System.Threading",
"System.Threading.Tasks",
"System.Threading.Tasks.Parallel",
"System.Threading.Thread",
"System.ValueTuple",
};
return ImmutableArray.CreateRange(files.Select(CreateUnresolvedReference));
}
/// <summary>
/// An array of <see cref="MetadataReference"/>s to be added to the script.
/// </summary>
/// <remarks>
/// The array may contain both resolved and unresolved references (<see cref="UnresolvedMetadataReference"/>).
/// Unresolved references are resolved when the script is about to be executed
/// (<see cref="Script.RunAsync(object, CancellationToken)"/>.
/// Any resolution errors are reported at that point through <see cref="CompilationErrorException"/>.
/// </remarks>
public ImmutableArray<MetadataReference> MetadataReferences { get; private set; }
/// <summary>
/// <see cref="MetadataReferenceResolver"/> to be used to resolve missing dependencies, unresolved metadata references and #r directives.
/// </summary>
public MetadataReferenceResolver MetadataResolver { get; private set; }
/// <summary>
/// <see cref="SourceReferenceResolver"/> to be used to resolve source of scripts referenced via #load directive.
/// </summary>
public SourceReferenceResolver SourceResolver { get; private set; }
/// <summary>
/// The namespaces, static classes and aliases imported by the script.
/// </summary>
public ImmutableArray<string> Imports { get; private set; }
/// <summary>
/// Specifies whether debugging symbols should be emitted.
/// </summary>
public bool EmitDebugInformation { get; private set; } = false;
/// <summary>
/// Specifies the encoding to be used when debugging scripts loaded from a file, or saved to a file for debugging purposes.
/// If it's null, the compiler will attempt to detect the necessary encoding for debugging
/// </summary>
public Encoding FileEncoding { get; private set; }
/// <summary>
/// The path to the script source if it originated from a file, empty otherwise.
/// </summary>
public string FilePath { get; private set; }
/// <summary>
/// Specifies whether or not optimizations should be performed on the output IL.
/// </summary>
public OptimizationLevel OptimizationLevel { get; private set; }
/// <summary>
/// Whether bounds checking on integer arithmetic is enforced by default or not.
/// </summary>
public bool CheckOverflow { get; private set; }
/// <summary>
/// Allow unsafe regions (i.e. unsafe modifiers on members and unsafe blocks).
/// </summary>
public bool AllowUnsafe { get; private set; }
/// <summary>
/// Global warning level (from 0 to 4).
/// </summary>
public int WarningLevel { get; private set; }
internal ParseOptions ParseOptions { get; private set; }
internal ScriptOptions(
string filePath,
ImmutableArray<MetadataReference> references,
ImmutableArray<string> namespaces,
MetadataReferenceResolver metadataResolver,
SourceReferenceResolver sourceResolver,
bool emitDebugInformation,
Encoding fileEncoding,
OptimizationLevel optimizationLevel,
bool checkOverflow,
bool allowUnsafe,
int warningLevel,
ParseOptions parseOptions)
{
Debug.Assert(filePath != null);
Debug.Assert(!references.IsDefault);
Debug.Assert(!namespaces.IsDefault);
Debug.Assert(metadataResolver != null);
Debug.Assert(sourceResolver != null);
FilePath = filePath;
MetadataReferences = references;
Imports = namespaces;
MetadataResolver = metadataResolver;
SourceResolver = sourceResolver;
EmitDebugInformation = emitDebugInformation;
FileEncoding = fileEncoding;
OptimizationLevel = optimizationLevel;
CheckOverflow = checkOverflow;
AllowUnsafe = allowUnsafe;
WarningLevel = warningLevel;
ParseOptions = parseOptions;
}
private ScriptOptions(ScriptOptions other)
: this(filePath: other.FilePath,
references: other.MetadataReferences,
namespaces: other.Imports,
metadataResolver: other.MetadataResolver,
sourceResolver: other.SourceResolver,
emitDebugInformation: other.EmitDebugInformation,
fileEncoding: other.FileEncoding,
optimizationLevel: other.OptimizationLevel,
checkOverflow: other.CheckOverflow,
allowUnsafe: other.AllowUnsafe,
warningLevel: other.WarningLevel,
parseOptions: other.ParseOptions)
{
}
// a reference to an assembly should by default be equivalent to #r, which applies recursive global alias:
private static readonly MetadataReferenceProperties s_assemblyReferenceProperties =
MetadataReferenceProperties.Assembly.WithRecursiveAliases(true);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the <see cref="FilePath"/> changed.
/// </summary>
public ScriptOptions WithFilePath(string filePath) =>
(FilePath == filePath) ? this : new ScriptOptions(this) { FilePath = filePath ?? "" };
private static MetadataReference CreateUnresolvedReference(string reference) =>
new UnresolvedMetadataReference(reference, s_assemblyReferenceProperties);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
private ScriptOptions WithReferences(ImmutableArray<MetadataReference> references) =>
MetadataReferences.Equals(references) ? this : new ScriptOptions(this) { MetadataReferences = CheckImmutableArray(references, nameof(references)) };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions WithReferences(IEnumerable<MetadataReference> references) =>
WithReferences(ToImmutableArrayChecked(references, nameof(references)));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions WithReferences(params MetadataReference[] references) =>
WithReferences((IEnumerable<MetadataReference>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions AddReferences(IEnumerable<MetadataReference> references) =>
WithReferences(ConcatChecked(MetadataReferences, references, nameof(references)));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
public ScriptOptions AddReferences(params MetadataReference[] references) =>
AddReferences((IEnumerable<MetadataReference>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
/// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception>
public ScriptOptions WithReferences(IEnumerable<Assembly> references) =>
WithReferences(SelectChecked(references, nameof(references), CreateReferenceFromAssembly));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
/// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception>
public ScriptOptions WithReferences(params Assembly[] references) =>
WithReferences((IEnumerable<Assembly>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
/// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception>
public ScriptOptions AddReferences(IEnumerable<Assembly> references) =>
AddReferences(SelectChecked(references, nameof(references), CreateReferenceFromAssembly));
private static MetadataReference CreateReferenceFromAssembly(Assembly assembly)
{
return MetadataReference.CreateFromAssemblyInternal(assembly, s_assemblyReferenceProperties);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
/// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception>
public ScriptOptions AddReferences(params Assembly[] references) =>
AddReferences((IEnumerable<Assembly>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions WithReferences(IEnumerable<string> references) =>
WithReferences(SelectChecked(references, nameof(references), CreateUnresolvedReference));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions WithReferences(params string[] references) =>
WithReferences((IEnumerable<string>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception>
public ScriptOptions AddReferences(IEnumerable<string> references) =>
AddReferences(SelectChecked(references, nameof(references), CreateUnresolvedReference));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
public ScriptOptions AddReferences(params string[] references) =>
AddReferences((IEnumerable<string>)references);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with specified <see cref="MetadataResolver"/>.
/// </summary>
public ScriptOptions WithMetadataResolver(MetadataReferenceResolver resolver) =>
MetadataResolver == resolver ? this : new ScriptOptions(this) { MetadataResolver = resolver };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with specified <see cref="SourceResolver"/>.
/// </summary>
public ScriptOptions WithSourceResolver(SourceReferenceResolver resolver) =>
SourceResolver == resolver ? this : new ScriptOptions(this) { SourceResolver = resolver };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
private ScriptOptions WithImports(ImmutableArray<string> imports) =>
Imports.Equals(imports) ? this : new ScriptOptions(this) { Imports = CheckImmutableArray(imports, nameof(imports)) };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
public ScriptOptions WithImports(IEnumerable<string> imports) =>
WithImports(ToImmutableArrayChecked(imports, nameof(imports)));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
public ScriptOptions WithImports(params string[] imports) =>
WithImports((IEnumerable<string>)imports);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with <see cref="Imports"/> added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
public ScriptOptions AddImports(IEnumerable<string> imports) =>
WithImports(ConcatChecked(Imports, imports, nameof(imports)));
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with <see cref="Imports"/> added.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception>
public ScriptOptions AddImports(params string[] imports) =>
AddImports((IEnumerable<string>)imports);
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with debugging information enabled.
/// </summary>
public ScriptOptions WithEmitDebugInformation(bool emitDebugInformation) =>
emitDebugInformation == EmitDebugInformation ? this : new ScriptOptions(this) { EmitDebugInformation = emitDebugInformation };
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with specified <see cref="FileEncoding"/>.
/// </summary>
public ScriptOptions WithFileEncoding(Encoding encoding) =>
encoding == FileEncoding ? this : new ScriptOptions(this) { FileEncoding = encoding };
/// <summary>
/// Create a new <see cref="ScriptOptions"/> with the specified <see cref="OptimizationLevel"/>.
/// </summary>
/// <returns></returns>
public ScriptOptions WithOptimizationLevel(OptimizationLevel optimizationLevel) =>
optimizationLevel == OptimizationLevel ? this : new ScriptOptions(this) { OptimizationLevel = optimizationLevel };
/// <summary>
/// Create a new <see cref="ScriptOptions"/> with unsafe code regions allowed.
/// </summary>
public ScriptOptions WithAllowUnsafe(bool allowUnsafe) =>
allowUnsafe == AllowUnsafe ? this : new ScriptOptions(this) { AllowUnsafe = allowUnsafe };
/// <summary>
/// Create a new <see cref="ScriptOptions"/> with bounds checking on integer arithmetic enforced.
/// </summary>
public ScriptOptions WithCheckOverflow(bool checkOverflow) =>
checkOverflow == CheckOverflow ? this : new ScriptOptions(this) { CheckOverflow = checkOverflow };
/// <summary>
/// Create a new <see cref="ScriptOptions"/> with the specific <see cref="WarningLevel"/>.
/// </summary>
public ScriptOptions WithWarningLevel(int warningLevel) =>
warningLevel == WarningLevel ? this : new ScriptOptions(this) { WarningLevel = warningLevel };
internal ScriptOptions WithParseOptions(ParseOptions parseOptions) =>
parseOptions == ParseOptions ? this : new ScriptOptions(this) { ParseOptions = parseOptions };
}
}
| -1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/EditorFeatures/CSharpTest/CodeActions/ConvertLinq/ConvertForEachToLinqQueryTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Editor.CSharp.UnitTests.CodeRefactorings;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.ConvertLinq
{
public class ConvertForEachToLinqQueryTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new CodeAnalysis.CSharp.ConvertLinq.ConvertForEachToLinqQuery.CSharpConvertForEachToLinqQueryProvider();
#region Query Expressions
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QueryForForWhere()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public IEnumerable<int> void Main(string[] args)
{
List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7};
List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70};
[|foreach (var x1 in c1)
{
foreach (var x2 in c2)
{
if (object.Equals(x1, x2 / 10))
{
yield return x1 + x2;
}
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public IEnumerable<int> void Main(string[] args)
{
List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7};
List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70};
return from x1 in c1
from x2 in c2
where object.Equals(x1, x2 / 10)
select x1 + x2;
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public IEnumerable<int> void Main(string[] args)
{
List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7};
List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70};
return c1.SelectMany(x1 => c2.Where(x2 => object.Equals(x1, x2 / 10)).Select(x2 => x1 + x2));
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QueryWithEscapedSymbols()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public IEnumerable<int> void Main(string[] args)
{
List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7};
List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70};
[|foreach (var @object in c1)
{
foreach (var x2 in c2)
{
yield return @object + x2;
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public IEnumerable<int> void Main(string[] args)
{
List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7};
List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70};
return from @object in c1
from x2 in c2
select @object + x2;
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public IEnumerable<int> void Main(string[] args)
{
List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7};
List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70};
return c1.SelectMany(@object => c2.Select(x2 => @object + x2));
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QueryForVarForWhere()
{
var source = @"
using System.Linq;
class C
{
IEnumerable<int> M()
{
[|foreach (var num in new int[] { 1, 2 })
{
var n1 = num + 1;
foreach (var a in new int[] { 5, 6 })
{
foreach (var x1 in new int[] { 3, 4 })
{
if (object.Equals(num, x1))
{
foreach (var x2 in new int[] { 7, 8 })
{
if (object.Equals(num, x2))
{
var n2 = x2 - 1;
yield return n2 + n1;
}
}
}
}
}|]
}
}
}";
var queryOutput = @"
using System.Linq;
class C
{
IEnumerable<int> M()
{
return from num in new int[] { 1, 2 }
let n1 = num + 1
from a in new int[] { 5, 6 }
from x1 in new int[] { 3, 4 }
where object.Equals(num, x1)
from x2 in new int[] { 7, 8 }
where object.Equals(num, x2)
let n2 = x2 - 1
select n2 + n1;
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
// No linq refactoring offered due to variable declaration within the outermost foreach.
await TestActionCountAsync(source, count: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QueryForVarForWhere_02()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M()
{
[|foreach (var num in new int[] { 1, 2 })
{
foreach (var a in new int[] { 5, 6 })
{
foreach (var x1 in new int[] { 3, 4 })
{
if (object.Equals(num, x1))
{
foreach (var x2 in new int[] { 7, 8 })
{
if (object.Equals(num, x2))
{
var n1 = num + 1;
var n2 = x2 - 1;
yield return n2 + n1;
}
}
}
}
}|]
}
}
}";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M()
{
return from num in new int[] { 1, 2 }
from a in new int[] { 5, 6 }
from x1 in new int[] { 3, 4 }
where object.Equals(num, x1)
from x2 in new int[] { 7, 8 }
where object.Equals(num, x2)
let n1 = num + 1
let n2 = x2 - 1
select n2 + n1;
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M()
{
foreach (var (num, x2) in (new int[] { 1, 2 }).SelectMany(num => (new int[] { 5, 6 }).SelectMany(a => (new int[] { 3, 4 }).Where(x1 => object.Equals(num, x1)).SelectMany(x1 => (new int[] { 7, 8 }).Where(x2 => object.Equals(num, x2)).Select(x2 => (num, x2))))))
{
var n1 = num + 1;
var n2 = x2 - 1;
yield return n2 + n1;
}
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QueryForVarForWhere_03()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M()
{
[|foreach (var num in new int[] { 1, 2 })
{
foreach (var a in new int[] { 5, 6 })
{
foreach (var x1 in new int[] { 3, 4 })
{
var n1 = num + 1;
if (object.Equals(num, x1))
{
foreach (var x2 in new int[] { 7, 8 })
{
if (object.Equals(num, x2))
{
var n2 = x2 - 1;
yield return n2 + n1;
}
}
}
}
}|]
}
}
}";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M()
{
return from num in new int[] { 1, 2 }
from a in new int[] { 5, 6 }
from x1 in new int[] { 3, 4 }
let n1 = num + 1
where object.Equals(num, x1)
from x2 in new int[] { 7, 8 }
where object.Equals(num, x2)
let n2 = x2 - 1
select n2 + n1;
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M()
{
foreach (var (num, x1) in (new int[] { 1, 2 }).SelectMany(num => (new int[] { 5, 6 }).SelectMany(a => (new int[] { 3, 4 }).Select(x1 => (num, x1)))))
{
var n1 = num + 1;
if (object.Equals(num, x1))
{
foreach (var x2 in new int[] { 7, 8 })
{
if (object.Equals(num, x2))
{
var n2 = x2 - 1;
yield return n2 + n1;
}
}
}
}
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QueryLet()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Query
{
void M()
{
List<int> c1 = new List<int>{ 1, 2, 3 };
List<int> r1 = new List<int>();
[|foreach (int x in c1)
{
var g = x * 10;
var z = g + x*100;
var a = 5 + z;
r1.Add(x + z - a);
}|]
}
}";
var queryOutput = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Query
{
void M()
{
List<int> c1 = new List<int>{ 1, 2, 3 };
List<int> r1 = (from int x in c1
let g = x * 10
let z = g + x * 100
let a = 5 + z
select x + z - a).ToList();
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
// No linq invocation refactoring offered due to variable declaration(s) in topmost foreach.
await TestActionCountAsync(source, count: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QueryEmptyDeclarations()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Query
{
void M()
{
[|foreach (int x in new[] {1,2})
{
int a = 3, b, c = 1;
if (x > c)
{
b = 0;
Console.Write(a + x + b);
}
}|]
}
}";
await TestMissingInRegularAndScriptAsync(source);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QueryWhereClause()
{
var source = @"
using System;
using System.Linq;
class C
{
IEnumerable<int> M()
{
var nums = new int[] { 1, 2, 3, 4 };
[|foreach (var x in nums)
{
if (x > 2)
{
yield return x;
}
}|]
}
}";
var queryOutput = @"
using System;
using System.Linq;
class C
{
IEnumerable<int> M()
{
var nums = new int[] { 1, 2, 3, 4 };
return from x in nums
where x > 2
select x;
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System;
using System.Linq;
class C
{
IEnumerable<int> M()
{
var nums = new int[] { 1, 2, 3, 4 };
return nums.Where(x => x > 2);
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QueryOverQueries()
{
var source = @"
using System;
using System.Linq;
class C
{
IEnumerable<int> M()
{
var nums = new int[] { 1, 2, 3, 4 };
[|foreach (var y in from x in nums select x)
{
foreach (var z in from x in nums select x)
{
yield return y;
}
}|]
}
}";
var queryOutput = @"
using System;
using System.Linq;
class C
{
IEnumerable<int> M()
{
var nums = new int[] { 1, 2, 3, 4 };
return from y in
from x in nums select x
from z in
from x in nums select x
select y;
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System;
using System.Linq;
class C
{
IEnumerable<int> M()
{
var nums = new int[] { 1, 2, 3, 4 };
return (from x in nums select x).SelectMany(y => (from x in nums select x).Select(z => y));
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QueryNoVariablesUsed()
{
var source = @"
using System;
using System.Linq;
class C
{
void M()
{
[|foreach (var a in new[] { 1 })
{
foreach (var b in new[] { 2 })
{
System.Console.Write(0);
}
}|]
}
}";
var queryOutput = @"
using System;
using System.Linq;
class C
{
void M()
{
foreach (var _ in from a in new[] { 1 }
from b in new[] { 2 }
select new { })
{
System.Console.Write(0);
}
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System;
using System.Linq;
class C
{
void M()
{
foreach (var _ in (new[] { 1 }).SelectMany(a => (new[] { 2 }).Select(b => new { })))
{
System.Console.Write(0);
}
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QueryNoBlock()
{
var source = @"
using System;
using System.Linq;
class C
{
void M()
{
[|foreach (var a in new[] { 1 })
foreach (var b in new[] { 2 })
System.Console.Write(a);|]
}
}";
var queryOutput = @"
using System;
using System.Linq;
class C
{
void M()
{
foreach (var a in from a in new[] { 1 }
from b in new[] { 2 }
select a)
{
System.Console.Write(a);
}
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System;
using System.Linq;
class C
{
void M()
{
foreach (var a in (new[] { 1 }).SelectMany(a => (new[] { 2 }).Select(b => a)))
{
System.Console.Write(a);
}
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QuerySelectExpression()
{
var source = @"
using System;
using System.Linq;
class C
{
void M()
{
[|foreach (var a in new[] { 1 })
foreach (var b in new[] { 2 })
Console.Write(a + b);|]
}
}";
var queryOutput = @"
using System;
using System.Linq;
class C
{
void M()
{
foreach (var (a, b) in from a in new[] { 1 }
from b in new[] { 2 }
select (a, b))
{
Console.Write(a + b);
}
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System;
using System.Linq;
class C
{
void M()
{
foreach (var (a, b) in (new[] { 1 }).SelectMany(a => (new[] { 2 }).Select(b => (a, b))))
{
Console.Write(a + b);
}
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QuerySelectMultipleExpressions()
{
var source = @"
using System;
using System.Linq;
class C
{
void M()
{
[|foreach (var a in new[] { 1 })
foreach (var b in new[] { 2 })
{
Console.Write(a + b);
Console.Write(a * b);
}|]
}
}";
var queryOutput = @"
using System;
using System.Linq;
class C
{
void M()
{
foreach (var (a, b) in from a in new[] { 1 }
from b in new[] { 2 }
select (a, b))
{
Console.Write(a + b);
Console.Write(a * b);
}
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System;
using System.Linq;
class C
{
void M()
{
foreach (var (a, b) in (new[] { 1 }).SelectMany(a => (new[] { 2 }).Select(b => (a, b))))
{
Console.Write(a + b);
Console.Write(a * b);
}
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task EmptyBody()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
foreach (var _ in from int n1 in nums
from int n2 in nums
select new { })
{
}
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
foreach (var _ in nums.SelectMany(n1 => nums.Select(n2 => new { })))
{
}
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task EmptyBodyNoBlock()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
[|foreach (int n1 in nums)
{
foreach (int n2 in nums);
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
foreach (var _ in from int n1 in nums
from int n2 in nums
select new { })
{
}
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
foreach (var _ in nums.SelectMany(n1 => nums.Select(n2 => new { })))
{
}
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task AddUsingToExistingList()
{
var source = @"
using System.Collections.Generic;
class C
{
void M(IEnumerable<int> nums)
{
[|foreach (int n1 in nums)
{
foreach (int n2 in nums);
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
foreach (var _ in from int n1 in nums
from int n2 in nums
select new { })
{
}
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
foreach (var _ in nums.SelectMany(n1 => nums.Select(n2 => new { })))
{
}
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task AddFirstUsing()
{
var source = @"
class C
{
void M(int[] nums)
{
[|foreach (int n1 in nums)
{
foreach (int n2 in nums);
}|]
}
}
";
var queryOutput = @"using System.Linq;
class C
{
void M(int[] nums)
{
foreach (var _ in from int n1 in nums
from int n2 in nums
select new { })
{
}
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"using System.Linq;
class C
{
void M(int[] nums)
{
foreach (var _ in nums.SelectMany(n1 => nums.Select(n2 => new { })))
{
}
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task EmptyBodyDeclarationAsLast()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
var a = n1 + n2;
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
foreach (var _ in from int n1 in nums
from int n2 in nums
let a = n1 + n2
select new { })
{
}
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
foreach (var (n1, n2) in nums.SelectMany(n1 => nums.Select(n2 => (n1, n2))))
{
var a = n1 + n2;
}
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task EmptyBodyMultipleDeclarationsAsLast()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
int a = n1 + n2, b = n1 * n2;
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
foreach (var _ in from int n1 in nums
from int n2 in nums
let a = n1 + n2
let b = n1 * n2
select new { })
{
}
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
foreach (var (n1, n2) in nums.SelectMany(n1 => nums.Select(n2 => (n1, n2))))
{
int a = n1 + n2, b = n1 * n2;
}
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
#endregion
#region Assignments, Declarations, Returns
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ReturnInvocationAndYieldReturn()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
yield return N(n1);
}
}|]
}
int N(int n) => n;
}
";
var queryOutput = @"
using System;
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
return from int n1 in nums
from int n2 in nums
select N(n1);
}
int N(int n) => n;
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System;
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
return nums.SelectMany(n1 => nums.Select(n2 => N(n1)));
}
int N(int n) => n;
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task BlockBodiedProperty()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
public class Test
{
private readonly int[] _nums = new int[] { 1, 2, 3, 4 };
public IEnumerable<int> Query1 { get { [|foreach (var x in _nums) { yield return x + 1; }|] } }
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
public class Test
{
private readonly int[] _nums = new int[] { 1, 2, 3, 4 };
public IEnumerable<int> Query1 { get { return from x in _nums select x + 1; } }
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
public class Test
{
private readonly int[] _nums = new int[] { 1, 2, 3, 4 };
public IEnumerable<int> Query1 { get { return _nums.Select(x => x + 1); } }
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ReturnIEnumerable()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
yield return n1;
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
return from int n1 in nums
from int n2 in nums
select n1;
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
return nums.SelectMany(n1 => nums.Select(n2 => n1));
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ReturnIEnumerableWithYieldReturnAndLocalFunction()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<IEnumerable<int>> M(IEnumerable<int> nums)
{
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
yield return f(n1);
}
}|]
yield break;
IEnumerable<int> f(int a)
{
yield return a;
}
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<IEnumerable<int>> M(IEnumerable<int> nums)
{
return from int n1 in nums
from int n2 in nums
select f(n1);
IEnumerable<int> f(int a)
{
yield return a;
}
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<IEnumerable<int>> M(IEnumerable<int> nums)
{
return nums.SelectMany(n1 => nums.Select(n2 => f(n1)));
IEnumerable<int> f(int a)
{
yield return a;
}
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ReturnIEnumerablePartialMethod()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
partial class C
{
partial IEnumerable<int> M(IEnumerable<int> nums);
}
partial class C
{
partial IEnumerable<int> M(IEnumerable<int> nums)
{
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
yield return n1;
}
}|]
yield break;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
partial class C
{
partial IEnumerable<int> M(IEnumerable<int> nums);
}
partial class C
{
partial IEnumerable<int> M(IEnumerable<int> nums)
{
return from int n1 in nums
from int n2 in nums
select n1;
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
partial class C
{
partial IEnumerable<int> M(IEnumerable<int> nums);
}
partial class C
{
partial IEnumerable<int> M(IEnumerable<int> nums)
{
return nums.SelectMany(n1 => nums.Select(n2 => n1));
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ReturnIEnumerableExtendedPartialMethod()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
partial class C
{
public partial IEnumerable<int> M(IEnumerable<int> nums);
}
partial class C
{
public partial IEnumerable<int> M(IEnumerable<int> nums)
{
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
yield return n1;
}
}|]
yield break;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
partial class C
{
public partial IEnumerable<int> M(IEnumerable<int> nums);
}
partial class C
{
public partial IEnumerable<int> M(IEnumerable<int> nums)
{
return from int n1 in nums
from int n2 in nums
select n1;
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
partial class C
{
public partial IEnumerable<int> M(IEnumerable<int> nums);
}
partial class C
{
public partial IEnumerable<int> M(IEnumerable<int> nums)
{
return nums.SelectMany(n1 => nums.Select(n2 => n1));
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
[WorkItem(31784, "https://github.com/dotnet/roslyn/issues/31784")]
public async Task QueryWhichRequiresSelectManyWithIdentityLambda()
{
var source = @"
using System.Collections.Generic;
class C
{
IEnumerable<int> M()
{
[|foreach (var x in new[] { new[] { 1, 2, 3 }, new[] { 4, 5, 6 } })
{
foreach (var y in x)
{
yield return y;
}
}|]
}
}
";
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M()
{
return (new[] { new[] { 1, 2, 3 }, new[] { 4, 5, 6 } }).SelectMany(x => x);
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
#endregion
#region In foreach
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QueryInForEachWithSameVariableNameAndDifferentType()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Linq;
class A
{
public static implicit operator int(A x)
{
throw null;
}
public static implicit operator A(int x)
{
throw null;
}
}
class B : A { }
class C
{
void M(IEnumerable<int> nums)
{
[|foreach (B a in nums)
{
foreach (A c in nums)
{
Console.Write(a.ToString());
}
}|]
}
}
";
var queryOutput = @"
using System;
using System.Collections.Generic;
using System.Linq;
class A
{
public static implicit operator int(A x)
{
throw null;
}
public static implicit operator A(int x)
{
throw null;
}
}
class B : A { }
class C
{
void M(IEnumerable<int> nums)
{
foreach (var a in from B a in nums
from A c in nums
select a)
{
Console.Write(a.ToString());
}
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System;
using System.Collections.Generic;
using System.Linq;
class A
{
public static implicit operator int(A x)
{
throw null;
}
public static implicit operator A(int x)
{
throw null;
}
}
class B : A { }
class C
{
void M(IEnumerable<int> nums)
{
foreach (var a in nums.SelectMany(a => nums.Select(c => a)))
{
Console.Write(a.ToString());
}
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QueryInForEachWithSameVariableNameAndSameType()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Linq;
class A
{
public static implicit operator int(A x)
{
throw null;
}
public static implicit operator A(int x)
{
throw null;
}
}
class C
{
void M(IEnumerable<int> nums)
{
[|foreach (A a in nums)
{
foreach (A c in nums)
{
Console.Write(a.ToString());
}
}|]
}
}
";
var queryOutput = @"
using System;
using System.Collections.Generic;
using System.Linq;
class A
{
public static implicit operator int(A x)
{
throw null;
}
public static implicit operator A(int x)
{
throw null;
}
}
class C
{
void M(IEnumerable<int> nums)
{
foreach (var a in from A a in nums
from A c in nums
select a)
{
Console.Write(a.ToString());
}
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System;
using System.Collections.Generic;
using System.Linq;
class A
{
public static implicit operator int(A x)
{
throw null;
}
public static implicit operator A(int x)
{
throw null;
}
}
class C
{
void M(IEnumerable<int> nums)
{
foreach (var a in nums.SelectMany(a => nums.Select(c => a)))
{
Console.Write(a.ToString());
}
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QueryInForEachWithConvertedType()
{
var source = @"
using System;
using System.Collections.Generic;
static class Extensions
{
public static IEnumerable<C> Select(this int[] x, Func<int, C> predicate) => throw null;
}
class C
{
public static implicit operator int(C x)
{
throw null;
}
public static implicit operator C(int x)
{
throw null;
}
IEnumerable<C> Test()
{
[|foreach (var x in new[] { 1, 2, 3 })
{
yield return x;
}|]
}
}
";
var queryOutput = @"
using System;
using System.Collections.Generic;
using System.Linq;
static class Extensions
{
public static IEnumerable<C> Select(this int[] x, Func<int, C> predicate) => throw null;
}
class C
{
public static implicit operator int(C x)
{
throw null;
}
public static implicit operator C(int x)
{
throw null;
}
IEnumerable<C> Test()
{
return from x in new[] { 1, 2, 3 }
select x;
}
}
";
await TestAsync(source, queryOutput, parseOptions: null);
var linqInvocationOutput = @"
using System;
using System.Collections.Generic;
using System.Linq;
static class Extensions
{
public static IEnumerable<C> Select(this int[] x, Func<int, C> predicate) => throw null;
}
class C
{
public static implicit operator int(C x)
{
throw null;
}
public static implicit operator C(int x)
{
throw null;
}
IEnumerable<C> Test()
{
return new[] { 1, 2, 3 };
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task IQueryableConvertedToIEnumerableInReturn()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
[|foreach (int n1 in nums.AsQueryable())
{
yield return n1;
}|]
yield break;
}
}";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
return from int n1 in nums.AsQueryable()
select n1;
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
return nums.AsQueryable();
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ReturnIQueryableConvertedToIEnumerableInAssignment()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
[|foreach (int n1 in nums.AsQueryable())
{
yield return n1;
}|]
}
}";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
return from int n1 in nums.AsQueryable()
select n1;
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
return nums.AsQueryable();
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
#endregion
#region In ToList
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListLastDeclarationMerge()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list0 = new List<int>(), list = new List<int>();
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
list.Add(n1);
}
}|]
return list;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list0 = new List<int>();
return (from int n1 in nums
from int n2 in nums
select n1).ToList();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list0 = new List<int>();
return (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListParameterizedConstructor()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list = new List<int>(nums);
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
list.Add(n1);
}
}|]
return list;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list = new List<int>(nums);
list.AddRange(from int n1 in nums
from int n2 in nums
select n1);
return list;
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list = new List<int>(nums);
list.AddRange(nums.SelectMany(n1 => nums.Select(n2 => n1)));
return list;
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListWithListInitializer()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list = new List<int>() { 1, 2, 3 };
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
list.Add(n1);
}
}|]
return list;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list = new List<int>() { 1, 2, 3 };
list.AddRange(from int n1 in nums
from int n2 in nums
select n1);
return list;
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list = new List<int>() { 1, 2, 3 };
list.AddRange(nums.SelectMany(n1 => nums.Select(n2 => n1)));
return list;
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListWithEmptyArgumentList()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list = new List<int> { };
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
list.Add(n1);
}
}|]
return list;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
return (from int n1 in nums
from int n2 in nums
select n1).ToList();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
return (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListNotLastDeclaration()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list = new List<int>(), list1 = new List<int>();
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
list.Add(n1);
}
}|]
return list;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list = new List<int>(), list1 = new List<int>();
list.AddRange(from int n1 in nums
from int n2 in nums
select n1);
return list;
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list = new List<int>(), list1 = new List<int>();
list.AddRange(nums.SelectMany(n1 => nums.Select(n2 => n1)));
return list;
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListAssignToParameter()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums, List<int> list)
{
list = new List<int>();
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
list.Add(n1);
}
}|]
return list;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums, List<int> list)
{
list = (from int n1 in nums
from int n2 in nums
select n1).ToList();
return list;
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums, List<int> list)
{
list = (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList();
return list;
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListToArrayElement()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums, List<int>[] lists)
{
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
lists[0].Add(n1);
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums, List<int>[] lists)
{
lists[0].AddRange(from int n1 in nums
from int n2 in nums
select n1);
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums, List<int>[] lists)
{
lists[0].AddRange(nums.SelectMany(n1 => nums.Select(n2 => n1)));
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListToNewArrayElement()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums, List<int>[] lists)
{
lists[0] = new List<int>();
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
lists[0].Add(n1);
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums, List<int>[] lists)
{
lists[0] = (from int n1 in nums
from int n2 in nums
select n1).ToList();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums, List<int>[] lists)
{
lists[0] = (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListHashSetNoConversion()
{
var source = @"
using System.Collections.Generic;
class C
{
void M(IEnumerable<int> nums)
{
var hashSet = new HashSet<int>();
[|foreach (int n1 in nums)
{
hashSet.Add(n1);
}|]
}
}
";
await TestMissingAsync(source);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListMergeWithReturn()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
var list = new List<int>();
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
list.Add(n1);
}
}|]
return list;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
return (from int n1 in nums
from int n2 in nums
select n1).ToList();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
return (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListSeparateDeclarationAndAssignmentMergeWithReturn()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list;
list = new List<int>();
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
list.Add(n1);
}
}|]
return list;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list;
return (from int n1 in nums
from int n2 in nums
select n1).ToList();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list;
return (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListSeparateDeclarationAndAssignment()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
List<int> list;
list = new List<int>();
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
list.Add(n1);
}
}|]
return list.Count;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
List<int> list;
list = (from int n1 in nums
from int n2 in nums
select n1).ToList();
return list.Count;
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
List<int> list;
list = (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList();
return list.Count;
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListTypeReplacement01()
{
var source = @"
using System;
using System.Linq;
using C = System.Collections.Generic.List<int>;
class Query
{
public static void Main(string[] args)
{
C c1 = new C { 1, 2, 3 };
C c2 = new C { 10, 20, 30 };
C c3 = new C { 100, 200, 300 };
C r1 = new C();
[|foreach (int x in c1)
{
foreach (int y in c2)
{
foreach (int z in c3)
{
var g = x + y + z;
if (x + y / 10 + z / 100 < 6)
{
r1.Add(g);
}
}
}
}|]
Console.WriteLine(r1);
}
}
";
var queryOutput = @"
using System;
using System.Linq;
using C = System.Collections.Generic.List<int>;
class Query
{
public static void Main(string[] args)
{
C c1 = new C { 1, 2, 3 };
C c2 = new C { 10, 20, 30 };
C c3 = new C { 100, 200, 300 };
C r1 = (from int x in c1
from int y in c2
from int z in c3
let g = x + y + z
where x + y / 10 + z / 100 < 6
select g).ToList();
Console.WriteLine(r1);
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System;
using System.Linq;
using C = System.Collections.Generic.List<int>;
class Query
{
public static void Main(string[] args)
{
C c1 = new C { 1, 2, 3 };
C c2 = new C { 10, 20, 30 };
C c3 = new C { 100, 200, 300 };
C r1 = new C();
foreach (var (x, y, z) in c1.SelectMany(x => c2.SelectMany(y => c3.Select(z => (x, y, z)))))
{
var g = x + y + z;
if (x + y / 10 + z / 100 < 6)
{
r1.Add(g);
}
}
Console.WriteLine(r1);
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListTypeReplacement02()
{
var source = @"
using System.Linq;
using System;
using C = System.Collections.Generic.List<int>;
class Query
{
public static void Main(string[] args)
{
C c1 = new C { 1, 2, 3 };
C c2 = new C { 10, 20, 30 };
C r1 = new C();
[|foreach (int x in c1)
{
foreach (var y in c2)
{
if (Equals(x, y / 10))
{
var z = x + y;
r1.Add(z);
}
}
}|]
Console.WriteLine(r1);
}
}
";
var queryOutput = @"
using System.Linq;
using System;
using C = System.Collections.Generic.List<int>;
class Query
{
public static void Main(string[] args)
{
C c1 = new C { 1, 2, 3 };
C c2 = new C { 10, 20, 30 };
C r1 = (from int x in c1
from y in c2
where Equals(x, y / 10)
let z = x + y
select z).ToList();
Console.WriteLine(r1);
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Linq;
using System;
using C = System.Collections.Generic.List<int>;
class Query
{
public static void Main(string[] args)
{
C c1 = new C { 1, 2, 3 };
C c2 = new C { 10, 20, 30 };
C r1 = new C();
foreach (var (x, y) in c1.SelectMany(x => c2.Where(y => Equals(x, y / 10)).Select(y => (x, y))))
{
var z = x + y;
r1.Add(z);
}
Console.WriteLine(r1);
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListPropertyAssignment()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
public class Test
{
public static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
var c = new C();
c.A = new List<int>();
[|foreach (var x in nums)
{
c.A.Add(x + 1);
}|]
}
class C
{
public List<int> A { get; set; }
}
}";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
public class Test
{
public static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
var c = new C();
c.A = (from x in nums
select x + 1).ToList();
}
class C
{
public List<int> A { get; set; }
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
public class Test
{
public static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
var c = new C();
c.A = (nums.Select(x => x + 1)).ToList();
}
class C
{
public List<int> A { get; set; }
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListPropertyAssignmentNoDeclaration()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
public class Test
{
void M()
{
var nums = new int[] { 1, 2, 3, 4 };
var c = new C();
[|foreach (var x in nums)
{
c.A.Add(x + 1);
}|]
}
class C
{
public List<int> A { get; set; }
}
}";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
public class Test
{
void M()
{
var nums = new int[] { 1, 2, 3, 4 };
var c = new C();
c.A.AddRange(from x in nums
select x + 1);
}
class C
{
public List<int> A { get; set; }
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
public class Test
{
void M()
{
var nums = new int[] { 1, 2, 3, 4 };
var c = new C();
c.A.AddRange(nums.Select(x => x + 1));
}
class C
{
public List<int> A { get; set; }
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListNoInitialization()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
public class Test
{
public List<int> A { get; set; }
void M()
{
[|foreach (var x in new int[] { 1, 2, 3, 4 })
{
A.Add(x + 1);
}|]
}
}";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
public class Test
{
public List<int> A { get; set; }
void M()
{
A.AddRange(from x in new int[] { 1, 2, 3, 4 }
select x + 1);
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
public class Test
{
public List<int> A { get; set; }
void M()
{
A.AddRange((new int[] { 1, 2, 3, 4 }).Select(x => x + 1));
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListOverride()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
public static class C
{
public static void Add<T>(this List<T> list, T value, T anotherValue) { }
}
public class Test
{
void M()
{
var list = new List<int>();
[|foreach (var x in new int[] { 1, 2, 3, 4 })
{
list.Add(x + 1, x);
}|]
}
}";
await TestMissingAsync(source);
}
#endregion
#region In Count
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountInMultipleDeclarationLast()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
int i = 0, cnt = 0;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
cnt++;
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
int i = 0, cnt = (from int n1 in nums
from int n2 in nums
select n1).Count();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
int i = 0, cnt = (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountInMultipleDeclarationNotLast()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
int cnt = 0, i = 0;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
cnt++;
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
int cnt = 0, i = 0;
cnt += (from int n1 in nums
from int n2 in nums
select n1).Count();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
int cnt = 0, i = 0;
cnt += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountInParameter()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums, int c)
{
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
c++;
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums, int c)
{
c += (from int n1 in nums
from int n2 in nums
select n1).Count();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums, int c)
{
c += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountInParameterAssignedToZero()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums, int c)
{
c = 0;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
c++;
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums, int c)
{
c = (from int n1 in nums
from int n2 in nums
select n1).Count();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums, int c)
{
c = (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountInParameterAssignedToNonZero()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums, int c)
{
c = 5;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
c++;
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums, int c)
{
c = 5;
c += (from int n1 in nums
from int n2 in nums
select n1).Count();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums, int c)
{
c = 5;
c += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountInDeclarationMergeToReturn()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
var cnt = 0;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
cnt++;
}
}|]
return cnt;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
return (from int n1 in nums
from int n2 in nums
select n1).Count();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
return (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountInDeclarationConversion()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
double M(IEnumerable<int> nums)
{
double c = 0;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
c++;
}
}|]
return c;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
double M(IEnumerable<int> nums)
{
return (from int n1 in nums
from int n2 in nums
select n1).Count();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
double M(IEnumerable<int> nums)
{
return (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountInMultipleDeclarationMergeToReturnLast()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int c = 0, cnt = 0;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
cnt++;
}
}|]
return cnt;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int c = 0;
return (from int n1 in nums
from int n2 in nums
select n1).Count();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int c = 0;
return (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountInMultipleDeclarationLastButNotZero()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int c = 0, cnt = 5;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
cnt++;
}
}|]
return cnt;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int c = 0, cnt = 5;
cnt += (from int n1 in nums
from int n2 in nums
select n1).Count();
return cnt;
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int c = 0, cnt = 5;
cnt += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
return cnt;
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountInMultipleDeclarationMergeToReturnNotLast()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int cnt = 0, c = 0;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
cnt++;
}
}|]
return cnt;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int cnt = 0, c = 0;
cnt += (from int n1 in nums
from int n2 in nums
select n1).Count();
return cnt;
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int cnt = 0, c = 0;
cnt += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
return cnt;
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountInMultipleDeclarationNonZeroToReturnNotLast()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int cnt = 5, c = 0;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
cnt++;
}
}|]
return cnt;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int cnt = 5, c = 0;
cnt += (from int n1 in nums
from int n2 in nums
select n1).Count();
return cnt;
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int cnt = 5, c = 0;
cnt += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
return cnt;
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountInAssignmentToZero()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int cnt;
cnt = 0;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
cnt++;
}
}|]
return cnt;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int cnt;
return (from int n1 in nums
from int n2 in nums
select n1).Count();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int cnt;
return (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountInAssignmentToNonZero()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int cnt;
cnt = 5;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
cnt++;
}
}|]
return cnt;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int cnt;
cnt = 5;
cnt += (from int n1 in nums
from int n2 in nums
select n1).Count();
return cnt;
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int cnt;
cnt = 5;
cnt += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
return cnt;
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountInParameterAssignedToZeroAndReturned()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums, int c)
{
c = 0;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
c++;
}
}|]
return c;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums, int c)
{
c = (from int n1 in nums
from int n2 in nums
select n1).Count();
return c;
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums, int c)
{
c = (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
return c;
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountDeclareWithNonZero()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
var count = 5;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
count++;
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
var count = 5;
count += (from int n1 in nums
from int n2 in nums
select n1).Count();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
var count = 5;
count += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountAssignWithZero()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
int count = 1;
count = 0;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
count++;
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
int count = 1;
count = (from int n1 in nums
from int n2 in nums
select n1).Count();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
int count = 1;
count = (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountAssignWithNonZero()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
var count = 0;
count = 4;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
count++;
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
var count = 0;
count = 4;
count += (from int n1 in nums
from int n2 in nums
select n1).Count();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
var count = 0;
count = 4;
count += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountAssignPropertyAssignedToZero()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class A { public int B { get; set; }}
class C
{
void M(IEnumerable<int> nums, A a)
{
a.B = 0;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
a.B++;
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class A { public int B { get; set; }}
class C
{
void M(IEnumerable<int> nums, A a)
{
a.B = (from int n1 in nums
from int n2 in nums
select n1).Count();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class A { public int B { get; set; }}
class C
{
void M(IEnumerable<int> nums, A a)
{
a.B = (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountAssignPropertyAssignedToNonZero()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class A { public int B { get; set; }}
class C
{
void M(IEnumerable<int> nums, A a)
{
a.B = 5;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
a.B++;
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class A { public int B { get; set; }}
class C
{
void M(IEnumerable<int> nums, A a)
{
a.B = 5;
a.B += (from int n1 in nums
from int n2 in nums
select n1).Count();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class A { public int B { get; set; }}
class C
{
void M(IEnumerable<int> nums, A a)
{
a.B = 5;
a.B += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountAssignPropertyNotKnownAssigned()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class A { public int B { get; set; }}
class C
{
void M(IEnumerable<int> nums, A a)
{
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
a.B++;
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class A { public int B { get; set; }}
class C
{
void M(IEnumerable<int> nums, A a)
{
a.B += (from int n1 in nums
from int n2 in nums
select n1).Count();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class A { public int B { get; set; }}
class C
{
void M(IEnumerable<int> nums, A a)
{
a.B += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountIQueryableInInvocation()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
int c = 0;
[|foreach (int n1 in nums.AsQueryable())
{
c++;
}|]
}
}";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
int c = (from int n1 in nums.AsQueryable()
select n1).Count();
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
int c = (nums.AsQueryable()).Count();
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
#endregion
#region Comments
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CommentsYieldReturn()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
[|// 1
foreach /* 2 */( /* 3 */ var /* 4 */ x /* 5 */ in /* 6 */ nums /* 7 */)// 8
{
// 9
/* 10 */
foreach /* 11 */ (/* 12 */ int /* 13 */ y /* 14 */ in /* 15 */ nums /* 16 */)/* 17 */ // 18
{// 19
/*20 */
if /* 21 */(/* 22 */ x > 2 /* 23 */) // 24
{ // 25
/* 26 */
yield /* 27 */ return /* 28 */ x * y /* 29 */; // 30
/* 31 */
}// 32
/* 33 */
} // 34
/* 35 */
}|] /* 36 */
/* 37 */
yield /* 38 */ break/* 39*/; // 40
}
}";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
return
// 25
// 1
from/* 3 *//* 2 *//* 4 */x /* 5 */ in/* 6 */nums/* 7 */// 8
// 9
/* 10 */
from/* 12 *//* 11 */int /* 13 */ y /* 14 */ in/* 15 */nums/* 16 *//* 17 */// 18
// 19
/*20 */
where/* 21 *//* 22 */x > 2/* 23 */// 24
/* 26 *//* 27 *//* 28 */
select x * y/* 29 *//* 31 */// 32
/* 33 */// 34
/* 35 *//* 36 */// 30
/* 37 *//* 38 *//* 39*/// 40
;
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
return nums /* 7 */.SelectMany(
// 1
/* 2 */// 25
/* 4 */x /* 5 */ => nums /* 16 */.Where(
/*20 *//* 21 */// 19
y =>
/* 22 */x > 2/* 23 */// 24
).Select(
// 9
/* 10 *//* 11 *//* 13 */y /* 14 */ =>
/* 26 *//* 27 *//* 28 */x * y/* 29 *//* 31 */// 32
/* 33 */// 34
/* 35 *//* 36 */// 30
/* 37 *//* 38 *//* 39*/// 40
/* 12 *//* 15 *//* 17 */// 18
)/* 3 *//* 6 */// 8
);
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CommentsToList()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
/* 1 */ var /* 2 */ list /* 3 */ = /* 4 */ new List<int>(); // 5
/* 6 */ [|foreach /* 7 */ (/* 8 */ var /* 9 */ x /* 10 */ in /* 11 */ nums /* 12 */) // 13
/* 14 */{ // 15
/* 16 */var /* 17 */ y /* 18 */ = /* 19 */ x + 1 /* 20 */; //21
/* 22 */ list.Add(/* 23 */y /* 24 */) /* 25 */;//26
/*27*/} //28|]
/*29*/return /*30*/ list /*31*/; //32
}
}";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
/*29*/
return /*30*/ /* 1 *//* 2 *//* 3 *//* 4 */// 5
/*31*/
(
/* 6 */from/* 8 *//* 7 *//* 9 */x /* 10 */ in/* 11 */nums/* 12 */// 13
/* 14 */// 15
/* 16 *//* 17 */
let y /* 18 */ = /* 19 */ x + 1/* 20 *///21
select y/* 24 *//*27*///28
).ToList()/* 22 *//* 23 *//* 25 *///26
; //32
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
// No linq refactoring offered due to variable declaration in outermost foreach.
await TestActionCountAsync(source, count: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CommentsToList_02()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
/* 1 */ var /* 2 */ list /* 3 */ = /* 4 */ new List<int>(); // 5
/* 6 */ [|foreach /* 7 */ (/* 8 */ var /* 9 */ x /* 10 */ in /* 11 */ nums /* 12 */) // 13
/* 14 */{ // 15
/* 16 */
list.Add(/* 17 */ x + 1 /* 18 */) /* 19 */;//20
/*21*/} //22|]
/*23*/return /*24*/ list /*25*/; //26
}
}";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
/*23*/
return /*24*/ /* 1 *//* 2 *//* 3 *//* 4 */// 5
/*25*/
(
/* 14 */// 15
/* 6 */from/* 8 *//* 7 *//* 9 */x /* 10 */ in/* 11 */nums/* 12 */// 13
select x + 1/* 18 *//*21*///22
).ToList()/* 16 *//* 17 *//* 19 *///20
; //26
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
/*23*/
return /*24*/ /* 1 *//* 2 *//* 3 *//* 4 */// 5
/*25*/
(nums /* 12 */.Select(
/* 6 *//* 7 *//* 14 */// 15
/* 9 */x /* 10 */ => x + 1/* 18 *//*21*///22
/* 8 *//* 11 */// 13
)).ToList()/* 16 *//* 17 *//* 19 *///20
; //26
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CommentsCount()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
/* 1 */ var /* 2 */ c /* 3 */ = /* 4 */ 0; // 5
/* 6 */ [| foreach /* 7 */ (/* 8 */ var /* 9 */ x /* 10 */ in /* 11 */ nums /* 12 */) // 13
/* 14 */{ // 15
/* 16 */ c++ /* 17 */;//18
/*19*/}|] //20
/*21*/return /*22*/ c /*23*/; //24
}
}";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
/*21*/
return /*22*/ /* 1 *//* 2 *//* 3 *//* 4 */// 5
/*23*/
(
/* 14 */// 15
/* 6 */from/* 8 *//* 7 *//* 9 */x /* 10 */ in/* 11 */nums/* 12 */// 13
select x/* 10 *//*19*///20
).Count()/* 16 *//* 17 *///18
; //24
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
/*21*/
return /*22*/ /* 1 *//* 2 *//* 3 *//* 4 */// 5
/*23*/
(nums /* 12 *//* 6 *//* 7 *//* 14 */// 15
/* 9 *//* 10 *//* 10 *//*19*///20
/* 8 *//* 11 */// 13
).Count()/* 16 *//* 17 *///18
; //24
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CommentsDefault()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
[|/* 1 */ foreach /* 2 */(int /* 3 */ n1 /* 4 */in /* 5 */ nums /* 6 */)// 7
/* 8*/{// 9
/* 10 */int /* 11 */ a /* 12 */ = /* 13 */ n1 + n1 /* 14*/, /* 15 */ b /*16*/ = /*17*/ n1 * n1/*18*/;//19
/*20*/Console.WriteLine(a + b);//21
/*22*/}/*23*/|]
}
}";
var queryOutput = @"
using System;
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
foreach (var (a /* 12 */ , b /*16*/ ) in
/* 1 */from/* 2 */int /* 3 */ n1 /* 4 */in/* 5 */nums/* 6 */// 7
/* 8*/// 9
/* 10 *//* 11 */
let a /* 12 */ = /* 13 */ n1 + n1/* 14*//* 15 */
let b /*16*/ = /*17*/ n1 * n1/*18*///19
select (a /* 12 */ , b /*16*/ )/*22*//*23*/)
{
/*20*/
Console.WriteLine(a + b);//21
}
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
// No linq refactoring offered due to variable declaration(s) in outermost foreach.
await TestActionCountAsync(source, count: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CommentsDefault_02()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
[|/* 1 */ foreach /* 2 */(int /* 3 */ n1 /* 4 */in /* 5 */ nums /* 6 */)// 7
/* 8*/{// 9
/* 10 */ if /* 11 */ (/* 12 */ n1 /* 13 */ > /* 14 */ 0/* 15 */ ) // 16
/* 17 */{ // 18
/*19*/Console.WriteLine(n1);//20
/* 21 */} // 22
/*23*/}/*24*/|]
}
}";
var queryOutput = @"
using System;
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
foreach (var n1 /* 4 */in
/* 17 */// 18
/* 1 */from/* 2 */int /* 3 */ n1 /* 4 */in/* 5 */nums/* 6 */// 7
/* 8*/// 9
/* 10 */
where/* 11 *//* 12 */n1 /* 13 */ > /* 14 */ 0/* 15 */// 16
select n1/* 4 *//* 21 */// 22
/*23*//*24*/
)
{
/*19*/
Console.WriteLine(n1);//20
}
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System;
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
foreach (var n1 /* 4 */in nums /* 6 */.Where(
/* 10 *//* 11 *//* 8*/// 9
n1 =>
/* 12 */n1 /* 13 */ > /* 14 */ 0/* 15 */// 16
)
/* 1 *//* 2 *//* 17 */// 18
/* 3 *//* 4 *//* 4 *//* 21 */// 22
/*23*//*24*//* 5 */// 7
)
{
/*19*/
Console.WriteLine(n1);//20
}
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
#endregion
#region Preprocessor directives
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task NoConversionPreprocessorDirectives()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
[|foreach(var x in nums)
{
#if (true)
yield return x + 1;
#endif
}|]
}
}";
// Cannot convert expressions with preprocessor directives
await TestMissingAsync(source);
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.ConvertLinq
{
public class ConvertForEachToLinqQueryTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new CodeAnalysis.CSharp.ConvertLinq.ConvertForEachToLinqQuery.CSharpConvertForEachToLinqQueryProvider();
#region Query Expressions
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QueryForForWhere()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public IEnumerable<int> void Main(string[] args)
{
List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7};
List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70};
[|foreach (var x1 in c1)
{
foreach (var x2 in c2)
{
if (object.Equals(x1, x2 / 10))
{
yield return x1 + x2;
}
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public IEnumerable<int> void Main(string[] args)
{
List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7};
List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70};
return from x1 in c1
from x2 in c2
where object.Equals(x1, x2 / 10)
select x1 + x2;
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public IEnumerable<int> void Main(string[] args)
{
List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7};
List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70};
return c1.SelectMany(x1 => c2.Where(x2 => object.Equals(x1, x2 / 10)).Select(x2 => x1 + x2));
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QueryWithEscapedSymbols()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public IEnumerable<int> void Main(string[] args)
{
List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7};
List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70};
[|foreach (var @object in c1)
{
foreach (var x2 in c2)
{
yield return @object + x2;
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public IEnumerable<int> void Main(string[] args)
{
List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7};
List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70};
return from @object in c1
from x2 in c2
select @object + x2;
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public IEnumerable<int> void Main(string[] args)
{
List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7};
List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70};
return c1.SelectMany(@object => c2.Select(x2 => @object + x2));
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QueryForVarForWhere()
{
var source = @"
using System.Linq;
class C
{
IEnumerable<int> M()
{
[|foreach (var num in new int[] { 1, 2 })
{
var n1 = num + 1;
foreach (var a in new int[] { 5, 6 })
{
foreach (var x1 in new int[] { 3, 4 })
{
if (object.Equals(num, x1))
{
foreach (var x2 in new int[] { 7, 8 })
{
if (object.Equals(num, x2))
{
var n2 = x2 - 1;
yield return n2 + n1;
}
}
}
}
}|]
}
}
}";
var queryOutput = @"
using System.Linq;
class C
{
IEnumerable<int> M()
{
return from num in new int[] { 1, 2 }
let n1 = num + 1
from a in new int[] { 5, 6 }
from x1 in new int[] { 3, 4 }
where object.Equals(num, x1)
from x2 in new int[] { 7, 8 }
where object.Equals(num, x2)
let n2 = x2 - 1
select n2 + n1;
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
// No linq refactoring offered due to variable declaration within the outermost foreach.
await TestActionCountAsync(source, count: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QueryForVarForWhere_02()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M()
{
[|foreach (var num in new int[] { 1, 2 })
{
foreach (var a in new int[] { 5, 6 })
{
foreach (var x1 in new int[] { 3, 4 })
{
if (object.Equals(num, x1))
{
foreach (var x2 in new int[] { 7, 8 })
{
if (object.Equals(num, x2))
{
var n1 = num + 1;
var n2 = x2 - 1;
yield return n2 + n1;
}
}
}
}
}|]
}
}
}";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M()
{
return from num in new int[] { 1, 2 }
from a in new int[] { 5, 6 }
from x1 in new int[] { 3, 4 }
where object.Equals(num, x1)
from x2 in new int[] { 7, 8 }
where object.Equals(num, x2)
let n1 = num + 1
let n2 = x2 - 1
select n2 + n1;
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M()
{
foreach (var (num, x2) in (new int[] { 1, 2 }).SelectMany(num => (new int[] { 5, 6 }).SelectMany(a => (new int[] { 3, 4 }).Where(x1 => object.Equals(num, x1)).SelectMany(x1 => (new int[] { 7, 8 }).Where(x2 => object.Equals(num, x2)).Select(x2 => (num, x2))))))
{
var n1 = num + 1;
var n2 = x2 - 1;
yield return n2 + n1;
}
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QueryForVarForWhere_03()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M()
{
[|foreach (var num in new int[] { 1, 2 })
{
foreach (var a in new int[] { 5, 6 })
{
foreach (var x1 in new int[] { 3, 4 })
{
var n1 = num + 1;
if (object.Equals(num, x1))
{
foreach (var x2 in new int[] { 7, 8 })
{
if (object.Equals(num, x2))
{
var n2 = x2 - 1;
yield return n2 + n1;
}
}
}
}
}|]
}
}
}";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M()
{
return from num in new int[] { 1, 2 }
from a in new int[] { 5, 6 }
from x1 in new int[] { 3, 4 }
let n1 = num + 1
where object.Equals(num, x1)
from x2 in new int[] { 7, 8 }
where object.Equals(num, x2)
let n2 = x2 - 1
select n2 + n1;
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M()
{
foreach (var (num, x1) in (new int[] { 1, 2 }).SelectMany(num => (new int[] { 5, 6 }).SelectMany(a => (new int[] { 3, 4 }).Select(x1 => (num, x1)))))
{
var n1 = num + 1;
if (object.Equals(num, x1))
{
foreach (var x2 in new int[] { 7, 8 })
{
if (object.Equals(num, x2))
{
var n2 = x2 - 1;
yield return n2 + n1;
}
}
}
}
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QueryLet()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Query
{
void M()
{
List<int> c1 = new List<int>{ 1, 2, 3 };
List<int> r1 = new List<int>();
[|foreach (int x in c1)
{
var g = x * 10;
var z = g + x*100;
var a = 5 + z;
r1.Add(x + z - a);
}|]
}
}";
var queryOutput = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Query
{
void M()
{
List<int> c1 = new List<int>{ 1, 2, 3 };
List<int> r1 = (from int x in c1
let g = x * 10
let z = g + x * 100
let a = 5 + z
select x + z - a).ToList();
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
// No linq invocation refactoring offered due to variable declaration(s) in topmost foreach.
await TestActionCountAsync(source, count: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QueryEmptyDeclarations()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Query
{
void M()
{
[|foreach (int x in new[] {1,2})
{
int a = 3, b, c = 1;
if (x > c)
{
b = 0;
Console.Write(a + x + b);
}
}|]
}
}";
await TestMissingInRegularAndScriptAsync(source);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QueryWhereClause()
{
var source = @"
using System;
using System.Linq;
class C
{
IEnumerable<int> M()
{
var nums = new int[] { 1, 2, 3, 4 };
[|foreach (var x in nums)
{
if (x > 2)
{
yield return x;
}
}|]
}
}";
var queryOutput = @"
using System;
using System.Linq;
class C
{
IEnumerable<int> M()
{
var nums = new int[] { 1, 2, 3, 4 };
return from x in nums
where x > 2
select x;
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System;
using System.Linq;
class C
{
IEnumerable<int> M()
{
var nums = new int[] { 1, 2, 3, 4 };
return nums.Where(x => x > 2);
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QueryOverQueries()
{
var source = @"
using System;
using System.Linq;
class C
{
IEnumerable<int> M()
{
var nums = new int[] { 1, 2, 3, 4 };
[|foreach (var y in from x in nums select x)
{
foreach (var z in from x in nums select x)
{
yield return y;
}
}|]
}
}";
var queryOutput = @"
using System;
using System.Linq;
class C
{
IEnumerable<int> M()
{
var nums = new int[] { 1, 2, 3, 4 };
return from y in
from x in nums select x
from z in
from x in nums select x
select y;
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System;
using System.Linq;
class C
{
IEnumerable<int> M()
{
var nums = new int[] { 1, 2, 3, 4 };
return (from x in nums select x).SelectMany(y => (from x in nums select x).Select(z => y));
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QueryNoVariablesUsed()
{
var source = @"
using System;
using System.Linq;
class C
{
void M()
{
[|foreach (var a in new[] { 1 })
{
foreach (var b in new[] { 2 })
{
System.Console.Write(0);
}
}|]
}
}";
var queryOutput = @"
using System;
using System.Linq;
class C
{
void M()
{
foreach (var _ in from a in new[] { 1 }
from b in new[] { 2 }
select new { })
{
System.Console.Write(0);
}
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System;
using System.Linq;
class C
{
void M()
{
foreach (var _ in (new[] { 1 }).SelectMany(a => (new[] { 2 }).Select(b => new { })))
{
System.Console.Write(0);
}
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QueryNoBlock()
{
var source = @"
using System;
using System.Linq;
class C
{
void M()
{
[|foreach (var a in new[] { 1 })
foreach (var b in new[] { 2 })
System.Console.Write(a);|]
}
}";
var queryOutput = @"
using System;
using System.Linq;
class C
{
void M()
{
foreach (var a in from a in new[] { 1 }
from b in new[] { 2 }
select a)
{
System.Console.Write(a);
}
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System;
using System.Linq;
class C
{
void M()
{
foreach (var a in (new[] { 1 }).SelectMany(a => (new[] { 2 }).Select(b => a)))
{
System.Console.Write(a);
}
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QuerySelectExpression()
{
var source = @"
using System;
using System.Linq;
class C
{
void M()
{
[|foreach (var a in new[] { 1 })
foreach (var b in new[] { 2 })
Console.Write(a + b);|]
}
}";
var queryOutput = @"
using System;
using System.Linq;
class C
{
void M()
{
foreach (var (a, b) in from a in new[] { 1 }
from b in new[] { 2 }
select (a, b))
{
Console.Write(a + b);
}
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System;
using System.Linq;
class C
{
void M()
{
foreach (var (a, b) in (new[] { 1 }).SelectMany(a => (new[] { 2 }).Select(b => (a, b))))
{
Console.Write(a + b);
}
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QuerySelectMultipleExpressions()
{
var source = @"
using System;
using System.Linq;
class C
{
void M()
{
[|foreach (var a in new[] { 1 })
foreach (var b in new[] { 2 })
{
Console.Write(a + b);
Console.Write(a * b);
}|]
}
}";
var queryOutput = @"
using System;
using System.Linq;
class C
{
void M()
{
foreach (var (a, b) in from a in new[] { 1 }
from b in new[] { 2 }
select (a, b))
{
Console.Write(a + b);
Console.Write(a * b);
}
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System;
using System.Linq;
class C
{
void M()
{
foreach (var (a, b) in (new[] { 1 }).SelectMany(a => (new[] { 2 }).Select(b => (a, b))))
{
Console.Write(a + b);
Console.Write(a * b);
}
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task EmptyBody()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
foreach (var _ in from int n1 in nums
from int n2 in nums
select new { })
{
}
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
foreach (var _ in nums.SelectMany(n1 => nums.Select(n2 => new { })))
{
}
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task EmptyBodyNoBlock()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
[|foreach (int n1 in nums)
{
foreach (int n2 in nums);
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
foreach (var _ in from int n1 in nums
from int n2 in nums
select new { })
{
}
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
foreach (var _ in nums.SelectMany(n1 => nums.Select(n2 => new { })))
{
}
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task AddUsingToExistingList()
{
var source = @"
using System.Collections.Generic;
class C
{
void M(IEnumerable<int> nums)
{
[|foreach (int n1 in nums)
{
foreach (int n2 in nums);
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
foreach (var _ in from int n1 in nums
from int n2 in nums
select new { })
{
}
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
foreach (var _ in nums.SelectMany(n1 => nums.Select(n2 => new { })))
{
}
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task AddFirstUsing()
{
var source = @"
class C
{
void M(int[] nums)
{
[|foreach (int n1 in nums)
{
foreach (int n2 in nums);
}|]
}
}
";
var queryOutput = @"using System.Linq;
class C
{
void M(int[] nums)
{
foreach (var _ in from int n1 in nums
from int n2 in nums
select new { })
{
}
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"using System.Linq;
class C
{
void M(int[] nums)
{
foreach (var _ in nums.SelectMany(n1 => nums.Select(n2 => new { })))
{
}
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task EmptyBodyDeclarationAsLast()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
var a = n1 + n2;
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
foreach (var _ in from int n1 in nums
from int n2 in nums
let a = n1 + n2
select new { })
{
}
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
foreach (var (n1, n2) in nums.SelectMany(n1 => nums.Select(n2 => (n1, n2))))
{
var a = n1 + n2;
}
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task EmptyBodyMultipleDeclarationsAsLast()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
int a = n1 + n2, b = n1 * n2;
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
foreach (var _ in from int n1 in nums
from int n2 in nums
let a = n1 + n2
let b = n1 * n2
select new { })
{
}
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
foreach (var (n1, n2) in nums.SelectMany(n1 => nums.Select(n2 => (n1, n2))))
{
int a = n1 + n2, b = n1 * n2;
}
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
#endregion
#region Assignments, Declarations, Returns
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ReturnInvocationAndYieldReturn()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
yield return N(n1);
}
}|]
}
int N(int n) => n;
}
";
var queryOutput = @"
using System;
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
return from int n1 in nums
from int n2 in nums
select N(n1);
}
int N(int n) => n;
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System;
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
return nums.SelectMany(n1 => nums.Select(n2 => N(n1)));
}
int N(int n) => n;
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task BlockBodiedProperty()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
public class Test
{
private readonly int[] _nums = new int[] { 1, 2, 3, 4 };
public IEnumerable<int> Query1 { get { [|foreach (var x in _nums) { yield return x + 1; }|] } }
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
public class Test
{
private readonly int[] _nums = new int[] { 1, 2, 3, 4 };
public IEnumerable<int> Query1 { get { return from x in _nums select x + 1; } }
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
public class Test
{
private readonly int[] _nums = new int[] { 1, 2, 3, 4 };
public IEnumerable<int> Query1 { get { return _nums.Select(x => x + 1); } }
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ReturnIEnumerable()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
yield return n1;
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
return from int n1 in nums
from int n2 in nums
select n1;
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
return nums.SelectMany(n1 => nums.Select(n2 => n1));
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ReturnIEnumerableWithYieldReturnAndLocalFunction()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<IEnumerable<int>> M(IEnumerable<int> nums)
{
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
yield return f(n1);
}
}|]
yield break;
IEnumerable<int> f(int a)
{
yield return a;
}
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<IEnumerable<int>> M(IEnumerable<int> nums)
{
return from int n1 in nums
from int n2 in nums
select f(n1);
IEnumerable<int> f(int a)
{
yield return a;
}
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<IEnumerable<int>> M(IEnumerable<int> nums)
{
return nums.SelectMany(n1 => nums.Select(n2 => f(n1)));
IEnumerable<int> f(int a)
{
yield return a;
}
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ReturnIEnumerablePartialMethod()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
partial class C
{
partial IEnumerable<int> M(IEnumerable<int> nums);
}
partial class C
{
partial IEnumerable<int> M(IEnumerable<int> nums)
{
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
yield return n1;
}
}|]
yield break;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
partial class C
{
partial IEnumerable<int> M(IEnumerable<int> nums);
}
partial class C
{
partial IEnumerable<int> M(IEnumerable<int> nums)
{
return from int n1 in nums
from int n2 in nums
select n1;
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
partial class C
{
partial IEnumerable<int> M(IEnumerable<int> nums);
}
partial class C
{
partial IEnumerable<int> M(IEnumerable<int> nums)
{
return nums.SelectMany(n1 => nums.Select(n2 => n1));
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ReturnIEnumerableExtendedPartialMethod()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
partial class C
{
public partial IEnumerable<int> M(IEnumerable<int> nums);
}
partial class C
{
public partial IEnumerable<int> M(IEnumerable<int> nums)
{
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
yield return n1;
}
}|]
yield break;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
partial class C
{
public partial IEnumerable<int> M(IEnumerable<int> nums);
}
partial class C
{
public partial IEnumerable<int> M(IEnumerable<int> nums)
{
return from int n1 in nums
from int n2 in nums
select n1;
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
partial class C
{
public partial IEnumerable<int> M(IEnumerable<int> nums);
}
partial class C
{
public partial IEnumerable<int> M(IEnumerable<int> nums)
{
return nums.SelectMany(n1 => nums.Select(n2 => n1));
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
[WorkItem(31784, "https://github.com/dotnet/roslyn/issues/31784")]
public async Task QueryWhichRequiresSelectManyWithIdentityLambda()
{
var source = @"
using System.Collections.Generic;
class C
{
IEnumerable<int> M()
{
[|foreach (var x in new[] { new[] { 1, 2, 3 }, new[] { 4, 5, 6 } })
{
foreach (var y in x)
{
yield return y;
}
}|]
}
}
";
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M()
{
return (new[] { new[] { 1, 2, 3 }, new[] { 4, 5, 6 } }).SelectMany(x => x);
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
#endregion
#region In foreach
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QueryInForEachWithSameVariableNameAndDifferentType()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Linq;
class A
{
public static implicit operator int(A x)
{
throw null;
}
public static implicit operator A(int x)
{
throw null;
}
}
class B : A { }
class C
{
void M(IEnumerable<int> nums)
{
[|foreach (B a in nums)
{
foreach (A c in nums)
{
Console.Write(a.ToString());
}
}|]
}
}
";
var queryOutput = @"
using System;
using System.Collections.Generic;
using System.Linq;
class A
{
public static implicit operator int(A x)
{
throw null;
}
public static implicit operator A(int x)
{
throw null;
}
}
class B : A { }
class C
{
void M(IEnumerable<int> nums)
{
foreach (var a in from B a in nums
from A c in nums
select a)
{
Console.Write(a.ToString());
}
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System;
using System.Collections.Generic;
using System.Linq;
class A
{
public static implicit operator int(A x)
{
throw null;
}
public static implicit operator A(int x)
{
throw null;
}
}
class B : A { }
class C
{
void M(IEnumerable<int> nums)
{
foreach (var a in nums.SelectMany(a => nums.Select(c => a)))
{
Console.Write(a.ToString());
}
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QueryInForEachWithSameVariableNameAndSameType()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Linq;
class A
{
public static implicit operator int(A x)
{
throw null;
}
public static implicit operator A(int x)
{
throw null;
}
}
class C
{
void M(IEnumerable<int> nums)
{
[|foreach (A a in nums)
{
foreach (A c in nums)
{
Console.Write(a.ToString());
}
}|]
}
}
";
var queryOutput = @"
using System;
using System.Collections.Generic;
using System.Linq;
class A
{
public static implicit operator int(A x)
{
throw null;
}
public static implicit operator A(int x)
{
throw null;
}
}
class C
{
void M(IEnumerable<int> nums)
{
foreach (var a in from A a in nums
from A c in nums
select a)
{
Console.Write(a.ToString());
}
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System;
using System.Collections.Generic;
using System.Linq;
class A
{
public static implicit operator int(A x)
{
throw null;
}
public static implicit operator A(int x)
{
throw null;
}
}
class C
{
void M(IEnumerable<int> nums)
{
foreach (var a in nums.SelectMany(a => nums.Select(c => a)))
{
Console.Write(a.ToString());
}
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task QueryInForEachWithConvertedType()
{
var source = @"
using System;
using System.Collections.Generic;
static class Extensions
{
public static IEnumerable<C> Select(this int[] x, Func<int, C> predicate) => throw null;
}
class C
{
public static implicit operator int(C x)
{
throw null;
}
public static implicit operator C(int x)
{
throw null;
}
IEnumerable<C> Test()
{
[|foreach (var x in new[] { 1, 2, 3 })
{
yield return x;
}|]
}
}
";
var queryOutput = @"
using System;
using System.Collections.Generic;
using System.Linq;
static class Extensions
{
public static IEnumerable<C> Select(this int[] x, Func<int, C> predicate) => throw null;
}
class C
{
public static implicit operator int(C x)
{
throw null;
}
public static implicit operator C(int x)
{
throw null;
}
IEnumerable<C> Test()
{
return from x in new[] { 1, 2, 3 }
select x;
}
}
";
await TestAsync(source, queryOutput, parseOptions: null);
var linqInvocationOutput = @"
using System;
using System.Collections.Generic;
using System.Linq;
static class Extensions
{
public static IEnumerable<C> Select(this int[] x, Func<int, C> predicate) => throw null;
}
class C
{
public static implicit operator int(C x)
{
throw null;
}
public static implicit operator C(int x)
{
throw null;
}
IEnumerable<C> Test()
{
return new[] { 1, 2, 3 };
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task IQueryableConvertedToIEnumerableInReturn()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
[|foreach (int n1 in nums.AsQueryable())
{
yield return n1;
}|]
yield break;
}
}";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
return from int n1 in nums.AsQueryable()
select n1;
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
return nums.AsQueryable();
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ReturnIQueryableConvertedToIEnumerableInAssignment()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
[|foreach (int n1 in nums.AsQueryable())
{
yield return n1;
}|]
}
}";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
return from int n1 in nums.AsQueryable()
select n1;
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
return nums.AsQueryable();
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
#endregion
#region In ToList
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListLastDeclarationMerge()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list0 = new List<int>(), list = new List<int>();
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
list.Add(n1);
}
}|]
return list;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list0 = new List<int>();
return (from int n1 in nums
from int n2 in nums
select n1).ToList();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list0 = new List<int>();
return (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListParameterizedConstructor()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list = new List<int>(nums);
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
list.Add(n1);
}
}|]
return list;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list = new List<int>(nums);
list.AddRange(from int n1 in nums
from int n2 in nums
select n1);
return list;
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list = new List<int>(nums);
list.AddRange(nums.SelectMany(n1 => nums.Select(n2 => n1)));
return list;
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListWithListInitializer()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list = new List<int>() { 1, 2, 3 };
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
list.Add(n1);
}
}|]
return list;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list = new List<int>() { 1, 2, 3 };
list.AddRange(from int n1 in nums
from int n2 in nums
select n1);
return list;
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list = new List<int>() { 1, 2, 3 };
list.AddRange(nums.SelectMany(n1 => nums.Select(n2 => n1)));
return list;
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListWithEmptyArgumentList()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list = new List<int> { };
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
list.Add(n1);
}
}|]
return list;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
return (from int n1 in nums
from int n2 in nums
select n1).ToList();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
return (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListNotLastDeclaration()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list = new List<int>(), list1 = new List<int>();
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
list.Add(n1);
}
}|]
return list;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list = new List<int>(), list1 = new List<int>();
list.AddRange(from int n1 in nums
from int n2 in nums
select n1);
return list;
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list = new List<int>(), list1 = new List<int>();
list.AddRange(nums.SelectMany(n1 => nums.Select(n2 => n1)));
return list;
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListAssignToParameter()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums, List<int> list)
{
list = new List<int>();
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
list.Add(n1);
}
}|]
return list;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums, List<int> list)
{
list = (from int n1 in nums
from int n2 in nums
select n1).ToList();
return list;
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums, List<int> list)
{
list = (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList();
return list;
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListToArrayElement()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums, List<int>[] lists)
{
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
lists[0].Add(n1);
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums, List<int>[] lists)
{
lists[0].AddRange(from int n1 in nums
from int n2 in nums
select n1);
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums, List<int>[] lists)
{
lists[0].AddRange(nums.SelectMany(n1 => nums.Select(n2 => n1)));
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListToNewArrayElement()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums, List<int>[] lists)
{
lists[0] = new List<int>();
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
lists[0].Add(n1);
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums, List<int>[] lists)
{
lists[0] = (from int n1 in nums
from int n2 in nums
select n1).ToList();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums, List<int>[] lists)
{
lists[0] = (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListHashSetNoConversion()
{
var source = @"
using System.Collections.Generic;
class C
{
void M(IEnumerable<int> nums)
{
var hashSet = new HashSet<int>();
[|foreach (int n1 in nums)
{
hashSet.Add(n1);
}|]
}
}
";
await TestMissingAsync(source);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListMergeWithReturn()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
var list = new List<int>();
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
list.Add(n1);
}
}|]
return list;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
return (from int n1 in nums
from int n2 in nums
select n1).ToList();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
return (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListSeparateDeclarationAndAssignmentMergeWithReturn()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list;
list = new List<int>();
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
list.Add(n1);
}
}|]
return list;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list;
return (from int n1 in nums
from int n2 in nums
select n1).ToList();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
List<int> list;
return (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListSeparateDeclarationAndAssignment()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
List<int> list;
list = new List<int>();
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
list.Add(n1);
}
}|]
return list.Count;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
List<int> list;
list = (from int n1 in nums
from int n2 in nums
select n1).ToList();
return list.Count;
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
List<int> list;
list = (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList();
return list.Count;
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListTypeReplacement01()
{
var source = @"
using System;
using System.Linq;
using C = System.Collections.Generic.List<int>;
class Query
{
public static void Main(string[] args)
{
C c1 = new C { 1, 2, 3 };
C c2 = new C { 10, 20, 30 };
C c3 = new C { 100, 200, 300 };
C r1 = new C();
[|foreach (int x in c1)
{
foreach (int y in c2)
{
foreach (int z in c3)
{
var g = x + y + z;
if (x + y / 10 + z / 100 < 6)
{
r1.Add(g);
}
}
}
}|]
Console.WriteLine(r1);
}
}
";
var queryOutput = @"
using System;
using System.Linq;
using C = System.Collections.Generic.List<int>;
class Query
{
public static void Main(string[] args)
{
C c1 = new C { 1, 2, 3 };
C c2 = new C { 10, 20, 30 };
C c3 = new C { 100, 200, 300 };
C r1 = (from int x in c1
from int y in c2
from int z in c3
let g = x + y + z
where x + y / 10 + z / 100 < 6
select g).ToList();
Console.WriteLine(r1);
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System;
using System.Linq;
using C = System.Collections.Generic.List<int>;
class Query
{
public static void Main(string[] args)
{
C c1 = new C { 1, 2, 3 };
C c2 = new C { 10, 20, 30 };
C c3 = new C { 100, 200, 300 };
C r1 = new C();
foreach (var (x, y, z) in c1.SelectMany(x => c2.SelectMany(y => c3.Select(z => (x, y, z)))))
{
var g = x + y + z;
if (x + y / 10 + z / 100 < 6)
{
r1.Add(g);
}
}
Console.WriteLine(r1);
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListTypeReplacement02()
{
var source = @"
using System.Linq;
using System;
using C = System.Collections.Generic.List<int>;
class Query
{
public static void Main(string[] args)
{
C c1 = new C { 1, 2, 3 };
C c2 = new C { 10, 20, 30 };
C r1 = new C();
[|foreach (int x in c1)
{
foreach (var y in c2)
{
if (Equals(x, y / 10))
{
var z = x + y;
r1.Add(z);
}
}
}|]
Console.WriteLine(r1);
}
}
";
var queryOutput = @"
using System.Linq;
using System;
using C = System.Collections.Generic.List<int>;
class Query
{
public static void Main(string[] args)
{
C c1 = new C { 1, 2, 3 };
C c2 = new C { 10, 20, 30 };
C r1 = (from int x in c1
from y in c2
where Equals(x, y / 10)
let z = x + y
select z).ToList();
Console.WriteLine(r1);
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Linq;
using System;
using C = System.Collections.Generic.List<int>;
class Query
{
public static void Main(string[] args)
{
C c1 = new C { 1, 2, 3 };
C c2 = new C { 10, 20, 30 };
C r1 = new C();
foreach (var (x, y) in c1.SelectMany(x => c2.Where(y => Equals(x, y / 10)).Select(y => (x, y))))
{
var z = x + y;
r1.Add(z);
}
Console.WriteLine(r1);
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListPropertyAssignment()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
public class Test
{
public static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
var c = new C();
c.A = new List<int>();
[|foreach (var x in nums)
{
c.A.Add(x + 1);
}|]
}
class C
{
public List<int> A { get; set; }
}
}";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
public class Test
{
public static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
var c = new C();
c.A = (from x in nums
select x + 1).ToList();
}
class C
{
public List<int> A { get; set; }
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
public class Test
{
public static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
var c = new C();
c.A = (nums.Select(x => x + 1)).ToList();
}
class C
{
public List<int> A { get; set; }
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListPropertyAssignmentNoDeclaration()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
public class Test
{
void M()
{
var nums = new int[] { 1, 2, 3, 4 };
var c = new C();
[|foreach (var x in nums)
{
c.A.Add(x + 1);
}|]
}
class C
{
public List<int> A { get; set; }
}
}";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
public class Test
{
void M()
{
var nums = new int[] { 1, 2, 3, 4 };
var c = new C();
c.A.AddRange(from x in nums
select x + 1);
}
class C
{
public List<int> A { get; set; }
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
public class Test
{
void M()
{
var nums = new int[] { 1, 2, 3, 4 };
var c = new C();
c.A.AddRange(nums.Select(x => x + 1));
}
class C
{
public List<int> A { get; set; }
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListNoInitialization()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
public class Test
{
public List<int> A { get; set; }
void M()
{
[|foreach (var x in new int[] { 1, 2, 3, 4 })
{
A.Add(x + 1);
}|]
}
}";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
public class Test
{
public List<int> A { get; set; }
void M()
{
A.AddRange(from x in new int[] { 1, 2, 3, 4 }
select x + 1);
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
public class Test
{
public List<int> A { get; set; }
void M()
{
A.AddRange((new int[] { 1, 2, 3, 4 }).Select(x => x + 1));
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task ToListOverride()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
public static class C
{
public static void Add<T>(this List<T> list, T value, T anotherValue) { }
}
public class Test
{
void M()
{
var list = new List<int>();
[|foreach (var x in new int[] { 1, 2, 3, 4 })
{
list.Add(x + 1, x);
}|]
}
}";
await TestMissingAsync(source);
}
#endregion
#region In Count
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountInMultipleDeclarationLast()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
int i = 0, cnt = 0;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
cnt++;
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
int i = 0, cnt = (from int n1 in nums
from int n2 in nums
select n1).Count();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
int i = 0, cnt = (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountInMultipleDeclarationNotLast()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
int cnt = 0, i = 0;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
cnt++;
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
int cnt = 0, i = 0;
cnt += (from int n1 in nums
from int n2 in nums
select n1).Count();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
int cnt = 0, i = 0;
cnt += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountInParameter()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums, int c)
{
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
c++;
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums, int c)
{
c += (from int n1 in nums
from int n2 in nums
select n1).Count();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums, int c)
{
c += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountInParameterAssignedToZero()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums, int c)
{
c = 0;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
c++;
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums, int c)
{
c = (from int n1 in nums
from int n2 in nums
select n1).Count();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums, int c)
{
c = (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountInParameterAssignedToNonZero()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums, int c)
{
c = 5;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
c++;
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums, int c)
{
c = 5;
c += (from int n1 in nums
from int n2 in nums
select n1).Count();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums, int c)
{
c = 5;
c += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountInDeclarationMergeToReturn()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
var cnt = 0;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
cnt++;
}
}|]
return cnt;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
return (from int n1 in nums
from int n2 in nums
select n1).Count();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
return (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountInDeclarationConversion()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
double M(IEnumerable<int> nums)
{
double c = 0;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
c++;
}
}|]
return c;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
double M(IEnumerable<int> nums)
{
return (from int n1 in nums
from int n2 in nums
select n1).Count();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
double M(IEnumerable<int> nums)
{
return (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountInMultipleDeclarationMergeToReturnLast()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int c = 0, cnt = 0;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
cnt++;
}
}|]
return cnt;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int c = 0;
return (from int n1 in nums
from int n2 in nums
select n1).Count();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int c = 0;
return (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountInMultipleDeclarationLastButNotZero()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int c = 0, cnt = 5;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
cnt++;
}
}|]
return cnt;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int c = 0, cnt = 5;
cnt += (from int n1 in nums
from int n2 in nums
select n1).Count();
return cnt;
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int c = 0, cnt = 5;
cnt += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
return cnt;
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountInMultipleDeclarationMergeToReturnNotLast()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int cnt = 0, c = 0;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
cnt++;
}
}|]
return cnt;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int cnt = 0, c = 0;
cnt += (from int n1 in nums
from int n2 in nums
select n1).Count();
return cnt;
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int cnt = 0, c = 0;
cnt += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
return cnt;
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountInMultipleDeclarationNonZeroToReturnNotLast()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int cnt = 5, c = 0;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
cnt++;
}
}|]
return cnt;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int cnt = 5, c = 0;
cnt += (from int n1 in nums
from int n2 in nums
select n1).Count();
return cnt;
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int cnt = 5, c = 0;
cnt += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
return cnt;
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountInAssignmentToZero()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int cnt;
cnt = 0;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
cnt++;
}
}|]
return cnt;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int cnt;
return (from int n1 in nums
from int n2 in nums
select n1).Count();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int cnt;
return (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountInAssignmentToNonZero()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int cnt;
cnt = 5;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
cnt++;
}
}|]
return cnt;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int cnt;
cnt = 5;
cnt += (from int n1 in nums
from int n2 in nums
select n1).Count();
return cnt;
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
int cnt;
cnt = 5;
cnt += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
return cnt;
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountInParameterAssignedToZeroAndReturned()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums, int c)
{
c = 0;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
c++;
}
}|]
return c;
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums, int c)
{
c = (from int n1 in nums
from int n2 in nums
select n1).Count();
return c;
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums, int c)
{
c = (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
return c;
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountDeclareWithNonZero()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
var count = 5;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
count++;
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
var count = 5;
count += (from int n1 in nums
from int n2 in nums
select n1).Count();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
var count = 5;
count += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountAssignWithZero()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
int count = 1;
count = 0;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
count++;
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
int count = 1;
count = (from int n1 in nums
from int n2 in nums
select n1).Count();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
int count = 1;
count = (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountAssignWithNonZero()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
var count = 0;
count = 4;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
count++;
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
var count = 0;
count = 4;
count += (from int n1 in nums
from int n2 in nums
select n1).Count();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
var count = 0;
count = 4;
count += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountAssignPropertyAssignedToZero()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class A { public int B { get; set; }}
class C
{
void M(IEnumerable<int> nums, A a)
{
a.B = 0;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
a.B++;
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class A { public int B { get; set; }}
class C
{
void M(IEnumerable<int> nums, A a)
{
a.B = (from int n1 in nums
from int n2 in nums
select n1).Count();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class A { public int B { get; set; }}
class C
{
void M(IEnumerable<int> nums, A a)
{
a.B = (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountAssignPropertyAssignedToNonZero()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class A { public int B { get; set; }}
class C
{
void M(IEnumerable<int> nums, A a)
{
a.B = 5;
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
a.B++;
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class A { public int B { get; set; }}
class C
{
void M(IEnumerable<int> nums, A a)
{
a.B = 5;
a.B += (from int n1 in nums
from int n2 in nums
select n1).Count();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class A { public int B { get; set; }}
class C
{
void M(IEnumerable<int> nums, A a)
{
a.B = 5;
a.B += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountAssignPropertyNotKnownAssigned()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class A { public int B { get; set; }}
class C
{
void M(IEnumerable<int> nums, A a)
{
[|foreach (int n1 in nums)
{
foreach (int n2 in nums)
{
a.B++;
}
}|]
}
}
";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class A { public int B { get; set; }}
class C
{
void M(IEnumerable<int> nums, A a)
{
a.B += (from int n1 in nums
from int n2 in nums
select n1).Count();
}
}
";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class A { public int B { get; set; }}
class C
{
void M(IEnumerable<int> nums, A a)
{
a.B += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count();
}
}
";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CountIQueryableInInvocation()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
int c = 0;
[|foreach (int n1 in nums.AsQueryable())
{
c++;
}|]
}
}";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
int c = (from int n1 in nums.AsQueryable()
select n1).Count();
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
int c = (nums.AsQueryable()).Count();
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
#endregion
#region Comments
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CommentsYieldReturn()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
[|// 1
foreach /* 2 */( /* 3 */ var /* 4 */ x /* 5 */ in /* 6 */ nums /* 7 */)// 8
{
// 9
/* 10 */
foreach /* 11 */ (/* 12 */ int /* 13 */ y /* 14 */ in /* 15 */ nums /* 16 */)/* 17 */ // 18
{// 19
/*20 */
if /* 21 */(/* 22 */ x > 2 /* 23 */) // 24
{ // 25
/* 26 */
yield /* 27 */ return /* 28 */ x * y /* 29 */; // 30
/* 31 */
}// 32
/* 33 */
} // 34
/* 35 */
}|] /* 36 */
/* 37 */
yield /* 38 */ break/* 39*/; // 40
}
}";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
return
// 25
// 1
from/* 3 *//* 2 *//* 4 */x /* 5 */ in/* 6 */nums/* 7 */// 8
// 9
/* 10 */
from/* 12 *//* 11 */int /* 13 */ y /* 14 */ in/* 15 */nums/* 16 *//* 17 */// 18
// 19
/*20 */
where/* 21 *//* 22 */x > 2/* 23 */// 24
/* 26 *//* 27 *//* 28 */
select x * y/* 29 *//* 31 */// 32
/* 33 */// 34
/* 35 *//* 36 */// 30
/* 37 *//* 38 *//* 39*/// 40
;
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
return nums /* 7 */.SelectMany(
// 1
/* 2 */// 25
/* 4 */x /* 5 */ => nums /* 16 */.Where(
/*20 *//* 21 */// 19
y =>
/* 22 */x > 2/* 23 */// 24
).Select(
// 9
/* 10 *//* 11 *//* 13 */y /* 14 */ =>
/* 26 *//* 27 *//* 28 */x * y/* 29 *//* 31 */// 32
/* 33 */// 34
/* 35 *//* 36 */// 30
/* 37 *//* 38 *//* 39*/// 40
/* 12 *//* 15 *//* 17 */// 18
)/* 3 *//* 6 */// 8
);
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CommentsToList()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
/* 1 */ var /* 2 */ list /* 3 */ = /* 4 */ new List<int>(); // 5
/* 6 */ [|foreach /* 7 */ (/* 8 */ var /* 9 */ x /* 10 */ in /* 11 */ nums /* 12 */) // 13
/* 14 */{ // 15
/* 16 */var /* 17 */ y /* 18 */ = /* 19 */ x + 1 /* 20 */; //21
/* 22 */ list.Add(/* 23 */y /* 24 */) /* 25 */;//26
/*27*/} //28|]
/*29*/return /*30*/ list /*31*/; //32
}
}";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
/*29*/
return /*30*/ /* 1 *//* 2 *//* 3 *//* 4 */// 5
/*31*/
(
/* 6 */from/* 8 *//* 7 *//* 9 */x /* 10 */ in/* 11 */nums/* 12 */// 13
/* 14 */// 15
/* 16 *//* 17 */
let y /* 18 */ = /* 19 */ x + 1/* 20 *///21
select y/* 24 *//*27*///28
).ToList()/* 22 *//* 23 *//* 25 *///26
; //32
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
// No linq refactoring offered due to variable declaration in outermost foreach.
await TestActionCountAsync(source, count: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CommentsToList_02()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
/* 1 */ var /* 2 */ list /* 3 */ = /* 4 */ new List<int>(); // 5
/* 6 */ [|foreach /* 7 */ (/* 8 */ var /* 9 */ x /* 10 */ in /* 11 */ nums /* 12 */) // 13
/* 14 */{ // 15
/* 16 */
list.Add(/* 17 */ x + 1 /* 18 */) /* 19 */;//20
/*21*/} //22|]
/*23*/return /*24*/ list /*25*/; //26
}
}";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
/*23*/
return /*24*/ /* 1 *//* 2 *//* 3 *//* 4 */// 5
/*25*/
(
/* 14 */// 15
/* 6 */from/* 8 *//* 7 *//* 9 */x /* 10 */ in/* 11 */nums/* 12 */// 13
select x + 1/* 18 *//*21*///22
).ToList()/* 16 *//* 17 *//* 19 *///20
; //26
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
List<int> M(IEnumerable<int> nums)
{
/*23*/
return /*24*/ /* 1 *//* 2 *//* 3 *//* 4 */// 5
/*25*/
(nums /* 12 */.Select(
/* 6 *//* 7 *//* 14 */// 15
/* 9 */x /* 10 */ => x + 1/* 18 *//*21*///22
/* 8 *//* 11 */// 13
)).ToList()/* 16 *//* 17 *//* 19 *///20
; //26
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CommentsCount()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
/* 1 */ var /* 2 */ c /* 3 */ = /* 4 */ 0; // 5
/* 6 */ [| foreach /* 7 */ (/* 8 */ var /* 9 */ x /* 10 */ in /* 11 */ nums /* 12 */) // 13
/* 14 */{ // 15
/* 16 */ c++ /* 17 */;//18
/*19*/}|] //20
/*21*/return /*22*/ c /*23*/; //24
}
}";
var queryOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
/*21*/
return /*22*/ /* 1 *//* 2 *//* 3 *//* 4 */// 5
/*23*/
(
/* 14 */// 15
/* 6 */from/* 8 *//* 7 *//* 9 */x /* 10 */ in/* 11 */nums/* 12 */// 13
select x/* 10 *//*19*///20
).Count()/* 16 *//* 17 *///18
; //24
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System.Collections.Generic;
using System.Linq;
class C
{
int M(IEnumerable<int> nums)
{
/*21*/
return /*22*/ /* 1 *//* 2 *//* 3 *//* 4 */// 5
/*23*/
(nums /* 12 *//* 6 *//* 7 *//* 14 */// 15
/* 9 *//* 10 *//* 10 *//*19*///20
/* 8 *//* 11 */// 13
).Count()/* 16 *//* 17 *///18
; //24
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CommentsDefault()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
[|/* 1 */ foreach /* 2 */(int /* 3 */ n1 /* 4 */in /* 5 */ nums /* 6 */)// 7
/* 8*/{// 9
/* 10 */int /* 11 */ a /* 12 */ = /* 13 */ n1 + n1 /* 14*/, /* 15 */ b /*16*/ = /*17*/ n1 * n1/*18*/;//19
/*20*/Console.WriteLine(a + b);//21
/*22*/}/*23*/|]
}
}";
var queryOutput = @"
using System;
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
foreach (var (a /* 12 */ , b /*16*/ ) in
/* 1 */from/* 2 */int /* 3 */ n1 /* 4 */in/* 5 */nums/* 6 */// 7
/* 8*/// 9
/* 10 *//* 11 */
let a /* 12 */ = /* 13 */ n1 + n1/* 14*//* 15 */
let b /*16*/ = /*17*/ n1 * n1/*18*///19
select (a /* 12 */ , b /*16*/ )/*22*//*23*/)
{
/*20*/
Console.WriteLine(a + b);//21
}
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
// No linq refactoring offered due to variable declaration(s) in outermost foreach.
await TestActionCountAsync(source, count: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task CommentsDefault_02()
{
var source = @"
using System;
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
[|/* 1 */ foreach /* 2 */(int /* 3 */ n1 /* 4 */in /* 5 */ nums /* 6 */)// 7
/* 8*/{// 9
/* 10 */ if /* 11 */ (/* 12 */ n1 /* 13 */ > /* 14 */ 0/* 15 */ ) // 16
/* 17 */{ // 18
/*19*/Console.WriteLine(n1);//20
/* 21 */} // 22
/*23*/}/*24*/|]
}
}";
var queryOutput = @"
using System;
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
foreach (var n1 /* 4 */in
/* 17 */// 18
/* 1 */from/* 2 */int /* 3 */ n1 /* 4 */in/* 5 */nums/* 6 */// 7
/* 8*/// 9
/* 10 */
where/* 11 *//* 12 */n1 /* 13 */ > /* 14 */ 0/* 15 */// 16
select n1/* 4 *//* 21 */// 22
/*23*//*24*/
)
{
/*19*/
Console.WriteLine(n1);//20
}
}
}";
await TestInRegularAndScriptAsync(source, queryOutput, index: 0);
var linqInvocationOutput = @"
using System;
using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<int> nums)
{
foreach (var n1 /* 4 */in nums /* 6 */.Where(
/* 10 *//* 11 *//* 8*/// 9
n1 =>
/* 12 */n1 /* 13 */ > /* 14 */ 0/* 15 */// 16
)
/* 1 *//* 2 *//* 17 */// 18
/* 3 *//* 4 *//* 4 *//* 21 */// 22
/*23*//*24*//* 5 */// 7
)
{
/*19*/
Console.WriteLine(n1);//20
}
}
}";
await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1);
}
#endregion
#region Preprocessor directives
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)]
public async Task NoConversionPreprocessorDirectives()
{
var source = @"
using System.Collections.Generic;
using System.Linq;
class C
{
IEnumerable<int> M(IEnumerable<int> nums)
{
[|foreach(var x in nums)
{
#if (true)
yield return x + 1;
#endif
}|]
}
}";
// Cannot convert expressions with preprocessor directives
await TestMissingAsync(source);
}
#endregion
}
}
| -1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Compilers/CSharp/Test/Symbol/Symbols/Metadata/PE/LoadingEvents.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using System;
using System.Linq;
using Xunit;
using static Roslyn.Test.Utilities.TestMetadata;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Metadata.PE
{
public class LoadingEvents : CSharpTestBase
{
[Fact]
public void LoadNonGenericEvents()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.Events,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("NonGeneric");
CheckInstanceAndStaticEvents(@class, "System.Action");
}
[Fact]
public void LoadGenericEvents()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.Events,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("Generic");
CheckInstanceAndStaticEvents(@class, "System.Action<T>");
}
[Fact]
public void LoadClosedGenericEvents()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.Events,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("ClosedGeneric");
CheckInstanceAndStaticEvents(@class, "System.Action<System.Int32>");
}
private static void CheckInstanceAndStaticEvents(NamedTypeSymbol @class, string eventTypeDisplayString)
{
var instanceEvent = @class.GetMember<EventSymbol>("InstanceEvent");
Assert.Equal(SymbolKind.Event, instanceEvent.Kind);
Assert.False(instanceEvent.IsStatic);
Assert.Equal(eventTypeDisplayString, instanceEvent.Type.ToTestDisplayString());
CheckAccessorShape(instanceEvent.AddMethod, instanceEvent);
CheckAccessorShape(instanceEvent.RemoveMethod, instanceEvent);
var staticEvent = @class.GetMember<EventSymbol>("StaticEvent");
Assert.Equal(SymbolKind.Event, staticEvent.Kind);
Assert.True(staticEvent.IsStatic);
Assert.Equal(eventTypeDisplayString, staticEvent.Type.ToTestDisplayString());
CheckAccessorShape(staticEvent.AddMethod, staticEvent);
CheckAccessorShape(staticEvent.RemoveMethod, staticEvent);
}
private static void CheckAccessorShape(MethodSymbol accessor, EventSymbol @event)
{
Assert.Same(@event, accessor.AssociatedSymbol);
switch (accessor.MethodKind)
{
case MethodKind.EventAdd:
Assert.Same(@event.AddMethod, accessor);
break;
case MethodKind.EventRemove:
Assert.Same(@event.RemoveMethod, accessor);
break;
default:
Assert.False(true, string.Format("Accessor {0} has unexpected MethodKind {1}", accessor, accessor.MethodKind));
break;
}
Assert.Equal(@event.IsAbstract, accessor.IsAbstract);
Assert.Equal(@event.IsOverride, @accessor.IsOverride);
Assert.Equal(@event.IsVirtual, @accessor.IsVirtual);
Assert.Equal(@event.IsSealed, @accessor.IsSealed);
Assert.Equal(@event.IsExtern, @accessor.IsExtern);
Assert.Equal(SpecialType.System_Void, accessor.ReturnType.SpecialType);
Assert.Equal(@event.Type, accessor.Parameters.Single().Type);
}
[Fact]
public void LoadSignatureMismatchEvents()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.Events,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("SignatureMismatch");
var mismatchedAddEvent = @class.GetMember<EventSymbol>("AddMismatch");
var mismatchedRemoveEvent = @class.GetMember<EventSymbol>("RemoveMismatch");
Assert.NotEqual(mismatchedAddEvent.Type, mismatchedAddEvent.AddMethod.Parameters.Single().Type);
Assert.True(mismatchedAddEvent.MustCallMethodsDirectly);
Assert.NotEqual(mismatchedRemoveEvent.Type, mismatchedRemoveEvent.RemoveMethod.Parameters.Single().Type);
Assert.True(mismatchedRemoveEvent.MustCallMethodsDirectly);
}
[Fact]
public void LoadMissingParameterEvents()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.Events,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("AccessorMissingParameter");
var noParamAddEvent = @class.GetMember<EventSymbol>("AddNoParam");
var noParamRemoveEvent = @class.GetMember<EventSymbol>("RemoveNoParam");
Assert.Equal(0, noParamAddEvent.AddMethod.Parameters.Length);
Assert.True(noParamAddEvent.MustCallMethodsDirectly);
Assert.Equal(0, noParamRemoveEvent.RemoveMethod.Parameters.Length);
Assert.True(noParamRemoveEvent.MustCallMethodsDirectly);
}
[Fact]
public void LoadNonDelegateEvent()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.Events,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("NonDelegateEvent");
var nonDelegateEvent = @class.GetMember<EventSymbol>("NonDelegate");
Assert.Equal(SpecialType.System_Int32, nonDelegateEvent.Type.SpecialType);
}
[Fact]
public void TestExplicitImplementationSimple()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Events.CSharp,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Interface").Single();
Assert.Equal(TypeKind.Interface, @interface.TypeKind);
var interfaceEvent = (EventSymbol)@interface.GetMembers("Event").Single();
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Class").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
Assert.True(@class.Interfaces().Contains(@interface));
var classEvent = (EventSymbol)@class.GetMembers("Interface.Event").Single();
var explicitImpl = classEvent.ExplicitInterfaceImplementations.Single();
Assert.Equal(interfaceEvent, explicitImpl);
}
[Fact]
public void TestExplicitImplementationGeneric()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Events.CSharp,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IGeneric").Single();
Assert.Equal(TypeKind.Interface, @interface.TypeKind);
var interfaceEvent = (EventSymbol)@interface.GetMembers("Event").Single();
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Generic").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
var substitutedInterface = @class.Interfaces().Single();
Assert.Equal(@interface, substitutedInterface.ConstructedFrom);
var substitutedInterfaceEvent = (EventSymbol)substitutedInterface.GetMembers("Event").Single();
Assert.Equal(interfaceEvent, substitutedInterfaceEvent.OriginalDefinition);
var classEvent = (EventSymbol)@class.GetMembers("IGeneric<S>.Event").Single();
var explicitImpl = classEvent.ExplicitInterfaceImplementations.Single();
Assert.Equal(substitutedInterfaceEvent, explicitImpl);
}
[Fact]
public void TestExplicitImplementationConstructed()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Events.CSharp,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IGeneric").Single();
Assert.Equal(TypeKind.Interface, @interface.TypeKind);
var interfaceEvent = (EventSymbol)@interface.GetMembers("Event").Single();
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Constructed").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
var substitutedInterface = @class.Interfaces().Single();
Assert.Equal(@interface, substitutedInterface.ConstructedFrom);
var substitutedInterfaceEvent = (EventSymbol)substitutedInterface.GetMembers("Event").Single();
Assert.Equal(interfaceEvent, substitutedInterfaceEvent.OriginalDefinition);
var classEvent = (EventSymbol)@class.GetMembers("IGeneric<System.Int32>.Event").Single();
var explicitImpl = classEvent.ExplicitInterfaceImplementations.Single();
Assert.Equal(substitutedInterfaceEvent, explicitImpl);
}
/// <summary>
/// A type def explicitly implements an interface, also a type def, but only
/// indirectly, via a type ref.
/// </summary>
[Fact]
public void TestExplicitImplementationDefRefDef()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Events.CSharp,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var defInterface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Interface").Single();
Assert.Equal(TypeKind.Interface, defInterface.TypeKind);
var defInterfaceEvent = (EventSymbol)defInterface.GetMembers("Event").Single();
var refInterface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IGenericInterface").Single();
Assert.Equal(TypeKind.Interface, defInterface.TypeKind);
Assert.True(refInterface.Interfaces().Contains(defInterface));
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IndirectImplementation").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
var classInterfacesConstructedFrom = @class.Interfaces().Select(i => i.ConstructedFrom);
Assert.Equal(2, classInterfacesConstructedFrom.Count());
Assert.Contains(defInterface, classInterfacesConstructedFrom);
Assert.Contains(refInterface, classInterfacesConstructedFrom);
var classEvent = (EventSymbol)@class.GetMembers("Interface.Event").Single();
var explicitImpl = classEvent.ExplicitInterfaceImplementations.Single();
Assert.Equal(defInterfaceEvent, explicitImpl);
}
/// <summary>
/// In metadata, nested types implicitly share all type parameters of their containing types.
/// This results in some extra computations when mapping a type parameter position to a type
/// parameter symbol.
/// </summary>
[Fact]
public void TestTypeParameterPositions()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Events.CSharp,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var outerInterface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IGeneric2").Single();
Assert.Equal(1, outerInterface.Arity);
Assert.Equal(TypeKind.Interface, outerInterface.TypeKind);
var outerInterfaceEvent = outerInterface.GetMembers().Single(m => m.Kind == SymbolKind.Event);
var outerClass = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Outer").Single();
Assert.Equal(1, outerClass.Arity);
Assert.Equal(TypeKind.Class, outerClass.TypeKind);
var innerInterface = (NamedTypeSymbol)outerClass.GetTypeMembers("IInner").Single();
Assert.Equal(1, innerInterface.Arity);
Assert.Equal(TypeKind.Interface, innerInterface.TypeKind);
var innerInterfaceEvent = innerInterface.GetMembers().Single(m => m.Kind == SymbolKind.Event);
var innerClass1 = (NamedTypeSymbol)outerClass.GetTypeMembers("Inner1").Single();
CheckInnerClassHelper(innerClass1, "IGeneric2<A>.Event", outerInterfaceEvent);
var innerClass2 = (NamedTypeSymbol)outerClass.GetTypeMembers("Inner2").Single();
CheckInnerClassHelper(innerClass2, "IGeneric2<T>.Event", outerInterfaceEvent);
var innerClass3 = (NamedTypeSymbol)outerClass.GetTypeMembers("Inner3").Single();
CheckInnerClassHelper(innerClass3, "Outer<T>.IInner<C>.Event", innerInterfaceEvent);
var innerClass4 = (NamedTypeSymbol)outerClass.GetTypeMembers("Inner4").Single();
CheckInnerClassHelper(innerClass4, "Outer<T>.IInner<T>.Event", innerInterfaceEvent);
}
private static void CheckInnerClassHelper(NamedTypeSymbol innerClass, string methodName, Symbol interfaceEvent)
{
var @interface = interfaceEvent.ContainingType;
Assert.Equal(1, innerClass.Arity);
Assert.Equal(TypeKind.Class, innerClass.TypeKind);
Assert.Equal(@interface, innerClass.Interfaces().Single().ConstructedFrom);
var innerClassEvent = (EventSymbol)innerClass.GetMembers(methodName).Single();
var innerClassImplementingEvent = innerClassEvent.ExplicitInterfaceImplementations.Single();
Assert.Equal(interfaceEvent, innerClassImplementingEvent.OriginalDefinition);
Assert.Equal(@interface, innerClassImplementingEvent.ContainingType.ConstructedFrom);
}
// NOTE: results differ from corresponding property test.
[WorkItem(543263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543263")]
[Fact]
public void TestMixedAccessorModifiers()
{
var assembly = MetadataTestHelpers.GetSymbolForReference(TestReferences.SymbolsTests.Events);
var globalNamespace = assembly.GlobalNamespace;
var type = globalNamespace.GetMember<NamedTypeSymbol>("AccessorModifierMismatch");
const VirtualnessModifiers @none = VirtualnessModifiers.None;
const VirtualnessModifiers @abstract = VirtualnessModifiers.Abstract;
const VirtualnessModifiers @virtual = VirtualnessModifiers.Virtual;
const VirtualnessModifiers @override = VirtualnessModifiers.Override;
const VirtualnessModifiers @sealed = VirtualnessModifiers.Sealed;
VirtualnessModifiers[] modList = new[]
{
@none,
@abstract,
@virtual,
@override,
@sealed,
};
int length = 1 + modList.Cast<int>().Max();
VirtualnessModifiers[,] expected = new VirtualnessModifiers[length, length];
expected[(int)@none, (int)@none] = @none;
expected[(int)@none, (int)@abstract] = @abstract;
expected[(int)@none, (int)@virtual] = @virtual;
expected[(int)@none, (int)@override] = @override;
expected[(int)@none, (int)@sealed] = @sealed;
expected[(int)@abstract, (int)@none] = @abstract;
expected[(int)@abstract, (int)@abstract] = @abstract;
expected[(int)@abstract, (int)@virtual] = @abstract;
expected[(int)@abstract, (int)@override] = @abstract | @override;
expected[(int)@abstract, (int)@sealed] = @abstract | @sealed;
expected[(int)@virtual, (int)@none] = @virtual;
expected[(int)@virtual, (int)@abstract] = @abstract;
expected[(int)@virtual, (int)@virtual] = @virtual;
expected[(int)@virtual, (int)@override] = @override;
expected[(int)@virtual, (int)@sealed] = @sealed;
expected[(int)@override, (int)@none] = @override;
expected[(int)@override, (int)@abstract] = @override | @abstract;
expected[(int)@override, (int)@virtual] = @override;
expected[(int)@override, (int)@override] = @override;
expected[(int)@override, (int)@sealed] = @sealed;
expected[(int)@sealed, (int)@none] = @sealed;
expected[(int)@sealed, (int)@abstract] = @abstract | @sealed;
expected[(int)@sealed, (int)@virtual] = @sealed;
expected[(int)@sealed, (int)@override] = @sealed;
expected[(int)@sealed, (int)@sealed] = @sealed;
// Table should be symmetrical.
for (int i = 0; i < length; i++)
{
for (int j = 0; j < length; j++)
{
Assert.Equal(expected[i, j], expected[j, i]);
}
}
foreach (var mod1 in modList)
{
foreach (var mod2 in modList)
{
var @event = type.GetMember<EventSymbol>(mod1.ToString() + mod2.ToString());
var addMethod = @event.AddMethod;
var removeMethod = @event.RemoveMethod;
Assert.Equal(mod1, GetVirtualnessModifiers(addMethod));
Assert.Equal(mod2, GetVirtualnessModifiers(removeMethod));
Assert.Equal(expected[(int)mod1, (int)mod2], GetVirtualnessModifiers(@event));
}
}
}
[Fact]
[WorkItem(1055825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1055825")]
public void AssociatedField()
{
var source = @"
public class C
{
public event System.Action E;
}
";
var reference = CreateCompilation(source).EmitToImageReference();
var comp = CreateCompilation("", new[] { reference }, TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var @event = type.GetMember<PEEventSymbol>("E");
Assert.True(@event.HasAssociatedField);
var field = @event.AssociatedField;
Assert.NotNull(field);
Assert.Equal(@event, field.AssociatedSymbol);
}
[Fact]
[WorkItem(1055825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1055825")]
public void AssociatedField_MultipleFields()
{
var ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.field private int32 E
.field private class [mscorlib]System.Action E
.method public hidebysig specialname instance void
add_E(class [mscorlib]System.Action 'value') cil managed
{
ldnull
throw
}
.method public hidebysig specialname instance void
remove_E(class [mscorlib]System.Action 'value') cil managed
{
ldnull
throw
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.event [mscorlib]System.Action E
{
.addon instance void C::add_E(class [mscorlib]System.Action)
.removeon instance void C::remove_E(class [mscorlib]System.Action)
} // end of event C::E
} // end of class C
";
var ilRef = CompileIL(ilSource);
var comp = CreateCompilation("", new[] { ilRef }, TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
comp.VerifyDiagnostics();
var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var @event = type.GetMembers().OfType<PEEventSymbol>().Single();
Assert.True(@event.HasAssociatedField);
var field = @event.AssociatedField;
Assert.NotNull(field);
Assert.Equal(@event, field.AssociatedSymbol);
Assert.Equal(@event.Type, field.Type);
}
[Fact]
[WorkItem(1055825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1055825")]
public void AssociatedField_DuplicateEvents()
{
var ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.field private class [mscorlib]System.Action E
.method public hidebysig specialname instance void
add_E(class [mscorlib]System.Action 'value') cil managed
{
ldnull
throw
}
.method public hidebysig specialname instance void
remove_E(class [mscorlib]System.Action 'value') cil managed
{
ldnull
throw
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.event [mscorlib]System.Action E
{
.addon instance void C::add_E(class [mscorlib]System.Action)
.removeon instance void C::remove_E(class [mscorlib]System.Action)
} // end of event C::E
.event [mscorlib]System.Action E
{
.addon instance void C::add_E(class [mscorlib]System.Action)
.removeon instance void C::remove_E(class [mscorlib]System.Action)
} // end of event C::E
} // end of class C
";
var ilRef = CompileIL(ilSource);
var comp = CreateCompilation("", new[] { ilRef }, TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
comp.VerifyDiagnostics();
var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var events = type.GetMembers().OfType<PEEventSymbol>();
Assert.Equal(2, events.Count());
AssertEx.All(events, e => e.HasAssociatedField);
var field = events.First().AssociatedField;
Assert.NotNull(field);
AssertEx.All(events, e => e.AssociatedField == field);
Assert.Contains(field.AssociatedSymbol, events);
}
[Flags]
private enum VirtualnessModifiers
{
None = 0,
Abstract = 1,
Virtual = 2,
Override = 4,
Sealed = 8, //actually indicates sealed override
}
private static VirtualnessModifiers GetVirtualnessModifiers(Symbol symbol)
{
VirtualnessModifiers mods = VirtualnessModifiers.None;
if (symbol.IsAbstract) mods |= VirtualnessModifiers.Abstract;
if (symbol.IsVirtual) mods |= VirtualnessModifiers.Virtual;
if (symbol.IsSealed) mods |= VirtualnessModifiers.Sealed;
else if (symbol.IsOverride) mods |= VirtualnessModifiers.Override;
return mods;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using System;
using System.Linq;
using Xunit;
using static Roslyn.Test.Utilities.TestMetadata;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Metadata.PE
{
public class LoadingEvents : CSharpTestBase
{
[Fact]
public void LoadNonGenericEvents()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.Events,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("NonGeneric");
CheckInstanceAndStaticEvents(@class, "System.Action");
}
[Fact]
public void LoadGenericEvents()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.Events,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("Generic");
CheckInstanceAndStaticEvents(@class, "System.Action<T>");
}
[Fact]
public void LoadClosedGenericEvents()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.Events,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("ClosedGeneric");
CheckInstanceAndStaticEvents(@class, "System.Action<System.Int32>");
}
private static void CheckInstanceAndStaticEvents(NamedTypeSymbol @class, string eventTypeDisplayString)
{
var instanceEvent = @class.GetMember<EventSymbol>("InstanceEvent");
Assert.Equal(SymbolKind.Event, instanceEvent.Kind);
Assert.False(instanceEvent.IsStatic);
Assert.Equal(eventTypeDisplayString, instanceEvent.Type.ToTestDisplayString());
CheckAccessorShape(instanceEvent.AddMethod, instanceEvent);
CheckAccessorShape(instanceEvent.RemoveMethod, instanceEvent);
var staticEvent = @class.GetMember<EventSymbol>("StaticEvent");
Assert.Equal(SymbolKind.Event, staticEvent.Kind);
Assert.True(staticEvent.IsStatic);
Assert.Equal(eventTypeDisplayString, staticEvent.Type.ToTestDisplayString());
CheckAccessorShape(staticEvent.AddMethod, staticEvent);
CheckAccessorShape(staticEvent.RemoveMethod, staticEvent);
}
private static void CheckAccessorShape(MethodSymbol accessor, EventSymbol @event)
{
Assert.Same(@event, accessor.AssociatedSymbol);
switch (accessor.MethodKind)
{
case MethodKind.EventAdd:
Assert.Same(@event.AddMethod, accessor);
break;
case MethodKind.EventRemove:
Assert.Same(@event.RemoveMethod, accessor);
break;
default:
Assert.False(true, string.Format("Accessor {0} has unexpected MethodKind {1}", accessor, accessor.MethodKind));
break;
}
Assert.Equal(@event.IsAbstract, accessor.IsAbstract);
Assert.Equal(@event.IsOverride, @accessor.IsOverride);
Assert.Equal(@event.IsVirtual, @accessor.IsVirtual);
Assert.Equal(@event.IsSealed, @accessor.IsSealed);
Assert.Equal(@event.IsExtern, @accessor.IsExtern);
Assert.Equal(SpecialType.System_Void, accessor.ReturnType.SpecialType);
Assert.Equal(@event.Type, accessor.Parameters.Single().Type);
}
[Fact]
public void LoadSignatureMismatchEvents()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.Events,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("SignatureMismatch");
var mismatchedAddEvent = @class.GetMember<EventSymbol>("AddMismatch");
var mismatchedRemoveEvent = @class.GetMember<EventSymbol>("RemoveMismatch");
Assert.NotEqual(mismatchedAddEvent.Type, mismatchedAddEvent.AddMethod.Parameters.Single().Type);
Assert.True(mismatchedAddEvent.MustCallMethodsDirectly);
Assert.NotEqual(mismatchedRemoveEvent.Type, mismatchedRemoveEvent.RemoveMethod.Parameters.Single().Type);
Assert.True(mismatchedRemoveEvent.MustCallMethodsDirectly);
}
[Fact]
public void LoadMissingParameterEvents()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.Events,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("AccessorMissingParameter");
var noParamAddEvent = @class.GetMember<EventSymbol>("AddNoParam");
var noParamRemoveEvent = @class.GetMember<EventSymbol>("RemoveNoParam");
Assert.Equal(0, noParamAddEvent.AddMethod.Parameters.Length);
Assert.True(noParamAddEvent.MustCallMethodsDirectly);
Assert.Equal(0, noParamRemoveEvent.RemoveMethod.Parameters.Length);
Assert.True(noParamRemoveEvent.MustCallMethodsDirectly);
}
[Fact]
public void LoadNonDelegateEvent()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.Events,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @class = globalNamespace.GetMember<NamedTypeSymbol>("NonDelegateEvent");
var nonDelegateEvent = @class.GetMember<EventSymbol>("NonDelegate");
Assert.Equal(SpecialType.System_Int32, nonDelegateEvent.Type.SpecialType);
}
[Fact]
public void TestExplicitImplementationSimple()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Events.CSharp,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Interface").Single();
Assert.Equal(TypeKind.Interface, @interface.TypeKind);
var interfaceEvent = (EventSymbol)@interface.GetMembers("Event").Single();
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Class").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
Assert.True(@class.Interfaces().Contains(@interface));
var classEvent = (EventSymbol)@class.GetMembers("Interface.Event").Single();
var explicitImpl = classEvent.ExplicitInterfaceImplementations.Single();
Assert.Equal(interfaceEvent, explicitImpl);
}
[Fact]
public void TestExplicitImplementationGeneric()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Events.CSharp,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IGeneric").Single();
Assert.Equal(TypeKind.Interface, @interface.TypeKind);
var interfaceEvent = (EventSymbol)@interface.GetMembers("Event").Single();
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Generic").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
var substitutedInterface = @class.Interfaces().Single();
Assert.Equal(@interface, substitutedInterface.ConstructedFrom);
var substitutedInterfaceEvent = (EventSymbol)substitutedInterface.GetMembers("Event").Single();
Assert.Equal(interfaceEvent, substitutedInterfaceEvent.OriginalDefinition);
var classEvent = (EventSymbol)@class.GetMembers("IGeneric<S>.Event").Single();
var explicitImpl = classEvent.ExplicitInterfaceImplementations.Single();
Assert.Equal(substitutedInterfaceEvent, explicitImpl);
}
[Fact]
public void TestExplicitImplementationConstructed()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Events.CSharp,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var @interface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IGeneric").Single();
Assert.Equal(TypeKind.Interface, @interface.TypeKind);
var interfaceEvent = (EventSymbol)@interface.GetMembers("Event").Single();
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Constructed").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
var substitutedInterface = @class.Interfaces().Single();
Assert.Equal(@interface, substitutedInterface.ConstructedFrom);
var substitutedInterfaceEvent = (EventSymbol)substitutedInterface.GetMembers("Event").Single();
Assert.Equal(interfaceEvent, substitutedInterfaceEvent.OriginalDefinition);
var classEvent = (EventSymbol)@class.GetMembers("IGeneric<System.Int32>.Event").Single();
var explicitImpl = classEvent.ExplicitInterfaceImplementations.Single();
Assert.Equal(substitutedInterfaceEvent, explicitImpl);
}
/// <summary>
/// A type def explicitly implements an interface, also a type def, but only
/// indirectly, via a type ref.
/// </summary>
[Fact]
public void TestExplicitImplementationDefRefDef()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Events.CSharp,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var defInterface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Interface").Single();
Assert.Equal(TypeKind.Interface, defInterface.TypeKind);
var defInterfaceEvent = (EventSymbol)defInterface.GetMembers("Event").Single();
var refInterface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IGenericInterface").Single();
Assert.Equal(TypeKind.Interface, defInterface.TypeKind);
Assert.True(refInterface.Interfaces().Contains(defInterface));
var @class = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IndirectImplementation").Single();
Assert.Equal(TypeKind.Class, @class.TypeKind);
var classInterfacesConstructedFrom = @class.Interfaces().Select(i => i.ConstructedFrom);
Assert.Equal(2, classInterfacesConstructedFrom.Count());
Assert.Contains(defInterface, classInterfacesConstructedFrom);
Assert.Contains(refInterface, classInterfacesConstructedFrom);
var classEvent = (EventSymbol)@class.GetMembers("Interface.Event").Single();
var explicitImpl = classEvent.ExplicitInterfaceImplementations.Single();
Assert.Equal(defInterfaceEvent, explicitImpl);
}
/// <summary>
/// In metadata, nested types implicitly share all type parameters of their containing types.
/// This results in some extra computations when mapping a type parameter position to a type
/// parameter symbol.
/// </summary>
[Fact]
public void TestTypeParameterPositions()
{
var assemblies = MetadataTestHelpers.GetSymbolsForReferences(
new[]
{
Net451.mscorlib,
TestReferences.SymbolsTests.ExplicitInterfaceImplementation.Events.CSharp,
});
var globalNamespace = assemblies.ElementAt(1).GlobalNamespace;
var outerInterface = (NamedTypeSymbol)globalNamespace.GetTypeMembers("IGeneric2").Single();
Assert.Equal(1, outerInterface.Arity);
Assert.Equal(TypeKind.Interface, outerInterface.TypeKind);
var outerInterfaceEvent = outerInterface.GetMembers().Single(m => m.Kind == SymbolKind.Event);
var outerClass = (NamedTypeSymbol)globalNamespace.GetTypeMembers("Outer").Single();
Assert.Equal(1, outerClass.Arity);
Assert.Equal(TypeKind.Class, outerClass.TypeKind);
var innerInterface = (NamedTypeSymbol)outerClass.GetTypeMembers("IInner").Single();
Assert.Equal(1, innerInterface.Arity);
Assert.Equal(TypeKind.Interface, innerInterface.TypeKind);
var innerInterfaceEvent = innerInterface.GetMembers().Single(m => m.Kind == SymbolKind.Event);
var innerClass1 = (NamedTypeSymbol)outerClass.GetTypeMembers("Inner1").Single();
CheckInnerClassHelper(innerClass1, "IGeneric2<A>.Event", outerInterfaceEvent);
var innerClass2 = (NamedTypeSymbol)outerClass.GetTypeMembers("Inner2").Single();
CheckInnerClassHelper(innerClass2, "IGeneric2<T>.Event", outerInterfaceEvent);
var innerClass3 = (NamedTypeSymbol)outerClass.GetTypeMembers("Inner3").Single();
CheckInnerClassHelper(innerClass3, "Outer<T>.IInner<C>.Event", innerInterfaceEvent);
var innerClass4 = (NamedTypeSymbol)outerClass.GetTypeMembers("Inner4").Single();
CheckInnerClassHelper(innerClass4, "Outer<T>.IInner<T>.Event", innerInterfaceEvent);
}
private static void CheckInnerClassHelper(NamedTypeSymbol innerClass, string methodName, Symbol interfaceEvent)
{
var @interface = interfaceEvent.ContainingType;
Assert.Equal(1, innerClass.Arity);
Assert.Equal(TypeKind.Class, innerClass.TypeKind);
Assert.Equal(@interface, innerClass.Interfaces().Single().ConstructedFrom);
var innerClassEvent = (EventSymbol)innerClass.GetMembers(methodName).Single();
var innerClassImplementingEvent = innerClassEvent.ExplicitInterfaceImplementations.Single();
Assert.Equal(interfaceEvent, innerClassImplementingEvent.OriginalDefinition);
Assert.Equal(@interface, innerClassImplementingEvent.ContainingType.ConstructedFrom);
}
// NOTE: results differ from corresponding property test.
[WorkItem(543263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543263")]
[Fact]
public void TestMixedAccessorModifiers()
{
var assembly = MetadataTestHelpers.GetSymbolForReference(TestReferences.SymbolsTests.Events);
var globalNamespace = assembly.GlobalNamespace;
var type = globalNamespace.GetMember<NamedTypeSymbol>("AccessorModifierMismatch");
const VirtualnessModifiers @none = VirtualnessModifiers.None;
const VirtualnessModifiers @abstract = VirtualnessModifiers.Abstract;
const VirtualnessModifiers @virtual = VirtualnessModifiers.Virtual;
const VirtualnessModifiers @override = VirtualnessModifiers.Override;
const VirtualnessModifiers @sealed = VirtualnessModifiers.Sealed;
VirtualnessModifiers[] modList = new[]
{
@none,
@abstract,
@virtual,
@override,
@sealed,
};
int length = 1 + modList.Cast<int>().Max();
VirtualnessModifiers[,] expected = new VirtualnessModifiers[length, length];
expected[(int)@none, (int)@none] = @none;
expected[(int)@none, (int)@abstract] = @abstract;
expected[(int)@none, (int)@virtual] = @virtual;
expected[(int)@none, (int)@override] = @override;
expected[(int)@none, (int)@sealed] = @sealed;
expected[(int)@abstract, (int)@none] = @abstract;
expected[(int)@abstract, (int)@abstract] = @abstract;
expected[(int)@abstract, (int)@virtual] = @abstract;
expected[(int)@abstract, (int)@override] = @abstract | @override;
expected[(int)@abstract, (int)@sealed] = @abstract | @sealed;
expected[(int)@virtual, (int)@none] = @virtual;
expected[(int)@virtual, (int)@abstract] = @abstract;
expected[(int)@virtual, (int)@virtual] = @virtual;
expected[(int)@virtual, (int)@override] = @override;
expected[(int)@virtual, (int)@sealed] = @sealed;
expected[(int)@override, (int)@none] = @override;
expected[(int)@override, (int)@abstract] = @override | @abstract;
expected[(int)@override, (int)@virtual] = @override;
expected[(int)@override, (int)@override] = @override;
expected[(int)@override, (int)@sealed] = @sealed;
expected[(int)@sealed, (int)@none] = @sealed;
expected[(int)@sealed, (int)@abstract] = @abstract | @sealed;
expected[(int)@sealed, (int)@virtual] = @sealed;
expected[(int)@sealed, (int)@override] = @sealed;
expected[(int)@sealed, (int)@sealed] = @sealed;
// Table should be symmetrical.
for (int i = 0; i < length; i++)
{
for (int j = 0; j < length; j++)
{
Assert.Equal(expected[i, j], expected[j, i]);
}
}
foreach (var mod1 in modList)
{
foreach (var mod2 in modList)
{
var @event = type.GetMember<EventSymbol>(mod1.ToString() + mod2.ToString());
var addMethod = @event.AddMethod;
var removeMethod = @event.RemoveMethod;
Assert.Equal(mod1, GetVirtualnessModifiers(addMethod));
Assert.Equal(mod2, GetVirtualnessModifiers(removeMethod));
Assert.Equal(expected[(int)mod1, (int)mod2], GetVirtualnessModifiers(@event));
}
}
}
[Fact]
[WorkItem(1055825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1055825")]
public void AssociatedField()
{
var source = @"
public class C
{
public event System.Action E;
}
";
var reference = CreateCompilation(source).EmitToImageReference();
var comp = CreateCompilation("", new[] { reference }, TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var @event = type.GetMember<PEEventSymbol>("E");
Assert.True(@event.HasAssociatedField);
var field = @event.AssociatedField;
Assert.NotNull(field);
Assert.Equal(@event, field.AssociatedSymbol);
}
[Fact]
[WorkItem(1055825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1055825")]
public void AssociatedField_MultipleFields()
{
var ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.field private int32 E
.field private class [mscorlib]System.Action E
.method public hidebysig specialname instance void
add_E(class [mscorlib]System.Action 'value') cil managed
{
ldnull
throw
}
.method public hidebysig specialname instance void
remove_E(class [mscorlib]System.Action 'value') cil managed
{
ldnull
throw
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.event [mscorlib]System.Action E
{
.addon instance void C::add_E(class [mscorlib]System.Action)
.removeon instance void C::remove_E(class [mscorlib]System.Action)
} // end of event C::E
} // end of class C
";
var ilRef = CompileIL(ilSource);
var comp = CreateCompilation("", new[] { ilRef }, TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
comp.VerifyDiagnostics();
var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var @event = type.GetMembers().OfType<PEEventSymbol>().Single();
Assert.True(@event.HasAssociatedField);
var field = @event.AssociatedField;
Assert.NotNull(field);
Assert.Equal(@event, field.AssociatedSymbol);
Assert.Equal(@event.Type, field.Type);
}
[Fact]
[WorkItem(1055825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1055825")]
public void AssociatedField_DuplicateEvents()
{
var ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.field private class [mscorlib]System.Action E
.method public hidebysig specialname instance void
add_E(class [mscorlib]System.Action 'value') cil managed
{
ldnull
throw
}
.method public hidebysig specialname instance void
remove_E(class [mscorlib]System.Action 'value') cil managed
{
ldnull
throw
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.event [mscorlib]System.Action E
{
.addon instance void C::add_E(class [mscorlib]System.Action)
.removeon instance void C::remove_E(class [mscorlib]System.Action)
} // end of event C::E
.event [mscorlib]System.Action E
{
.addon instance void C::add_E(class [mscorlib]System.Action)
.removeon instance void C::remove_E(class [mscorlib]System.Action)
} // end of event C::E
} // end of class C
";
var ilRef = CompileIL(ilSource);
var comp = CreateCompilation("", new[] { ilRef }, TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
comp.VerifyDiagnostics();
var type = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var events = type.GetMembers().OfType<PEEventSymbol>();
Assert.Equal(2, events.Count());
AssertEx.All(events, e => e.HasAssociatedField);
var field = events.First().AssociatedField;
Assert.NotNull(field);
AssertEx.All(events, e => e.AssociatedField == field);
Assert.Contains(field.AssociatedSymbol, events);
}
[Flags]
private enum VirtualnessModifiers
{
None = 0,
Abstract = 1,
Virtual = 2,
Override = 4,
Sealed = 8, //actually indicates sealed override
}
private static VirtualnessModifiers GetVirtualnessModifiers(Symbol symbol)
{
VirtualnessModifiers mods = VirtualnessModifiers.None;
if (symbol.IsAbstract) mods |= VirtualnessModifiers.Abstract;
if (symbol.IsVirtual) mods |= VirtualnessModifiers.Virtual;
if (symbol.IsSealed) mods |= VirtualnessModifiers.Sealed;
else if (symbol.IsOverride) mods |= VirtualnessModifiers.Override;
return mods;
}
}
}
| -1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Declarations/StaticKeywordRecommender.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations
''' <summary>
''' Recommends the "Static" keyword for the start of a statement.
''' </summary>
Friend Class StaticKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) =
ImmutableArray.Create(New RecommendedKeyword("Static", VBFeaturesResources.Specifies_that_one_or_more_declared_local_variables_are_to_remain_in_existence_and_retain_their_latest_values_after_the_procedure_in_which_they_are_declared_terminates))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
Return If(context.IsMultiLineStatementContext, s_keywords, ImmutableArray(Of RecommendedKeyword).Empty)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations
''' <summary>
''' Recommends the "Static" keyword for the start of a statement.
''' </summary>
Friend Class StaticKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) =
ImmutableArray.Create(New RecommendedKeyword("Static", VBFeaturesResources.Specifies_that_one_or_more_declared_local_variables_are_to_remain_in_existence_and_retain_their_latest_values_after_the_procedure_in_which_they_are_declared_terminates))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
Return If(context.IsMultiLineStatementContext, s_keywords, ImmutableArray(Of RecommendedKeyword).Empty)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/EditorFeatures/CSharpTest/SignatureHelp/ElementAccessExpressionSignatureHelpProviderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp
{
public class ElementAccessExpressionSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests
{
internal override Type GetSignatureHelpProviderType()
=> typeof(ElementAccessExpressionSignatureHelpProvider);
#region "Regular tests"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersOn1()
{
var markup = @"
class C
{
public string this[int a]
{
get { return null; }
set { }
}
}
class D
{
void Goo()
{
var c = new C();
var x = [|c[$$|]];
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
[WorkItem(24311, "https://github.com/dotnet/roslyn/issues/24311")]
public async Task TestInvocationWithParametersOn1_WithRefReturn()
{
var markup = @"
class C
{
public ref int this[int a]
{
get { throw null; }
}
void Goo(C c)
{
[|c[$$]|]
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("ref int C[int a]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
[WorkItem(24311, "https://github.com/dotnet/roslyn/issues/24311")]
public async Task TestInvocationWithParametersOn1_WithRefReadonlyReturn()
{
var markup = @"
class C
{
public ref readonly int this[int a]
{
get { throw null; }
}
void Goo(C c)
{
[|c[$$]|]
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("ref readonly int C[int a]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(636117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636117")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnExpression()
{
var markup = @"
class C
{
public string this[int a]
{
get { return null; }
set { }
}
}
class D
{
void Goo()
{
C[] c = new C[1];
c[0][$$
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersXmlCommentsOn1()
{
var markup = @"
class C
{
/// <summary>
/// Summary for this.
/// </summary>
/// <param name=""a"">Param a</param>
public string this[int a]
{
get { return null; }
set { }
}
}
class D
{
void Goo()
{
var c = new C();
var x = [|c[$$|]];
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", "Summary for this.", "Param a", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersOn2()
{
var markup = @"
class C
{
public string this[int a, bool b]
{
get { return null; }
set { }
}
}
class D
{
void Goo()
{
var c = new C();
var x = [|c[22, $$|]];
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a, bool b]", string.Empty, string.Empty, currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersXmlComentsOn2()
{
var markup = @"
class C
{
/// <summary>
/// Summary for this.
/// </summary>
/// <param name=""a"">Param a</param>
/// <param name=""b"">Param b</param>
public string this[int a, bool b]
{
get { return null; }
set { }
}
}
class D
{
void Goo()
{
var c = new C();
var x = [|c[22, $$|]];
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a, bool b]", "Summary for this.", "Param b", currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutClosingBracketWithParameters()
{
var markup =
@"class C
{
public string this[int a]
{
get { return null; }
set { }
}
}
class D
{
void Goo()
{
var c = new C();
var x = [|c[$$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutClosingBracketWithParametersOn2()
{
var markup = @"
class C
{
public string this[int a, bool b]
{
get { return null; }
set { }
}
}
class D
{
void Goo()
{
var c = new C();
var x = [|c[22, $$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a, bool b]", string.Empty, string.Empty, currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems);
}
#endregion
#region "Current Parameter Name"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestCurrentParameterName()
{
var markup = @"
class C
{
public string this[int a, bool b]
{
get { return null; }
set { }
}
}
class D
{
void Goo()
{
var c = new C();
var x = [|c[b: false, a: $$42|]];
}
}";
await VerifyCurrentParameterNameAsync(markup, "a");
}
#endregion
#region "Trigger tests"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnTriggerBracket()
{
var markup = @"
class C
{
public string this[int a]
{
get { return null; }
set { }
}
}
class D
{
void Goo()
{
var c = new C();
var x = [|c[$$|]];
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnTriggerComma()
{
var markup = @"
class C
{
public string this[int a, bool b]
{
get { return null; }
set { }
}
}
class D
{
void Goo()
{
var c = new C();
var x = [|c[42,$$|]];
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a, bool b]", string.Empty, string.Empty, currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestNoInvocationOnSpace()
{
var markup = @"
class C
{
public string this[int a, bool b]
{
get { return null; }
set { }
}
}
class D
{
void Goo()
{
var c = new C();
var x = [|c[42, $$|]];
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestTriggerCharacters()
{
char[] expectedCharacters = { ',', '[' };
char[] unexpectedCharacters = { ' ', '(', '<' };
VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters);
}
#endregion
#region "EditorBrowsable tests"
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Indexer_PropertyAlways()
{
var markup = @"
class Program
{
void M()
{
new Goo()[$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public int this[int x]
{
get { return 5; }
set { }
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("int Goo[int x]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Indexer_PropertyNever()
{
var markup = @"
class Program
{
void M()
{
new Goo()[$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public int this[int x]
{
get { return 5; }
set { }
}
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("int Goo[int x]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItemsMetadataReference,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Indexer_PropertyAdvanced()
{
var markup = @"
class Program
{
void M()
{
new Goo()[$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public int this[int x]
{
get { return 5; }
set { }
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("int Goo[int x]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Indexer_PropertyNeverOnOneOfTwoOverloads()
{
var markup = @"
class Program
{
void M()
{
new Goo()[$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public int this[int x]
{
get { return 5; }
set { }
}
public int this[double d]
{
get { return 5; }
set { }
}
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("int Goo[double d]", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("int Goo[double d]", string.Empty, string.Empty, currentParameterIndex: 0),
new SignatureHelpTestItem("int Goo[int x]", string.Empty, string.Empty, currentParameterIndex: 0),
};
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Indexer_GetBrowsableNeverIgnored()
{
var markup = @"
class Program
{
void M()
{
new Goo()[$$
}
}";
var referencedCode = @"
public class Goo
{
public int this[int x]
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
get { return 5; }
set { }
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("int Goo[int x]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Indexer_SetBrowsableNeverIgnored()
{
var markup = @"
class Program
{
void M()
{
new Goo()[$$
}
}";
var referencedCode = @"
public class Goo
{
public int this[int x]
{
get { return 5; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
set { }
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("int Goo[int x]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Indexer_GetSetBrowsableNeverIgnored()
{
var markup = @"
class Program
{
void M()
{
new Goo()[$$
}
}";
var referencedCode = @"
public class Goo
{
public int this[int x]
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
get { return 5; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
set { }
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("int Goo[int x]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
#endregion
#region Indexed Property tests
[WorkItem(530811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530811")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task IndexedProperty()
{
var markup = @"class Program
{
void M()
{
CCC c = new CCC();
c.IndexProp[$$
}
}";
// Note that <COMImport> is required by compiler. Bug 17013 tracks enabling indexed property for non-COM types.
var referencedCode = @"Imports System.Runtime.InteropServices
<ComImport()>
<GuidAttribute(CCC.ClassId)>
Public Class CCC
#Region ""COM GUIDs""
Public Const ClassId As String = ""9d965fd2-1514-44f6-accd-257ce77c46b0""
Public Const InterfaceId As String = ""a9415060-fdf0-47e3-bc80-9c18f7f39cf6""
Public Const EventsId As String = ""c6a866a5-5f97-4b53-a5df-3739dc8ff1bb""
# End Region
''' <summary>
''' An index property from VB
''' </summary>
''' <param name=""p1"">p1 is an integer index</param>
''' <returns>A string</returns>
Public Property IndexProp(ByVal p1 As Integer) As String
Get
Return Nothing
End Get
Set(ByVal value As String)
End Set
End Property
End Class";
var metadataItems = new List<SignatureHelpTestItem>();
metadataItems.Add(new SignatureHelpTestItem("string CCC.IndexProp[int p1]", string.Empty, string.Empty, currentParameterIndex: 0));
var projectReferenceItems = new List<SignatureHelpTestItem>();
projectReferenceItems.Add(new SignatureHelpTestItem("string CCC.IndexProp[int p1]", "An index property from VB", "p1 is an integer index", currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: metadataItems,
expectedOrderedItemsSameSolution: projectReferenceItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.VisualBasic);
}
#endregion
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task FieldUnavailableInOneLinkedFile()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if GOO
public int this[int z]
{
get
{
return 0;
}
}
#endif
void goo()
{
var x = this[$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"int C[int z]\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", currentParameterIndex: 0);
await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task ExcludeFilesWithInactiveRegions()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO,BAR"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if GOO
public int this[int z]
{
get
{
return 0;
}
}
#endif
#if BAR
void goo()
{
var x = this[$$
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" />
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"int C[int z]\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", currentParameterIndex: 0);
await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false);
}
public class IncompleteElementAccessExpressionSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests
{
internal override Type GetSignatureHelpProviderType()
=> typeof(ElementAccessExpressionSignatureHelpProvider);
[WorkItem(636117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636117")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocation()
{
var markup = @"
class C
{
public string this[int a]
{
get { return null; }
set { }
}
}
class D
{
void Goo()
{
var c = new C();
c[$$]
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(939417, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939417")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task ConditionalIndexer()
{
var markup = @"
public class P
{
public int this[int z]
{
get
{
return 0;
}
}
public void goo()
{
P p = null;
p?[$$]
}
}
";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("int P[int z]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(32, "https://github.com/dotnet/roslyn/issues/32")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task NonIdentifierConditionalIndexer()
{
var expected = new[] { new SignatureHelpTestItem("char string[int index]") };
await TestAsync(
@"class C
{
void M()
{
""""?[$$ }
}", expected); // inline with a string literal
await TestAsync(
@"class C
{
void M()
{
""""?[/**/$$ }
}", expected); // inline with a string literal and multiline comment
await TestAsync(
@"class C
{
void M()
{
("""")?[$$ }
}", expected); // parenthesized expression
await TestAsync(
@"class C
{
void M()
{
new System.String(' ', 1)?[$$ }
}", expected); // new object expression
// more complicated parenthesized expression
await TestAsync(
@"class C
{
void M()
{
(null as System.Collections.Generic.List<int>)?[$$ }
}", new[] { new SignatureHelpTestItem("int System.Collections.Generic.List<int>[int index]") });
}
[WorkItem(1067933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067933")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InvokedWithNoToken()
{
var markup = @"
// goo[$$";
await TestAsync(markup);
}
[WorkItem(2482, "https://github.com/dotnet/roslyn/issues/2482")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task WhereExpressionLooksLikeArrayTypeSyntaxOfQualifiedName()
{
var markup = @"
class WithIndexer
{
public int this[int index] { get { return 0; } }
}
class TestClass
{
public WithIndexer Item { get; set; }
public void Method(TestClass tc)
{
// `tc.Item[]` parses as ArrayTypeSyntax with an ElementType of QualifiedNameSyntax
tc.Item[$$]
}
}
";
await TestAsync(markup, new[] { new SignatureHelpTestItem("int WithIndexer[int index]") }, usePreviousCharAsTrigger: true);
}
[WorkItem(20507, "https://github.com/dotnet/roslyn/issues/20507")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InConditionalIndexingFollowedByMemberAccess()
{
var markup = @"
class Indexable
{
public Indexable this[int x] { get => null; }
Indexable Count;
static void Main(string[] args)
{
Indexable x;
x?[$$].Count;
}
}
";
await TestAsync(markup, new[] { new SignatureHelpTestItem("Indexable Indexable[int x]") }, usePreviousCharAsTrigger: false);
}
[WorkItem(20507, "https://github.com/dotnet/roslyn/issues/20507")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InConditionalIndexingFollowedByConditionalAccess()
{
var markup = @"
class Indexable
{
public Indexable this[int x] { get => null; }
Indexable Count;
static void Main(string[] args)
{
Indexable x;
x?[$$].Count?.Count;
}
}
";
await TestAsync(markup, new[] { new SignatureHelpTestItem("Indexable Indexable[int x]") }, usePreviousCharAsTrigger: 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.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp
{
public class ElementAccessExpressionSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests
{
internal override Type GetSignatureHelpProviderType()
=> typeof(ElementAccessExpressionSignatureHelpProvider);
#region "Regular tests"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersOn1()
{
var markup = @"
class C
{
public string this[int a]
{
get { return null; }
set { }
}
}
class D
{
void Goo()
{
var c = new C();
var x = [|c[$$|]];
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
[WorkItem(24311, "https://github.com/dotnet/roslyn/issues/24311")]
public async Task TestInvocationWithParametersOn1_WithRefReturn()
{
var markup = @"
class C
{
public ref int this[int a]
{
get { throw null; }
}
void Goo(C c)
{
[|c[$$]|]
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("ref int C[int a]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
[WorkItem(24311, "https://github.com/dotnet/roslyn/issues/24311")]
public async Task TestInvocationWithParametersOn1_WithRefReadonlyReturn()
{
var markup = @"
class C
{
public ref readonly int this[int a]
{
get { throw null; }
}
void Goo(C c)
{
[|c[$$]|]
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("ref readonly int C[int a]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(636117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636117")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnExpression()
{
var markup = @"
class C
{
public string this[int a]
{
get { return null; }
set { }
}
}
class D
{
void Goo()
{
C[] c = new C[1];
c[0][$$
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersXmlCommentsOn1()
{
var markup = @"
class C
{
/// <summary>
/// Summary for this.
/// </summary>
/// <param name=""a"">Param a</param>
public string this[int a]
{
get { return null; }
set { }
}
}
class D
{
void Goo()
{
var c = new C();
var x = [|c[$$|]];
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", "Summary for this.", "Param a", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersOn2()
{
var markup = @"
class C
{
public string this[int a, bool b]
{
get { return null; }
set { }
}
}
class D
{
void Goo()
{
var c = new C();
var x = [|c[22, $$|]];
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a, bool b]", string.Empty, string.Empty, currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersXmlComentsOn2()
{
var markup = @"
class C
{
/// <summary>
/// Summary for this.
/// </summary>
/// <param name=""a"">Param a</param>
/// <param name=""b"">Param b</param>
public string this[int a, bool b]
{
get { return null; }
set { }
}
}
class D
{
void Goo()
{
var c = new C();
var x = [|c[22, $$|]];
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a, bool b]", "Summary for this.", "Param b", currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutClosingBracketWithParameters()
{
var markup =
@"class C
{
public string this[int a]
{
get { return null; }
set { }
}
}
class D
{
void Goo()
{
var c = new C();
var x = [|c[$$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutClosingBracketWithParametersOn2()
{
var markup = @"
class C
{
public string this[int a, bool b]
{
get { return null; }
set { }
}
}
class D
{
void Goo()
{
var c = new C();
var x = [|c[22, $$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a, bool b]", string.Empty, string.Empty, currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems);
}
#endregion
#region "Current Parameter Name"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestCurrentParameterName()
{
var markup = @"
class C
{
public string this[int a, bool b]
{
get { return null; }
set { }
}
}
class D
{
void Goo()
{
var c = new C();
var x = [|c[b: false, a: $$42|]];
}
}";
await VerifyCurrentParameterNameAsync(markup, "a");
}
#endregion
#region "Trigger tests"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnTriggerBracket()
{
var markup = @"
class C
{
public string this[int a]
{
get { return null; }
set { }
}
}
class D
{
void Goo()
{
var c = new C();
var x = [|c[$$|]];
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnTriggerComma()
{
var markup = @"
class C
{
public string this[int a, bool b]
{
get { return null; }
set { }
}
}
class D
{
void Goo()
{
var c = new C();
var x = [|c[42,$$|]];
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a, bool b]", string.Empty, string.Empty, currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestNoInvocationOnSpace()
{
var markup = @"
class C
{
public string this[int a, bool b]
{
get { return null; }
set { }
}
}
class D
{
void Goo()
{
var c = new C();
var x = [|c[42, $$|]];
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestTriggerCharacters()
{
char[] expectedCharacters = { ',', '[' };
char[] unexpectedCharacters = { ' ', '(', '<' };
VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters);
}
#endregion
#region "EditorBrowsable tests"
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Indexer_PropertyAlways()
{
var markup = @"
class Program
{
void M()
{
new Goo()[$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public int this[int x]
{
get { return 5; }
set { }
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("int Goo[int x]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Indexer_PropertyNever()
{
var markup = @"
class Program
{
void M()
{
new Goo()[$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public int this[int x]
{
get { return 5; }
set { }
}
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("int Goo[int x]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItemsMetadataReference,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Indexer_PropertyAdvanced()
{
var markup = @"
class Program
{
void M()
{
new Goo()[$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public int this[int x]
{
get { return 5; }
set { }
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("int Goo[int x]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Indexer_PropertyNeverOnOneOfTwoOverloads()
{
var markup = @"
class Program
{
void M()
{
new Goo()[$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public int this[int x]
{
get { return 5; }
set { }
}
public int this[double d]
{
get { return 5; }
set { }
}
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("int Goo[double d]", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("int Goo[double d]", string.Empty, string.Empty, currentParameterIndex: 0),
new SignatureHelpTestItem("int Goo[int x]", string.Empty, string.Empty, currentParameterIndex: 0),
};
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Indexer_GetBrowsableNeverIgnored()
{
var markup = @"
class Program
{
void M()
{
new Goo()[$$
}
}";
var referencedCode = @"
public class Goo
{
public int this[int x]
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
get { return 5; }
set { }
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("int Goo[int x]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Indexer_SetBrowsableNeverIgnored()
{
var markup = @"
class Program
{
void M()
{
new Goo()[$$
}
}";
var referencedCode = @"
public class Goo
{
public int this[int x]
{
get { return 5; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
set { }
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("int Goo[int x]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_Indexer_GetSetBrowsableNeverIgnored()
{
var markup = @"
class Program
{
void M()
{
new Goo()[$$
}
}";
var referencedCode = @"
public class Goo
{
public int this[int x]
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
get { return 5; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
set { }
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("int Goo[int x]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
#endregion
#region Indexed Property tests
[WorkItem(530811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530811")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task IndexedProperty()
{
var markup = @"class Program
{
void M()
{
CCC c = new CCC();
c.IndexProp[$$
}
}";
// Note that <COMImport> is required by compiler. Bug 17013 tracks enabling indexed property for non-COM types.
var referencedCode = @"Imports System.Runtime.InteropServices
<ComImport()>
<GuidAttribute(CCC.ClassId)>
Public Class CCC
#Region ""COM GUIDs""
Public Const ClassId As String = ""9d965fd2-1514-44f6-accd-257ce77c46b0""
Public Const InterfaceId As String = ""a9415060-fdf0-47e3-bc80-9c18f7f39cf6""
Public Const EventsId As String = ""c6a866a5-5f97-4b53-a5df-3739dc8ff1bb""
# End Region
''' <summary>
''' An index property from VB
''' </summary>
''' <param name=""p1"">p1 is an integer index</param>
''' <returns>A string</returns>
Public Property IndexProp(ByVal p1 As Integer) As String
Get
Return Nothing
End Get
Set(ByVal value As String)
End Set
End Property
End Class";
var metadataItems = new List<SignatureHelpTestItem>();
metadataItems.Add(new SignatureHelpTestItem("string CCC.IndexProp[int p1]", string.Empty, string.Empty, currentParameterIndex: 0));
var projectReferenceItems = new List<SignatureHelpTestItem>();
projectReferenceItems.Add(new SignatureHelpTestItem("string CCC.IndexProp[int p1]", "An index property from VB", "p1 is an integer index", currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: metadataItems,
expectedOrderedItemsSameSolution: projectReferenceItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.VisualBasic);
}
#endregion
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task FieldUnavailableInOneLinkedFile()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if GOO
public int this[int z]
{
get
{
return 0;
}
}
#endif
void goo()
{
var x = this[$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"int C[int z]\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", currentParameterIndex: 0);
await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task ExcludeFilesWithInactiveRegions()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO,BAR"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if GOO
public int this[int z]
{
get
{
return 0;
}
}
#endif
#if BAR
void goo()
{
var x = this[$$
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" />
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"int C[int z]\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", currentParameterIndex: 0);
await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false);
}
public class IncompleteElementAccessExpressionSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests
{
internal override Type GetSignatureHelpProviderType()
=> typeof(ElementAccessExpressionSignatureHelpProvider);
[WorkItem(636117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636117")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocation()
{
var markup = @"
class C
{
public string this[int a]
{
get { return null; }
set { }
}
}
class D
{
void Goo()
{
var c = new C();
c[$$]
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("string C[int a]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(939417, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939417")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task ConditionalIndexer()
{
var markup = @"
public class P
{
public int this[int z]
{
get
{
return 0;
}
}
public void goo()
{
P p = null;
p?[$$]
}
}
";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("int P[int z]", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(32, "https://github.com/dotnet/roslyn/issues/32")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task NonIdentifierConditionalIndexer()
{
var expected = new[] { new SignatureHelpTestItem("char string[int index]") };
await TestAsync(
@"class C
{
void M()
{
""""?[$$ }
}", expected); // inline with a string literal
await TestAsync(
@"class C
{
void M()
{
""""?[/**/$$ }
}", expected); // inline with a string literal and multiline comment
await TestAsync(
@"class C
{
void M()
{
("""")?[$$ }
}", expected); // parenthesized expression
await TestAsync(
@"class C
{
void M()
{
new System.String(' ', 1)?[$$ }
}", expected); // new object expression
// more complicated parenthesized expression
await TestAsync(
@"class C
{
void M()
{
(null as System.Collections.Generic.List<int>)?[$$ }
}", new[] { new SignatureHelpTestItem("int System.Collections.Generic.List<int>[int index]") });
}
[WorkItem(1067933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067933")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InvokedWithNoToken()
{
var markup = @"
// goo[$$";
await TestAsync(markup);
}
[WorkItem(2482, "https://github.com/dotnet/roslyn/issues/2482")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task WhereExpressionLooksLikeArrayTypeSyntaxOfQualifiedName()
{
var markup = @"
class WithIndexer
{
public int this[int index] { get { return 0; } }
}
class TestClass
{
public WithIndexer Item { get; set; }
public void Method(TestClass tc)
{
// `tc.Item[]` parses as ArrayTypeSyntax with an ElementType of QualifiedNameSyntax
tc.Item[$$]
}
}
";
await TestAsync(markup, new[] { new SignatureHelpTestItem("int WithIndexer[int index]") }, usePreviousCharAsTrigger: true);
}
[WorkItem(20507, "https://github.com/dotnet/roslyn/issues/20507")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InConditionalIndexingFollowedByMemberAccess()
{
var markup = @"
class Indexable
{
public Indexable this[int x] { get => null; }
Indexable Count;
static void Main(string[] args)
{
Indexable x;
x?[$$].Count;
}
}
";
await TestAsync(markup, new[] { new SignatureHelpTestItem("Indexable Indexable[int x]") }, usePreviousCharAsTrigger: false);
}
[WorkItem(20507, "https://github.com/dotnet/roslyn/issues/20507")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InConditionalIndexingFollowedByConditionalAccess()
{
var markup = @"
class Indexable
{
public Indexable this[int x] { get => null; }
Indexable Count;
static void Main(string[] args)
{
Indexable x;
x?[$$].Count?.Count;
}
}
";
await TestAsync(markup, new[] { new SignatureHelpTestItem("Indexable Indexable[int x]") }, usePreviousCharAsTrigger: false);
}
}
}
}
| -1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Workspaces/Core/Portable/ExtensionOrderAttribute.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
namespace Microsoft.CodeAnalysis
{
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public sealed class ExtensionOrderAttribute : Attribute
{
public ExtensionOrderAttribute()
{
}
public string After { get; set; }
public string Before { get; set; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
namespace Microsoft.CodeAnalysis
{
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public sealed class ExtensionOrderAttribute : Attribute
{
public ExtensionOrderAttribute()
{
}
public string After { get; set; }
public string Before { get; set; }
}
}
| -1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Compilers/CSharp/Test/Emit/Emit/DesktopStrongNameProviderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.IO;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using static Roslyn.Test.Utilities.SigningTestHelpers;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class DesktopStrongNameProviderTests : CSharpTestBase
{
[WorkItem(13995, "https://github.com/dotnet/roslyn/issues/13995")]
[Fact]
public void RespectCustomTempPath()
{
var tempDir = Temp.CreateDirectory();
var provider = new DesktopStrongNameProvider(tempPath: tempDir.Path);
Assert.Equal(tempDir.Path, provider.FileSystem.GetTempPath());
}
[Fact]
public void RespectDefaultTempPath()
{
var provider = new DesktopStrongNameProvider(tempPath: null);
Assert.Equal(Path.GetTempPath(), provider.FileSystem.GetTempPath());
}
[Fact]
public void EmitWithCustomTempPath()
{
string src = @"
class C
{
public static void Main(string[] args) { }
}";
var tempDir = Temp.CreateDirectory();
var provider = new DesktopStrongNameProvider(ImmutableArray<string>.Empty, new VirtualizedStrongNameFileSystem(tempDir.Path));
var options = TestOptions
.DebugExe
.WithStrongNameProvider(provider)
.WithCryptoKeyFile(SigningTestHelpers.KeyPairFile);
var comp = CreateCompilation(src, options: options);
comp.VerifyEmitDiagnostics();
}
[Fact]
public void EmitWithDefaultTempPath()
{
string src = @"
class C
{
public static void Main(string[] args) { }
}";
var provider = new DesktopStrongNameProvider(ImmutableArray<string>.Empty, new VirtualizedStrongNameFileSystem());
var options = TestOptions
.DebugExe
.WithStrongNameProvider(provider)
.WithCryptoKeyFile(SigningTestHelpers.KeyPairFile);
var comp = CreateCompilation(src, options: options);
comp.VerifyEmitDiagnostics();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.IO;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using static Roslyn.Test.Utilities.SigningTestHelpers;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class DesktopStrongNameProviderTests : CSharpTestBase
{
[WorkItem(13995, "https://github.com/dotnet/roslyn/issues/13995")]
[Fact]
public void RespectCustomTempPath()
{
var tempDir = Temp.CreateDirectory();
var provider = new DesktopStrongNameProvider(tempPath: tempDir.Path);
Assert.Equal(tempDir.Path, provider.FileSystem.GetTempPath());
}
[Fact]
public void RespectDefaultTempPath()
{
var provider = new DesktopStrongNameProvider(tempPath: null);
Assert.Equal(Path.GetTempPath(), provider.FileSystem.GetTempPath());
}
[Fact]
public void EmitWithCustomTempPath()
{
string src = @"
class C
{
public static void Main(string[] args) { }
}";
var tempDir = Temp.CreateDirectory();
var provider = new DesktopStrongNameProvider(ImmutableArray<string>.Empty, new VirtualizedStrongNameFileSystem(tempDir.Path));
var options = TestOptions
.DebugExe
.WithStrongNameProvider(provider)
.WithCryptoKeyFile(SigningTestHelpers.KeyPairFile);
var comp = CreateCompilation(src, options: options);
comp.VerifyEmitDiagnostics();
}
[Fact]
public void EmitWithDefaultTempPath()
{
string src = @"
class C
{
public static void Main(string[] args) { }
}";
var provider = new DesktopStrongNameProvider(ImmutableArray<string>.Empty, new VirtualizedStrongNameFileSystem());
var options = TestOptions
.DebugExe
.WithStrongNameProvider(provider)
.WithCryptoKeyFile(SigningTestHelpers.KeyPairFile);
var comp = CreateCompilation(src, options: options);
comp.VerifyEmitDiagnostics();
}
}
}
| -1 |
dotnet/roslyn | 55,099 | EnC: Include added types in changed types of emit result | The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | tmat | 2021-07-23T23:32:01Z | 2021-07-26T21:02:38Z | 5e956729df67fdd6610253b05e1a232fe595af73 | ac374afe09c3d75acb41a3ae5d78d88ed1250cb6 | EnC: Include added types in changed types of emit result. The types are reported to the application via runtime event. The application needs to know about added types, not just updated ones.
\+ Simplify some EnC tests. | ./src/Analyzers/VisualBasic/CodeFixes/RemoveUnnecessaryParentheses/VisualBasicRemoveUnnecessaryParenthesesCodeFixProvider.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 System.Threading
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.RemoveUnnecessaryParentheses
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessaryParentheses
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.RemoveUnnecessaryParentheses), [Shared]>
Friend Class VisualBasicRemoveUnnecessaryParenthesesCodeFixProvider
Inherits AbstractRemoveUnnecessaryParenthesesCodeFixProvider(Of ParenthesizedExpressionSyntax)
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New()
End Sub
Protected Overrides Function CanRemoveParentheses(current As ParenthesizedExpressionSyntax, semanticModel As SemanticModel, cancellationtoken As CancellationToken) As Boolean
Return VisualBasicRemoveUnnecessaryParenthesesDiagnosticAnalyzer.CanRemoveParenthesesHelper(
current, semanticModel, precedence:=Nothing, clarifiesPrecedence:=Nothing)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports System.Diagnostics.CodeAnalysis
Imports System.Threading
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.RemoveUnnecessaryParentheses
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessaryParentheses
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.RemoveUnnecessaryParentheses), [Shared]>
Friend Class VisualBasicRemoveUnnecessaryParenthesesCodeFixProvider
Inherits AbstractRemoveUnnecessaryParenthesesCodeFixProvider(Of ParenthesizedExpressionSyntax)
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New()
End Sub
Protected Overrides Function CanRemoveParentheses(current As ParenthesizedExpressionSyntax, semanticModel As SemanticModel, cancellationtoken As CancellationToken) As Boolean
Return VisualBasicRemoveUnnecessaryParenthesesDiagnosticAnalyzer.CanRemoveParenthesesHelper(
current, semanticModel, precedence:=Nothing, clarifiesPrecedence:=Nothing)
End Function
End Class
End Namespace
| -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.