diff --git a/.vsts-ci.yml b/.vsts-ci.yml index 4eac359176e30..3970d6664b993 100644 --- a/.vsts-ci.yml +++ b/.vsts-ci.yml @@ -11,6 +11,8 @@ queue: variables: BuildPlatform: 'Any CPU' + InsertTargetBranchFullName: 'lab/d16.0stg472' + InsertTargetBranchShortName: 'd16.0stg472' steps: - task: NuGetCommand@2 inputs: @@ -22,6 +24,11 @@ steps: signType: real condition: and(succeeded(), in(variables['PB_SignType'], 'test', 'real')) +- task: ms-vseng.MicroBuildTasks.965C8DC6-1483-45C9-B384-5AC75DA1F1A4.MicroBuildOptProfPlugin@1 + inputs: + skipRunOptimize: true + displayName: 'Install OptProf Plugin' + - task: ms-vseng.MicroBuildTasks.32f78468-e895-4f47-962c-58a699361df8.MicroBuildSwixPlugin@1 inputs: feedSource: 'https://devdiv-test.pkgs.visualstudio.com/_packaging/MicroBuildToolset/nuget/v3/index.json' @@ -53,6 +60,65 @@ steps: filePath: 'build\scripts\publish-assets.ps1' condition: succeeded() +### BEGIN OPTPROF TASKS ### + +# Publish optprof configuration files +- task: ms-vscs-artifact.build-tasks.artifactDropTask-1.artifactDropTask@0 + inputs: + dropServiceURI: 'https://devdiv.artifacts.visualstudio.com' + buildNumber: 'ProfilingInputs/DevDiv/$(Build.Repository.Name)/$(Build.SourceBranchName)/$(Build.BuildId)' + sourcePath: '$(Build.SourcesDirectory)\Binaries\$(BuildConfiguration)\DevDivInsertionFiles\OptProf' + toLowerCase: false + usePat: false + displayName: 'OPTPROF - Publish to Artifact Services - ProfilingInputs' + condition: succeededOrFailed() + +# Created a exe that will install visual studio with this version +- task: PowerShell@2 + inputs: + filePath: build\scripts\setmanifestpaths.ps1 + failOnStderr: true + displayName: 'OPTPROF - Set VSTS variables for vsman files' + condition: succeededOrFailed() + +- task: ms-vseng.MicroBuildTasks.0e9d0d4d-71ec-4e4e-ae40-db9896f1ae74.MicroBuildBuildVSBootstrapper@1 + inputs: + vsMajorVersion: 16 + channelName: int.$(InsertTargetBranchShortName) + manifests: $(SetupManifests) + outputFolder: '$(Build.SourcesDirectory)\Binaries\VSSetup\$(BuildConfiguration)\Insertion' + displayName: 'OPTPROF - Build VS bootstrapper' + condition: succeededOrFailed() + +# Publish run settings +- task: PowerShell@2 + inputs: + filePath: build\scripts\createrunsettings.ps1 + arguments: -release + failOnStderr: true + displayName: 'OPTPROF - generate runsettings file' + condition: succeededOrFailed() + +# Publish bootstrapper info +- task: PublishBuildArtifacts@1 + inputs: + PathtoPublish: $(Build.StagingDirectory)\MicroBuild\Output + ArtifactName: MicroBuildOutputs + ArtifactType: Container + displayName: 'OPTPROF - Publish Artifact: MicroBuildOutputs' + condition: succeededOrFailed() + +# Publish scripts to get the branch of VS that this inserts into +- task: PublishBuildArtifacts@1 + inputs: + PathtoPublish: '$(Build.SourcesDirectory)\Binaries\$(BuildConfiguration)\DevDivInsertionFiles\BranchInfo' + ArtifactName: BranchInfo + ArtifactType: Container + displayName: 'OPTPROF - Publish Artifact: BranchInfo' + condition: succeededOrFailed() + +### END OPTPROF TASKS ### + - task: PublishBuildArtifacts@1 displayName: Publish Logs inputs: diff --git a/Roslyn.sln b/Roslyn.sln index e95bd88166528..f34b9afc6e195 100644 --- a/Roslyn.sln +++ b/Roslyn.sln @@ -367,10 +367,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Pool EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Workspaces.MSBuild.UnitTests", "src\Workspaces\MSBuildTest\Microsoft.CodeAnalysis.Workspaces.MSBuild.UnitTests.csproj", "{037F06F0-3BE8-42D0-801E-2F74FC380AB8}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DevDivPackagesDebugger_DoNotUse", "src\Setup\DevDivPackages\Debugger\DevDivPackagesDebugger_DoNotUse.csproj", "{18BDB5D5-340B-4834-B4FC-0327729A4A26}" -EndProject -Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "Roslyn.BuildDevDivInsertionFiles", "src\Setup\DevDivInsertionFiles\Roslyn.BuildDevDivInsertionFiles.vbproj", "{5FE910A9-E7C9-40E1-AAF1-6C6C7DD61B67}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "InteractiveHost64", "src\Interactive\Host\InteractiveHost64.csproj", "{2F11618A-9251-4609-B3D5-CE4D2B3D3E49}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.VisualStudio.IntegrationTest.IntegrationService", "src\VisualStudio\IntegrationTest\IntegrationService\Microsoft.VisualStudio.IntegrationTest.IntegrationService.csproj", "{764D2C19-0187-4837-A2A3-96DDC6EF4CE2}" @@ -397,14 +393,18 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VS.Tools.Roslyn.Package", " EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Package", "src\NuGet\Microsoft.CodeAnalysis.Package.csproj", "{B9843F65-262E-4F40-A0BC-2CBEF7563A44}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PortableFacades.Setup", "src\Setup\DevDivVsix\PortableFacades\PortableFacades.Setup.csproj", "{952808C5-799A-4CAA-964C-2AA78458CEC7}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Compilers.Setup", "src\Setup\DevDivVsix\CompilersPackage\Microsoft.CodeAnalysis.Compilers.Setup.csproj", "{03607817-6800-40B6-BEAA-D6F437CD62B7}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "dotnet-format", "src\Tools\dotnet-format\dotnet-format.csproj", "{4A9B5423-11BF-4E1D-B231-C9A2FDD78EC4}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Installer.Package", "src\Setup\Installer\Installer.Package.csproj", "{6A68FDF9-24B3-4CB6-A808-96BF50D1BCE5}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis.Workspaces.Desktop.UnitTests", "src\Workspaces\DesktopTest\Microsoft.CodeAnalysis.Workspaces.Desktop.UnitTests.csproj", "{23405307-7EFF-4774-8B11-8F5885439761}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Insertion", "Insertion", "{AFA5F921-0650-45E8-B293-51A0BB89DEA0}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DevDivInsertionFiles", "src\Setup\DevDivInsertionFiles\DevDivInsertionFiles.csproj", "{6362616E-6A47-48F0-9EE0-27800B306ACB}" +EndProject Global GlobalSection(SharedMSBuildProjectFiles) = preSolution src\Compilers\VisualBasic\BasicAnalyzerDriver\BasicAnalyzerDriver.projitems*{2523d0e6-df32-4a3e-8ae0-a19bffae2ef6}*SharedItemsImports = 4 @@ -1006,14 +1006,6 @@ Global {037F06F0-3BE8-42D0-801E-2F74FC380AB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {037F06F0-3BE8-42D0-801E-2F74FC380AB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {037F06F0-3BE8-42D0-801E-2F74FC380AB8}.Release|Any CPU.Build.0 = Release|Any CPU - {18BDB5D5-340B-4834-B4FC-0327729A4A26}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {18BDB5D5-340B-4834-B4FC-0327729A4A26}.Debug|Any CPU.Build.0 = Debug|Any CPU - {18BDB5D5-340B-4834-B4FC-0327729A4A26}.Release|Any CPU.ActiveCfg = Release|Any CPU - {18BDB5D5-340B-4834-B4FC-0327729A4A26}.Release|Any CPU.Build.0 = Release|Any CPU - {5FE910A9-E7C9-40E1-AAF1-6C6C7DD61B67}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5FE910A9-E7C9-40E1-AAF1-6C6C7DD61B67}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5FE910A9-E7C9-40E1-AAF1-6C6C7DD61B67}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5FE910A9-E7C9-40E1-AAF1-6C6C7DD61B67}.Release|Any CPU.Build.0 = Release|Any CPU {2F11618A-9251-4609-B3D5-CE4D2B3D3E49}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2F11618A-9251-4609-B3D5-CE4D2B3D3E49}.Debug|Any CPU.Build.0 = Debug|Any CPU {2F11618A-9251-4609-B3D5-CE4D2B3D3E49}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -1058,10 +1050,6 @@ Global {B9843F65-262E-4F40-A0BC-2CBEF7563A44}.Debug|Any CPU.Build.0 = Debug|Any CPU {B9843F65-262E-4F40-A0BC-2CBEF7563A44}.Release|Any CPU.ActiveCfg = Release|Any CPU {B9843F65-262E-4F40-A0BC-2CBEF7563A44}.Release|Any CPU.Build.0 = Release|Any CPU - {952808C5-799A-4CAA-964C-2AA78458CEC7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {952808C5-799A-4CAA-964C-2AA78458CEC7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {952808C5-799A-4CAA-964C-2AA78458CEC7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {952808C5-799A-4CAA-964C-2AA78458CEC7}.Release|Any CPU.Build.0 = Release|Any CPU {03607817-6800-40B6-BEAA-D6F437CD62B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {03607817-6800-40B6-BEAA-D6F437CD62B7}.Debug|Any CPU.Build.0 = Debug|Any CPU {03607817-6800-40B6-BEAA-D6F437CD62B7}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -1074,6 +1062,14 @@ Global {6A68FDF9-24B3-4CB6-A808-96BF50D1BCE5}.Debug|Any CPU.Build.0 = Debug|Any CPU {6A68FDF9-24B3-4CB6-A808-96BF50D1BCE5}.Release|Any CPU.ActiveCfg = Release|Any CPU {6A68FDF9-24B3-4CB6-A808-96BF50D1BCE5}.Release|Any CPU.Build.0 = Release|Any CPU + {23405307-7EFF-4774-8B11-8F5885439761}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {23405307-7EFF-4774-8B11-8F5885439761}.Debug|Any CPU.Build.0 = Debug|Any CPU + {23405307-7EFF-4774-8B11-8F5885439761}.Release|Any CPU.ActiveCfg = Release|Any CPU + {23405307-7EFF-4774-8B11-8F5885439761}.Release|Any CPU.Build.0 = Release|Any CPU + {6362616E-6A47-48F0-9EE0-27800B306ACB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6362616E-6A47-48F0-9EE0-27800B306ACB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6362616E-6A47-48F0-9EE0-27800B306ACB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6362616E-6A47-48F0-9EE0-27800B306ACB}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -1245,8 +1241,6 @@ Global {FC2AE90B-2E4B-4045-9FDD-73D4F5ED6C89} = {C2D1346B-9665-4150-B644-075CF1636BAA} {49E7C367-181B-499C-AC2E-8E17C81418D6} = {C2D1346B-9665-4150-B644-075CF1636BAA} {037F06F0-3BE8-42D0-801E-2F74FC380AB8} = {55A62CFA-1155-46F1-ADF3-BEEE51B58AB5} - {18BDB5D5-340B-4834-B4FC-0327729A4A26} = {C2D1346B-9665-4150-B644-075CF1636BAA} - {5FE910A9-E7C9-40E1-AAF1-6C6C7DD61B67} = {FD0FAF5F-1DED-485C-99FA-84B97F3A8EEC} {2F11618A-9251-4609-B3D5-CE4D2B3D3E49} = {5CA5F70E-0FDB-467B-B22C-3CD5994F0087} {764D2C19-0187-4837-A2A3-96DDC6EF4CE2} = {CC126D03-7EAC-493F-B187-DCDEE1EF6A70} {9860FCF7-3111-4C12-A16F-ACEBA42D930F} = {FD0FAF5F-1DED-485C-99FA-84B97F3A8EEC} @@ -1260,10 +1254,12 @@ Global {0EB22BD1-B8B1-417D-8276-F475C2E190FF} = {BE25E872-1667-4649-9D19-96B83E75A44E} {3636D3E2-E3EF-4815-B020-819F382204CD} = {BE25E872-1667-4649-9D19-96B83E75A44E} {B9843F65-262E-4F40-A0BC-2CBEF7563A44} = {C52D8057-43AF-40E6-A01B-6CDBB7301985} - {952808C5-799A-4CAA-964C-2AA78458CEC7} = {BE25E872-1667-4649-9D19-96B83E75A44E} {03607817-6800-40B6-BEAA-D6F437CD62B7} = {BE25E872-1667-4649-9D19-96B83E75A44E} {4A9B5423-11BF-4E1D-B231-C9A2FDD78EC4} = {FD0FAF5F-1DED-485C-99FA-84B97F3A8EEC} {6A68FDF9-24B3-4CB6-A808-96BF50D1BCE5} = {BE25E872-1667-4649-9D19-96B83E75A44E} + {23405307-7EFF-4774-8B11-8F5885439761} = {55A62CFA-1155-46F1-ADF3-BEEE51B58AB5} + {AFA5F921-0650-45E8-B293-51A0BB89DEA0} = {8DBA5174-B0AA-4561-82B1-A46607697753} + {6362616E-6A47-48F0-9EE0-27800B306ACB} = {AFA5F921-0650-45E8-B293-51A0BB89DEA0} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {604E6B91-7BC0-4126-AE07-D4D2FEFC3D29} diff --git a/build/Targets/GenerateCompilerExecutableBindingRedirects.targets b/build/Targets/GenerateCompilerExecutableBindingRedirects.targets index c53025d6cadde..2d1972cf4c583 100644 --- a/build/Targets/GenerateCompilerExecutableBindingRedirects.targets +++ b/build/Targets/GenerateCompilerExecutableBindingRedirects.targets @@ -30,44 +30,17 @@ 1.2.3.0 - - 4.0.1.0 - - - 4.0.1.0 - - - 4.0.3.0 - - - 4.1.2.0 - - - 4.0.2.0 - - - 4.0.2.0 - - - 4.0.1.0 - 1.4.3.0 - - 4.0.1.0 - - - 4.0.1.0 - - - 4.0.1.0 + + 4.0.4.0 - - 4.0.1.0 + + 4.1.1.0 - - 4.1.0.0 + + 4.2.0.0 diff --git a/build/Targets/Imports.targets b/build/Targets/Imports.targets index ed70d10b6ab43..542b7c9158ed9 100644 --- a/build/Targets/Imports.targets +++ b/build/Targets/Imports.targets @@ -15,7 +15,7 @@ - false + false $(ArtifactsConfigurationDir)DevDivPackages\Roslyn\ diff --git a/build/Targets/Packages.props b/build/Targets/Packages.props index 70ef45e98fba7..502f31d1efae8 100644 --- a/build/Targets/Packages.props +++ b/build/Targets/Packages.props @@ -59,14 +59,14 @@ 0.8.31-beta 1.0.35 1.3.0 - 1.1.0-beta1-63011-01 - 1.1.0-beta1-63011-01 + 1.1.0-beta1-63314-01 + 1.1.0-beta1-63314-01 1.7.0 1.5.0 - 4.7.2-alpha-00001 + 4.7.2-alpha-00001 1.0.27-prerelease-01811-02 2.1.0-prerelease-02419-02 - 1.0.0-beta.18455.10 + 1.0.0-beta.18519.9 2.1.1 2.1.1 3.13.8 @@ -74,6 +74,8 @@ 14.3.25407-alpha 1.0.0-beta1-63011-01 8.0.0.0-alpha + + 15.9.0-dev2 2.9.0-beta7-63018-03 $(RoslynDiagnosticsNugetPackageVersion) 2.0.0 @@ -162,94 +164,34 @@ 4.0.0-rc-2048 1.1.0-beta1-62506-02 105.2.3 - 2.11.0-beta1-63312-06 + 2.11.0-beta3.20181025.2 $(RoslynDiagnosticsNugetPackageVersion) 0.2.4-beta 1.0.0-beta2-63222-01 1.0.0-beta2-63222-01 0.5.0-alpha - 1.0.0-beta3.18523.2 + 1.0.0-beta3.18526.1 0.1.3 - 1.0.0-beta3.18525.2 + 1.0.0-beta3.18526.1 + 1.0.0-beta3.18524.2 + 1.0.0-beta3.18524.2 4.3.0 0.0.4 1.3.23 - 4.3.0 - 4.3.0 - 4.3.0 1.5.0 0.1.0-alpha-63227-01 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 4.5.0 - 4.3.0 - 4.3.0 - 5.0.0 - 4.3.0 - 4.3.0 - 4.3.0 4.3.0 - 4.3.0 4.3.0 - 4.3.0 - 4.3.0 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.3 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 1.6.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 + 4.5.0 + 4.5.0 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 4.5.24 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 - 4.3.0 + + 4.5.0 + 4.5.0 1.1.2 1.1.0.14 15.8.68-develop-g109a00ff diff --git a/build/Targets/RepoToolset/OptimizationData.targets b/build/Targets/RepoToolset/OptimizationData.targets index 8316e4122f362..f480da9eb22fa 100644 --- a/build/Targets/RepoToolset/OptimizationData.targets +++ b/build/Targets/RepoToolset/OptimizationData.targets @@ -1,31 +1,31 @@ - + $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - - + + + + <_PreviousOptimizedFile>$([System.IO.Path]::Combine($(IbcOptimizationDataDir), '$(TargetName).pgo')) $(IntermediateOutputPath)$(TargetFileName).pcbm - $(NuGetPackageRoot)\RoslynDependencies.OptimizationData\$(RoslynDependenciesOptimizationDataVersion)\content\OptimizationData - $([System.IO.Path]::GetFullPath('$(OptimizationDataFolderPath)\$(TargetName).pgo')) - $(NuGetPackageRoot)\Microsoft.DotNet.IBCMerge\$(MicrosoftDotNetIBCMerge)\lib\net45\ibcmerge.exe - + + @@ -36,27 +36,55 @@ - + + + + + <_IbcArgs>-q -f -partialNGEN -minify -delete -mo "%(OptimizeAssembly.Identity)" -incremental "%(OptimizeAssembly.PreviousOptimizedFile)" + + + - A local build emulating an official build can pass /p:SkipApplyOptimizations=true to avoid this error. - --> - + DependsOnTargets="_CalculateIbcArgs" + Condition="'@(OptimizeAssembly)' != '' and '$(Configuration)' == 'Release' and '$(ContinuousIntegrationBuild)' == 'true'"> + + + <_IbcMergePath>$(NuGetPackageRoot)microsoft.dotnet.ibcmerge\$(MicrosoftDotNetIBCMergeVersion)\lib\net45\ibcmerge.exe - + <_RunIbcMerge>false + <_RunIbcMerge Condition="'$(OfficialBuild)' == 'true' or Exists('$(_IbcMergePath)')">true + - + + + Condition="'$(_RunIbcMerge)' == 'true'"> + + + + \ No newline at end of file diff --git a/build/Targets/RepoToolset/Sign.proj b/build/Targets/RepoToolset/Sign.proj index 42683eeb48d1b..79dfa28dc6467 100644 --- a/build/Targets/RepoToolset/Sign.proj +++ b/build/Targets/RepoToolset/Sign.proj @@ -5,13 +5,23 @@ + + + + - + - - + + + + - - - + + @@ -60,15 +69,16 @@ - + diff --git a/build/Targets/Roslyn.Toolsets.Xunit.targets b/build/Targets/Roslyn.Toolsets.Xunit.targets index 5d58888befc44..660e23d069881 100644 --- a/build/Targets/Roslyn.Toolsets.Xunit.targets +++ b/build/Targets/Roslyn.Toolsets.Xunit.targets @@ -11,6 +11,9 @@ + + + - - - - + + + + + + + + + + + + + + + + diff --git a/build/ToolsetPackages/InternalToolset.csproj b/build/ToolsetPackages/InternalToolset.csproj index baa1f68cdd1e6..8f50d4f74073a 100644 --- a/build/ToolsetPackages/InternalToolset.csproj +++ b/build/ToolsetPackages/InternalToolset.csproj @@ -2,9 +2,9 @@ - net46 + net472 - + diff --git a/build/ToolsetPackages/RoslynToolset.csproj b/build/ToolsetPackages/RoslynToolset.csproj index f754ace6d13f0..a723d48f69310 100644 --- a/build/ToolsetPackages/RoslynToolset.csproj +++ b/build/ToolsetPackages/RoslynToolset.csproj @@ -2,7 +2,7 @@ - net46;netcoreapp2.1 + net472;netcoreapp2.1 @@ -14,12 +14,11 @@ - - + @@ -31,6 +30,8 @@ + + diff --git a/build/config/optprof.json b/build/config/optprof.json new file mode 100644 index 0000000000000..90ad3bf17922e --- /dev/null +++ b/build/config/optprof.json @@ -0,0 +1,214 @@ +{ + "products": [ + { + "name": "Roslyn.VisualStudio.Setup.vsix", + "tests": [ + { + "container": "DDRIT.RPS.CSharp", + "testCases": [ + "DDRIT.RPS.CSharp.CSharpTest.EditingAndDesigner" + ] + }, + { + "container": "VSPE", + "testCases": [ + "VSPE.OptProfTests.vs_perf_designtime_ide_searchtest", + "VSPE.OptProfTests.vs_perf_designtime_editor_intellisense_globalcompletionlist_cs", + "VSPE.OptProfTests.vs_asl_cs_scenario", + "VSPE.OptProfTests.vs_ddbvtqa_vbwi", + "VSPE.OptProfTests.vs_asl_vb_scenario", + "VSPE.OptProfTests.vs_env_solution_createnewproject_vb_winformsapp" + ] + } + ] + }, + { + "name": "ExpressionEvaluatorPackage.vsix", + "tests": [ + { + "container": "DDRIT.RPS.CSharp", + "testCases": [ + "DDRIT.RPS.CSharp.CSharpTest.BuildAndDebugging" + ] + } + ] + }, + { + "name": "Microsoft.CodeAnalysis.Compilers.vsix", + "tests": [ + { + "container": "DDRIT.RPS.CSharp", + "testCases": [ + "DDRIT.RPS.CSharp.CSharpTest.BuildAndDebugging" + ] + } + ] + }, + { + "name": "Roslyn.VisualStudio.InteractiveComponents.vsix", + "tests": [ + { + "container": "DDRIT.RPS.CSharp", + "testCases": [ + "DDRIT.RPS.CSharp.CSharpTest.EditingAndDesigner" + ] + } + ] + } + ], + "assemblies" : [ + { + "assembly": "System.Collections.Immutable.dll", + "instrumentationArguments": [ + { + "relativeInstallationFolder": "Common7/IDE/PrivateAssemblies", + "instrumentationExecutable" : "Common7/IDE/vsn.exe" + } + ], + "tests": [ + { + "container": "DDRIT.RPS.CSharp", + "testCases": [ + "DDRIT.RPS.CSharp.CSharpTest.BuildAndDebugging" + ] + } + ] + }, + { + "assembly": "System.Reflection.Metadata.dll", + "instrumentationArguments": [ + { + "relativeInstallationFolder": "Common7/IDE/PrivateAssemblies", + "instrumentationExecutable" : "Common7/IDE/vsn.exe" + } + ], + "tests": [ + { + "container": "DDRIT.RPS.CSharp", + "testCases": [ + "DDRIT.RPS.CSharp.CSharpTest.BuildAndDebugging" + ] + } + ] + }, + { + "assembly": "Microsoft.Build.Conversion.Core.dll", + "instrumentationArguments": [ + { + "relativeInstallationFolder": "MSBuild/15.0/Bin", + "instrumentationExecutable" : "Common7/IDE/vsn.exe" + } + ], + "tests": [ + { + "container": "DDRIT.RPS.CSharp", + "testCases": [ + "DDRIT.RPS.CSharp.CSharpTest.BuildAndDebugging" + ] + } + ] + }, + { + "assembly": "Microsoft.Build.dll", + "instrumentationArguments": [ + { + "relativeInstallationFolder": "MSBuild/15.0/Bin", + "instrumentationExecutable" : "Common7/IDE/vsn.exe" + } + ], + "tests": [ + { + "container": "DDRIT.RPS.CSharp", + "testCases": [ + "DDRIT.RPS.CSharp.CSharpTest.BuildAndDebugging" + ] + } + ] + }, + { + "assembly": "Microsoft.Build.Engine.dll", + "instrumentationArguments": [ + { + "relativeInstallationFolder": "MSBuild/15.0/Bin", + "instrumentationExecutable" : "Common7/IDE/vsn.exe" + } + ], + "tests": [ + { + "container": "DDRIT.RPS.CSharp", + "testCases": [ + "DDRIT.RPS.CSharp.CSharpTest.BuildAndDebugging" + ] + } + ] + }, + { + "assembly": "Microsoft.Build.Framework.dll", + "instrumentationArguments": [ + { + "relativeInstallationFolder": "MSBuild/15.0/Bin", + "instrumentationExecutable" : "Common7/IDE/vsn.exe" + } + ], + "tests": [ + { + "container": "DDRIT.RPS.CSharp", + "testCases": [ + "DDRIT.RPS.CSharp.CSharpTest.BuildAndDebugging" + ] + } + ] + }, + { + "assembly": "Microsoft.Build.Tasks.Core.dll", + "instrumentationArguments": [ + { + "relativeInstallationFolder": "MSBuild/15.0/Bin", + "instrumentationExecutable" : "Common7/IDE/vsn.exe" + } + ], + "tests": [ + { + "container": "DDRIT.RPS.CSharp", + "testCases": [ + "DDRIT.RPS.CSharp.CSharpTest.BuildAndDebugging" + ] + } + ] + }, + { + "assembly": "Microsoft.Build.Utilities.Core.dll", + "instrumentationArguments": [ + { + "relativeInstallationFolder": "MSBuild/15.0/Bin", + "instrumentationExecutable" : "Common7/IDE/vsn.exe" + } + ], + "tests": [ + { + "container": "DDRIT.RPS.CSharp", + "testCases": [ + "DDRIT.RPS.CSharp.CSharpTest.BuildAndDebugging" + ] + } + ] + }, + { + "assembly": "System.Threading.Tasks.Dataflow.dll", + "instrumentationArguments": [ + { + "relativeInstallationFolder": "MSBuild/15.0/Bin", + "instrumentationExecutable" : "Common7/IDE/vsn.exe" + } + ], + "tests": [ + { + "container": "DDRIT.RPS.CSharp", + "testCases": [ + "DDRIT.RPS.CSharp.CSharpTest.BuildAndDebugging" + ] + } + ] + } + ] +} \ No newline at end of file diff --git a/build/scripts/build.ps1 b/build/scripts/build.ps1 index 27892d6a7b62b..afd8ac3780195 100644 --- a/build/scripts/build.ps1 +++ b/build/scripts/build.ps1 @@ -251,7 +251,7 @@ function Build-Artifacts() { } if ($build -and $pack -and (-not $buildCoreClr)) { - Build-InsertionItems + Build-OptProfData } if ($cibuild) { @@ -260,17 +260,23 @@ function Build-Artifacts() { } } -function Build-InsertionItems() { - - $setupDir = Join-Path $RepoRoot "src\Setup" - Push-Location $setupDir - try { - Write-Host "Building VS Insertion artifacts" - Exec-Console (Join-Path $configDir "Exes\Roslyn.BuildDevDivInsertionFiles\Roslyn.BuildDevDivInsertionFiles.exe") "$configDir $(Get-PackagesDir)" - } - finally { - Pop-Location - } +function Build-OptProfData() { + $optProfToolDir = Get-PackageDir "RoslynTools.OptProf" + $optProfToolExe = Join-Path $optProfToolDir "tools\roslyn.optprof.exe" + $configFile = Join-Path $RepoRoot "build\config\optprof.json" + $insertionFolder = Join-Path $vsSetupDir "Insertion" + $outputFolder = Join-Path $configDir "DevDivInsertionFiles\OptProf" + Write-Host "Generating optprof data using '$configFile' into '$outputFolder'" + $optProfArgs = "--configFile $configFile --insertionFolder $insertionFolder --outputFolder $outputFolder" + Exec-Console $optProfToolExe $optProfArgs + + # Write Out Branch we are inserting into + $vsBranchFolder = Join-Path $configDir "DevDivInsertionFiles\BranchInfo" + New-Item -ItemType Directory -Force -Path $vsBranchFolder + $vsBranchText = Join-Path $vsBranchFolder "vsbranch.txt" + # InsertTargetBranchFullName is defined in .vsts-ci.yml + $vsBranch = $Env:InsertTargetBranchFullName + $vsBranch >> $vsBranchText } function Build-CheckLocStatus() { @@ -350,7 +356,7 @@ function Test-XUnit() { $unitDir = Join-Path $configDir "UnitTests" $runTests = Join-Path $configDir "Exes\RunTests\RunTests.exe" - $xunitDir = Join-Path (Get-PackageDir "xunit.runner.console") "tools\net452" + $xunitDir = Join-Path (Get-PackageDir "xunit.runner.console") "tools\net472" $args = "$xunitDir" $args += " -logpath:$logsDir" $args += " -nocache" diff --git a/build/scripts/createrunsettings.ps1 b/build/scripts/createrunsettings.ps1 new file mode 100644 index 0000000000000..8ae3a10994988 --- /dev/null +++ b/build/scripts/createrunsettings.ps1 @@ -0,0 +1,35 @@ +[CmdletBinding(PositionalBinding=$false)] +param ( + [switch]$release = $false) + +Set-StrictMode -version 2.0 +$ErrorActionPreference = "Stop" + +try { + . (Join-Path $PSScriptRoot "build-utils.ps1") + Push-Location $repoDir + + Write-Host "Repo Dir $repoDir" + Write-Host "Binaries Dir $binariesDir" + + $buildConfiguration = if ($release) { "Release" } else { "Debug" } + $configDir = Join-Path (Join-Path $binariesDir "VSSetup") $buildConfiguration + + $optProfToolDir = Get-PackageDir "Roslyn.OptProf.RunSettings.Generator" + $optProfToolExe = Join-Path $optProfToolDir "tools\roslyn.optprof.runsettings.generator.exe" + $configFile = Join-Path $repoDir "build\config\optprof.json" + $outputFolder = Join-Path $configDir "Insertion\RunSettings" + $optProfArgs = "--configFile $configFile --outputFolder $outputFolder --buildNumber 28218.3001 " + + Exec-Console $optProfToolExe $optProfArgs + exit 0 +} +catch { + Write-Host $_ + Write-Host $_.Exception + Write-Host $_.ScriptStackTrace + exit 1 +} +finally { + Pop-Location +} \ No newline at end of file diff --git a/build/scripts/findibc.ps1 b/build/scripts/findibc.ps1 new file mode 100644 index 0000000000000..f962065278636 --- /dev/null +++ b/build/scripts/findibc.ps1 @@ -0,0 +1,39 @@ +[CmdletBinding(PositionalBinding=$false)] +param ( + [string]$intermediateAssembly, + [string]$ibcRootFolder) + +try { + $assemblyName = [System.IO.Path]::GetFileName($intermediateAssembly) + $fullPath = [System.IO.Path]::GetFullPath($ibcRootFolder) + if(![System.IO.Directory]::Exists($fullPath)){ + # There is no product data directory return + return "" + } + $root = (New-Object -TypeName System.IO.DirectoryInfo -ArgumentList $fullPath) + $dllEntry = [System.Linq.Enumerable]::SingleOrDefault($root.EnumerateFiles($assemblyName,[System.IO.SearchOption]::AllDirectories)) + if (!$dllEntry) + { + return ""; + } + + $ibcFileInfos = $dllEntry.Directory.EnumerateFiles("*.ibc") + $strings = (New-Object "System.Collections.Generic.List[System.String]") + foreach ($ibcFileInfo in $ibcFileInfos) + { + $name = $ibcFileInfo.FullName + $strings.Add($name) + } + $ibcFiles = $strings -join ' ' + + return $ibcFiles +} +catch { + Write-Host $_ + Write-Host $_.Exception + Write-Host $_.ScriptStackTrace + exit 1 +} +finally { + Pop-Location +} \ No newline at end of file diff --git a/build/scripts/setmanifestpaths.ps1 b/build/scripts/setmanifestpaths.ps1 new file mode 100644 index 0000000000000..38f5aa463225e --- /dev/null +++ b/build/scripts/setmanifestpaths.ps1 @@ -0,0 +1,15 @@ +# Take care to return nothing if we don't yet have any vsman files +# as will occur at the start of the build. +# This will allow us to set it after the build when called again. + +$vsmanpath = "Binaries/VSSetup/$Env:BuildConfiguration/Insertion" +if (Test-Path $vsmanpath) { + $SetupManifests = [string]::Join(',', (Get-ChildItem "Binaries/VSSetup/$Env:BuildConfiguration/Insertion/*.vsman")) + Write-Host "Using the following manifests '$SetupManifests'" + Write-Host "SetupManifests=$SetupManifests" + Write-Host "##vso[task.setvariable variable=SetupManifests;]$SetupManifests" + Set-Item -Path "env:SetupManifests" -Value $SetupManifests +} +else { + Write-Host "Unable to find manifest files" +} \ No newline at end of file diff --git a/build/scripts/tests.sh b/build/scripts/tests.sh index ce8505360f63a..77210ba684038 100755 --- a/build/scripts/tests.sh +++ b/build/scripts/tests.sh @@ -43,7 +43,7 @@ if [[ "${runtime}" == "dotnet" ]]; then ) xunit_console="${nuget_dir}"/xunit.runner.console/"${xunit_console_version}"/tools/netcoreapp2.0/xunit.console.dll elif [[ "${runtime}" =~ ^(mono|mono-debug)$ ]]; then - file_list=( "${unittest_dir}"/*/net46/*.UnitTests.dll ) + file_list=( "${unittest_dir}"/*/net472/*.UnitTests.dll ) file_skiplist=( # Omitted because we appear to be missing things necessary to compile vb.net. # See https://github.com/mono/mono/issues/10679 diff --git a/src/Compilers/CSharp/Portable/Binder/Binder.ValueChecks.cs b/src/Compilers/CSharp/Portable/Binder/Binder.ValueChecks.cs index 7cc11f35bd6e5..708d8b90b67a7 100644 --- a/src/Compilers/CSharp/Portable/Binder/Binder.ValueChecks.cs +++ b/src/Compilers/CSharp/Portable/Binder/Binder.ValueChecks.cs @@ -411,7 +411,7 @@ internal bool CheckValueKind(SyntaxNode node, BoundExpression expr, BindValueKin } var receiver = ((BoundPointerElementAccess)expr).Expression; - if (receiver is BoundFieldAccess fieldAccess && fieldAccess.FieldSymbol.IsFixed) + if (receiver is BoundFieldAccess fieldAccess && fieldAccess.FieldSymbol.IsFixedSizeBuffer) { return CheckValueKind(node, fieldAccess.ReceiverOpt, valueKind, checkingReceiver: true, diagnostics); } @@ -692,7 +692,7 @@ private bool CheckFieldValueKind(SyntaxNode node, BoundFieldAccess fieldAccess, } } - if (fieldSymbol.IsFixed) + if (fieldSymbol.IsFixedSizeBuffer) { Error(diagnostics, GetStandardLvalueError(valueKind), node); return false; diff --git a/src/Compilers/CSharp/Portable/Binder/Binder_Constraints.cs b/src/Compilers/CSharp/Portable/Binder/Binder_Constraints.cs index 70847b2a115d5..de97086ec5b39 100644 --- a/src/Compilers/CSharp/Portable/Binder/Binder_Constraints.cs +++ b/src/Compilers/CSharp/Portable/Binder/Binder_Constraints.cs @@ -222,7 +222,7 @@ internal static bool IsValidConstraint( } // Ignore nullability when comparing constraints. - if (constraintTypes.Contains(c => type.Equals(c, TypeCompareKind.ConsiderEverything))) + if (constraintTypes.Contains(c => type.Equals(c, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes))) { // "Duplicate constraint '{0}' for type parameter '{1}'" Error(diagnostics, ErrorCode.ERR_DuplicateBound, syntax, type.TypeSymbol.SetUnknownNullabilityForReferenceTypes(), typeParameterName); diff --git a/src/Compilers/CSharp/Portable/Binder/Binder_Conversions.cs b/src/Compilers/CSharp/Portable/Binder/Binder_Conversions.cs index b0ea9a8725f18..35a1e30d33436 100644 --- a/src/Compilers/CSharp/Portable/Binder/Binder_Conversions.cs +++ b/src/Compilers/CSharp/Portable/Binder/Binder_Conversions.cs @@ -80,7 +80,7 @@ protected BoundExpression CreateConversion( // We need to preserve any conversion that changes the type (even identity conversions, like object->dynamic), // or that was explicitly written in code (so that GetSemanticInfo can find the syntax in the bound tree). - if (!isCast && source.Type == destination) + if (!isCast && source.Type.Equals(destination, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { return source; } diff --git a/src/Compilers/CSharp/Portable/Binder/Binder_Expressions.cs b/src/Compilers/CSharp/Portable/Binder/Binder_Expressions.cs index ad59105515904..534ce82d634bc 100644 --- a/src/Compilers/CSharp/Portable/Binder/Binder_Expressions.cs +++ b/src/Compilers/CSharp/Portable/Binder/Binder_Expressions.cs @@ -6329,7 +6329,7 @@ protected BoundExpression BindFieldAccess( hasError = this.CheckInstanceOrStatic(node, receiver, fieldSymbol, ref resultKind, diagnostics); } - if (!hasError && fieldSymbol.IsFixed && !IsInsideNameof) + if (!hasError && fieldSymbol.IsFixedSizeBuffer && !IsInsideNameof) { // SPEC: In a member access of the form E.I, if E is of a struct type and a member lookup of I in // that struct type identifies a fixed size member, then E.I is evaluated an classified as follows: diff --git a/src/Compilers/CSharp/Portable/Binder/Binder_Invocation.cs b/src/Compilers/CSharp/Portable/Binder/Binder_Invocation.cs index 64794fe61442d..8d4f33f35803f 100644 --- a/src/Compilers/CSharp/Portable/Binder/Binder_Invocation.cs +++ b/src/Compilers/CSharp/Portable/Binder/Binder_Invocation.cs @@ -1388,7 +1388,7 @@ private ImmutableArray BuildArgumentsForErrorRecovery(AnalyzedA { candidateType = parameterType; } - else if (!candidateType.Equals(parameterType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)) + else if (!candidateType.Equals(parameterType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { // type mismatch candidateType = null; diff --git a/src/Compilers/CSharp/Portable/Binder/Binder_Operators.cs b/src/Compilers/CSharp/Portable/Binder/Binder_Operators.cs index 3f674b83e0ec9..fac79146f0a33 100644 --- a/src/Compilers/CSharp/Portable/Binder/Binder_Operators.cs +++ b/src/Compilers/CSharp/Portable/Binder/Binder_Operators.cs @@ -2263,7 +2263,7 @@ internal bool IsMoveableVariable(BoundExpression expr, out Symbol accessedLocalO // is not a fixed size buffer expression, or if the expression is a fixed size buffer // member_access of the form E.I and E is a fixed variable BoundExpression underlyingExpr = ((BoundPointerElementAccess)expr).Expression; - if (underlyingExpr is BoundFieldAccess fieldAccess && fieldAccess.FieldSymbol.IsFixed) + if (underlyingExpr is BoundFieldAccess fieldAccess && fieldAccess.FieldSymbol.IsFixedSizeBuffer) { expr = fieldAccess.ReceiverOpt; continue; diff --git a/src/Compilers/CSharp/Portable/Binder/Binder_Statements.cs b/src/Compilers/CSharp/Portable/Binder/Binder_Statements.cs index 5c4e2aedb3eb5..4a8ff5348bebf 100644 --- a/src/Compilers/CSharp/Portable/Binder/Binder_Statements.cs +++ b/src/Compilers/CSharp/Portable/Binder/Binder_Statements.cs @@ -1105,7 +1105,7 @@ private bool IsValidFixedVariableInitializer(TypeSymbol declType, SourceLocalSym case BoundKind.FieldAccess: var fa = (BoundFieldAccess)initializerOpt; - if (fa.FieldSymbol.IsFixed) + if (fa.FieldSymbol.IsFixedSizeBuffer) { elementType = ((PointerTypeSymbol)fa.Type).PointedAtType.TypeSymbol; break; @@ -1517,6 +1517,11 @@ internal static bool AccessingAutoPropertyFromConstructor(BoundPropertyAccess pr private static bool AccessingAutoPropertyFromConstructor(BoundExpression receiver, PropertySymbol propertySymbol, Symbol fromMember) { + if (!propertySymbol.IsDefinition && propertySymbol.ContainingType.Equals(propertySymbol.ContainingType.OriginalDefinition, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) + { + propertySymbol = propertySymbol.OriginalDefinition; + } + var sourceProperty = propertySymbol as SourcePropertySymbol; var propertyIsStatic = propertySymbol.IsStatic; diff --git a/src/Compilers/CSharp/Portable/Binder/Semantics/BestTypeInferrer.cs b/src/Compilers/CSharp/Portable/Binder/Semantics/BestTypeInferrer.cs index 691d1d631dd0c..9895cb4b544ac 100644 --- a/src/Compilers/CSharp/Portable/Binder/Semantics/BestTypeInferrer.cs +++ b/src/Compilers/CSharp/Portable/Binder/Semantics/BestTypeInferrer.cs @@ -63,7 +63,7 @@ public static TypeSymbol InferBestType( // SPEC: If no such S exists, the expressions have no best common type. // All non-null types are candidates for best type inference. - IEqualityComparer comparer = conversions.IncludeNullability ? TypeSymbol.EqualsIncludingNullableComparer : TypeSymbol.EqualsConsiderEverything; + IEqualityComparer comparer = conversions.IncludeNullability ? TypeSymbol.EqualsConsiderEverything : TypeSymbol.EqualsIgnoringNullableComparer; HashSet candidateTypes = new HashSet(comparer); foreach (BoundExpression expr in exprs) { @@ -201,7 +201,7 @@ internal static TypeSymbol GetBestType( } else { - if (!better.Equals(best, TypeCompareKind.IgnoreDynamicAndTupleNames)) + if (!better.Equals(best, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { hadNullabilityMismatch = false; } @@ -224,7 +224,7 @@ internal static TypeSymbol GetBestType( { TypeSymbol type = types[i]; TypeSymbol better = Better(best, type, conversions, out bool hadMismatch, ref useSiteDiagnostics); - if (!best.Equals(better, TypeCompareKind.ConsiderEverything)) + if (!best.Equals(better, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { hadNullabilityMismatch = false; return null; @@ -275,7 +275,7 @@ private static TypeSymbol Better( return type2; } - if (type1.Equals(type2, TypeCompareKind.IgnoreDynamicAndTupleNames)) + if (type1.Equals(type2, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { return MethodTypeInferrer.Merge( TypeSymbolWithAnnotations.Create(type1), diff --git a/src/Compilers/CSharp/Portable/Binder/Semantics/Conversions/ConversionsBase.cs b/src/Compilers/CSharp/Portable/Binder/Semantics/Conversions/ConversionsBase.cs index 400337420c5ce..c21ae19ebfd58 100644 --- a/src/Compilers/CSharp/Portable/Binder/Semantics/Conversions/ConversionsBase.cs +++ b/src/Compilers/CSharp/Portable/Binder/Semantics/Conversions/ConversionsBase.cs @@ -1379,7 +1379,7 @@ private static bool HasIdentityConversionInternal(TypeSymbol type1, TypeSymbol t Debug.Assert((object)type2 != null); var compareKind = includeNullability ? - TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes | TypeCompareKind.UnknownNullableModifierMatchesAny : + TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes : TypeCompareKind.AllIgnoreOptions; return type1.Equals(type2, compareKind); } diff --git a/src/Compilers/CSharp/Portable/Binder/Semantics/OverloadResolution/MethodTypeInference.cs b/src/Compilers/CSharp/Portable/Binder/Semantics/OverloadResolution/MethodTypeInference.cs index 9a437199b774f..37de9b74f51e3 100644 --- a/src/Compilers/CSharp/Portable/Binder/Semantics/OverloadResolution/MethodTypeInference.cs +++ b/src/Compilers/CSharp/Portable/Binder/Semantics/OverloadResolution/MethodTypeInference.cs @@ -2337,7 +2337,7 @@ private bool Fix(int iParam, ref bool hadNullabilityMismatch, ref HashSet(EqualsIgnoringDynamicAndTupleNamesComparer.Instance); + var candidates = new Dictionary(EqualsIgnoringDynamicTupleNamesAndNullabilityComparer.Instance); // Optimization: if we have one exact bound then we need not add any // inexact bounds; we're just going to remove them anyway. @@ -2430,7 +2430,7 @@ private static TypeSymbolWithAnnotations Fix( { foreach (var candidate2 in initialCandidates) { - if (!candidate.Equals(candidate2, TypeCompareKind.CompareNullableModifiersForReferenceTypes) && + if (!candidate.Equals(candidate2, TypeCompareKind.ConsiderEverything) && !ImplicitConversionExists(candidate2, candidate, ref useSiteDiagnostics, conversions.WithNullability(false))) { goto OuterBreak; @@ -2443,7 +2443,7 @@ private static TypeSymbolWithAnnotations Fix( } else { - Debug.Assert(!best.Equals(candidate, TypeCompareKind.IgnoreDynamicAndTupleNames)); + Debug.Assert(!best.Equals(candidate, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); // best candidate is not unique best = default; break; @@ -2630,7 +2630,7 @@ private TypeSymbolWithAnnotations InferReturnType(BoundExpression source, NamedT { for (int p = 0; p < anonymousFunction.ParameterCount; ++p) { - if (!anonymousFunction.ParameterType(p).TypeSymbol.Equals(fixedDelegateParameters[p].Type.TypeSymbol, TypeCompareKind.IgnoreDynamicAndTupleNames)) + if (!anonymousFunction.ParameterType(p).TypeSymbol.Equals(fixedDelegateParameters[p].Type.TypeSymbol, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { return default; } @@ -2823,7 +2823,7 @@ private static void AddOrMergeCandidate( ref bool hadNullabilityMismatch) { Debug.Assert(conversions.IncludeNullability || - newCandidate.SetUnknownNullabilityForReferenceTypes().Equals(newCandidate, TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + newCandidate.SetUnknownNullabilityForReferenceTypes().Equals(newCandidate, TypeCompareKind.ConsiderEverything)); if (candidates.TryGetValue(newCandidate, out TypeSymbolWithAnnotations oldCandidate)) { @@ -2852,7 +2852,7 @@ private static void MergeOrRemoveCandidates( Debug.Assert(variance == VarianceKind.In || variance == VarianceKind.Out); // SPEC: For each lower (upper) bound U of Xi all types to which there is not an // SPEC: implicit conversion from (to) U are removed from the candidate set. - var comparison = conversions.IncludeNullability ? TypeCompareKind.CompareNullableModifiersForReferenceTypes : TypeCompareKind.ConsiderEverything; + var comparison = conversions.IncludeNullability ? TypeCompareKind.ConsiderEverything : TypeCompareKind.IgnoreNullableModifiersForReferenceTypes; foreach (var bound in bounds) { foreach (var candidate in initialCandidates) @@ -2877,7 +2877,7 @@ private static void MergeOrRemoveCandidates( { candidates.Remove(candidate); } - else if (bound.Equals(candidate, TypeCompareKind.IgnoreDynamicAndTupleNames)) + else if (bound.Equals(candidate, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { // SPEC: 4.7 The Dynamic Type // Type inference (7.5.2) will prefer dynamic over object if both are candidates. @@ -2928,9 +2928,9 @@ private static void MergeAndReplaceIfStillCandidate( /// This is a comparer that ignores differences in dynamic-ness and tuple names. /// But it has a special case for top-level object vs. dynamic for purpose of method type inference. /// - private sealed class EqualsIgnoringDynamicAndTupleNamesComparer : EqualityComparer + private sealed class EqualsIgnoringDynamicTupleNamesAndNullabilityComparer : EqualityComparer { - internal static readonly EqualsIgnoringDynamicAndTupleNamesComparer Instance = new EqualsIgnoringDynamicAndTupleNamesComparer(); + internal static readonly EqualsIgnoringDynamicTupleNamesAndNullabilityComparer Instance = new EqualsIgnoringDynamicTupleNamesAndNullabilityComparer(); public override int GetHashCode(TypeSymbolWithAnnotations obj) { @@ -2943,7 +2943,7 @@ public override bool Equals(TypeSymbolWithAnnotations x, TypeSymbolWithAnnotatio // but dynamic and object are not considered equal for backwards compatibility. if (x.IsDynamic() ^ y.IsDynamic()) { return false; } - return x.Equals(y, TypeCompareKind.IgnoreDynamicAndTupleNames); + return x.Equals(y, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } } } diff --git a/src/Compilers/CSharp/Portable/BoundTree/DecisionTreeBuilder.cs b/src/Compilers/CSharp/Portable/BoundTree/DecisionTreeBuilder.cs index 7bf33d7aa149f..74444f1c61160 100644 --- a/src/Compilers/CSharp/Portable/BoundTree/DecisionTreeBuilder.cs +++ b/src/Compilers/CSharp/Portable/BoundTree/DecisionTreeBuilder.cs @@ -185,7 +185,7 @@ private DecisionTree AddByValue(DecisionTree.Guarded guarded, BoundConstantPatte private DecisionTree AddByValue(DecisionTree.ByValue byValue, BoundConstantPattern value, DecisionMaker makeDecision) { - Debug.Assert(value.Value.Type.Equals(byValue.Type, TypeCompareKind.IgnoreDynamicAndTupleNames)); + Debug.Assert(value.Value.Type.Equals(byValue.Type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); if (byValue.Default != null) { return AddByValue(byValue.Default, value, makeDecision); @@ -277,7 +277,7 @@ private DecisionTree AddByValue(DecisionTree.ByType byType, BoundConstantPattern var kvp = byType.TypeAndDecision[i]; var matchedType = kvp.Key; var decision = kvp.Value; - if (matchedType.Equals(value.Value.Type, TypeCompareKind.IgnoreDynamicAndTupleNames)) + if (matchedType.Equals(value.Value.Type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { forType = decision; break; @@ -354,7 +354,7 @@ private DecisionTree AddByType(DecisionTree decision, TypeSymbol type, DecisionM DecisionTree result; if (byValue.Default == null) { - if (byValue.Type.Equals(type, TypeCompareKind.IgnoreDynamicAndTupleNames)) + if (byValue.Type.Equals(type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { result = byValue.Default = makeDecision(byValue.Expression, byValue.Type); } @@ -421,7 +421,7 @@ private DecisionTree AddByType(DecisionTree.ByType byType, TypeSymbol type, Deci if (byType.TypeAndDecision.Count != 0) { var lastTypeAndDecision = byType.TypeAndDecision.Last(); - if (lastTypeAndDecision.Key.Equals(type, TypeCompareKind.IgnoreDynamicAndTupleNames)) + if (lastTypeAndDecision.Key.Equals(type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { result = Add(lastTypeAndDecision.Value, makeDecision); } diff --git a/src/Compilers/CSharp/Portable/BoundTree/UnboundLambda.cs b/src/Compilers/CSharp/Portable/BoundTree/UnboundLambda.cs index e5780e1cdda50..ba1c3ad0eaad3 100644 --- a/src/Compilers/CSharp/Portable/BoundTree/UnboundLambda.cs +++ b/src/Compilers/CSharp/Portable/BoundTree/UnboundLambda.cs @@ -334,7 +334,7 @@ internal abstract class UnboundLambdaState [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/23582", Constraint = "Avoid " + nameof(ConcurrentDictionary) + " which has a large default size, but this cache is normally small.")] - private ImmutableDictionary _bindingCache = ImmutableDictionary.Empty.WithComparers(TypeSymbol.EqualsIncludingNullableComparer); + private ImmutableDictionary _bindingCache = ImmutableDictionary.Empty.WithComparers(TypeSymbol.EqualsConsiderEverything); [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/23582", @@ -468,7 +468,7 @@ private BoundLambda ReallyBind(NamedTypeSymbol delegateType) lambdaSymbol = returnInferenceLambda.Symbol; var lambdaReturnType = lambdaSymbol.ReturnType; if ((object)LambdaSymbol.InferenceFailureReturnType != lambdaReturnType.TypeSymbol && - lambdaReturnType.Equals(returnType, TypeCompareKind.CompareNullableModifiersForReferenceTypes) && lambdaSymbol.RefKind == refKind) + lambdaReturnType.Equals(returnType, TypeCompareKind.ConsiderEverything) && lambdaSymbol.RefKind == refKind) { lambdaBodyBinder = returnInferenceLambda.Binder; block = returnInferenceLambda.Body; @@ -663,7 +663,7 @@ public override bool Equals(object obj) for (int i = 0; i < this.ParameterTypes.Length; i++) { - if (!other.ParameterTypes[i].Equals(this.ParameterTypes[i], TypeCompareKind.CompareNullableModifiersForReferenceTypes) || + if (!other.ParameterTypes[i].Equals(this.ParameterTypes[i], TypeCompareKind.ConsiderEverything) || other.ParameterRefKinds[i] != this.ParameterRefKinds[i]) { return false; diff --git a/src/Compilers/CSharp/Portable/CodeGen/EmitAddress.cs b/src/Compilers/CSharp/Portable/CodeGen/EmitAddress.cs index b0b697474d60a..af42a145ccc77 100644 --- a/src/Compilers/CSharp/Portable/CodeGen/EmitAddress.cs +++ b/src/Compilers/CSharp/Portable/CodeGen/EmitAddress.cs @@ -531,7 +531,7 @@ private LocalDefinition EmitInstanceFieldAddress(BoundFieldAccess fieldAccess, A // Both the buffer backing struct and its only field should be at the same location, // so we could in theory just use address of the struct, but in some contexts that causes // PEVerify errors because the struct has unexpected type. (Ex: struct& when int& is expected) - if (field.IsFixed) + if (field.IsFixedSizeBuffer) { var fixedImpl = field.FixedImplementationType(_module); var fixedElementField = fixedImpl.FixedElementField; diff --git a/src/Compilers/CSharp/Portable/CodeGen/Optimizer.cs b/src/Compilers/CSharp/Portable/CodeGen/Optimizer.cs index f5fdea521a92c..aabfdffc21c4c 100644 --- a/src/Compilers/CSharp/Portable/CodeGen/Optimizer.cs +++ b/src/Compilers/CSharp/Portable/CodeGen/Optimizer.cs @@ -1010,7 +1010,7 @@ public override BoundNode VisitAssignmentOperator(BoundAssignmentOperator node) internal static bool IsFixedBufferAssignmentToRefLocal(BoundExpression left, BoundExpression right, bool isRef) => isRef && right is BoundFieldAccess fieldAccess && - fieldAccess.FieldSymbol.IsFixed && + fieldAccess.FieldSymbol.IsFixedSizeBuffer && left.Type.Equals(((PointerTypeSymbol)right.Type).PointedAtType.TypeSymbol, TypeCompareKind.AllIgnoreOptions); // indirect assignment is assignment to a value referenced indirectly diff --git a/src/Compilers/CSharp/Portable/Compiler/MethodCompiler.cs b/src/Compilers/CSharp/Portable/Compiler/MethodCompiler.cs index aa2695bdfdfc7..cb0c3fde3b66d 100644 --- a/src/Compilers/CSharp/Portable/Compiler/MethodCompiler.cs +++ b/src/Compilers/CSharp/Portable/Compiler/MethodCompiler.cs @@ -540,7 +540,7 @@ private void CompileNamedType(NamedTypeSymbol containingType) SetGlobalErrorIfTrue(constantValue == null || constantValue.IsBad); } - if (fieldSymbol.IsFixed && compilationState.Emitting) + if (fieldSymbol.IsFixedSizeBuffer && compilationState.Emitting) { // force the generation of implementation types for fixed-size buffers TypeSymbol discarded = fieldSymbol.FixedImplementationType(compilationState.ModuleBuilderOpt); diff --git a/src/Compilers/CSharp/Portable/Emitter/EditAndContinue/CSharpSymbolMatcher.cs b/src/Compilers/CSharp/Portable/Emitter/EditAndContinue/CSharpSymbolMatcher.cs index ec58ec40bc43e..e37394f5280b1 100644 --- a/src/Compilers/CSharp/Portable/Emitter/EditAndContinue/CSharpSymbolMatcher.cs +++ b/src/Compilers/CSharp/Portable/Emitter/EditAndContinue/CSharpSymbolMatcher.cs @@ -850,7 +850,7 @@ public bool Equals(TypeSymbol source, TypeSymbol other) var visitedSource = (TypeSymbol)_matcher.Visit(source); var visitedOther = (_deepTranslatorOpt != null) ? (TypeSymbol)_deepTranslatorOpt.Visit(other) : other; - return visitedSource?.Equals(visitedOther, TypeCompareKind.IgnoreDynamicAndTupleNames) == true; + return visitedSource?.Equals(visitedOther, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes) == true; } } } diff --git a/src/Compilers/CSharp/Portable/Emitter/Model/FieldSymbolAdapter.cs b/src/Compilers/CSharp/Portable/Emitter/Model/FieldSymbolAdapter.cs index 38151e94bc152..91c7bb7b84f91 100644 --- a/src/Compilers/CSharp/Portable/Emitter/Model/FieldSymbolAdapter.cs +++ b/src/Compilers/CSharp/Portable/Emitter/Model/FieldSymbolAdapter.cs @@ -22,7 +22,7 @@ Cci.ITypeReference Cci.IFieldReference.GetType(EmitContext context) TypeSymbolWithAnnotations fieldType = this.Type; var customModifiers = fieldType.CustomModifiers; - var isFixed = this.IsFixed; + var isFixed = this.IsFixedSizeBuffer; var implType = isFixed ? this.FixedImplementationType(moduleBeingBuilt) : fieldType.TypeSymbol; var type = moduleBeingBuilt.Translate(implType, syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNodeOpt, diff --git a/src/Compilers/CSharp/Portable/Emitter/Model/SymbolAdapter.cs b/src/Compilers/CSharp/Portable/Emitter/Model/SymbolAdapter.cs index 3a60b1f639820..f316dc92b9c17 100644 --- a/src/Compilers/CSharp/Portable/Emitter/Model/SymbolAdapter.cs +++ b/src/Compilers/CSharp/Portable/Emitter/Model/SymbolAdapter.cs @@ -48,10 +48,7 @@ void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor) /// internal bool IsDefinitionOrDistinct() { - return this.IsDefinition || - !(this is NamedTypeSymbol namedTypeSymbol ? - namedTypeSymbol.Equals(namedTypeSymbol.OriginalDefinition, TypeCompareKind.CompareNullableModifiersForReferenceTypes) : - this.Equals(this.OriginalDefinition)); + return this.IsDefinition || !this.Equals(this.OriginalDefinition); } IEnumerable Cci.IReference.GetAttributes(EmitContext context) diff --git a/src/Compilers/CSharp/Portable/FlowAnalysis/DataFlowPass.cs b/src/Compilers/CSharp/Portable/FlowAnalysis/DataFlowPass.cs index aaf26b3171589..bca81cb3ac975 100644 --- a/src/Compilers/CSharp/Portable/FlowAnalysis/DataFlowPass.cs +++ b/src/Compilers/CSharp/Portable/FlowAnalysis/DataFlowPass.cs @@ -375,7 +375,7 @@ public static void Analyze(CSharpCompilation compilation, MethodSymbol member, B walker.Free(); } - if (member.NonNullTypes != null && + if (member.NonNullTypes == true && compilation.LanguageVersion >= MessageID.IDS_FeatureNullableReferenceTypes.RequiredVersion()) { NullableWalker.Analyze(compilation, member, node, diagnostics); @@ -771,7 +771,7 @@ protected override bool TryGetReceiverAndMember(BoundExpression expr, out BoundE { var fieldAccess = (BoundFieldAccess)expr; var fieldSymbol = fieldAccess.FieldSymbol; - if (fieldSymbol.IsStatic || fieldSymbol.IsFixed) + if (fieldSymbol.IsStatic || fieldSymbol.IsFixedSizeBuffer) { return false; } @@ -827,7 +827,7 @@ protected bool MayRequireTracking(BoundExpression receiverOpt, FieldSymbol field (object)fieldSymbol != null && //simplifies calling pattern for events receiverOpt != null && !fieldSymbol.IsStatic && - !fieldSymbol.IsFixed && + !fieldSymbol.IsFixedSizeBuffer && receiverOpt.Kind != BoundKind.TypeExpression && MayRequireTrackingReceiverType(receiverOpt.Type) && !receiverOpt.Type.IsPrimitiveRecursiveStruct(); @@ -1885,7 +1885,7 @@ protected void CheckAssigned(BoundExpression expr, SyntaxNode node) case BoundKind.FieldAccess: var field = (BoundFieldAccess)expr; var symbol = field.FieldSymbol; - if (!symbol.IsFixed && MayRequireTracking(field.ReceiverOpt, symbol)) + if (!symbol.IsFixedSizeBuffer && MayRequireTracking(field.ReceiverOpt, symbol)) { CheckAssigned(expr, symbol, node); } @@ -2050,7 +2050,7 @@ public override BoundNode VisitFieldAccess(BoundFieldAccess node) var result = base.VisitFieldAccess(node); NoteRead(node.FieldSymbol); - if (node.FieldSymbol.IsFixed && node.Syntax != null && !SyntaxFacts.IsFixedStatementExpression(node.Syntax)) + if (node.FieldSymbol.IsFixedSizeBuffer && node.Syntax != null && !SyntaxFacts.IsFixedStatementExpression(node.Syntax)) { Symbol receiver = UseNonFieldSymbolUnsafely(node.ReceiverOpt); if ((object)receiver != null) diff --git a/src/Compilers/CSharp/Portable/FlowAnalysis/EmptyStructTypeCache.cs b/src/Compilers/CSharp/Portable/FlowAnalysis/EmptyStructTypeCache.cs index cd59f17be5d39..a5677c4bbe0c6 100644 --- a/src/Compilers/CSharp/Portable/FlowAnalysis/EmptyStructTypeCache.cs +++ b/src/Compilers/CSharp/Portable/FlowAnalysis/EmptyStructTypeCache.cs @@ -175,7 +175,7 @@ private FieldSymbol GetActualInstanceField(Symbol member, NamedTypeSymbol type) return null; } - return (field.IsFixed || ShouldIgnoreStructField(field, field.Type.TypeSymbol)) ? null : field.AsMember(type); + return (field.IsFixedSizeBuffer || ShouldIgnoreStructField(field, field.Type.TypeSymbol)) ? null : field.AsMember(type); case SymbolKind.Event: EventSymbol eventSymbol = (EventSymbol)member; diff --git a/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.cs b/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.cs index 097b93cd0a3bd..b31afaaa67013 100644 --- a/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.cs +++ b/src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker.cs @@ -333,7 +333,7 @@ protected override bool TryGetReceiverAndMember(BoundExpression expr, out BoundE { var fieldAccess = (BoundFieldAccess)expr; var fieldSymbol = fieldAccess.FieldSymbol; - if (fieldSymbol.IsStatic || fieldSymbol.IsFixed) + if (fieldSymbol.IsStatic || fieldSymbol.IsFixedSizeBuffer) { return false; } @@ -651,7 +651,7 @@ private void TrackNullableStateForAssignment(BoundExpression value, TypeSymbolWi // } // For now, we copy a limited set of BoundNode types that shouldn't contain cycles. if ((value.Kind == BoundKind.ObjectCreationExpression || value.Kind == BoundKind.AnonymousObjectCreationExpression || value.Kind == BoundKind.DynamicObjectCreationExpression || targetType.TypeSymbol.IsAnonymousType) && - targetType.TypeSymbol.Equals(valueType.TypeSymbol, TypeCompareKind.ConsiderEverything)) // https://github.com/dotnet/roslyn/issues/29968 Allow assignment to base type. + targetType.TypeSymbol.Equals(valueType.TypeSymbol, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) // https://github.com/dotnet/roslyn/issues/29968 Allow assignment to base type. { if (valueSlot > 0) { @@ -660,7 +660,7 @@ private void TrackNullableStateForAssignment(BoundExpression value, TypeSymbolWi } } else if (EmptyStructTypeCache.IsTrackableStructType(targetType.TypeSymbol) && - targetType.TypeSymbol.Equals(valueType.TypeSymbol, TypeCompareKind.ConsiderEverything)) + targetType.TypeSymbol.Equals(valueType.TypeSymbol, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { InheritNullableStateOfTrackableStruct(targetType.TypeSymbol, targetSlot, valueSlot, IsByRefTarget(targetSlot), slotWatermark: GetSlotWatermark()); } @@ -1051,7 +1051,7 @@ private static bool AreCloseEnough(TypeSymbol typeA, TypeSymbol typeB) bool canIgnoreType(TypeSymbol type) => (object)type.VisitType((t, unused1, unused2) => t.IsErrorType() || t.IsDynamic() || t.HasUseSiteError, (object)null) != null; return canIgnoreType(typeA) || canIgnoreType(typeB) || - typeA.Equals(typeB, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreDynamicAndTupleNames); // Ignore TupleElementNames (see https://github.com/dotnet/roslyn/issues/23651). + typeA.Equals(typeB, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamicAndTupleNames); // Ignore TupleElementNames (see https://github.com/dotnet/roslyn/issues/23651). } #endif @@ -2846,7 +2846,7 @@ private static Symbol AsMemberOfType(NamedTypeSymbol containingType, Symbol symb private static Symbol AsMemberOfTupleType(TupleTypeSymbol tupleType, Symbol symbol) { - if (symbol.ContainingType.Equals(tupleType, TypeCompareKind.CompareNullableModifiersForReferenceTypes)) + if (symbol.ContainingType.Equals(tupleType)) { return symbol; } @@ -4367,13 +4367,13 @@ private void CheckPossibleNullReceiver(BoundExpression receiverOpt) private static bool IsNullabilityMismatch(TypeSymbolWithAnnotations type1, TypeSymbolWithAnnotations type2) { return type1.Equals(type2, TypeCompareKind.AllIgnoreOptions) && - !type1.Equals(type2, TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes | TypeCompareKind.UnknownNullableModifierMatchesAny); + !type1.Equals(type2, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } private static bool IsNullabilityMismatch(TypeSymbol type1, TypeSymbol type2) { return type1.Equals(type2, TypeCompareKind.AllIgnoreOptions) && - !type1.Equals(type2, TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes | TypeCompareKind.UnknownNullableModifierMatchesAny); + !type1.Equals(type2, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } private bool? InferResultNullabilityFromApplicableCandidates(ImmutableArray applicableMembers) diff --git a/src/Compilers/CSharp/Portable/FlowAnalysis/PreciseAbstractFlowPass.cs b/src/Compilers/CSharp/Portable/FlowAnalysis/PreciseAbstractFlowPass.cs index 32db9a9042319..bed20ffa04b78 100644 --- a/src/Compilers/CSharp/Portable/FlowAnalysis/PreciseAbstractFlowPass.cs +++ b/src/Compilers/CSharp/Portable/FlowAnalysis/PreciseAbstractFlowPass.cs @@ -1775,7 +1775,7 @@ public override BoundNode VisitFieldAccess(BoundFieldAccess node) private void VisitFieldAccessInternal(BoundExpression receiverOpt, FieldSymbol fieldSymbol) { bool asLvalue = (object)fieldSymbol != null && - (fieldSymbol.IsFixed || + (fieldSymbol.IsFixedSizeBuffer || !fieldSymbol.IsStatic && fieldSymbol.ContainingType.TypeKind == TypeKind.Struct && receiverOpt != null && diff --git a/src/Compilers/CSharp/Portable/Lowering/AsyncRewriter/AsyncMethodToStateMachineRewriter.cs b/src/Compilers/CSharp/Portable/Lowering/AsyncRewriter/AsyncMethodToStateMachineRewriter.cs index 8f10678866700..9e4a18f355222 100644 --- a/src/Compilers/CSharp/Portable/Lowering/AsyncRewriter/AsyncMethodToStateMachineRewriter.cs +++ b/src/Compilers/CSharp/Portable/Lowering/AsyncRewriter/AsyncMethodToStateMachineRewriter.cs @@ -92,7 +92,7 @@ internal AsyncMethodToStateMachineRewriter( : null; _dynamicFactory = new LoweredDynamicOperationFactory(F, methodOrdinal); - _awaiterFields = new Dictionary(TypeSymbol.EqualsIgnoringDynamicAndTupleNamesComparer); + _awaiterFields = new Dictionary(TypeSymbol.EqualsIgnoringDynamicTupleNamesAndNullabilityComparer); _nextAwaiterId = slotAllocatorOpt?.PreviousAwaiterSlotCount ?? 0; } diff --git a/src/Compilers/CSharp/Portable/Lowering/AsyncRewriter/AwaitExpressionSpiller.cs b/src/Compilers/CSharp/Portable/Lowering/AsyncRewriter/AwaitExpressionSpiller.cs index e91a51dc012ed..a5c7ec109a010 100644 --- a/src/Compilers/CSharp/Portable/Lowering/AsyncRewriter/AwaitExpressionSpiller.cs +++ b/src/Compilers/CSharp/Portable/Lowering/AsyncRewriter/AwaitExpressionSpiller.cs @@ -589,6 +589,15 @@ public override BoundNode VisitReturnStatement(BoundReturnStatement node) return UpdateStatement(builder, node.Update(node.RefKind, expression), substituteTemps: true); } + public override BoundNode VisitYieldReturnStatement(BoundYieldReturnStatement node) + { + EnterStatement(node); + + BoundSpillSequenceBuilder builder = null; + var expression = VisitExpression(ref builder, node.Expression); + return UpdateStatement(builder, node.Update(expression), substituteTemps: true); + } + #if DEBUG public override BoundNode DefaultVisit(BoundNode node) { diff --git a/src/Compilers/CSharp/Portable/Lowering/LambdaRewriter/ExpressionLambdaRewriter.cs b/src/Compilers/CSharp/Portable/Lowering/LambdaRewriter/ExpressionLambdaRewriter.cs index a3e1a77b45683..65236d5964ae2 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LambdaRewriter/ExpressionLambdaRewriter.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LambdaRewriter/ExpressionLambdaRewriter.cs @@ -113,7 +113,7 @@ internal static BoundNode RewriteLambda(BoundLambda node, TypeCompilationState c { var r = new ExpressionLambdaRewriter(compilationState, typeMap, node.Syntax, recursionDepth, diagnostics); var result = r.VisitLambdaInternal(node); - if (node.Type != result.Type) + if (!node.Type.Equals(result.Type, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { diagnostics.Add(ErrorCode.ERR_MissingPredefinedMember, node.Syntax.Location, r.ExpressionType, "Lambda"); } diff --git a/src/Compilers/CSharp/Portable/Lowering/LambdaRewriter/LambdaRewriter.cs b/src/Compilers/CSharp/Portable/Lowering/LambdaRewriter/LambdaRewriter.cs index caf896e29d44b..b9ec618b3d71a 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LambdaRewriter/LambdaRewriter.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LambdaRewriter/LambdaRewriter.cs @@ -937,7 +937,7 @@ private ImmutableArray SubstituteTypeArguments(Immuta // https://github.com/dotnet/roslyn/issues/30069 Is this weaker assert sufficient? //Debug.Assert((object)oldTypeArg == newTypeArg); - Debug.Assert(oldTypeArg.Equals(newTypeArg, TypeCompareKind.CompareNullableModifiersForReferenceTypes | TypeCompareKind.UnknownNullableModifierMatchesAny)); + Debug.Assert(oldTypeArg.Equals(newTypeArg, TypeCompareKind.UnknownNullableModifierMatchesAny)); builder.Add(newTypeArg); } diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter.cs index 378bf70199890..e664171430cb3 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter.cs @@ -187,7 +187,7 @@ private BoundExpression VisitExpressionImpl(BoundExpression node) // Dynamic type will be erased in emit phase. It is considered equivalent to Object in lowered bound trees. // Unused deconstructions are lowered to produce a return value that isn't a tuple type. Debug.Assert(visited == null || visited.HasErrors || ReferenceEquals(visited.Type, node.Type) || - visited.Type.Equals(node.Type, TypeCompareKind.IgnoreDynamicAndTupleNames) || + visited.Type.Equals(node.Type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes) || IsUnusedDeconstruction(node)); if (visited != null && visited != node) diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Conversion.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Conversion.cs index 2d402b94e2f77..a5d4bec52a19b 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Conversion.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Conversion.cs @@ -30,7 +30,7 @@ public override BoundNode VisitConversion(BoundConversion node) var result = MakeConversionNode(node, node.Syntax, rewrittenOperand, node.Conversion, node.Checked, node.ExplicitCastInCode, node.ConstantValue, rewrittenType); var toType = node.Type; - Debug.Assert(result.Type.Equals(toType, TypeCompareKind.IgnoreDynamicAndTupleNames)); + Debug.Assert(result.Type.Equals(toType, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); // 4.1.6 C# spec: To force a value of a floating point type to the exact precision of its type, an explicit cast can be used. // It means that explicit casts to (double) or (float) should be preserved on the node. @@ -241,7 +241,7 @@ private BoundExpression MakeConversionNode( { // we keep tuple literal conversions in the tree for the purpose of semantic model (for example when they are casts in the source) // for the purpose of lowering/codegeneration they are identity conversions. - Debug.Assert(rewrittenOperand.Type.Equals(rewrittenType, TypeCompareKind.IgnoreDynamicAndTupleNames)); + Debug.Assert(rewrittenOperand.Type.Equals(rewrittenType, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); return rewrittenOperand; } diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Field.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Field.cs index 224a821c32b85..bb0af1ed10825 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Field.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Field.cs @@ -31,7 +31,7 @@ private BoundExpression MakeFieldAccess( oldNodeOpt.Update(rewrittenReceiver, fieldSymbol, constantValueOpt, resultKind, type) : new BoundFieldAccess(syntax, rewrittenReceiver, fieldSymbol, constantValueOpt, resultKind, type); - if (fieldSymbol.IsFixed) + if (fieldSymbol.IsFixedSizeBuffer) { // a reference to a fixed buffer is translated into its address result = new BoundAddressOfOperator(syntax, result, type, false); diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_NullCoalescingOperator.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_NullCoalescingOperator.cs index 639e0e6311094..13fbc77e938a2 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_NullCoalescingOperator.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_NullCoalescingOperator.cs @@ -31,7 +31,7 @@ private BoundExpression MakeNullCoalescingOperator( Debug.Assert(rewrittenRight != null); Debug.Assert(leftConversion.IsValid); Debug.Assert((object)rewrittenResultType != null); - Debug.Assert(rewrittenRight.Type.Equals(rewrittenResultType, TypeCompareKind.IgnoreDynamicAndTupleNames)); + Debug.Assert(rewrittenRight.Type.Equals(rewrittenResultType, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); if (_inExpressionLambda) { @@ -143,7 +143,7 @@ private BoundExpression MakeNullCoalescingOperator( // MakeConversion(temp, rewrittenResultType) BoundExpression convertedLeft = GetConvertedLeftForNullCoalescingOperator(boundTemp, leftConversion, rewrittenResultType); - Debug.Assert(convertedLeft.HasErrors || convertedLeft.Type.Equals(rewrittenResultType, TypeCompareKind.IgnoreDynamicAndTupleNames)); + Debug.Assert(convertedLeft.HasErrors || convertedLeft.Type.Equals(rewrittenResultType, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); // (temp != null) ? MakeConversion(temp, LeftConversion) : RightOperand BoundExpression conditionalExpression = RewriteConditionalOperator( @@ -156,7 +156,7 @@ private BoundExpression MakeNullCoalescingOperator( isRef: false); Debug.Assert(conditionalExpression.ConstantValue == null); // we shouldn't have hit this else case otherwise - Debug.Assert(conditionalExpression.Type.Equals(rewrittenResultType, TypeCompareKind.IgnoreDynamicAndTupleNames)); + Debug.Assert(conditionalExpression.Type.Equals(rewrittenResultType, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); return new BoundSequence( syntax: syntax, diff --git a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_PointerElementAccess.cs b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_PointerElementAccess.cs index 48cb147be083f..b9a409a85f04e 100644 --- a/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_PointerElementAccess.cs +++ b/src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_PointerElementAccess.cs @@ -16,7 +16,7 @@ public override BoundNode VisitPointerElementAccess(BoundPointerElementAccess no private BoundExpression LowerReceiverOfPointerElementAccess(BoundExpression receiver) { - if (receiver is BoundFieldAccess fieldAccess && fieldAccess.FieldSymbol.IsFixed) + if (receiver is BoundFieldAccess fieldAccess && fieldAccess.FieldSymbol.IsFixedSizeBuffer) { var loweredFieldReceiver = VisitExpression(fieldAccess.ReceiverOpt); fieldAccess = fieldAccess.Update(loweredFieldReceiver, fieldAccess.FieldSymbol, fieldAccess.ConstantValueOpt, fieldAccess.ResultKind, fieldAccess.Type); diff --git a/src/Compilers/CSharp/Portable/Lowering/StateMachineRewriter/MethodToStateMachineRewriter.cs b/src/Compilers/CSharp/Portable/Lowering/StateMachineRewriter/MethodToStateMachineRewriter.cs index e9de055560733..b965b16b19106 100644 --- a/src/Compilers/CSharp/Portable/Lowering/StateMachineRewriter/MethodToStateMachineRewriter.cs +++ b/src/Compilers/CSharp/Portable/Lowering/StateMachineRewriter/MethodToStateMachineRewriter.cs @@ -452,7 +452,7 @@ private void FreeReusableHoistedField(StateMachineFieldSymbol field) { if (_lazyAvailableReusableHoistedFields == null) { - _lazyAvailableReusableHoistedFields = new Dictionary>(TypeSymbol.EqualsIgnoringDynamicAndTupleNamesComparer); + _lazyAvailableReusableHoistedFields = new Dictionary>(TypeSymbol.EqualsIgnoringDynamicTupleNamesAndNullabilityComparer); } _lazyAvailableReusableHoistedFields.Add(field.Type.TypeSymbol, fields = new ArrayBuilder()); diff --git a/src/Compilers/CSharp/Portable/Lowering/SyntheticBoundNodeFactory.cs b/src/Compilers/CSharp/Portable/Lowering/SyntheticBoundNodeFactory.cs index 5e42dfa48723b..80ec461ae3850 100644 --- a/src/Compilers/CSharp/Portable/Lowering/SyntheticBoundNodeFactory.cs +++ b/src/Compilers/CSharp/Portable/Lowering/SyntheticBoundNodeFactory.cs @@ -670,7 +670,7 @@ public BoundExpression ComplexConditionalReceiver(BoundExpression valueTypeRecei public BoundExpression Coalesce(BoundExpression left, BoundExpression right) { - Debug.Assert(left.Type.Equals(right.Type, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)); + Debug.Assert(left.Type.Equals(right.Type, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); Debug.Assert(left.Type.IsReferenceType); return new BoundNullCoalescingOperator(Syntax, left, right, Conversion.Identity, BoundNullCoalescingOperatorResultKind.LeftType, left.Type) { WasCompilerGenerated = true }; diff --git a/src/Compilers/CSharp/Portable/Microsoft.CodeAnalysis.CSharp.csproj b/src/Compilers/CSharp/Portable/Microsoft.CodeAnalysis.CSharp.csproj index 68eed022cf446..e17fce94e4be9 100644 --- a/src/Compilers/CSharp/Portable/Microsoft.CodeAnalysis.CSharp.csproj +++ b/src/Compilers/CSharp/Portable/Microsoft.CodeAnalysis.CSharp.csproj @@ -7,7 +7,7 @@ Library Microsoft.CodeAnalysis.CSharp true - netstandard1.3 + netstandard2.0 ..\CSharpCodeAnalysisRules.ruleset true @@ -19,10 +19,8 @@ - + - - diff --git a/src/Compilers/CSharp/Portable/Operations/CSharpOperationFactory.cs b/src/Compilers/CSharp/Portable/Operations/CSharpOperationFactory.cs index 2baf5159cb080..c1733fcb9ae36 100644 --- a/src/Compilers/CSharp/Portable/Operations/CSharpOperationFactory.cs +++ b/src/Compilers/CSharp/Portable/Operations/CSharpOperationFactory.cs @@ -1188,7 +1188,7 @@ private ICoalesceOperation CreateBoundNullCoalescingOperatorOperation(BoundNullC Conversion valueConversion = boundNullCoalescingOperator.LeftConversion; if (valueConversion.Exists && !valueConversion.IsIdentity && - boundNullCoalescingOperator.Type.Equals(boundNullCoalescingOperator.LeftOperand.Type?.StrippedType(), TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)) + boundNullCoalescingOperator.Type.Equals(boundNullCoalescingOperator.LeftOperand.Type?.StrippedType(), TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { valueConversion = Conversion.Identity; } diff --git a/src/Compilers/CSharp/Portable/Symbols/ArrayTypeSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/ArrayTypeSymbol.cs index e55316b75fc3d..7ca8893987b84 100644 --- a/src/Compilers/CSharp/Portable/Symbols/ArrayTypeSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/ArrayTypeSymbol.cs @@ -406,7 +406,7 @@ internal override TypeSymbol SetUnknownNullabilityForReferenceTypes() internal override TypeSymbol MergeNullability(TypeSymbol other, VarianceKind variance, out bool hadNullabilityMismatch) { - Debug.Assert(this.Equals(other, TypeCompareKind.IgnoreDynamicAndTupleNames)); + Debug.Assert(this.Equals(other, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); TypeSymbolWithAnnotations elementType = ElementType.MergeNullability(((ArrayTypeSymbol)other).ElementType, VarianceKind.None, out hadNullabilityMismatch); return WithElementType(elementType); } diff --git a/src/Compilers/CSharp/Portable/Symbols/Compilation_WellKnownMembers.cs b/src/Compilers/CSharp/Portable/Symbols/Compilation_WellKnownMembers.cs index db855f0948726..a76ddfdace1ca 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Compilation_WellKnownMembers.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Compilation_WellKnownMembers.cs @@ -1076,7 +1076,7 @@ protected override bool MatchTypeToTypeId(TypeSymbol type, int typeId) return true; } - return type == type.OriginalDefinition; + return type.Equals(type.OriginalDefinition, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } return false; @@ -1097,7 +1097,7 @@ protected override bool MatchTypeToTypeId(TypeSymbol type, int typeId) WellKnownType wellKnownId = (WellKnownType)typeId; if (wellKnownId.IsWellKnownType()) { - return (type == _compilation.GetWellKnownType(wellKnownId)); + return type.Equals(_compilation.GetWellKnownType(wellKnownId), TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } return base.MatchTypeToTypeId(type, typeId); diff --git a/src/Compilers/CSharp/Portable/Symbols/ConstraintsHelper.cs b/src/Compilers/CSharp/Portable/Symbols/ConstraintsHelper.cs index f24187bcf5201..74ef5b90fc132 100644 --- a/src/Compilers/CSharp/Portable/Symbols/ConstraintsHelper.cs +++ b/src/Compilers/CSharp/Portable/Symbols/ConstraintsHelper.cs @@ -689,7 +689,7 @@ private static bool HasDuplicateInterfaces(NamedTypeSymbol type, ConsList - public virtual bool IsFixed { get { return false; } } + public virtual bool IsFixedSizeBuffer { get { return false; } } /// - /// If IsFixed is true, the value between brackets in the fixed-size-buffer declaration. - /// If IsFixed is false FixedSize is 0. + /// If IsFixedSizeBuffer is true, the value between brackets in the fixed-size-buffer declaration. + /// If IsFixedSizeBuffer is false FixedSize is 0. /// Note that for fixed-a size buffer declaration, this.Type will be a pointer type, of which /// the pointed-to type will be the declared element type of the fixed-size buffer. /// public virtual int FixedSize { get { return 0; } } /// - /// If this.IsFixed is true, returns the underlying implementation type for the + /// If this.IsFixedSizeBuffer is true, returns the underlying implementation type for the /// fixed-size buffer when emitted. Otherwise returns null. /// internal virtual NamedTypeSymbol FixedImplementationType(PEModuleBuilder emitModule) diff --git a/src/Compilers/CSharp/Portable/Symbols/MemberSignatureComparer.cs b/src/Compilers/CSharp/Portable/Symbols/MemberSignatureComparer.cs index 85a5b608eb6f1..d36812bdbe684 100644 --- a/src/Compilers/CSharp/Portable/Symbols/MemberSignatureComparer.cs +++ b/src/Compilers/CSharp/Portable/Symbols/MemberSignatureComparer.cs @@ -44,7 +44,7 @@ internal class MemberSignatureComparer : IEqualityComparer considerTypeConstraints: false, considerRefKindDifferences: true, considerCallingConvention: true, - typeComparison: TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreDynamicAndTupleNames); + typeComparison: TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamicAndTupleNames); /// /// Same as except that it specially treats nullable types. @@ -56,7 +56,7 @@ internal class MemberSignatureComparer : IEqualityComparer considerTypeConstraints: false, considerRefKindDifferences: true, considerCallingConvention: true, - typeComparison: TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreDynamicAndTupleNames, + typeComparison: TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamicAndTupleNames, useSpecialHandlingForNullableTypes: true); /// @@ -79,7 +79,7 @@ internal class MemberSignatureComparer : IEqualityComparer considerTypeConstraints: false, // constraints are checked by caller instead considerCallingConvention: true, considerRefKindDifferences: true, - typeComparison: TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreDynamicAndTupleNames); + typeComparison: TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamicAndTupleNames); /// /// This instance is used as a fallback when it is determined that one member does not implicitly implement @@ -93,7 +93,7 @@ internal class MemberSignatureComparer : IEqualityComparer considerTypeConstraints: false, considerCallingConvention: false, considerRefKindDifferences: true, - typeComparison: TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreDynamicAndTupleNames); //shouldn't actually matter for source members + typeComparison: TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamicAndTupleNames); //shouldn't actually matter for source members /// /// This instance is used to determine if two C# member declarations in source conflict with each other. @@ -110,7 +110,7 @@ internal class MemberSignatureComparer : IEqualityComparer considerTypeConstraints: false, considerCallingConvention: false, considerRefKindDifferences: false, - typeComparison: TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreDynamicAndTupleNames); //shouldn't actually matter for source members + typeComparison: TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamicAndTupleNames); //shouldn't actually matter for source members /// /// This instance is used to determine if a partial method implementation matches the definition. @@ -123,7 +123,7 @@ internal class MemberSignatureComparer : IEqualityComparer considerTypeConstraints: false, considerCallingConvention: false, considerRefKindDifferences: true, - typeComparison: TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreDynamicAndTupleNames); + typeComparison: TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamicAndTupleNames); /// /// This instance is used to check whether one member overrides another, according to the C# definition. @@ -135,7 +135,7 @@ internal class MemberSignatureComparer : IEqualityComparer considerTypeConstraints: false, considerCallingConvention: false, //ignore static-ness considerRefKindDifferences: true, - typeComparison: TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreDynamicAndTupleNames); + typeComparison: TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamicAndTupleNames); /// /// Same as except that it specially treats nullable types. @@ -147,7 +147,7 @@ internal class MemberSignatureComparer : IEqualityComparer considerTypeConstraints: false, considerCallingConvention: false, //ignore static-ness considerRefKindDifferences: true, - typeComparison: TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreDynamicAndTupleNames, + typeComparison: TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamicAndTupleNames, useSpecialHandlingForNullableTypes: true); /// @@ -161,7 +161,7 @@ internal class MemberSignatureComparer : IEqualityComparer considerTypeConstraints: false, considerCallingConvention: false, //ignore static-ness considerRefKindDifferences: false, - typeComparison: TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreDynamic); + typeComparison: TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamic); /// /// This instance checks whether two signatures match excluding tuples names, in both return type and parameters. @@ -174,7 +174,7 @@ internal class MemberSignatureComparer : IEqualityComparer considerTypeConstraints: false, considerCallingConvention: false, //ignore static-ness considerRefKindDifferences: false, - typeComparison: TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreDynamicAndTupleNames); + typeComparison: TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamicAndTupleNames); /// /// This instance is used to check whether one property or event overrides another, according to the C# definition. @@ -188,7 +188,7 @@ internal class MemberSignatureComparer : IEqualityComparer considerTypeConstraints: false, considerCallingConvention: false, //ignore static-ness considerRefKindDifferences: true, - typeComparison: TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreDynamicAndTupleNames); + typeComparison: TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamicAndTupleNames); /// /// Same as except that it pays attention to custom modifiers and return type. @@ -202,7 +202,7 @@ internal class MemberSignatureComparer : IEqualityComparer considerTypeConstraints: false, considerCallingConvention: false, //ignore static-ness considerRefKindDifferences: true, - typeComparison: TypeCompareKind.IgnoreDynamicAndTupleNames); + typeComparison: TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); /// /// Same as except that it specially treats nullable types. @@ -214,7 +214,7 @@ internal class MemberSignatureComparer : IEqualityComparer considerTypeConstraints: false, considerCallingConvention: false, //ignore static-ness considerRefKindDifferences: true, - typeComparison: TypeCompareKind.IgnoreDynamicAndTupleNames, + typeComparison: TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes, useSpecialHandlingForNullableTypes: true); /// @@ -228,7 +228,7 @@ internal class MemberSignatureComparer : IEqualityComparer considerTypeConstraints: false, considerCallingConvention: false, //ignore static-ness considerRefKindDifferences: false, - typeComparison: TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreDynamicAndTupleNames); + typeComparison: TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamicAndTupleNames); /// /// This instance is intended to reflect the definition of signature equality used by the runtime @@ -243,7 +243,7 @@ internal class MemberSignatureComparer : IEqualityComparer considerTypeConstraints: false, considerCallingConvention: true, considerRefKindDifferences: false, - typeComparison: TypeCompareKind.IgnoreDynamicAndTupleNames); + typeComparison: TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); /// /// Same as , but distinguishes between ref and out. During override resolution, @@ -257,7 +257,7 @@ internal class MemberSignatureComparer : IEqualityComparer considerTypeConstraints: false, considerCallingConvention: true, considerRefKindDifferences: true, - typeComparison: TypeCompareKind.IgnoreDynamicAndTupleNames); + typeComparison: TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); /// /// This instance is the same as RuntimeSignatureComparer. @@ -270,7 +270,7 @@ internal class MemberSignatureComparer : IEqualityComparer considerTypeConstraints: false, // constraints are checked by caller instead considerCallingConvention: true, considerRefKindDifferences: false, - typeComparison: TypeCompareKind.IgnoreDynamicAndTupleNames); + typeComparison: TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); // NOTE: Not used anywhere. Do we still need to keep it? /// @@ -284,7 +284,7 @@ internal class MemberSignatureComparer : IEqualityComparer considerTypeConstraints: true, considerCallingConvention: true, considerRefKindDifferences: true, - typeComparison: TypeCompareKind.IgnoreDynamicAndTupleNames); + typeComparison: TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); /// /// This instance is used to search for members that have identical signatures in every regard. @@ -296,7 +296,7 @@ internal class MemberSignatureComparer : IEqualityComparer considerTypeConstraints: false, considerCallingConvention: true, considerRefKindDifferences: true, - typeComparison: TypeCompareKind.IgnoreDynamicAndTupleNames); //if it was a true explicit impl, we expect it to remain so after retargeting + typeComparison: TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); //if it was a true explicit impl, we expect it to remain so after retargeting /// /// This instance is used for performing approximate overload resolution of documentation @@ -309,7 +309,7 @@ internal class MemberSignatureComparer : IEqualityComparer considerTypeConstraints: false, considerCallingConvention: false, //ignore static-ness considerRefKindDifferences: true, - typeComparison: TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreDynamicAndTupleNames); + typeComparison: TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamicAndTupleNames); // Compare the "unqualified" part of the member name (no explicit part) private readonly bool _considerName; @@ -512,7 +512,7 @@ public int GetHashCode(Symbol member) } if (_considerReturnType && member.GetMemberArity() == 0 && - (_typeComparison & TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds) == 0) // If it is generic, then type argument might be in return type. + (_typeComparison & TypeCompareKind.AllIgnoreOptions) == 0) // If it is generic, then type argument might be in return type. { hash = Hash.Combine(member.GetTypeOrReturnType().GetHashCode(), hash); } @@ -638,7 +638,7 @@ public static bool HaveSameConstraints(TypeParameterSymbol typeParameter1, TypeM return false; } - return HaveSameTypeConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2, TypeSymbol.EqualsIgnoringDynamicAndTupleNamesComparer); + return HaveSameTypeConstraints(typeParameter1, typeMap1, typeParameter2, typeMap2, TypeSymbol.EqualsIgnoringDynamicTupleNamesAndNullabilityComparer); } private static bool HaveSameTypeConstraints(TypeParameterSymbol typeParameter1, TypeMap typeMap1, TypeParameterSymbol typeParameter2, TypeMap typeMap2, EqualityComparer comparer) diff --git a/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/MetadataDecoder.cs b/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/MetadataDecoder.cs index d582ed8bbb64d..20efc3c035c76 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/MetadataDecoder.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/MetadataDecoder.cs @@ -515,8 +515,8 @@ internal override Symbol GetSymbolForMemberRef(MemberReferenceHandle memberRef, HashSet useSiteDiagnostics = null; if (scope != targetTypeSymbol && !(targetTypeSymbol.IsInterfaceType() - ? scope.AllInterfacesNoUseSiteDiagnostics.Contains((NamedTypeSymbol)targetTypeSymbol) - : scope.IsDerivedFrom(targetTypeSymbol, TypeCompareKind.ConsiderEverything, useSiteDiagnostics: ref useSiteDiagnostics))) + ? scope.AllInterfacesNoUseSiteDiagnostics.IndexOf((NamedTypeSymbol)targetTypeSymbol, 0, TypeSymbol.EqualsIgnoringNullableComparer) != -1 + : scope.IsDerivedFrom(targetTypeSymbol, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes, useSiteDiagnostics: ref useSiteDiagnostics))) { return null; } diff --git a/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PEFieldSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PEFieldSymbol.cs index c6f59804d5a6f..9cfe239476a88 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PEFieldSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Metadata/PE/PEFieldSymbol.cs @@ -273,7 +273,7 @@ internal override TypeSymbolWithAnnotations GetFieldType(ConsList f return _lazyType.ToType(); } - public override bool IsFixed + public override bool IsFixedSizeBuffer { get { diff --git a/src/Compilers/CSharp/Portable/Symbols/NamedTypeSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/NamedTypeSymbol.cs index 2c8eff92257ff..db8d6cb9f5375 100644 --- a/src/Compilers/CSharp/Portable/Symbols/NamedTypeSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/NamedTypeSymbol.cs @@ -684,7 +684,7 @@ internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) } if ((thisIsOriginalDefinition || otherIsOriginalDefinition) && - (comparison & (TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.CompareNullableModifiersForReferenceTypes)) == TypeCompareKind.CompareNullableModifiersForReferenceTypes) + (comparison & (TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.AllNullableIgnoreOptions)) == 0) { return false; } @@ -733,7 +733,7 @@ private bool EqualsComplicatedCases(NamedTypeSymbol other, TypeCompareKind compa } if ((thisIsNotConstructed || otherIsNotConstructed) && - (comparison & (TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.CompareNullableModifiersForReferenceTypes)) == TypeCompareKind.CompareNullableModifiersForReferenceTypes) + (comparison & (TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.AllNullableIgnoreOptions)) == 0) { return false; } @@ -849,7 +849,7 @@ internal override TypeSymbol SetUnknownNullabilityForReferenceTypes() internal override TypeSymbol MergeNullability(TypeSymbol other, VarianceKind variance, out bool hadNullabilityMismatch) { - Debug.Assert(this.Equals(other, TypeCompareKind.IgnoreDynamicAndTupleNames)); + Debug.Assert(this.Equals(other, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); if (!IsGenericType) { @@ -892,7 +892,7 @@ private static bool MergeTypeArgumentNullability( out bool hadNullabilityMismatch) { Debug.Assert(typeA.IsGenericType); - Debug.Assert(typeA.Equals(typeB, TypeCompareKind.IgnoreDynamicAndTupleNames)); + Debug.Assert(typeA.Equals(typeB, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); hadNullabilityMismatch = false; diff --git a/src/Compilers/CSharp/Portable/Symbols/PointerTypeSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/PointerTypeSymbol.cs index da043006d9000..cabc47f1402da 100644 --- a/src/Compilers/CSharp/Portable/Symbols/PointerTypeSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/PointerTypeSymbol.cs @@ -276,7 +276,7 @@ internal override TypeSymbol SetUnknownNullabilityForReferenceTypes() internal override TypeSymbol MergeNullability(TypeSymbol other, VarianceKind variance, out bool hadNullabilityMismatch) { - Debug.Assert(this.Equals(other, TypeCompareKind.IgnoreDynamicAndTupleNames)); + Debug.Assert(this.Equals(other, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); TypeSymbolWithAnnotations pointedAtType = PointedAtType.MergeNullability(((PointerTypeSymbol)other).PointedAtType, VarianceKind.None, out hadNullabilityMismatch); return WithPointedAtType(pointedAtType); } diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/CustomModifierUtils.cs b/src/Compilers/CSharp/Portable/Symbols/Source/CustomModifierUtils.cs index 94bd4c929af47..5658a163d6df3 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/CustomModifierUtils.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/CustomModifierUtils.cs @@ -78,7 +78,7 @@ internal static TypeSymbol CopyTypeCustomModifiers(TypeSymbol sourceType, TypeSy TypeSymbol typeWithDynamic = DynamicTypeDecoder.TransformTypeWithoutCustomModifierFlags(sourceType, containingAssembly, refKind, flags); TypeSymbol resultType; - if (destinationType.ContainsTuple() && !sourceType.Equals(destinationType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreDynamic)) + if (destinationType.ContainsTuple() && !sourceType.Equals(destinationType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamic)) { // We also preserve tuple names, if present and different ImmutableArray names = CSharpCompilation.TupleNamesEncoder.Encode(destinationType); @@ -101,10 +101,10 @@ internal static TypeSymbol CopyTypeCustomModifiers(TypeSymbol sourceType, TypeSy bool transformResult = resultType.ApplyNullableTransforms(flagsBuilder.ToImmutableAndFree(), nonNullTypesContext, ref position, out resultType); Debug.Assert(transformResult && position == length); - Debug.Assert(resultType.Equals(sourceType, TypeCompareKind.IgnoreDynamicAndTupleNames)); // Same custom modifiers as source type. - // Note: We would want to check nullability, but that would pull on NonNullTypes too early (ie. cause cycles). + Debug.Assert(resultType.Equals(sourceType, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); // Same custom modifiers as source type. + Debug.Assert(resultType.Equals(destinationType, - TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)); // Same object/dynamic and tuple names as destination type. + TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); // Same object/dynamic and tuple names as destination type. return resultType; } diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/FieldSymbolWithAttributesAndModifiers.cs b/src/Compilers/CSharp/Portable/Symbols/Source/FieldSymbolWithAttributesAndModifiers.cs index 962a644fc8afd..b7b5420157e53 100755 --- a/src/Compilers/CSharp/Portable/Symbols/Source/FieldSymbolWithAttributesAndModifiers.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/FieldSymbolWithAttributesAndModifiers.cs @@ -54,7 +54,7 @@ public sealed override bool IsConst public sealed override bool IsVolatile => (Modifiers & DeclarationModifiers.Volatile) != 0; - public sealed override bool IsFixed + public sealed override bool IsFixedSizeBuffer => (Modifiers & DeclarationModifiers.Fixed) != 0; /// diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceEnumConstantSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceEnumConstantSymbol.cs index 13df4f1b43453..9bed9037874ee 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceEnumConstantSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceEnumConstantSymbol.cs @@ -111,7 +111,7 @@ internal sealed override void ForceComplete(SourceLocation locationOpt, Cancella break; case CompletionPart.FixedSize: - Debug.Assert(!this.IsFixed); + Debug.Assert(!this.IsFixedSizeBuffer); state.NotePartComplete(CompletionPart.FixedSize); break; diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceEventSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceEventSymbol.cs index 3d2e602e62d41..5a12942208cf9 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceEventSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceEventSymbol.cs @@ -568,7 +568,7 @@ protected static void CopyEventCustomModifiers(EventSymbol eventWithCustomModifi // We do an extra check before copying the type to handle the case where the overriding // event (incorrectly) has a different type than the overridden event. In such cases, // we want to retain the original (incorrect) type to avoid hiding the type given in source. - if (type.TypeSymbol.Equals(overriddenEventType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreDynamic)) + if (type.TypeSymbol.Equals(overriddenEventType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamic)) { type = type.WithTypeAndModifiers(CustomModifierUtils.CopyTypeCustomModifiers(overriddenEventType, type.TypeSymbol, containingAssembly, nonNullTypesContext), eventWithCustomModifiers.Type.CustomModifiers); diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceFixedFieldSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceFixedFieldSymbol.cs index 3c2c61c1bb632..a9c607679f9d7 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceFixedFieldSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceFixedFieldSymbol.cs @@ -30,7 +30,7 @@ internal SourceFixedFieldSymbol( { // Checked in parser: a fixed field declaration requires a length in square brackets - Debug.Assert(this.IsFixed); + Debug.Assert(this.IsFixedSizeBuffer); } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder attributes) diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberContainerSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberContainerSymbol.cs index 3f637e54187ba..4a6edd640d076 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberContainerSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberContainerSymbol.cs @@ -596,7 +596,7 @@ private void NoteFieldDefinitions() foreach (var member in _lazyMembersAndInitializers.NonTypeNonIndexerMembers) { FieldSymbol field; - if (!member.IsFieldOrFieldLikeEvent(out field) || field.IsConst || field.IsFixed) + if (!member.IsFieldOrFieldLikeEvent(out field) || field.IsConst || field.IsFixedSizeBuffer) { continue; } diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberContainerSymbol_ImplementationChecks.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberContainerSymbol_ImplementationChecks.cs index 9a0e0a8417fdf..43bef68795f89 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberContainerSymbol_ImplementationChecks.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberContainerSymbol_ImplementationChecks.cs @@ -730,9 +730,7 @@ private static void CheckOverrideMember(Symbol overridingMember, OverriddenOrHid else if (((CSharpParseOptions)overridingMemberLocation.SourceTree?.Options)?.IsFeatureEnabled(MessageID.IDS_FeatureNullableReferenceTypes) == true && (compilation = overridingMember.DeclaringCompilation) != null && !overridingMemberType.Equals(overriddenProperty.Type, - TypeCompareKind.AllIgnoreOptions | - TypeCompareKind.CompareNullableModifiersForReferenceTypes | - TypeCompareKind.UnknownNullableModifierMatchesAny)) + TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInTypeOnOverride, overridingMemberLocation); } @@ -776,9 +774,7 @@ private static void CheckOverrideMember(Symbol overridingMember, OverriddenOrHid else if (((CSharpParseOptions)overridingMemberLocation.SourceTree?.Options)?.IsFeatureEnabled(MessageID.IDS_FeatureNullableReferenceTypes) == true && (compilation = overridingMember.DeclaringCompilation) != null && !overridingMemberType.Equals(overriddenEvent.Type, - TypeCompareKind.AllIgnoreOptions | - TypeCompareKind.CompareNullableModifiersForReferenceTypes | - TypeCompareKind.UnknownNullableModifierMatchesAny)) + TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInTypeOnOverride, overridingMemberLocation); } @@ -813,9 +809,7 @@ private static void CheckOverrideMember(Symbol overridingMember, OverriddenOrHid !overridingMember.IsImplicitlyDeclared && !overridingMember.IsAccessor() && (compilation = overridingMember.DeclaringCompilation) != null && !overridingMethod.ReturnType.Equals(overriddenMethod.ReturnType, - TypeCompareKind.AllIgnoreOptions | - TypeCompareKind.CompareNullableModifiersForReferenceTypes | - TypeCompareKind.UnknownNullableModifierMatchesAny)) + TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, overridingMemberLocation); } @@ -842,9 +836,7 @@ private static void CheckOverrideMember(Symbol overridingMember, OverriddenOrHid { var overridenParameterType = overriddenParameters[i].Type; if (!overridingParameters[i].Type.Equals(overridenParameterType, - TypeCompareKind.AllIgnoreOptions | - TypeCompareKind.CompareNullableModifiersForReferenceTypes | - TypeCompareKind.UnknownNullableModifierMatchesAny) && + TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes) && overridingParameters[i].Type.Equals(overridenParameterType, TypeCompareKind.AllIgnoreOptions)) { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, overridingMemberLocation, new FormattedSymbol(overridingParameters[i], SymbolDisplayFormat.ShortFormat)); diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberFieldSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberFieldSymbol.cs index 46648056971b3..a09913b3cbf2f 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberFieldSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberFieldSymbol.cs @@ -124,7 +124,7 @@ public override int FixedSize { get { - Debug.Assert(!this.IsFixed, "Subclasses representing fixed fields must override"); + Debug.Assert(!this.IsFixedSizeBuffer, "Subclasses representing fixed fields must override"); state.NotePartComplete(CompletionPart.FixedSize); return 0; } @@ -267,7 +267,7 @@ internal sealed override void ForceComplete(SourceLocation locationOpt, Cancella internal override NamedTypeSymbol FixedImplementationType(PEModuleBuilder emitModule) { - Debug.Assert(!this.IsFixed, "Subclasses representing fixed fields must override"); + Debug.Assert(!this.IsFixedSizeBuffer, "Subclasses representing fixed fields must override"); return null; } } @@ -487,7 +487,7 @@ internal sealed override TypeSymbolWithAnnotations GetFieldType(ConsList definitionParameters = definition.ConstructIfGeneric(implementation.TypeArguments).Parameters; for (int i = 0; i < implementationParameters.Length; i++) { - if (!implementationParameters[i].Type.Equals(definitionParameters[i].Type, TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes) && + if (!implementationParameters[i].Type.Equals(definitionParameters[i].Type, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions) && implementationParameters[i].Type.Equals(definitionParameters[i].Type, TypeCompareKind.AllIgnoreOptions)) { diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial, implementation.Locations[0], new FormattedSymbol(implementationParameters[i], SymbolDisplayFormat.ShortFormat)); diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertySymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertySymbol.cs index 1f57503d90e6b..6548d3f21cfa0 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertySymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourcePropertySymbol.cs @@ -271,7 +271,7 @@ private SourcePropertySymbol( // We do an extra check before copying the type to handle the case where the overriding // property (incorrectly) has a different type than the overridden property. In such cases, // we want to retain the original (incorrect) type to avoid hiding the type given in source. - if (type.TypeSymbol.Equals(overriddenPropertyType.TypeSymbol, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreDynamic)) + if (type.TypeSymbol.Equals(overriddenPropertyType.TypeSymbol, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes | TypeCompareKind.IgnoreDynamic)) { type = type.WithTypeAndModifiers( CustomModifierUtils.CopyTypeCustomModifiers(overriddenPropertyType.TypeSymbol, type.TypeSymbol, this.ContainingAssembly, nonNullTypesContext: this), diff --git a/src/Compilers/CSharp/Portable/Symbols/Source/SourceUserDefinedOperatorSymbolBase.cs b/src/Compilers/CSharp/Portable/Symbols/Source/SourceUserDefinedOperatorSymbolBase.cs index 19d20d0f924ea..25d5d69be297c 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Source/SourceUserDefinedOperatorSymbolBase.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Source/SourceUserDefinedOperatorSymbolBase.cs @@ -281,9 +281,11 @@ private void CheckUserDefinedConversionSignature(DiagnosticBag diagnostics) // SPEC: Either S0 or T0 is the class or struct type in which the operator // SPEC: declaration takes place. - if (source0.TupleUnderlyingTypeOrSelf() != this.ContainingType && target0.TupleUnderlyingTypeOrSelf() != this.ContainingType && + if (!source0.TupleUnderlyingTypeOrSelf().Equals(this.ContainingType, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes) && + !target0.TupleUnderlyingTypeOrSelf().Equals(this.ContainingType, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes) && // allow conversion between T and Nullable in declaration of Nullable - source != this.ContainingType && target != this.ContainingType) + !source.Equals(this.ContainingType, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes) && + !target.Equals(this.ContainingType, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { // CS0556: User-defined conversion must convert to or from the enclosing type diagnostics.Add(ErrorCode.ERR_ConversionNotInvolvingContainedType, this.Locations[0]); @@ -293,8 +295,8 @@ private void CheckUserDefinedConversionSignature(DiagnosticBag diagnostics) // SPEC: * S0 and T0 are different types: if ((ContainingType.SpecialType == SpecialType.System_Nullable_T) - ? source.Equals(target, TypeCompareKind.IgnoreTupleNames) - : source0.Equals(target0, TypeCompareKind.IgnoreTupleNames)) + ? source.Equals(target, TypeCompareKind.IgnoreTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes) + : source0.Equals(target0, TypeCompareKind.IgnoreTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { // CS0555: User-defined operator cannot take an object of the enclosing type // and convert to an object of the enclosing type @@ -373,7 +375,7 @@ private void CheckUserDefinedConversionSignature(DiagnosticBag diagnostics) TypeSymbol same; TypeSymbol different; - if (source0.Equals(this.ContainingType, TypeCompareKind.IgnoreTupleNames)) + if (source0.Equals(this.ContainingType, TypeCompareKind.IgnoreTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { same = source; different = target; @@ -394,12 +396,12 @@ private void CheckUserDefinedConversionSignature(DiagnosticBag diagnostics) HashSet useSiteDiagnostics = null; - if (same.IsDerivedFrom(different, TypeCompareKind.IgnoreTupleNames, useSiteDiagnostics: ref useSiteDiagnostics)) // tomat: ignoreDynamic should be true, but we don't want to introduce breaking change. See bug 605326. + if (same.IsDerivedFrom(different, TypeCompareKind.IgnoreTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes, useSiteDiagnostics: ref useSiteDiagnostics)) // tomat: ignoreDynamic should be true, but we don't want to introduce breaking change. See bug 605326. { // '{0}': user-defined conversions to or from a base class are not allowed diagnostics.Add(ErrorCode.ERR_ConversionWithBase, this.Locations[0], this); } - else if (different.IsDerivedFrom(same, TypeCompareKind.IgnoreTupleNames, useSiteDiagnostics: ref useSiteDiagnostics)) // tomat: ignoreDynamic should be true, but we don't want to introduce breaking change. See bug 605326. + else if (different.IsDerivedFrom(same, TypeCompareKind.IgnoreTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes, useSiteDiagnostics: ref useSiteDiagnostics)) // tomat: ignoreDynamic should be true, but we don't want to introduce breaking change. See bug 605326. { // '{0}': user-defined conversions to or from a derived class are not allowed diagnostics.Add(ErrorCode.ERR_ConversionWithDerived, this.Locations[0], this); @@ -414,7 +416,7 @@ private void CheckUnarySignature(DiagnosticBag diagnostics) // SPEC: A unary + - ! ~ operator must take a single parameter of type // SPEC: T or T? and can return any type. - if (this.ParameterTypes[0].TypeSymbol.StrippedType().TupleUnderlyingTypeOrSelf() != this.ContainingType) + if (!this.ParameterTypes[0].TypeSymbol.StrippedType().TupleUnderlyingTypeOrSelf().Equals(this.ContainingType, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { // The parameter of a unary operator must be the containing type diagnostics.Add(ErrorCode.ERR_BadUnaryOperatorSignature, this.Locations[0]); @@ -439,7 +441,7 @@ private void CheckTrueFalseSignature(DiagnosticBag diagnostics) diagnostics.Add(ErrorCode.ERR_OpTFRetType, this.Locations[0]); } - if (this.ParameterTypes[0].TypeSymbol.StrippedType().TupleUnderlyingTypeOrSelf() != this.ContainingType) + if (!this.ParameterTypes[0].TypeSymbol.StrippedType().TupleUnderlyingTypeOrSelf().Equals(this.ContainingType, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { // The parameter of a unary operator must be the containing type diagnostics.Add(ErrorCode.ERR_BadUnaryOperatorSignature, this.Locations[0]); @@ -489,12 +491,12 @@ private void CheckIncrementDecrementSignature(DiagnosticBag diagnostics) var parameterType = this.ParameterTypes[0].TypeSymbol; HashSet useSiteDiagnostics = null; - if (parameterType.StrippedType().TupleUnderlyingTypeOrSelf() != this.ContainingType) + if (!parameterType.StrippedType().TupleUnderlyingTypeOrSelf().Equals(this.ContainingType, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { // CS0559: The parameter type for ++ or -- operator must be the containing type diagnostics.Add(ErrorCode.ERR_BadIncDecSignature, this.Locations[0]); } - else if (!this.ReturnType.TypeSymbol.EffectiveTypeNoUseSiteDiagnostics.IsEqualToOrDerivedFrom(parameterType, TypeCompareKind.IgnoreTupleNames, useSiteDiagnostics: ref useSiteDiagnostics)) + else if (!this.ReturnType.TypeSymbol.EffectiveTypeNoUseSiteDiagnostics.IsEqualToOrDerivedFrom(parameterType, TypeCompareKind.IgnoreTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes, useSiteDiagnostics: ref useSiteDiagnostics)) { // CS0448: The return type for ++ or -- operator must match the parameter type // or be derived from the parameter type @@ -510,7 +512,7 @@ private void CheckShiftSignature(DiagnosticBag diagnostics) // SPEC: of which must have type T or T? and the second of which must // SPEC: have type int or int?, and can return any type. - if (this.ParameterTypes[0].TypeSymbol.StrippedType().TupleUnderlyingTypeOrSelf() != this.ContainingType || + if (!this.ParameterTypes[0].TypeSymbol.StrippedType().TupleUnderlyingTypeOrSelf().Equals(this.ContainingType, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes) || this.ParameterTypes[1].TypeSymbol.StrippedType().SpecialType != SpecialType.System_Int32) { // CS0546: The first operand of an overloaded shift operator must have the @@ -531,8 +533,8 @@ private void CheckBinarySignature(DiagnosticBag diagnostics) { // SPEC: A binary nonshift operator must take two parameters, at least // SPEC: one of which must have the type T or T?, and can return any type. - if (this.ParameterTypes[0].TypeSymbol.StrippedType().TupleUnderlyingTypeOrSelf() != this.ContainingType && - this.ParameterTypes[1].TypeSymbol.StrippedType().TupleUnderlyingTypeOrSelf() != this.ContainingType) + if (!this.ParameterTypes[0].TypeSymbol.StrippedType().TupleUnderlyingTypeOrSelf().Equals(this.ContainingType, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes) && + !this.ParameterTypes[1].TypeSymbol.StrippedType().TupleUnderlyingTypeOrSelf().Equals(this.ContainingType, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { // CS0563: One of the parameters of a binary operator must be the containing type diagnostics.Add(ErrorCode.ERR_BadBinaryOperatorSignature, this.Locations[0]); diff --git a/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedIntrinsicOperatorSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedIntrinsicOperatorSymbol.cs index b0c4ef5dd7abc..033342ba5e29a 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedIntrinsicOperatorSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedIntrinsicOperatorSymbol.cs @@ -18,17 +18,17 @@ internal sealed class SynthesizedIntrinsicOperatorSymbol : MethodSymbol public SynthesizedIntrinsicOperatorSymbol(TypeSymbol leftType, string name, TypeSymbol rightType, TypeSymbol returnType, bool isCheckedBuiltin) { - if (leftType.Equals(rightType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)) + if (leftType.Equals(rightType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { _containingType = leftType; } - else if (rightType.Equals(returnType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)) + else if (rightType.Equals(returnType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { _containingType = rightType; } else { - Debug.Assert(leftType.Equals(returnType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)); + Debug.Assert(leftType.Equals(returnType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); _containingType = leftType; } diff --git a/src/Compilers/CSharp/Portable/Symbols/Tuples/TupleTypeSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/Tuples/TupleTypeSymbol.cs index 9ee50e5c14a80..13feaadca1d23 100644 --- a/src/Compilers/CSharp/Portable/Symbols/Tuples/TupleTypeSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/Tuples/TupleTypeSymbol.cs @@ -1458,7 +1458,7 @@ internal override TypeSymbol SetUnknownNullabilityForReferenceTypes() internal override TypeSymbol MergeNullability(TypeSymbol other, VarianceKind variance, out bool hadNullabilityMismatch) { - Debug.Assert(this.Equals(other, TypeCompareKind.IgnoreDynamicAndTupleNames)); + Debug.Assert(this.Equals(other, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); var otherTuple = other as TupleTypeSymbol; if (otherTuple is null) { diff --git a/src/Compilers/CSharp/Portable/Symbols/TypeParameterSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/TypeParameterSymbol.cs index 80d165ab09c40..740c500f85406 100644 --- a/src/Compilers/CSharp/Portable/Symbols/TypeParameterSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/TypeParameterSymbol.cs @@ -684,7 +684,7 @@ internal override TypeSymbol SetUnknownNullabilityForReferenceTypes() internal override TypeSymbol MergeNullability(TypeSymbol other, VarianceKind variance, out bool hadNullabilityMismatch) { - Debug.Assert(this.Equals(other, TypeCompareKind.IgnoreDynamicAndTupleNames)); + Debug.Assert(this.Equals(other, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); hadNullabilityMismatch = false; return this; } diff --git a/src/Compilers/CSharp/Portable/Symbols/TypeSymbol.cs b/src/Compilers/CSharp/Portable/Symbols/TypeSymbol.cs index 24fcd1346d67d..b036fe1e073d7 100644 --- a/src/Compilers/CSharp/Portable/Symbols/TypeSymbol.cs +++ b/src/Compilers/CSharp/Portable/Symbols/TypeSymbol.cs @@ -108,20 +108,17 @@ private InterfaceInfo GetInterfaceInfo() internal static readonly EqualityComparer EqualsIgnoringTupleNames = new TypeSymbolComparer(TypeCompareKind.IgnoreTupleNames); + internal static readonly EqualityComparer EqualsIgnoringTupleNamesAndNullability = new TypeSymbolComparer(TypeCompareKind.IgnoreTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); + /// /// A comparer that treats dynamic and object as "the same" types, and also ignores tuple element names differences. /// - internal static readonly EqualityComparer EqualsIgnoringDynamicAndTupleNamesComparer = new TypeSymbolComparer(TypeCompareKind.IgnoreDynamicAndTupleNames); + internal static readonly EqualityComparer EqualsIgnoringDynamicTupleNamesAndNullabilityComparer = new TypeSymbolComparer(TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); - /// - /// A comparator that pays attention to nullable modifiers in addition to default behavior. - /// - internal static readonly EqualityComparer EqualsIncludingNullableComparer = new TypeSymbolComparer(TypeCompareKind.CompareNullableModifiersForReferenceTypes); + internal static readonly EqualityComparer EqualsIgnoringNullableComparer = new TypeSymbolComparer(TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); internal static readonly EqualityComparer EqualsAllIgnoreOptionsPlusNullableWithUnknownMatchesAnyComparer = - new TypeSymbolComparer(TypeCompareKind.AllIgnoreOptions | - TypeCompareKind.CompareNullableModifiersForReferenceTypes | - TypeCompareKind.UnknownNullableModifierMatchesAny); + new TypeSymbolComparer(TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); /// /// The original definition of this symbol. If this symbol is constructed from another @@ -360,7 +357,7 @@ protected virtual ImmutableArray GetAllInterfaces() protected virtual ImmutableArray MakeAllInterfaces() { var result = ArrayBuilder.GetInstance(); - var visited = new HashSet(EqualsIgnoringTupleNames); + var visited = new HashSet(EqualsIgnoringTupleNamesAndNullability); for (var baseType = this; !ReferenceEquals(baseType, null); baseType = baseType.BaseTypeNoUseSiteDiagnostics) { @@ -1161,9 +1158,7 @@ internal static void CheckNullableReferenceTypeMismatchOnImplementingMember(Symb TypeSymbolWithAnnotations implementedMemberType = implementedMember.GetTypeOrReturnType(); if (!implementingMemberType.Equals(implementedMemberType, - TypeCompareKind.AllIgnoreOptions | - TypeCompareKind.CompareNullableModifiersForReferenceTypes | - TypeCompareKind.UnknownNullableModifierMatchesAny) && + TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes) && implementingMemberType.Equals(implementedMemberType, TypeCompareKind.AllIgnoreOptions)) { diagnostics.Add(implementingMember.Kind == SymbolKind.Method ? @@ -1184,9 +1179,7 @@ internal static void CheckNullableReferenceTypeMismatchOnImplementingMember(Symb var implementedParameterType = implementedParameters[i].Type; if (!implementingParameters[i].Type.Equals(implementedParameterType, - TypeCompareKind.AllIgnoreOptions | - TypeCompareKind.CompareNullableModifiersForReferenceTypes | - TypeCompareKind.UnknownNullableModifierMatchesAny) && + TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes) && implementingParameters[i].Type.Equals(implementedParameterType, TypeCompareKind.AllIgnoreOptions)) { diagnostics.Add(isExplicit ? diff --git a/src/Compilers/CSharp/Portable/Symbols/TypeSymbolWithAnnotations.cs b/src/Compilers/CSharp/Portable/Symbols/TypeSymbolWithAnnotations.cs index 723852d5e40d8..6aeec3bb73c28 100644 --- a/src/Compilers/CSharp/Portable/Symbols/TypeSymbolWithAnnotations.cs +++ b/src/Compilers/CSharp/Portable/Symbols/TypeSymbolWithAnnotations.cs @@ -441,7 +441,7 @@ public bool Equals(TypeSymbolWithAnnotations other, TypeCompareKind comparison) return false; } - if ((comparison & TypeCompareKind.CompareNullableModifiersForReferenceTypes) != 0) + if ((comparison & TypeCompareKind.IgnoreNullableModifiersForReferenceTypes) == 0) { var thisIsNullable = IsNullable; var otherIsNullable = other.IsNullable; @@ -481,7 +481,7 @@ public override bool Equals(TypeSymbolWithAnnotations x, TypeSymbolWithAnnotatio { return y.IsNull; } - return x.Equals(y, TypeCompareKind.CompareNullableModifiersForReferenceTypes); + return x.Equals(y, TypeCompareKind.ConsiderEverything); } } @@ -524,7 +524,7 @@ internal TypeSymbolWithAnnotations SubstituteTypeCore(AbstractTypeMap typeMap, b Debug.Assert(newTypeWithModifiers.NonNullTypesContext.NonNullTypes == null); Debug.Assert(newTypeWithModifiers.CustomModifiers.IsEmpty); - if (typeSymbol.Equals(newTypeWithModifiers.TypeSymbol, TypeCompareKind.CompareNullableModifiersForReferenceTypes) && + if (typeSymbol.Equals(newTypeWithModifiers.TypeSymbol, TypeCompareKind.ConsiderEverything) && newCustomModifiers == CustomModifiers) { return this; // substitution had no effect on the type or modifiers @@ -770,7 +770,7 @@ public override int GetHashCode() { return 0; } - return Hash.Combine(TypeSymbol.GetHashCode(), IsAnnotated.GetHashCode()); + return TypeSymbol.GetHashCode(); } #pragma warning disable CS0809 @@ -1078,7 +1078,7 @@ internal override TypeSymbolWithAnnotations SubstituteType(TypeSymbolWithAnnotat var newUnderlying = _underlying.SubstituteTypeCore(typeMap, withTupleUnification); if (!newUnderlying.IsSameAs(this._underlying)) { - if ((newUnderlying.TypeSymbol.Equals(this._underlying.TypeSymbol, TypeCompareKind.CompareNullableModifiersForReferenceTypes) || + if ((newUnderlying.TypeSymbol.Equals(this._underlying.TypeSymbol, TypeCompareKind.ConsiderEverything) || newUnderlying.TypeSymbol is IndexedTypeParameterSymbolForOverriding) && newUnderlying.CustomModifiers.IsEmpty) { diff --git a/src/Compilers/CSharp/Portable/Symbols/TypeUnification.cs b/src/Compilers/CSharp/Portable/Symbols/TypeUnification.cs index 564414d9b2fbd..14b180383a9a8 100644 --- a/src/Compilers/CSharp/Portable/Symbols/TypeUnification.cs +++ b/src/Compilers/CSharp/Portable/Symbols/TypeUnification.cs @@ -28,7 +28,7 @@ public static bool CanUnify(TypeSymbol t1, TypeSymbol t2) var substituted1 = SubstituteAllTypeParameters(substitution, TypeSymbolWithAnnotations.Create(t1)); var substituted2 = SubstituteAllTypeParameters(substitution, TypeSymbolWithAnnotations.Create(t2)); - Debug.Assert(substituted1.TypeSymbol.Equals(substituted2.TypeSymbol, TypeCompareKind.IgnoreTupleNames)); + Debug.Assert(substituted1.TypeSymbol.Equals(substituted2.TypeSymbol, TypeCompareKind.IgnoreTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); Debug.Assert(substituted1.CustomModifiers.SequenceEqual(substituted2.CustomModifiers)); } #endif diff --git a/src/Compilers/CSharp/Test/CommandLine/CommandLineTests.cs b/src/Compilers/CSharp/Test/CommandLine/CommandLineTests.cs index ccd1a1af876c9..161381872f3e8 100644 --- a/src/Compilers/CSharp/Test/CommandLine/CommandLineTests.cs +++ b/src/Compilers/CSharp/Test/CommandLine/CommandLineTests.cs @@ -5041,7 +5041,7 @@ public class CS1698_a {} CleanupAllGeneratedFiles(cs1698.Path); } - [Fact] + [ConditionalFact(typeof(ClrOnly), Reason="https://github.com/dotnet/roslyn/issues/30926")] public void BinaryFileErrorTest() { var binaryPath = Temp.CreateFile().WriteAllBytes(TestResources.NetFX.v4_0_30319.mscorlib).Path; @@ -9852,7 +9852,7 @@ public void MissingCompilerAssembly() $"Could not load file or assembly '{typeof(ImmutableArray).Assembly.FullName}' or one of its dependencies. The system cannot find the file specified.", result.Output.Trim()); } - +#if NET472 [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void LoadingAnalyzerNetStandard13() { @@ -9860,7 +9860,7 @@ public void LoadingAnalyzerNetStandard13() var srcFileName = "src.cs"; var analyzerDir = Temp.CreateDirectory(); - var analyzerFile = analyzerDir.CreateFile(analyzerFileName).WriteAllBytes(CreateCSharpAnalyzerNetStandard13(Path.GetFileNameWithoutExtension(analyzerFileName))); + var analyzerFile = analyzerDir.CreateFile(analyzerFileName).WriteAllBytes(DesktopTestHelpers.CreateCSharpAnalyzerNetStandard13(Path.GetFileNameWithoutExtension(analyzerFileName))); var srcFile = analyzerDir.CreateFile(srcFileName).WriteAllText("public class C { }"); var result = ProcessUtilities.Run(s_CSharpCompilerExecutable, arguments: $"/nologo /t:library /analyzer:{analyzerFileName} {srcFileName}", workingDirectory: analyzerDir.Path); @@ -9869,198 +9869,7 @@ public void LoadingAnalyzerNetStandard13() Assert.Equal(0, result.ExitCode); } - - private static ImmutableArray CreateCSharpAnalyzerNetStandard13(string analyzerAssemblyName) - { - var minSystemCollectionsImmutableSource = @" -[assembly: System.Reflection.AssemblyVersion(""1.2.3.0"")] - -namespace System.Collections.Immutable -{ - public struct ImmutableArray - { - } -} -"; - - var minCodeAnalysisSource = @" -using System; - -[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] - -namespace Microsoft.CodeAnalysis.Diagnostics -{ - [AttributeUsage(AttributeTargets.Class)] - public sealed class DiagnosticAnalyzerAttribute : Attribute - { - public DiagnosticAnalyzerAttribute(string firstLanguage, params string[] additionalLanguages) {} - } - - public abstract class DiagnosticAnalyzer - { - public abstract System.Collections.Immutable.ImmutableArray SupportedDiagnostics { get; } - public abstract void Initialize(AnalysisContext context); - } - - public abstract class AnalysisContext - { - } -} - -namespace Microsoft.CodeAnalysis -{ - public sealed class DiagnosticDescriptor - { - } -} -"; - var minSystemCollectionsImmutableImage = CSharpCompilation.Create( - "System.Collections.Immutable", - new[] { SyntaxFactory.ParseSyntaxTree(minSystemCollectionsImmutableSource) }, - new[] { MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Runtime) }, - new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, cryptoPublicKey: TestResources.TestKeys.PublicKey_b03f5f7f11d50a3a)).EmitToArray(); - - var minSystemCollectionsImmutableRef = MetadataReference.CreateFromImage(minSystemCollectionsImmutableImage); - - var minCodeAnalysisImage = CSharpCompilation.Create( - "Microsoft.CodeAnalysis", - new[] { SyntaxFactory.ParseSyntaxTree(minCodeAnalysisSource) }, - new[] - { - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Runtime), - minSystemCollectionsImmutableRef - }, - new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, cryptoPublicKey: TestResources.TestKeys.PublicKey_31bf3856ad364e35)).EmitToArray(); - - var minCodeAnalysisRef = MetadataReference.CreateFromImage(minCodeAnalysisImage); - - var analyzerSource = @" -using System; -using System.Collections.ObjectModel; -using System.Collections.Immutable; -using System.ComponentModel; -using System.Diagnostics; -using System.Globalization; -using System.IO; -using System.IO.Compression; -using System.Net.Http; -using System.Net.Security; -using System.Net.Sockets; -using System.Reflection; -using System.Runtime.InteropServices; -using System.Runtime.Serialization; -using System.Security.AccessControl; -using System.Security.Cryptography; -using System.Security.Principal; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using System.Xml; -using System.Xml.Serialization; -using System.Xml.XPath; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.Win32.SafeHandles; - -[DiagnosticAnalyzer(""C#"")] -public class TestAnalyzer : DiagnosticAnalyzer -{ - public override ImmutableArray SupportedDiagnostics => throw new NotImplementedException(new[] - { - typeof(Win32Exception), // Microsoft.Win32.Primitives - typeof(AppContext), // System.AppContext - typeof(Console), // System.Console - typeof(ValueTuple), // System.ValueTuple - typeof(FileVersionInfo), // System.Diagnostics.FileVersionInfo - typeof(Process), // System.Diagnostics.Process - typeof(ChineseLunisolarCalendar), // System.Globalization.Calendars - typeof(ZipArchive), // System.IO.Compression - typeof(ZipFile), // System.IO.Compression.ZipFile - typeof(FileOptions), // System.IO.FileSystem - typeof(FileAttributes), // System.IO.FileSystem.Primitives - typeof(HttpClient), // System.Net.Http - typeof(AuthenticatedStream), // System.Net.Security - typeof(IOControlCode), // System.Net.Sockets - typeof(RuntimeInformation), // System.Runtime.InteropServices.RuntimeInformation - typeof(SerializationException), // System.Runtime.Serialization.Primitives - typeof(GenericIdentity), // System.Security.Claims - typeof(Aes), // System.Security.Cryptography.Algorithms - typeof(CspParameters), // System.Security.Cryptography.Csp - typeof(AsnEncodedData), // System.Security.Cryptography.Encoding - typeof(AsymmetricAlgorithm), // System.Security.Cryptography.Primitives - typeof(SafeX509ChainHandle), // System.Security.Cryptography.X509Certificates - typeof(IXmlLineInfo), // System.Xml.ReaderWriter - typeof(XmlNode), // System.Xml.XmlDocument - typeof(XPathDocument), // System.Xml.XPath - typeof(XDocumentExtensions), // System.Xml.XPath.XDocument - typeof(CodePagesEncodingProvider),// System.Text.Encoding.CodePages - typeof(ValueTask<>), // System.Threading.Tasks.Extensions - - // csc doesn't ship with facades for the following assemblies. - // Analyzers can't use them unless they carry the facade with them. - - // typeof(SafePipeHandle), // System.IO.Pipes - // typeof(StackFrame), // System.Diagnostics.StackTrace - // typeof(BindingFlags), // System.Reflection.TypeExtensions - // typeof(AccessControlActions), // System.Security.AccessControl - // typeof(SafeAccessTokenHandle), // System.Security.Principal.Windows - // typeof(Thread), // System.Threading.Thread - }.Length.ToString()); - - public override void Initialize(AnalysisContext context) - { - } -}"; - - var analyzerImage = CSharpCompilation.Create( - analyzerAssemblyName, - new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree(analyzerSource) }, - new MetadataReference[] - { - minCodeAnalysisRef, - minSystemCollectionsImmutableRef, - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.Microsoft_Win32_Primitives), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_AppContext), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Console), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard10.System_ValueTuple), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Diagnostics_FileVersionInfo), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Diagnostics_Process), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Diagnostics_StackTrace), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Globalization_Calendars), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_IO_Compression), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_IO_Compression_ZipFile), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_IO_FileSystem), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_IO_FileSystem_Primitives), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_IO_Pipes), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Net_Http), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Net_Security), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Net_Sockets), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Reflection_TypeExtensions), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Runtime), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard11.System_Runtime_InteropServices_RuntimeInformation), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Runtime_Serialization_Primitives), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Security_AccessControl), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Security_Claims), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Security_Cryptography_Algorithms), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Security_Cryptography_Csp), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Security_Cryptography_Encoding), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Security_Cryptography_Primitives), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Security_Cryptography_X509Certificates), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Security_Principal_Windows), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Threading_Thread), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard10.System_Threading_Tasks_Extensions), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Xml_ReaderWriter), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Xml_XmlDocument), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Xml_XPath), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Xml_XPath_XDocument), - MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Text_Encoding_CodePages) - }, - new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)).EmitToArray(); - - return analyzerImage; - } - - +#endif [WorkItem(406649, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=484417")] [ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")] public void MicrosoftDiaSymReaderNativeAltLoadPath() diff --git a/src/Compilers/CSharp/Test/Emit/Attributes/EmitTestStrongNameProvider.cs b/src/Compilers/CSharp/Test/Emit/Attributes/EmitTestStrongNameProvider.cs index befcdb409ab2b..f4a062527d609 100644 --- a/src/Compilers/CSharp/Test/Emit/Attributes/EmitTestStrongNameProvider.cs +++ b/src/Compilers/CSharp/Test/Emit/Attributes/EmitTestStrongNameProvider.cs @@ -1,5 +1,7 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +// The use of SigningTestHelpers makes this necessary for now. Fix is tracked by https://github.com/dotnet/roslyn/issues/25228 +#if NET472 using System; using System.Collections.Immutable; using System.IO; @@ -161,3 +163,4 @@ public static void Main(string[] args) { } } } } +#endif diff --git a/src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenAsyncIteratorTests.cs b/src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenAsyncIteratorTests.cs index 11d0bf1f3edde..af896e6e8f8ca 100644 --- a/src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenAsyncIteratorTests.cs +++ b/src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenAsyncIteratorTests.cs @@ -56,6 +56,252 @@ class C comp.VerifyEmitDiagnostics(expected); } + private CSharpCompilation CreateCompilationWithAsyncIterator(string source, CSharpCompilationOptions options = null) + => CreateCompilationWithTasksExtensions(new[] { source, s_common }, options: options); + + [Fact] + [WorkItem(30566, "https://github.com/dotnet/roslyn/issues/30566")] + public void AsyncIteratorBug30566() + { + var comp = CreateCompilationWithAsyncIterator(@" +using System; +class C +{ + public async System.Collections.Generic.IAsyncEnumerable M() + { + yield return await GetTemperatureAsync(); + yield return await GetTemperatureAsync(); + } + + private static Random CapturedRandom = new Random(); + + public async System.Threading.Tasks.Task GetTemperatureAsync() + { + await System.Threading.Tasks.Task.Delay(CapturedRandom.Next(1, 8)); + return CapturedRandom.Next(50, 100); + } +}"); + CompileAndVerify(comp); + } + + [Fact] + [WorkItem(30566, "https://github.com/dotnet/roslyn/issues/30566")] + public void YieldReturnAwait1() + { + var comp = CreateCompilationWithAsyncIterator(@" +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +class C +{ + public static async IAsyncEnumerable M() + { + yield return await Task.FromResult(2); + await Task.Delay(1); + yield return await Task.FromResult(8); + } + public static async Task Main(string[] args) + { + await foreach (var i in M()) + { + Console.WriteLine(i); + } + } +}", TestOptions.ReleaseExe); + var verifier = CompileAndVerify(comp, expectedOutput: @" +2 +8"); + } + + [Fact] + [WorkItem(30566, "https://github.com/dotnet/roslyn/issues/30566")] + public void YieldReturnAwait2() + { + var comp = CreateCompilationWithAsyncIterator(@" +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +class C +{ + public static async IAsyncEnumerable M(Task[]> arr) + { + foreach (var t in await arr) + { + yield return await t; + } + } + public static async Task Main(string[] args) + { + var arr = new Task[] { + Task.FromResult(2), + Task.FromResult(8) + }; + await foreach (var i in M(Task.FromResult(arr))) + { + Console.WriteLine(i); + } + } +}", TestOptions.ReleaseExe); + var verifier = CompileAndVerify(comp, expectedOutput: @" +2 +8"); + verifier.VerifyIL("C.d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" +{ + // Code size 362 (0x16a) + .maxstack 3 + .locals init (int V_0, + System.Threading.Tasks.Task[] V_1, + System.Runtime.CompilerServices.TaskAwaiter[]> V_2, + C.d__0 V_3, + int V_4, + System.Runtime.CompilerServices.TaskAwaiter V_5, + System.Exception V_6) + IL_0000: ldarg.0 + IL_0001: ldfld ""int C.d__0.<>1__state"" + IL_0006: stloc.0 + .try + { + IL_0007: ldloc.0 + IL_0008: switch ( + IL_0054, + IL_00cf, + IL_0112) + IL_0019: ldarg.0 + IL_001a: ldfld ""System.Threading.Tasks.Task[]> C.d__0.arr"" + IL_001f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter[]> System.Threading.Tasks.Task[]>.GetAwaiter()"" + IL_0024: stloc.2 + IL_0025: ldloca.s V_2 + IL_0027: call ""bool System.Runtime.CompilerServices.TaskAwaiter[]>.IsCompleted.get"" + IL_002c: brtrue.s IL_0070 + IL_002e: ldarg.0 + IL_002f: ldc.i4.0 + IL_0030: dup + IL_0031: stloc.0 + IL_0032: stfld ""int C.d__0.<>1__state"" + IL_0037: ldarg.0 + IL_0038: ldloc.2 + IL_0039: stfld ""System.Runtime.CompilerServices.TaskAwaiter[]> C.d__0.<>u__1"" + IL_003e: ldarg.0 + IL_003f: stloc.3 + IL_0040: ldarg.0 + IL_0041: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder C.d__0.<>t__builder"" + IL_0046: ldloca.s V_2 + IL_0048: ldloca.s V_3 + IL_004a: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted[]>, C.d__0>(ref System.Runtime.CompilerServices.TaskAwaiter[]>, ref C.d__0)"" + IL_004f: leave IL_0169 + IL_0054: ldarg.0 + IL_0055: ldfld ""System.Runtime.CompilerServices.TaskAwaiter[]> C.d__0.<>u__1"" + IL_005a: stloc.2 + IL_005b: ldarg.0 + IL_005c: ldflda ""System.Runtime.CompilerServices.TaskAwaiter[]> C.d__0.<>u__1"" + IL_0061: initobj ""System.Runtime.CompilerServices.TaskAwaiter[]>"" + IL_0067: ldarg.0 + IL_0068: ldc.i4.m1 + IL_0069: dup + IL_006a: stloc.0 + IL_006b: stfld ""int C.d__0.<>1__state"" + IL_0070: ldloca.s V_2 + IL_0072: call ""System.Threading.Tasks.Task[] System.Runtime.CompilerServices.TaskAwaiter[]>.GetResult()"" + IL_0077: stloc.1 + IL_0078: ldarg.0 + IL_0079: ldloc.1 + IL_007a: stfld ""System.Threading.Tasks.Task[] C.d__0.<>7__wrap1"" + IL_007f: ldarg.0 + IL_0080: ldc.i4.0 + IL_0081: stfld ""int C.d__0.<>7__wrap2"" + IL_0086: br IL_0120 + IL_008b: ldarg.0 + IL_008c: ldfld ""System.Threading.Tasks.Task[] C.d__0.<>7__wrap1"" + IL_0091: ldarg.0 + IL_0092: ldfld ""int C.d__0.<>7__wrap2"" + IL_0097: ldelem.ref + IL_0098: callvirt ""System.Runtime.CompilerServices.TaskAwaiter System.Threading.Tasks.Task.GetAwaiter()"" + IL_009d: stloc.s V_5 + IL_009f: ldloca.s V_5 + IL_00a1: call ""bool System.Runtime.CompilerServices.TaskAwaiter.IsCompleted.get"" + IL_00a6: brtrue.s IL_00ec + IL_00a8: ldarg.0 + IL_00a9: ldc.i4.1 + IL_00aa: dup + IL_00ab: stloc.0 + IL_00ac: stfld ""int C.d__0.<>1__state"" + IL_00b1: ldarg.0 + IL_00b2: ldloc.s V_5 + IL_00b4: stfld ""System.Runtime.CompilerServices.TaskAwaiter C.d__0.<>u__2"" + IL_00b9: ldarg.0 + IL_00ba: stloc.3 + IL_00bb: ldarg.0 + IL_00bc: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder C.d__0.<>t__builder"" + IL_00c1: ldloca.s V_5 + IL_00c3: ldloca.s V_3 + IL_00c5: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted, C.d__0>(ref System.Runtime.CompilerServices.TaskAwaiter, ref C.d__0)"" + IL_00ca: leave IL_0169 + IL_00cf: ldarg.0 + IL_00d0: ldfld ""System.Runtime.CompilerServices.TaskAwaiter C.d__0.<>u__2"" + IL_00d5: stloc.s V_5 + IL_00d7: ldarg.0 + IL_00d8: ldflda ""System.Runtime.CompilerServices.TaskAwaiter C.d__0.<>u__2"" + IL_00dd: initobj ""System.Runtime.CompilerServices.TaskAwaiter"" + IL_00e3: ldarg.0 + IL_00e4: ldc.i4.m1 + IL_00e5: dup + IL_00e6: stloc.0 + IL_00e7: stfld ""int C.d__0.<>1__state"" + IL_00ec: ldloca.s V_5 + IL_00ee: call ""int System.Runtime.CompilerServices.TaskAwaiter.GetResult()"" + IL_00f3: stloc.s V_4 + IL_00f5: ldarg.0 + IL_00f6: ldloc.s V_4 + IL_00f8: stfld ""int C.d__0.<>2__current"" + IL_00fd: ldarg.0 + IL_00fe: ldc.i4.2 + IL_00ff: stfld ""int C.d__0.<>1__state"" + IL_0104: ldarg.0 + IL_0105: ldflda ""System.Threading.Tasks.ManualResetValueTaskSourceLogic C.d__0.<>v__promiseOfValueOrEnd"" + IL_010a: ldc.i4.1 + IL_010b: call ""void System.Threading.Tasks.ManualResetValueTaskSourceLogic.SetResult(bool)"" + IL_0110: leave.s IL_0169 + IL_0112: ldarg.0 + IL_0113: ldarg.0 + IL_0114: ldfld ""int C.d__0.<>7__wrap2"" + IL_0119: ldc.i4.1 + IL_011a: add + IL_011b: stfld ""int C.d__0.<>7__wrap2"" + IL_0120: ldarg.0 + IL_0121: ldfld ""int C.d__0.<>7__wrap2"" + IL_0126: ldarg.0 + IL_0127: ldfld ""System.Threading.Tasks.Task[] C.d__0.<>7__wrap1"" + IL_012c: ldlen + IL_012d: conv.i4 + IL_012e: blt IL_008b + IL_0133: ldarg.0 + IL_0134: ldnull + IL_0135: stfld ""System.Threading.Tasks.Task[] C.d__0.<>7__wrap1"" + IL_013a: leave.s IL_0155 + } + catch System.Exception + { + IL_013c: stloc.s V_6 + IL_013e: ldarg.0 + IL_013f: ldc.i4.s -2 + IL_0141: stfld ""int C.d__0.<>1__state"" + IL_0146: ldarg.0 + IL_0147: ldflda ""System.Threading.Tasks.ManualResetValueTaskSourceLogic C.d__0.<>v__promiseOfValueOrEnd"" + IL_014c: ldloc.s V_6 + IL_014e: call ""void System.Threading.Tasks.ManualResetValueTaskSourceLogic.SetException(System.Exception)"" + IL_0153: leave.s IL_0169 + } + IL_0155: ldarg.0 + IL_0156: ldc.i4.s -2 + IL_0158: stfld ""int C.d__0.<>1__state"" + IL_015d: ldarg.0 + IL_015e: ldflda ""System.Threading.Tasks.ManualResetValueTaskSourceLogic C.d__0.<>v__promiseOfValueOrEnd"" + IL_0163: ldc.i4.0 + IL_0164: call ""void System.Threading.Tasks.ManualResetValueTaskSourceLogic.SetResult(bool)"" + IL_0169: ret +}"); + } + [Fact] public void AsyncIteratorInCSharp7_3() { diff --git a/src/Compilers/CSharp/Test/Emit/CodeGen/FixedSizeBufferTests.cs b/src/Compilers/CSharp/Test/Emit/CodeGen/FixedSizeBufferTests.cs index f27c2dcdd4a26..70344f7569b94 100644 --- a/src/Compilers/CSharp/Test/Emit/CodeGen/FixedSizeBufferTests.cs +++ b/src/Compilers/CSharp/Test/Emit/CodeGen/FixedSizeBufferTests.cs @@ -570,7 +570,7 @@ static void Main() var f = (FieldSymbol)comp2.GlobalNamespace.GetTypeMembers("S")[0].GetMembers("x")[0]; Assert.Equal("x", f.Name); - Assert.True(f.IsFixed); + Assert.True(f.IsFixedSizeBuffer); Assert.Equal("int*", f.Type.ToString()); Assert.Equal(10, f.FixedSize); } diff --git a/src/Compilers/CSharp/Test/Emit/Emit/NoPiaEmbedTypes.cs b/src/Compilers/CSharp/Test/Emit/Emit/NoPiaEmbedTypes.cs index 3d7bd77179bdc..50bb3b37f5a30 100644 --- a/src/Compilers/CSharp/Test/Emit/Emit/NoPiaEmbedTypes.cs +++ b/src/Compilers/CSharp/Test/Emit/Emit/NoPiaEmbedTypes.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -#if NET46 +#if NET472 using Microsoft.Cci; using Microsoft.CodeAnalysis.CSharp.Symbols; diff --git a/src/Compilers/CSharp/Test/Emit/Microsoft.CodeAnalysis.CSharp.Emit.UnitTests.csproj b/src/Compilers/CSharp/Test/Emit/Microsoft.CodeAnalysis.CSharp.Emit.UnitTests.csproj index 0d4f6ffefde82..1774fb693eb8f 100644 --- a/src/Compilers/CSharp/Test/Emit/Microsoft.CodeAnalysis.CSharp.Emit.UnitTests.csproj +++ b/src/Compilers/CSharp/Test/Emit/Microsoft.CodeAnalysis.CSharp.Emit.UnitTests.csproj @@ -35,7 +35,6 @@ - diff --git a/src/Compilers/CSharp/Test/Emit/PrivateProtected.cs b/src/Compilers/CSharp/Test/Emit/PrivateProtected.cs index 754a3d7f024de..8f7da5d025798 100644 --- a/src/Compilers/CSharp/Test/Emit/PrivateProtected.cs +++ b/src/Compilers/CSharp/Test/Emit/PrivateProtected.cs @@ -1,6 +1,6 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -#if NET46 +#if NET472 using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; diff --git a/src/Compilers/CSharp/Test/Semantic/Semantics/NullableReferenceTypesTests.cs b/src/Compilers/CSharp/Test/Semantic/Semantics/NullableReferenceTypesTests.cs index 752a6d35701f5..d5d2381a23d92 100644 --- a/src/Compilers/CSharp/Test/Semantic/Semantics/NullableReferenceTypesTests.cs +++ b/src/Compilers/CSharp/Test/Semantic/Semantics/NullableReferenceTypesTests.cs @@ -318,6 +318,144 @@ partial class C9 { } Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new C9()").WithArguments("C9", "Base", "b", "void Program.F(Base b)").WithLocation(18, 11)); } + [WorkItem(30840, "https://github.com/dotnet/roslyn/issues/30840")] + [Fact] + public void Directive_EnableAndDisable_01() + { + var source = +@"#nullable enable +class Program +{ + static void F(object x) + { + object? y = null; + F(y); // warning + } +#nullable disable + static void G() + { + F(null); + } +}"; + var comp = CreateCompilation(source); + comp.VerifyDiagnostics( + // (7,11): warning CS8604: Possible null reference argument for parameter 'x' in 'void Program.F(object x)'. + // F(y); // warning + Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("x", "void Program.F(object x)").WithLocation(7, 11)); + } + + [WorkItem(30840, "https://github.com/dotnet/roslyn/issues/30840")] + [Fact] + public void Directive_EnableAndDisable_02() + { + var source = +@"class Program +{ +#nullable disable + static void G() + { + F(null); + } +#nullable enable + static void F(object x) + { + object? y = null; + F(y); // warning + } +}"; + var comp = CreateCompilation(source); + comp.VerifyDiagnostics( + // (12,11): warning CS8604: Possible null reference argument for parameter 'x' in 'void Program.F(object x)'. + // F(y); // warning + Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("x", "void Program.F(object x)").WithLocation(12, 11)); + } + + [WorkItem(30840, "https://github.com/dotnet/roslyn/issues/30840")] + [Fact] + public void Directive_EnableAndDisable_03() + { + var source = +@"class Program +{ + static void F(object x) + { + object? y = null; + F(y); // warning + } +#nullable disable + static void G() + { + F(null); + } +}"; + var comp = CreateCompilation(source, options: WithNonNullTypesTrue()); + comp.VerifyDiagnostics( + // (6,11): warning CS8604: Possible null reference argument for parameter 'x' in 'void Program.F(object x)'. + // F(y); // warning + Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("x", "void Program.F(object x)").WithLocation(6, 11)); + } + + [WorkItem(30840, "https://github.com/dotnet/roslyn/issues/30840")] + [Fact] + public void Directive_EnableAndDisable_04() + { + var source = +@"class Program +{ + static void G() + { + F(null); + } +#nullable enable + static void F(object x) + { + object? y = null; + F(y); // warning + } +}"; + var comp = CreateCompilation(source, options: WithNonNullTypesFalse()); + comp.VerifyDiagnostics( + // (11,11): warning CS8604: Possible null reference argument for parameter 'x' in 'void Program.F(object x)'. + // F(y); // warning + Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("x", "void Program.F(object x)").WithLocation(11, 11)); + } + + [WorkItem(30862, "https://github.com/dotnet/roslyn/issues/30862")] + [Fact] + public void DirectiveDisableWarningEnable() + { + var source = +@"#nullable enable +class Program +{ + static void F(object x) + { + } +#nullable disable + static void F1(object? y, object? z) + { + F(y); +#pragma warning restore 8604 + F(z); // 1 + } + static void F2(object? w) + { + F(w); // 2 + } +}"; + var comp = CreateCompilation(source); + comp.VerifyDiagnostics( + // (8,26): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. + // static void F1(object? y, object? z) + Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 26), + // (8,37): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. + // static void F1(object? y, object? z) + Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 37), + // (14,26): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. + // static void F2(object? w) + Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(14, 26)); + } + [Fact, WorkItem(29318, "https://github.com/dotnet/roslyn/issues/29318")] public void IsOperatorOnNonNullExpression() { @@ -966,12 +1104,7 @@ class D3 ); var c3 = CreateCompilation(new[] { source }, options: WithNonNullTypesFalse()); - c3.VerifyDiagnostics(expectedDiagnostics - .Concat(new[] { - // (37,17): warning CS8602: Possible dereference of a null reference. - // void M4() { Event(new C()); } // warn 21 - Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "Event").WithLocation(37, 17) - }).ToArray()); + c3.VerifyDiagnostics(expectedDiagnostics); } [Fact] @@ -2495,8 +2628,8 @@ static void F(object o, D d) var comp2B = CreateCompilation(source2, references: new[] { ref0, ref1 }); comp2B.VerifyDiagnostics(); - var expectedDiagnostics = new[] - { + var comp2C = CreateCompilation(new[] { source2 }, options: WithNonNullTypesTrue(), references: new[] { ref0, ref1 }); + comp2C.VerifyDiagnostics( // (5,9): warning CS8602: Possible dereference of a null reference. // ((I)a).F(o).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((I)a).F(o)").WithLocation(5, 9), @@ -2514,13 +2647,10 @@ static void F(object o, D d) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((I)d).F(o)").WithLocation(19, 9), // (20,18): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // ((I)d).G(null).ToString(); - Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(20, 18) - }; - var comp2C = CreateCompilation(new[] { source2 }, options: WithNonNullTypesTrue(), references: new[] { ref0, ref1 }); - comp2C.VerifyDiagnostics(expectedDiagnostics); + Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(20, 18)); var comp2D = CreateCompilation(new[] { source2 }, options: WithNonNullTypesFalse(), references: new[] { ref0, ref1 }); - comp2D.VerifyDiagnostics(expectedDiagnostics); + comp2D.VerifyDiagnostics(); } [Fact] @@ -4081,6 +4211,7 @@ public void M2() ); } + [WorkItem(30840, "https://github.com/dotnet/roslyn/issues/30840")] [Fact] public void NonNullTypesFalse_Foreach() { @@ -4099,7 +4230,7 @@ public void M2() foreach (string? ns in NCollection()) // 1 { - ns /*T:string?*/ .ToString(); // 2 + ns /*T:string?*/ .ToString(); } foreach (var s1 in Collection()) @@ -4109,7 +4240,7 @@ public void M2() foreach (var ns1 in NCollection()) { - ns1 /*T:string?*/ .ToString(); // 3 + ns1 /*T:string?*/ .ToString(); } foreach (string s in FalseCollection()) @@ -4117,9 +4248,9 @@ public void M2() s /*T:string*/ .ToString(); } - foreach (string? ns in FalseNCollection()) // 4 + foreach (string? ns in FalseNCollection()) // 2 { - ns /*T:string?*/ .ToString(); // 5 + ns /*T:string?*/ .ToString(); } foreach (var s1 in FalseCollection()) @@ -4129,7 +4260,7 @@ public void M2() foreach (var ns1 in FalseNCollection()) { - ns1 /*T:string?*/ .ToString(); // 6 + ns1 /*T:string?*/ .ToString(); } } @@ -4143,7 +4274,7 @@ public void M2() string[] FalseCollection() => throw null; " + NonNullTypesOff() + @" - string?[] FalseNCollection() => throw null; // 7 + string?[] FalseNCollection() => throw null; // 3 } "; var compilation = CreateCompilation(new[] { source }, options: WithNonNullTypesTrue()); @@ -4151,26 +4282,14 @@ public void M2() compilation.VerifyTypes(); compilation.VerifyDiagnostics( // (60,11): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. - // string?[] FalseNCollection() => throw null; // 7 + // string?[] FalseNCollection() => throw null; // 3 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(60, 11), // (14,24): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // foreach (string? ns in NCollection()) // 1 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(14, 24), // (34,24): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. - // foreach (string? ns in FalseNCollection()) // 4 - Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(34, 24), - // (16,13): warning CS8602: Possible dereference of a null reference. - // ns /*T:string?*/ .ToString(); // 2 - Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns").WithLocation(16, 13), - // (26,13): warning CS8602: Possible dereference of a null reference. - // ns1 /*T:string?*/ .ToString(); // 3 - Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns1").WithLocation(26, 13), - // (36,13): warning CS8602: Possible dereference of a null reference. - // ns /*T:string?*/ .ToString(); // 5 - Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns").WithLocation(36, 13), - // (46,13): warning CS8602: Possible dereference of a null reference. - // ns1 /*T:string?*/ .ToString(); // 6 - Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns1").WithLocation(46, 13) + // foreach (string? ns in FalseNCollection()) // 2 + Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(34, 24) ); } @@ -4262,6 +4381,7 @@ public void M() ); } + [WorkItem(30840, "https://github.com/dotnet/roslyn/issues/30840")] [Fact] public void NonNullTypesFalse_OutVars() { @@ -4331,22 +4451,7 @@ public void M() Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 24), // (21,29): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // FalseNOut(out string? ns3); // 3 - Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(21, 29), - // (14,9): warning CS8602: Possible dereference of a null reference. - // ns2 /*T:string?*/ .ToString(); // 2 - Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns2").WithLocation(14, 9), - // (22,9): warning CS8602: Possible dereference of a null reference. - // ns3 /*T:string?*/ .ToString(); // 4 - Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns3").WithLocation(22, 9), - // (27,14): warning CS8600: Converting null literal or possible null value to non-nullable type. - // s4 = null; // 5 - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(27, 14), - // (30,9): warning CS8602: Possible dereference of a null reference. - // ns4 /*T:string?*/ .ToString(); // 6 - Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns4").WithLocation(30, 9), - // (38,9): warning CS8602: Possible dereference of a null reference. - // ns5 /*T:string?*/ .ToString(); // 7 - Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns5").WithLocation(38, 9) + Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(21, 29) ); } @@ -4440,6 +4545,7 @@ public class Base ); } + [WorkItem(30840, "https://github.com/dotnet/roslyn/issues/30840")] [Fact] public void NonNullTypesFalse_LocalDeclarations() { @@ -4456,23 +4562,23 @@ public void M() s2 = null; string? ns2 = NMethod(); // 1 - ns2 /*T:string?*/ .ToString(); // 2 + ns2 /*T:string?*/ .ToString(); ns2 = null; string s3 = FalseMethod(); s3 /*T:string*/ .ToString(); s3 = null; - string? ns3 = FalseNMethod(); // 3 - ns3 /*T:string?*/ .ToString(); // 4 + string? ns3 = FalseNMethod(); // 2 + ns3 /*T:string?*/ .ToString(); ns3 = null; var s4 = Method(); s4 /*T:string!*/ .ToString(); - s4 = null; // 5 + s4 = null; var ns4 = NMethod(); - ns4 /*T:string?*/ .ToString(); // 6 + ns4 /*T:string?*/ .ToString(); ns4 = null; var s5 = FalseMethod(); @@ -4480,7 +4586,7 @@ public void M() s5 = null; var ns5 = FalseNMethod(); - ns5 /*T:string?*/ .ToString(); // 7 + ns5 /*T:string?*/ .ToString(); ns5 = null; } } @@ -4496,7 +4602,7 @@ public class Base public string FalseMethod() => throw null; " + NonNullTypesOff() + @" - public string? FalseNMethod() => throw null; // 8 + public string? FalseNMethod() => throw null; // 3 } "; var compilation = CreateCompilation(new[] { source }); @@ -4504,29 +4610,14 @@ public class Base compilation.VerifyTypes(); compilation.VerifyDiagnostics( // (54,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. - // public string? FalseNMethod() => throw null; // 8 + // public string? FalseNMethod() => throw null; // 3 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(54, 18), // (13,15): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // string? ns2 = NMethod(); // 1 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 15), // (21,15): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. - // string? ns3 = FalseNMethod(); // 3 - Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(21, 15), - // (14,9): warning CS8602: Possible dereference of a null reference. - // ns2 /*T:string?*/ .ToString(); // 2 - Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns2").WithLocation(14, 9), - // (22,9): warning CS8602: Possible dereference of a null reference. - // ns3 /*T:string?*/ .ToString(); // 4 - Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns3").WithLocation(22, 9), - // (27,14): warning CS8600: Converting null literal or possible null value to non-nullable type. - // s4 = null; // 5 - Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(27, 14), - // (30,9): warning CS8602: Possible dereference of a null reference. - // ns4 /*T:string?*/ .ToString(); // 6 - Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns4").WithLocation(30, 9), - // (38,9): warning CS8602: Possible dereference of a null reference. - // ns5 /*T:string?*/ .ToString(); // 7 - Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns5").WithLocation(38, 9) + // string? ns3 = FalseNMethod(); // 2 + Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(21, 15) ); } @@ -4704,7 +4795,7 @@ public void M(T t, NT nt) { t.Item /*T:S*/ .ToString(); t.Item = null; - nt.Item /*T:S?*/ .ToString(); // warn 4 + nt.Item /*T:S?*/ .ToString(); nt.Item = null; } } @@ -4716,9 +4807,6 @@ public void M(T t, NT nt) // (23,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // where NT : List // warn 3 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(23, 22), - // (29,9): warning CS8602: Possible dereference of a null reference. - // nt.Item /*T:S?*/ .ToString(); // warn 4 - Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "nt.Item").WithLocation(29, 9), // (14,18): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // t.Item = null; // warn 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 18), @@ -5918,11 +6006,11 @@ void Dummy() foreach (string memberName in new[] { "E1", "E2" }) { var member = type.GetMember(memberName); - Assert.False(member.Type.Equals(member.OverriddenEvent.Type, TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + Assert.False(member.Type.Equals(member.OverriddenEvent.Type, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } var e3 = type.GetMember("E3"); - Assert.True(e3.Type.Equals(e3.OverriddenEvent.Type, TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + Assert.True(e3.Type.Equals(e3.OverriddenEvent.Type, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (string typeName in new[] { "A", "B1", "B2" }) @@ -5931,8 +6019,8 @@ void Dummy() foreach (var ev in type.GetMembers().OfType()) { - Assert.True(ev.Type.Equals(ev.AddMethod.Parameters.Last().Type, TypeCompareKind.CompareNullableModifiersForReferenceTypes)); - Assert.True(ev.Type.Equals(ev.RemoveMethod.Parameters.Last().Type, TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + Assert.True(ev.Type.Equals(ev.AddMethod.Parameters.Last().Type, TypeCompareKind.ConsiderEverything)); + Assert.True(ev.Type.Equals(ev.RemoveMethod.Parameters.Last().Type, TypeCompareKind.ConsiderEverything)); } } } @@ -6042,8 +6130,8 @@ public class B2 : A void verifyMethodMatchesOverridden(bool expectMatch, NamedTypeSymbol type, string methodName) { var member = type.GetMember(methodName); - Assert.Equal(expectMatch, member.ReturnType.Equals(member.OverriddenMethod.ReturnType, TypeCompareKind.CompareNullableModifiersForReferenceTypes)); - Assert.Equal(expectMatch, member.Parameters.Single().Type.Equals(member.OverriddenMethod.Parameters.Single().Type, TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + Assert.Equal(expectMatch, member.ReturnType.Equals(member.OverriddenMethod.ReturnType, TypeCompareKind.ConsiderEverything)); + Assert.Equal(expectMatch, member.Parameters.Single().Type.Equals(member.OverriddenMethod.Parameters.Single().Type, TypeCompareKind.ConsiderEverything)); } } @@ -6301,7 +6389,7 @@ void Dummy() var type = compilation.GetTypeByMetadataName(typeName); var impl = (EventSymbol)type.FindImplementationForInterfaceMember(member); - Assert.False(impl.Type.Equals(member.Type, TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + Assert.False(impl.Type.Equals(member.Type, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } } @@ -6312,7 +6400,7 @@ void Dummy() var type = compilation.GetTypeByMetadataName(typeName); var impl = (EventSymbol)type.FindImplementationForInterfaceMember(e3); - Assert.True(impl.Type.Equals(e3.Type, TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + Assert.True(impl.Type.Equals(e3.Type, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (string typeName in new[] { "IA", "B1", "B2" }) @@ -6321,8 +6409,8 @@ void Dummy() foreach (var ev in type.GetMembers().OfType()) { - Assert.True(ev.Type.Equals(ev.AddMethod.Parameters.Last().Type, TypeCompareKind.CompareNullableModifiersForReferenceTypes)); - Assert.True(ev.Type.Equals(ev.RemoveMethod.Parameters.Last().Type, TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + Assert.True(ev.Type.Equals(ev.AddMethod.Parameters.Last().Type, TypeCompareKind.ConsiderEverything)); + Assert.True(ev.Type.Equals(ev.RemoveMethod.Parameters.Last().Type, TypeCompareKind.ConsiderEverything)); } } } @@ -6403,13 +6491,13 @@ class B2 : IB var member = ia.GetMember(memberName); var impl = (EventSymbol)b1.FindImplementationForInterfaceMember(member); - Assert.False(impl.Type.Equals(member.Type, TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + Assert.False(impl.Type.Equals(member.Type, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } var e3 = ia.GetMember("E3"); { var impl = (EventSymbol)b1.FindImplementationForInterfaceMember(e3); - Assert.True(impl.Type.Equals(e3.Type, TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + Assert.True(impl.Type.Equals(e3.Type, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (string typeName in new[] { "IA", "B1" }) @@ -6418,8 +6506,8 @@ class B2 : IB foreach (var ev in type.GetMembers().OfType()) { - Assert.True(ev.Type.Equals(ev.AddMethod.Parameters.Last().Type, TypeCompareKind.CompareNullableModifiersForReferenceTypes)); - Assert.True(ev.Type.Equals(ev.RemoveMethod.Parameters.Last().Type, TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + Assert.True(ev.Type.Equals(ev.AddMethod.Parameters.Last().Type, TypeCompareKind.ConsiderEverything)); + Assert.True(ev.Type.Equals(ev.RemoveMethod.Parameters.Last().Type, TypeCompareKind.ConsiderEverything)); } } } @@ -6500,12 +6588,12 @@ public override string?[]? this[long x] // 3 foreach (var member in compilation.GetTypeByMetadataName("B1").GetMembers().OfType()) { - Assert.False(member.Type.Equals(member.OverriddenProperty.Type, TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + Assert.False(member.Type.Equals(member.OverriddenProperty.Type, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (var member in compilation.GetTypeByMetadataName("B2").GetMembers().OfType()) { - Assert.True(member.Type.Equals(member.OverriddenProperty.Type, TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + Assert.True(member.Type.Equals(member.OverriddenProperty.Type, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (string typeName in new[] { "A1", "B1", "A2", "B2" }) @@ -6514,8 +6602,8 @@ public override string?[]? this[long x] // 3 foreach (var property in type.GetMembers().OfType()) { - Assert.True(property.Type.Equals(property.GetMethod.ReturnType, TypeCompareKind.CompareNullableModifiersForReferenceTypes)); - Assert.True(property.Type.Equals(property.SetMethod.Parameters.Last().Type, TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + Assert.True(property.Type.Equals(property.GetMethod.ReturnType, TypeCompareKind.ConsiderEverything)); + Assert.True(property.Type.Equals(property.SetMethod.Parameters.Last().Type, TypeCompareKind.ConsiderEverything)); } } } @@ -6651,13 +6739,13 @@ public string?[]? this[long x] foreach (var member in compilation.GetTypeByMetadataName("IA").GetMembers().OfType()) { var impl = (PropertySymbol)b.FindImplementationForInterfaceMember(member); - Assert.False(impl.Type.Equals(member.Type, TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + Assert.False(impl.Type.Equals(member.Type, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (var member in compilation.GetTypeByMetadataName("IA2").GetMembers().OfType()) { var impl = (PropertySymbol)b.FindImplementationForInterfaceMember(member); - Assert.True(impl.Type.Equals(member.Type, TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + Assert.True(impl.Type.Equals(member.Type, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (string typeName in new[] { "IA", "IA2", "B" }) @@ -6666,8 +6754,8 @@ public string?[]? this[long x] foreach (var property in type.GetMembers().OfType()) { - Assert.True(property.Type.Equals(property.GetMethod.ReturnType, TypeCompareKind.CompareNullableModifiersForReferenceTypes)); - Assert.True(property.Type.Equals(property.SetMethod.Parameters.Last().Type, TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + Assert.True(property.Type.Equals(property.GetMethod.ReturnType, TypeCompareKind.ConsiderEverything)); + Assert.True(property.Type.Equals(property.SetMethod.Parameters.Last().Type, TypeCompareKind.ConsiderEverything)); } } } @@ -6742,13 +6830,13 @@ string[] IA.this[int x] // 1 foreach (var member in compilation.GetTypeByMetadataName("IA").GetMembers().OfType()) { var impl = (PropertySymbol)b.FindImplementationForInterfaceMember(member); - Assert.False(impl.Type.Equals(member.Type, TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + Assert.False(impl.Type.Equals(member.Type, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (var member in compilation.GetTypeByMetadataName("IA2").GetMembers().OfType()) { var impl = (PropertySymbol)b.FindImplementationForInterfaceMember(member); - Assert.True(impl.Type.Equals(member.Type, TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + Assert.True(impl.Type.Equals(member.Type, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (string typeName in new[] { "IA", "IA2", "B" }) @@ -6757,8 +6845,8 @@ string[] IA.this[int x] // 1 foreach (var property in type.GetMembers().OfType()) { - Assert.True(property.Type.Equals(property.GetMethod.ReturnType, TypeCompareKind.CompareNullableModifiersForReferenceTypes)); - Assert.True(property.Type.Equals(property.SetMethod.Parameters.Last().Type, TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + Assert.True(property.Type.Equals(property.GetMethod.ReturnType, TypeCompareKind.ConsiderEverything)); + Assert.True(property.Type.Equals(property.SetMethod.Parameters.Last().Type, TypeCompareKind.ConsiderEverything)); } } } @@ -6815,12 +6903,12 @@ class B : A { var member = b.GetMember(memberName); Assert.False(member.ReturnType.Equals(member.OverriddenMethod.ConstructIfGeneric(member.TypeParameters.SelectAsArray(t => TypeSymbolWithAnnotations.Create(t))).ReturnType, - TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } var m3 = b.GetMember("M3"); Assert.True(m3.ReturnType.Equals(m3.OverriddenMethod.ConstructIfGeneric(m3.TypeParameters.SelectAsArray(t => TypeSymbolWithAnnotations.Create(t))).ReturnType, - TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } [Fact] @@ -6935,7 +7023,7 @@ class B : IA var implementing = (MethodSymbol)b.FindImplementationForInterfaceMember(member); var implemented = member.ConstructIfGeneric(implementing.TypeParameters.SelectAsArray(t => TypeSymbolWithAnnotations.Create(t))); Assert.False(implementing.ReturnType.Equals(implemented.ReturnType, - TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } { @@ -6943,7 +7031,7 @@ class B : IA var implementing = (MethodSymbol)b.FindImplementationForInterfaceMember(member); var implemented = member.ConstructIfGeneric(implementing.TypeParameters.SelectAsArray(t => TypeSymbolWithAnnotations.Create(t))); Assert.True(implementing.ReturnType.Equals(implemented.ReturnType, - TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } } @@ -7003,7 +7091,7 @@ class B : IA var implementing = (MethodSymbol)b.FindImplementationForInterfaceMember(member); var implemented = member.ConstructIfGeneric(implementing.TypeParameters.SelectAsArray(t => TypeSymbolWithAnnotations.Create(t))); Assert.False(implementing.ReturnType.Equals(implemented.ReturnType, - TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } { @@ -7011,7 +7099,7 @@ class B : IA var implementing = (MethodSymbol)b.FindImplementationForInterfaceMember(member); var implemented = member.ConstructIfGeneric(implementing.TypeParameters.SelectAsArray(t => TypeSymbolWithAnnotations.Create(t))); Assert.True(implementing.ReturnType.Equals(implemented.ReturnType, - TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } } @@ -7173,12 +7261,12 @@ public override void M3(T?[]? x) { var member = b.GetMember(memberName); Assert.False(member.Parameters[0].Type.Equals(member.OverriddenMethod.ConstructIfGeneric(member.TypeParameters.SelectAsArray(t => TypeSymbolWithAnnotations.Create(t))).Parameters[0].Type, - TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } var m3 = b.GetMember("M3"); Assert.True(m3.Parameters[0].Type.Equals(m3.OverriddenMethod.ConstructIfGeneric(m3.TypeParameters.SelectAsArray(t => TypeSymbolWithAnnotations.Create(t))).Parameters[0].Type, - TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } [Fact] @@ -7396,7 +7484,7 @@ public void M3(T?[]? x) where T : class var implementing = (MethodSymbol)b.FindImplementationForInterfaceMember(member); var implemented = member.ConstructIfGeneric(implementing.TypeParameters.SelectAsArray(t => TypeSymbolWithAnnotations.Create(t))); Assert.False(implementing.Parameters[0].Type.Equals(implemented.Parameters[0].Type, - TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } { @@ -7404,7 +7492,7 @@ public void M3(T?[]? x) where T : class var implementing = (MethodSymbol)b.FindImplementationForInterfaceMember(member); var implemented = member.ConstructIfGeneric(implementing.TypeParameters.SelectAsArray(t => TypeSymbolWithAnnotations.Create(t))); Assert.True(implementing.Parameters[0].Type.Equals(implemented.Parameters[0].Type, - TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } } @@ -7459,7 +7547,7 @@ void IA.M3(T?[]? x) var implementing = (MethodSymbol)b.FindImplementationForInterfaceMember(member); var implemented = member.ConstructIfGeneric(implementing.TypeParameters.SelectAsArray(t => TypeSymbolWithAnnotations.Create(t))); Assert.False(implementing.Parameters[0].Type.Equals(implemented.Parameters[0].Type, - TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } { @@ -7467,7 +7555,7 @@ void IA.M3(T?[]? x) var implementing = (MethodSymbol)b.FindImplementationForInterfaceMember(member); var implemented = member.ConstructIfGeneric(implementing.TypeParameters.SelectAsArray(t => TypeSymbolWithAnnotations.Create(t))); Assert.True(implementing.Parameters[0].Type.Equals(implemented.Parameters[0].Type, - TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } } @@ -7535,13 +7623,13 @@ public override int this[string?[]? x] // 3 { foreach (var member in compilation.GetTypeByMetadataName(typeName).GetMembers().OfType()) { - Assert.False(member.Parameters[0].Type.Equals(member.OverriddenProperty.Parameters[0].Type, TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + Assert.False(member.Parameters[0].Type.Equals(member.OverriddenProperty.Parameters[0].Type, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } } foreach (var member in compilation.GetTypeByMetadataName("B3").GetMembers().OfType()) { - Assert.True(member.Parameters[0].Type.Equals(member.OverriddenProperty.Parameters[0].Type, TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + Assert.True(member.Parameters[0].Type.Equals(member.OverriddenProperty.Parameters[0].Type, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (string typeName in new[] { "A1", "A2", "A3", "B1", "B2", "B3" }) @@ -7550,8 +7638,8 @@ public override int this[string?[]? x] // 3 foreach (var property in type.GetMembers().OfType()) { - Assert.True(property.Type.Equals(property.GetMethod.ReturnType, TypeCompareKind.CompareNullableModifiersForReferenceTypes)); - Assert.True(property.Type.Equals(property.SetMethod.Parameters.Last().Type, TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + Assert.True(property.Type.Equals(property.GetMethod.ReturnType, TypeCompareKind.ConsiderEverything)); + Assert.True(property.Type.Equals(property.SetMethod.Parameters.Last().Type, TypeCompareKind.ConsiderEverything)); } } } @@ -7620,13 +7708,13 @@ public int this[string?[]? x] // 3 { var implemented = compilation.GetTypeByMetadataName(typeName[0]).GetMembers().OfType().Single(); var implementing = (PropertySymbol)compilation.GetTypeByMetadataName(typeName[1]).FindImplementationForInterfaceMember(implemented); - Assert.False(implementing.Parameters[0].Type.Equals(implemented.Parameters[0].Type, TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + Assert.False(implementing.Parameters[0].Type.Equals(implemented.Parameters[0].Type, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } { var implemented = compilation.GetTypeByMetadataName("IA3").GetMembers().OfType().Single(); var implementing = (PropertySymbol)compilation.GetTypeByMetadataName("B3").FindImplementationForInterfaceMember(implemented); - Assert.True(implementing.Parameters[0].Type.Equals(implemented.Parameters[0].Type, TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + Assert.True(implementing.Parameters[0].Type.Equals(implemented.Parameters[0].Type, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (string typeName in new[] { "IA1", "IA2", "IA3", "B1", "B2", "B3" }) @@ -7635,8 +7723,8 @@ public int this[string?[]? x] // 3 foreach (var property in type.GetMembers().OfType()) { - Assert.True(property.Type.Equals(property.GetMethod.ReturnType, TypeCompareKind.CompareNullableModifiersForReferenceTypes)); - Assert.True(property.Type.Equals(property.SetMethod.Parameters.Last().Type, TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + Assert.True(property.Type.Equals(property.GetMethod.ReturnType, TypeCompareKind.ConsiderEverything)); + Assert.True(property.Type.Equals(property.SetMethod.Parameters.Last().Type, TypeCompareKind.ConsiderEverything)); } } } @@ -7705,13 +7793,13 @@ int IA3.this[string?[]? x] // 3 { var implemented = compilation.GetTypeByMetadataName(typeName[0]).GetMembers().OfType().Single(); var implementing = (PropertySymbol)compilation.GetTypeByMetadataName(typeName[1]).FindImplementationForInterfaceMember(implemented); - Assert.False(implementing.Parameters[0].Type.Equals(implemented.Parameters[0].Type, TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + Assert.False(implementing.Parameters[0].Type.Equals(implemented.Parameters[0].Type, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } { var implemented = compilation.GetTypeByMetadataName("IA3").GetMembers().OfType().Single(); var implementing = (PropertySymbol)compilation.GetTypeByMetadataName("B3").FindImplementationForInterfaceMember(implemented); - Assert.True(implementing.Parameters[0].Type.Equals(implemented.Parameters[0].Type, TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + Assert.True(implementing.Parameters[0].Type.Equals(implemented.Parameters[0].Type, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (string typeName in new[] { "IA1", "IA2", "IA3", "B1", "B2", "B3" }) @@ -7720,8 +7808,8 @@ int IA3.this[string?[]? x] // 3 foreach (var property in type.GetMembers().OfType()) { - Assert.True(property.Type.Equals(property.GetMethod.ReturnType, TypeCompareKind.CompareNullableModifiersForReferenceTypes)); - Assert.True(property.Type.Equals(property.SetMethod.Parameters.Last().Type, TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + Assert.True(property.Type.Equals(property.GetMethod.ReturnType, TypeCompareKind.ConsiderEverything)); + Assert.True(property.Type.Equals(property.SetMethod.Parameters.Last().Type, TypeCompareKind.ConsiderEverything)); } } } @@ -7770,11 +7858,11 @@ partial void M1(T? x, T[]? y, System.Action z, System.Action?[]? u for (int i = 0; i < 3; i++) { Assert.False(m1Impl.Parameters[i].Type.Equals(m1Def.Parameters[i].Type, - TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } Assert.True(m1Impl.Parameters[3].Type.Equals(m1Def.Parameters[3].Type, - TypeCompareKind.AllIgnoreOptions | TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } [Fact] @@ -28663,6 +28751,7 @@ void Test23(CL0.CL1 c, Action x23) c.VerifyDiagnostics(expected); } + [WorkItem(30840, "https://github.com/dotnet/roslyn/issues/30840")] [Fact] public void NonNullTypes_03() { @@ -28766,31 +28855,7 @@ void Test23(CL0.CL1 c, Action x23) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(15, 27), // (8,38): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // void Test21(CL0.CL1 c, Action? x21) // 4 - Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 38), - // (17,18): warning CS8601: Possible null reference assignment. - // E1 = x11; // 2 - Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x11").WithLocation(17, 18), - // (22,19): hidden CS8607: Expression is probably never null. - // x12 = E1 ?? x12; // 3 - Diagnostic(ErrorCode.HDN_ExpressionIsProbablyNeverNull, "E1").WithLocation(22, 19), - // (10,20): warning CS8601: Possible null reference assignment. - // c.F1 = x21; // 5 - Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x21").WithLocation(10, 20), - // (11,20): warning CS8601: Possible null reference assignment. - // c.P1 = x21; // 6 - Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x21").WithLocation(11, 20), - // (12,18): warning CS8604: Possible null reference argument for parameter 'x3' in 'void CL1.M3(Action x3)'. - // c.M3(x21); // 7 - Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x21").WithArguments("x3", "void CL1.M3(Action x3)").WithLocation(12, 18), - // (17,19): hidden CS8607: Expression is probably never null. - // x22 = c.F1 ?? x22; // 8 - Diagnostic(ErrorCode.HDN_ExpressionIsProbablyNeverNull, "c.F1").WithLocation(17, 19), - // (18,19): hidden CS8607: Expression is probably never null. - // x22 = c.P1 ?? x22; // 9 - Diagnostic(ErrorCode.HDN_ExpressionIsProbablyNeverNull, "c.P1").WithLocation(18, 19), - // (19,19): hidden CS8607: Expression is probably never null. - // x22 = c.M1() ?? x22; // 10 - Diagnostic(ErrorCode.HDN_ExpressionIsProbablyNeverNull, "c.M1()").WithLocation(19, 19) + Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 38) ); CSharpCompilation c1 = CreateCompilation(new[] { lib }, @@ -28802,7 +28867,22 @@ void Test23(CL0.CL1 c, Action x23) var expectedDiagnostics = new[] { // (8,38): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // void Test21(CL0.CL1 c, Action? x21) // 4 - Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 38), + Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 38) + }; + + c = CreateCompilation(new[] { source2 }, new[] { c1.ToMetadataReference() }, + parseOptions: TestOptions.Regular8, + options: WithNonNullTypesFalse()); + + c.VerifyDiagnostics(expectedDiagnostics); + + c = CreateCompilation(new[] { source2 }, new[] { c1.EmitToImageReference() }, + parseOptions: TestOptions.Regular8, + options: WithNonNullTypesFalse()); + + c.VerifyDiagnostics(expectedDiagnostics); + + expectedDiagnostics = new[] { // (10,20): warning CS8601: Possible null reference assignment. // c.F1 = x21; // 5 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x21").WithLocation(10, 20), @@ -28820,22 +28900,32 @@ void Test23(CL0.CL1 c, Action x23) Diagnostic(ErrorCode.HDN_ExpressionIsProbablyNeverNull, "c.P1").WithLocation(18, 19), // (19,19): hidden CS8607: Expression is probably never null. // x22 = c.M1() ?? x22; // 10 - Diagnostic(ErrorCode.HDN_ExpressionIsProbablyNeverNull, "c.M1()").WithLocation(19, 19) + Diagnostic(ErrorCode.HDN_ExpressionIsProbablyNeverNull, "c.M1()").WithLocation(19, 19), + // (24,19): warning CS8600: Converting null literal or possible null value to non-nullable type. + // x23 = c.F2; + Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.F2").WithLocation(24, 19), + // (25,19): warning CS8600: Converting null literal or possible null value to non-nullable type. + // x23 = c.P2; + Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.P2").WithLocation(25, 19), + // (26,19): warning CS8600: Converting null literal or possible null value to non-nullable type. + // x23 = c.M2(); + Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.M2()").WithLocation(26, 19) }; c = CreateCompilation(new[] { source2 }, new[] { c1.ToMetadataReference() }, parseOptions: TestOptions.Regular8, - options: WithNonNullTypesFalse()); + options: WithNonNullTypesTrue()); c.VerifyDiagnostics(expectedDiagnostics); c = CreateCompilation(new[] { source2 }, new[] { c1.EmitToImageReference() }, parseOptions: TestOptions.Regular8, - options: WithNonNullTypesFalse()); + options: WithNonNullTypesTrue()); c.VerifyDiagnostics(expectedDiagnostics); } + [WorkItem(30840, "https://github.com/dotnet/roslyn/issues/30840")] [Fact] public void NonNullTypes_04() { @@ -28943,24 +29033,6 @@ void Test23(CL0.CL1 c, Action x23) // (20,19): hidden CS8607: Expression is probably never null. // x12 = E1 ?? x12; // 3 Diagnostic(ErrorCode.HDN_ExpressionIsProbablyNeverNull, "E1").WithLocation(20, 19), - // (11,20): warning CS8601: Possible null reference assignment. - // c.F1 = x21; // 5 - Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x21").WithLocation(11, 20), - // (12,20): warning CS8601: Possible null reference assignment. - // c.P1 = x21; // 6 - Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x21").WithLocation(12, 20), - // (13,18): warning CS8604: Possible null reference argument for parameter 'x3' in 'void CL1.M3(Action x3)'. - // c.M3(x21); // 7 - Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x21").WithArguments("x3", "void CL1.M3(Action x3)").WithLocation(13, 18), - // (18,19): hidden CS8607: Expression is probably never null. - // x22 = c.F1 ?? x22; // 8 - Diagnostic(ErrorCode.HDN_ExpressionIsProbablyNeverNull, "c.F1").WithLocation(18, 19), - // (19,19): hidden CS8607: Expression is probably never null. - // x22 = c.P1 ?? x22; // 9 - Diagnostic(ErrorCode.HDN_ExpressionIsProbablyNeverNull, "c.P1").WithLocation(19, 19), - // (20,19): hidden CS8607: Expression is probably never null. - // x22 = c.M1() ?? x22; // 10 - Diagnostic(ErrorCode.HDN_ExpressionIsProbablyNeverNull, "c.M1()").WithLocation(20, 19), // (25,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x13 = E2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "E2").WithLocation(25, 19) @@ -28976,25 +29048,7 @@ void Test23(CL0.CL1 c, Action x23) { // (9,38): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // void Test21(CL0.CL1 c, Action? x21) // 4 - Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(9, 38), - // (11,20): warning CS8601: Possible null reference assignment. - // c.F1 = x21; // 5 - Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x21").WithLocation(11, 20), - // (12,20): warning CS8601: Possible null reference assignment. - // c.P1 = x21; // 6 - Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x21").WithLocation(12, 20), - // (13,18): warning CS8604: Possible null reference argument for parameter 'x3' in 'void CL1.M3(Action x3)'. - // c.M3(x21); // 7 - Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x21").WithArguments("x3", "void CL1.M3(Action x3)").WithLocation(13, 18), - // (18,19): hidden CS8607: Expression is probably never null. - // x22 = c.F1 ?? x22; // 8 - Diagnostic(ErrorCode.HDN_ExpressionIsProbablyNeverNull, "c.F1").WithLocation(18, 19), - // (19,19): hidden CS8607: Expression is probably never null. - // x22 = c.P1 ?? x22; // 9 - Diagnostic(ErrorCode.HDN_ExpressionIsProbablyNeverNull, "c.P1").WithLocation(19, 19), - // (20,19): hidden CS8607: Expression is probably never null. - // x22 = c.M1() ?? x22; // 10 - Diagnostic(ErrorCode.HDN_ExpressionIsProbablyNeverNull, "c.M1()").WithLocation(20, 19) + Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(9, 38) }; c = CreateCompilation(new[] { source2 }, new[] { c1.ToMetadataReference() }, @@ -29010,6 +29064,7 @@ void Test23(CL0.CL1 c, Action x23) c.VerifyDiagnostics(expected); } + [WorkItem(30840, "https://github.com/dotnet/roslyn/issues/30840")] [Fact] public void NonNullTypes_05() { @@ -29119,24 +29174,6 @@ void Test23(CL0.CL1 c, Action x23) // (20,19): hidden CS8607: Expression is probably never null. // x12 = E1 ?? x12; // 3 Diagnostic(ErrorCode.HDN_ExpressionIsProbablyNeverNull, "E1").WithLocation(20, 19), - // (12,20): warning CS8601: Possible null reference assignment. - // c.F1 = x21; // 5 - Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x21").WithLocation(12, 20), - // (13,20): warning CS8601: Possible null reference assignment. - // c.P1 = x21; // 6 - Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x21").WithLocation(13, 20), - // (14,18): warning CS8604: Possible null reference argument for parameter 'x3' in 'void CL1.M3(Action x3)'. - // c.M3(x21); // 7 - Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x21").WithArguments("x3", "void CL1.M3(Action x3)").WithLocation(14, 18), - // (19,19): hidden CS8607: Expression is probably never null. - // x22 = c.F1 ?? x22; // 8 - Diagnostic(ErrorCode.HDN_ExpressionIsProbablyNeverNull, "c.F1").WithLocation(19, 19), - // (20,19): hidden CS8607: Expression is probably never null. - // x22 = c.P1 ?? x22; // 9 - Diagnostic(ErrorCode.HDN_ExpressionIsProbablyNeverNull, "c.P1").WithLocation(20, 19), - // (21,19): hidden CS8607: Expression is probably never null. - // x22 = c.M1() ?? x22; // 10 - Diagnostic(ErrorCode.HDN_ExpressionIsProbablyNeverNull, "c.M1()").WithLocation(21, 19), // (25,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x13 = E2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "E2").WithLocation(25, 19) @@ -29152,25 +29189,7 @@ void Test23(CL0.CL1 c, Action x23) { // (10,38): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // void Test21(CL0.CL1 c, Action? x21) // 4 - Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(10, 38), - // (12,20): warning CS8601: Possible null reference assignment. - // c.F1 = x21; // 5 - Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x21").WithLocation(12, 20), - // (13,20): warning CS8601: Possible null reference assignment. - // c.P1 = x21; // 6 - Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x21").WithLocation(13, 20), - // (14,18): warning CS8604: Possible null reference argument for parameter 'x3' in 'void CL1.M3(Action x3)'. - // c.M3(x21); // 7 - Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x21").WithArguments("x3", "void CL1.M3(Action x3)").WithLocation(14, 18), - // (19,19): hidden CS8607: Expression is probably never null. - // x22 = c.F1 ?? x22; // 8 - Diagnostic(ErrorCode.HDN_ExpressionIsProbablyNeverNull, "c.F1").WithLocation(19, 19), - // (20,19): hidden CS8607: Expression is probably never null. - // x22 = c.P1 ?? x22; // 9 - Diagnostic(ErrorCode.HDN_ExpressionIsProbablyNeverNull, "c.P1").WithLocation(20, 19), - // (21,19): hidden CS8607: Expression is probably never null. - // x22 = c.M1() ?? x22; // 10 - Diagnostic(ErrorCode.HDN_ExpressionIsProbablyNeverNull, "c.M1()").WithLocation(21, 19) + Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(10, 38) }; c = CreateCompilation(new[] { source2 }, new[] { c1.ToMetadataReference() }, @@ -31906,7 +31925,6 @@ internal void F() { } ); } - // https://github.com/dotnet/roslyn/issues/29902: Binder should report an error for `!!`. [Fact] [WorkItem(29902, "https://github.com/dotnet/roslyn/issues/29902")] public void SuppressNullableWarning_Multiple() @@ -31927,7 +31945,7 @@ static void G(string s) var comp = CreateCompilation( new[] { source }, options: WithNonNullTypesTrue(), parseOptions: TestOptions.Regular8); - comp.VerifyDiagnostics(/* ... */); + comp.VerifyDiagnostics(); } [Fact] @@ -51374,6 +51392,324 @@ public class EqualityComparer Assert.True(getDefault.IsDefinition); } + [Fact] + public void ExpressionTrees_ByRefDynamic() + { + string source = @" +using System; +using System.Linq.Expressions; + +class Program +{ + static void Main() + { + Expression> e = x => Goo(ref x); + } + + static void Goo(ref T x) { } +} +"; + CompileAndVerify(source, targetFramework: TargetFramework.StandardAndCSharp, options: WithNonNullTypesTrue()); + } + + [Fact] + [WorkItem(30677, "https://github.com/dotnet/roslyn/issues/30677")] + public void TestErrorsImplementingGenericNestedInterfaces_Explicit() + { + var text = @" +using System.Collections.Generic; +class Outer +{ + internal class Inner + { + protected internal interface Interface + { + T Property { set; } + void Method(T a, U[] b, List c, Dictionary d); + } + internal class Derived4 + { + internal class Derived5 : Outer.Inner.Interface + { + T Outer.Inner.Interface.Property + { + set { } + } + void Inner.Interface.Method(T a, U[] b, List c, Dictionary D) + { + } + } + internal class Derived6 : Outer.Inner.Interface + { + T Outer.Inner.Interface.Property + { + set { } + } + void Inner.Interface.Method(T a, U[] b, List c, Dictionary D) + { + } + } + } + } +} +"; + + // https://github.com/dotnet/roslyn/issues/30677 - The following errors are unexpected: + // (24,39): error CS0535: 'Outer.Inner.Derived4.Derived6' does not implement interface member 'Outer.Inner.Interface.Method(T, U[], List, Dictionary)' + // (20,22): error CS0540: 'Outer.Inner.Derived4.Derived5.Method(T, U[], List, Dictionary)': containing type does not implement interface 'Outer.Inner.Interface' + // (30,22): error CS0540: 'Outer.Inner.Derived4.Derived6.Outer.Inner.Interface.Method(T, U[], List, Dictionary)': containing type does not implement interface 'Outer.Inner.Interface' + CreateCompilation(text, options: WithNonNullTypesTrue()).VerifyDiagnostics( + // (14,39): error CS0535: 'Outer.Inner.Derived4.Derived5' does not implement interface member 'Outer.Inner.Interface.Method(T, U[], List, Dictionary)' + // internal class Derived5 : Outer.Inner.Interface + Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer.Inner.Interface").WithArguments("Outer.Inner.Derived4.Derived5", "Outer.Inner.Interface.Method(T, U[], System.Collections.Generic.List, System.Collections.Generic.Dictionary)").WithLocation(14, 39), + // (20,22): error CS0540: 'Outer.Inner.Derived4.Derived5.Method(T, U[], List, Dictionary)': containing type does not implement interface 'Outer.Inner.Interface' + // void Inner.Interface.Method(T a, U[] b, List c, Dictionary D) + Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Inner.Interface").WithArguments("Outer.Inner.Derived4.Derived5.Method(T, U[], System.Collections.Generic.List, System.Collections.Generic.Dictionary)", "Outer.Inner.Interface").WithLocation(20, 22), + // (20,47): error CS0539: 'Outer.Inner.Derived4.Derived5.Method(T, U[], List, Dictionary)' in explicit interface declaration is not a member of interface + // void Inner.Interface.Method(T a, U[] b, List c, Dictionary D) + Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Outer.Inner.Derived4.Derived5.Method(T, U[], System.Collections.Generic.List, System.Collections.Generic.Dictionary)").WithLocation(20, 47), + // (24,39): error CS0535: 'Outer.Inner.Derived4.Derived6' does not implement interface member 'Outer.Inner.Interface.Method(T, U[], List, Dictionary)' + // internal class Derived6 : Outer.Inner.Interface + Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer.Inner.Interface").WithArguments("Outer.Inner.Derived4.Derived6", "Outer.Inner.Interface.Method(T, U[], System.Collections.Generic.List, System.Collections.Generic.Dictionary)").WithLocation(24, 39), + // (30,22): error CS0540: 'Outer.Inner.Derived4.Derived6.Outer.Inner.Interface.Method(T, U[], List, Dictionary)': containing type does not implement interface 'Outer.Inner.Interface' + // void Inner.Interface.Method(T a, U[] b, List c, Dictionary D) + Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Inner.Interface").WithArguments("Outer.Inner.Derived4.Derived6.Outer.Inner.Interface.Method(T, U[], System.Collections.Generic.List, System.Collections.Generic.Dictionary)", "Outer.Inner.Interface").WithLocation(30, 22) + ); + } + + [Fact] + [WorkItem(30677, "https://github.com/dotnet/roslyn/issues/30677")] + public void TestErrorsImplementingGenericNestedInterfaces_Explicit_IncorrectPartialQualification() + { + var source = @" +using System.Collections.Generic; +class Outer +{ + internal class Inner + { + protected internal interface Interface + { + T Property { set; } + void Method(T a, U[] b, List c, Dictionary d); + } + internal class Derived3 : Interface + { + T Interface.Property + { + set { } + } + void Inner.Interface.Method(T a, U[] B, List C, Dictionary d) + { + } + } + } +} +"; + + // https://github.com/dotnet/roslyn/issues/30677 - Expect no errors + CreateCompilation(source, options: WithNonNullTypesTrue()).VerifyDiagnostics( + // (12,35): error CS0535: 'Outer.Inner.Derived3' does not implement interface member 'Outer.Inner.Interface.Method(T, U[], List, Dictionary)' + // internal class Derived3 : Interface + Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Interface").WithArguments("Outer.Inner.Derived3", "Outer.Inner.Interface.Method(T, U[], System.Collections.Generic.List, System.Collections.Generic.Dictionary)").WithLocation(12, 35), + // (18,18): error CS0540: 'Outer.Inner.Derived3.Outer.Inner.Interface.Method(T, U[], List, Dictionary)': containing type does not implement interface 'Outer.Inner.Interface' + // void Inner.Interface.Method(T a, U[] B, List C, Dictionary d) + Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "Inner.Interface").WithArguments("Outer.Inner.Derived3.Outer.Inner.Interface.Method(T, U[], System.Collections.Generic.List, System.Collections.Generic.Dictionary)", "Outer.Inner.Interface").WithLocation(18, 18) + ); + } + + [Fact] + public void WriteOfReadonlyStaticMemberOfAnotherInstantiation01() + { + var text = +@"public static class Goo +{ + static Goo() + { + Goo.Y = 3; + } + + public static int Y { get; } +}"; + CreateCompilation(text, options: WithNonNullTypesTrue(TestOptions.ReleaseDll)).VerifyDiagnostics(); + CreateCompilation(text, options: WithNonNullTypesTrue(TestOptions.ReleaseDll), parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyDiagnostics(); + } + + [Fact] + public void TestOverrideGenericMethodWithTypeParamDiffNameWithCustomModifiers() + { + var text = @" +namespace Metadata +{ + using System; + public class GD : Outer.Inner + { + public override void Method(string[] x, ulong[] y, X[] z) { Console.Write(""Hello {0}"", z.Length); } + + static void Main() + { + new GD().Method(null, null, new byte[] { 0, 127, 255 }); + } + } +} +"; + var verifier = CompileAndVerify( + text, + new[] { TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll }, + options: WithNonNullTypesTrue(TestOptions.ReleaseExe), + expectedOutput: @"Hello 3", + expectedSignatures: new[] + { + // The ILDASM output is following,and Roslyn handles it correctly. + // Verifier tool gives different output due to the limitation of Reflection + // @".method public hidebysig virtual instance System.Void Method(" + + // @"System.String modopt([mscorlib]System.Runtime.CompilerServices.IsConst)[] modopt([mscorlib]System.Runtime.CompilerServices.IsConst) x," + + // @"UInt64 modopt([mscorlib]System.Runtime.CompilerServices.IsConst)[] modopt([mscorlib]System.Runtime.CompilerServices.IsConst) y," + + // @"!!X modopt([mscorlib]System.Runtime.CompilerServices.IsConst)[] modopt([mscorlib]System.Runtime.CompilerServices.IsConst) z) cil managed") + Signature("Metadata.GD", "Method", + @".method public hidebysig virtual instance System.Void Method(" + + @"modopt(System.Runtime.CompilerServices.IsConst) System.String[] x, " + + @"modopt(System.Runtime.CompilerServices.IsConst) System.UInt64[] y, modopt(System.Runtime.CompilerServices.IsConst) X[] z) cil managed"), + }); + } + + [Fact(Skip = "https://github.com/dotnet/roslyn/issues/30747 Type load failed.")] + [WorkItem(30747, "https://github.com/dotnet/roslyn/issues/30747")] + public void MissingTypeKindBasisTypes() + { + var source1 = @" +public struct A {} + +public enum B {} + +public class C {} +public delegate void D(); + +public interface I1 {} +"; + var compilation1 = CreateEmptyCompilation(source1, options: WithNonNullTypesTrue(TestOptions.ReleaseDll), references: new[] { MinCorlibRef }); + compilation1.VerifyEmitDiagnostics(); + + Assert.Equal(TypeKind.Struct, compilation1.GetTypeByMetadataName("A").TypeKind); + Assert.Equal(TypeKind.Enum, compilation1.GetTypeByMetadataName("B").TypeKind); + Assert.Equal(TypeKind.Class, compilation1.GetTypeByMetadataName("C").TypeKind); + Assert.Equal(TypeKind.Delegate, compilation1.GetTypeByMetadataName("D").TypeKind); + Assert.Equal(TypeKind.Interface, compilation1.GetTypeByMetadataName("I1").TypeKind); + + var source2 = @" +interface I2 +{ + I1 M(A a, B b, C c, D d); +} +"; + + var compilation2 = CreateEmptyCompilation(source2, options: WithNonNullTypesTrue(TestOptions.ReleaseDll), references: new[] { compilation1.EmitToImageReference(), MinCorlibRef }); + + compilation2.VerifyEmitDiagnostics(); + CompileAndVerify(compilation2); + + Assert.Equal(TypeKind.Struct, compilation2.GetTypeByMetadataName("A").TypeKind); + Assert.Equal(TypeKind.Enum, compilation2.GetTypeByMetadataName("B").TypeKind); + Assert.Equal(TypeKind.Class, compilation2.GetTypeByMetadataName("C").TypeKind); + Assert.Equal(TypeKind.Delegate, compilation2.GetTypeByMetadataName("D").TypeKind); + Assert.Equal(TypeKind.Interface, compilation2.GetTypeByMetadataName("I1").TypeKind); + + var compilation3 = CreateEmptyCompilation(source2, options: WithNonNullTypesTrue(TestOptions.ReleaseDll), references: new[] { compilation1.ToMetadataReference(), MinCorlibRef }); + + compilation3.VerifyEmitDiagnostics(); + CompileAndVerify(compilation3); + + Assert.Equal(TypeKind.Struct, compilation3.GetTypeByMetadataName("A").TypeKind); + Assert.Equal(TypeKind.Enum, compilation3.GetTypeByMetadataName("B").TypeKind); + Assert.Equal(TypeKind.Class, compilation3.GetTypeByMetadataName("C").TypeKind); + Assert.Equal(TypeKind.Delegate, compilation3.GetTypeByMetadataName("D").TypeKind); + Assert.Equal(TypeKind.Interface, compilation3.GetTypeByMetadataName("I1").TypeKind); + + var compilation4 = CreateEmptyCompilation(source2, options: WithNonNullTypesTrue(TestOptions.ReleaseDll), references: new[] { compilation1.EmitToImageReference() }); + + compilation4.VerifyDiagnostics( + // (4,10): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2'. + // I1 M(A a, B b, C c, D d); + Diagnostic(ErrorCode.ERR_NoTypeDef, "A").WithArguments("System.ValueType", "mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(4, 10), + // (4,15): error CS0012: The type 'Enum' is defined in an assembly that is not referenced. You must add a reference to assembly 'mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2'. + // I1 M(A a, B b, C c, D d); + Diagnostic(ErrorCode.ERR_NoTypeDef, "B").WithArguments("System.Enum", "mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(4, 15), + // (4,25): error CS0012: The type 'MulticastDelegate' is defined in an assembly that is not referenced. You must add a reference to assembly 'mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2'. + // I1 M(A a, B b, C c, D d); + Diagnostic(ErrorCode.ERR_NoTypeDef, "D").WithArguments("System.MulticastDelegate", "mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(4, 25) + ); + + var a = compilation4.GetTypeByMetadataName("A"); + var b = compilation4.GetTypeByMetadataName("B"); + var c = compilation4.GetTypeByMetadataName("C"); + var d = compilation4.GetTypeByMetadataName("D"); + var i1 = compilation4.GetTypeByMetadataName("I1"); + Assert.Equal(TypeKind.Class, a.TypeKind); + Assert.NotNull(a.GetUseSiteDiagnostic()); + Assert.Equal(TypeKind.Class, b.TypeKind); + Assert.NotNull(b.GetUseSiteDiagnostic()); + Assert.Equal(TypeKind.Class, c.TypeKind); + Assert.Null(c.GetUseSiteDiagnostic()); + Assert.Equal(TypeKind.Class, d.TypeKind); + Assert.NotNull(d.GetUseSiteDiagnostic()); + Assert.Equal(TypeKind.Interface, i1.TypeKind); + Assert.Null(i1.GetUseSiteDiagnostic()); + + var compilation5 = CreateEmptyCompilation(source2, options: WithNonNullTypesTrue(TestOptions.ReleaseDll), references: new[] { compilation1.ToMetadataReference() }); + + compilation5.VerifyEmitDiagnostics( + // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. + Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1) + ); + CompileAndVerify(compilation5); + + Assert.Equal(TypeKind.Struct, compilation5.GetTypeByMetadataName("A").TypeKind); + Assert.Equal(TypeKind.Enum, compilation5.GetTypeByMetadataName("B").TypeKind); + Assert.Equal(TypeKind.Class, compilation5.GetTypeByMetadataName("C").TypeKind); + Assert.Equal(TypeKind.Delegate, compilation5.GetTypeByMetadataName("D").TypeKind); + Assert.Equal(TypeKind.Interface, compilation5.GetTypeByMetadataName("I1").TypeKind); + + var compilation6 = CreateEmptyCompilation(source2, options: WithNonNullTypesTrue(TestOptions.ReleaseDll), references: new[] { compilation1.EmitToImageReference(), MscorlibRef }); + + compilation6.VerifyDiagnostics( + // (4,10): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2'. + // I1 M(A a, B b, C c, D d); + Diagnostic(ErrorCode.ERR_NoTypeDef, "A").WithArguments("System.ValueType", "mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(4, 10), + // (4,15): error CS0012: The type 'Enum' is defined in an assembly that is not referenced. You must add a reference to assembly 'mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2'. + // I1 M(A a, B b, C c, D d); + Diagnostic(ErrorCode.ERR_NoTypeDef, "B").WithArguments("System.Enum", "mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(4, 15), + // (4,25): error CS0012: The type 'MulticastDelegate' is defined in an assembly that is not referenced. You must add a reference to assembly 'mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2'. + // I1 M(A a, B b, C c, D d); + Diagnostic(ErrorCode.ERR_NoTypeDef, "D").WithArguments("System.MulticastDelegate", "mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(4, 25) + ); + + a = compilation6.GetTypeByMetadataName("A"); + b = compilation6.GetTypeByMetadataName("B"); + c = compilation6.GetTypeByMetadataName("C"); + d = compilation6.GetTypeByMetadataName("D"); + i1 = compilation6.GetTypeByMetadataName("I1"); + Assert.Equal(TypeKind.Class, a.TypeKind); + Assert.NotNull(a.GetUseSiteDiagnostic()); + Assert.Equal(TypeKind.Class, b.TypeKind); + Assert.NotNull(b.GetUseSiteDiagnostic()); + Assert.Equal(TypeKind.Class, c.TypeKind); + Assert.Null(c.GetUseSiteDiagnostic()); + Assert.Equal(TypeKind.Class, d.TypeKind); + Assert.NotNull(d.GetUseSiteDiagnostic()); + Assert.Equal(TypeKind.Interface, i1.TypeKind); + Assert.Null(i1.GetUseSiteDiagnostic()); + + var compilation7 = CreateEmptyCompilation(source2, options: WithNonNullTypesTrue(TestOptions.ReleaseDll), references: new[] { compilation1.ToMetadataReference(), MscorlibRef }); + + compilation7.VerifyEmitDiagnostics(); + CompileAndVerify(compilation7); + + Assert.Equal(TypeKind.Struct, compilation7.GetTypeByMetadataName("A").TypeKind); + Assert.Equal(TypeKind.Enum, compilation7.GetTypeByMetadataName("B").TypeKind); + Assert.Equal(TypeKind.Class, compilation7.GetTypeByMetadataName("C").TypeKind); + Assert.Equal(TypeKind.Delegate, compilation7.GetTypeByMetadataName("D").TypeKind); + Assert.Equal(TypeKind.Interface, compilation7.GetTypeByMetadataName("I1").TypeKind); + } + [Fact] public void AccessPropertyWithoutArguments() { diff --git a/src/Compilers/CSharp/Test/Semantic/Semantics/OperatorTests.cs b/src/Compilers/CSharp/Test/Semantic/Semantics/OperatorTests.cs index 87d5a4757feab..0601b614eeafa 100644 --- a/src/Compilers/CSharp/Test/Semantic/Semantics/OperatorTests.cs +++ b/src/Compilers/CSharp/Test/Semantic/Semantics/OperatorTests.cs @@ -6526,7 +6526,7 @@ bool Test(S1? s1) comp.VerifyDiagnostics(); var expectedOperator = comp.GlobalNamespace.GetMember("S1").GetMembers(WellKnownMemberNames.EqualityOperatorName). - OfType().Single(m => m.ParameterTypes[0].Equals(m.ParameterTypes[1], TypeCompareKind.CompareNullableModifiersForReferenceTypes)); + OfType().Single(m => m.ParameterTypes[0].Equals(m.ParameterTypes[1], TypeCompareKind.ConsiderEverything)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); diff --git a/src/Compilers/CSharp/Test/Symbol/Microsoft.CodeAnalysis.CSharp.Symbol.UnitTests.csproj b/src/Compilers/CSharp/Test/Symbol/Microsoft.CodeAnalysis.CSharp.Symbol.UnitTests.csproj index 5987e6f827e30..a96e49a95e424 100644 --- a/src/Compilers/CSharp/Test/Symbol/Microsoft.CodeAnalysis.CSharp.Symbol.UnitTests.csproj +++ b/src/Compilers/CSharp/Test/Symbol/Microsoft.CodeAnalysis.CSharp.Symbol.UnitTests.csproj @@ -26,8 +26,4 @@ - - - - \ No newline at end of file diff --git a/src/Compilers/CSharp/Test/Symbol/Symbols/Source/FieldTests.cs b/src/Compilers/CSharp/Test/Symbol/Symbols/Source/FieldTests.cs index 828e7c95344a8..756d408a6d7cb 100644 --- a/src/Compilers/CSharp/Test/Symbol/Symbols/Source/FieldTests.cs +++ b/src/Compilers/CSharp/Test/Symbol/Symbols/Source/FieldTests.cs @@ -489,5 +489,43 @@ static System.Action F() "Error: Field name value__ is reserved for Enums only.", "Error: Field name value__ is reserved for Enums only."); } + + [WorkItem(26364, "https://github.com/dotnet/roslyn/issues/26364")] + [Fact] + public void FixedSizeBufferTrue() + { + var text = +@" +unsafe struct S +{ + private fixed byte goo[10]; +} +"; + var comp = CreateEmptyCompilation(text); + var global = comp.GlobalNamespace; + var s = global.GetTypeMember("S"); + var goo = s.GetMember("goo"); + + Assert.True(goo.IsFixedSizeBuffer); + } + + [WorkItem(26364, "https://github.com/dotnet/roslyn/issues/26364")] + [Fact] + public void FixedSizeBufferFalse() + { + var text = +@" +unsafe struct S +{ + private byte goo; +} +"; + var comp = CreateEmptyCompilation(text); + var global = comp.GlobalNamespace; + var s = global.GetTypeMember("S"); + var goo = s.GetMember("goo"); + + Assert.False(goo.IsFixedSizeBuffer); + } } } diff --git a/src/Compilers/CSharp/Test/Symbol/Symbols/TypeTests.cs b/src/Compilers/CSharp/Test/Symbol/Symbols/TypeTests.cs index ac3177a395fa2..f4845b212bc20 100644 --- a/src/Compilers/CSharp/Test/Symbol/Symbols/TypeTests.cs +++ b/src/Compilers/CSharp/Test/Symbol/Symbols/TypeTests.cs @@ -1799,7 +1799,7 @@ class Goo { var Func_Dynamic = (Goo.GetMembers("Z")[0] as FieldSymbol).Type.TypeSymbol; var Func_Object = (Goo.GetMembers("W")[0] as FieldSymbol).Type.TypeSymbol; - var comparator = TypeSymbol.EqualsIgnoringDynamicAndTupleNamesComparer; + var comparator = TypeSymbol.EqualsIgnoringDynamicTupleNamesAndNullabilityComparer; Assert.NotEqual(Object, Dynamic); Assert.Equal(comparator.GetHashCode(Dynamic), comparator.GetHashCode(Object)); Assert.True(comparator.Equals(Dynamic, Object)); diff --git a/src/Compilers/CSharp/csc/App.config b/src/Compilers/CSharp/csc/App.config index 0b8bc41dc17f4..7472b129cb6f9 100644 --- a/src/Compilers/CSharp/csc/App.config +++ b/src/Compilers/CSharp/csc/App.config @@ -3,7 +3,7 @@ - + diff --git a/src/Compilers/CSharp/csc/Program.cs b/src/Compilers/CSharp/csc/Program.cs index 2edd734c18335..bdeeeca9d4144 100644 --- a/src/Compilers/CSharp/csc/Program.cs +++ b/src/Compilers/CSharp/csc/Program.cs @@ -25,7 +25,7 @@ public static int Main(string[] args) private static int MainCore(string[] args) { -#if NET46 +#if NET472 var loader = new DesktopAnalyzerAssemblyLoader(); #else var loader = new CoreClrAnalyzerAssemblyLoader(); diff --git a/src/Compilers/CSharp/csc/csc.csproj b/src/Compilers/CSharp/csc/csc.csproj index 81163b5895619..28318d26b3a77 100644 --- a/src/Compilers/CSharp/csc/csc.csproj +++ b/src/Compilers/CSharp/csc/csc.csproj @@ -55,7 +55,7 @@ - + PreserveNewest diff --git a/src/Compilers/Core/CodeAnalysisTest/AnalyzerFileReferenceTests.cs b/src/Compilers/Core/CodeAnalysisTest/AnalyzerFileReferenceTests.cs index edb0a72bc867e..df26e84848d56 100644 --- a/src/Compilers/Core/CodeAnalysisTest/AnalyzerFileReferenceTests.cs +++ b/src/Compilers/Core/CodeAnalysisTest/AnalyzerFileReferenceTests.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // This file references the DesktopAnalyzerAssemblyLoader, which is only present in desktop -#if NET46 +#if NET472 using System; using System.Collections.Generic; @@ -226,14 +226,14 @@ public class TestAnalyzer : DiagnosticAnalyzer var immutable = dir.CopyFile(typeof(ImmutableArray).Assembly.Location); var analyzer = dir.CopyFile(typeof(DiagnosticAnalyzer).Assembly.Location); var test = dir.CopyFile(typeof(FromFileLoader).Assembly.Location); - dir.CopyFile(Path.Combine(Path.GetDirectoryName(typeof(CSharp.CSharpCompilation).Assembly.Location), "System.IO.FileSystem.dll")); var analyzerCompilation = CSharp.CSharpCompilation.Create( "MyAnalyzer", new SyntaxTree[] { CSharp.SyntaxFactory.ParseSyntaxTree(analyzerSource) }, new MetadataReference[] { - TestReferences.NetStandard13.SystemRuntime, + TestReferences.NetStandard20.NetStandard, + TestReferences.NetStandard20.SystemRuntimeRef, MetadataReference.CreateFromFile(immutable.Path), MetadataReference.CreateFromFile(analyzer.Path) }, diff --git a/src/Compilers/Core/CodeAnalysisTest/DesktopAnalyzerAssemblyLoaderTests.cs b/src/Compilers/Core/CodeAnalysisTest/DesktopAnalyzerAssemblyLoaderTests.cs index 28dcd47d7731b..429bca3997447 100644 --- a/src/Compilers/Core/CodeAnalysisTest/DesktopAnalyzerAssemblyLoaderTests.cs +++ b/src/Compilers/Core/CodeAnalysisTest/DesktopAnalyzerAssemblyLoaderTests.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // The DesktopAnalyzerAssemblyLoader type is only present on desktop -#if NET46 +#if NET472 using System; using System.IO; diff --git a/src/Compilers/Core/CodeAnalysisTest/MetadataReferences/MetadataReferenceTests.cs b/src/Compilers/Core/CodeAnalysisTest/MetadataReferences/MetadataReferenceTests.cs index 0239bf1122ce6..1c3cab8c1bb87 100644 --- a/src/Compilers/Core/CodeAnalysisTest/MetadataReferences/MetadataReferenceTests.cs +++ b/src/Compilers/Core/CodeAnalysisTest/MetadataReferences/MetadataReferenceTests.cs @@ -20,7 +20,7 @@ namespace Microsoft.CodeAnalysis.UnitTests public class MetadataReferenceTests : TestBase { // Tests require AppDomains -#if NET46 +#if NET472 [Fact] public void CreateFromAssembly_NoMetadata() { diff --git a/src/Compilers/Core/CodeAnalysisTest/MetadataReferences/ModuleMetadataTests.cs b/src/Compilers/Core/CodeAnalysisTest/MetadataReferences/ModuleMetadataTests.cs index e3d4345837e36..486794b5ff4f8 100644 --- a/src/Compilers/Core/CodeAnalysisTest/MetadataReferences/ModuleMetadataTests.cs +++ b/src/Compilers/Core/CodeAnalysisTest/MetadataReferences/ModuleMetadataTests.cs @@ -83,9 +83,7 @@ public void CreateFromFile() Assert.Throws(() => ModuleMetadata.CreateFromFile(@"c:\*")); char systemDrive = Environment.GetFolderPath(Environment.SpecialFolder.Windows)[0]; - Assert.Throws(() => ModuleMetadata.CreateFromFile(@"http://goo.bar")); - Assert.Throws(() => ModuleMetadata.CreateFromFile(@"\\.\COM1")); - + Assert.Throws(() => ModuleMetadata.CreateFromFile(@"http://goo.bar")); Assert.Throws(() => ModuleMetadata.CreateFromFile(systemDrive + @":\file_that_does_not_exists.dll")); Assert.Throws(() => ModuleMetadata.CreateFromFile(systemDrive + @":\directory_that_does_not_exists\file_that_does_not_exists.dll")); Assert.Throws(() => ModuleMetadata.CreateFromFile(systemDrive + @":\" + new string('x', 1000))); diff --git a/src/Compilers/Core/MSBuildTask/Microsoft.Build.Tasks.CodeAnalysis.csproj b/src/Compilers/Core/MSBuildTask/Microsoft.Build.Tasks.CodeAnalysis.csproj index 87561dae688b0..b183e3c4dd19c 100644 --- a/src/Compilers/Core/MSBuildTask/Microsoft.Build.Tasks.CodeAnalysis.csproj +++ b/src/Compilers/Core/MSBuildTask/Microsoft.Build.Tasks.CodeAnalysis.csproj @@ -78,7 +78,6 @@ - diff --git a/src/Compilers/Core/MSBuildTaskTests/Microsoft.Build.Tasks.CodeAnalysis.UnitTests.csproj b/src/Compilers/Core/MSBuildTaskTests/Microsoft.Build.Tasks.CodeAnalysis.UnitTests.csproj index cf281c5b6454c..afa233aeb66e6 100644 --- a/src/Compilers/Core/MSBuildTaskTests/Microsoft.Build.Tasks.CodeAnalysis.UnitTests.csproj +++ b/src/Compilers/Core/MSBuildTaskTests/Microsoft.Build.Tasks.CodeAnalysis.UnitTests.csproj @@ -7,7 +7,7 @@ Library Microsoft.CodeAnalysis.BuildTasks.UnitTests true - net46 + net472 $(RoslynDesktopRuntimeIdentifier) UnitTest diff --git a/src/Compilers/Core/Portable/CommandLine/CommonCommandLineParser.cs b/src/Compilers/Core/Portable/CommandLine/CommonCommandLineParser.cs index af6a46b1e7dd4..178ba323bcd06 100644 --- a/src/Compilers/Core/Portable/CommandLine/CommonCommandLineParser.cs +++ b/src/Compilers/Core/Portable/CommandLine/CommonCommandLineParser.cs @@ -429,7 +429,7 @@ internal static bool TryParseClientArgs( { bool hasValue; string value; - if (IsClientArgsOption(arg, "/keepalive", out hasValue, out value)) + if (isClientArgsOption(arg, "keepalive", out hasValue, out value)) { if (string.IsNullOrEmpty(value)) { @@ -455,7 +455,7 @@ internal static bool TryParseClientArgs( continue; } - if (IsClientArgsOption(arg, "/shared", out hasValue, out value)) + if (isClientArgsOption(arg, "shared", out hasValue, out value)) { if (hasValue) { @@ -485,30 +485,36 @@ internal static bool TryParseClientArgs( parsedArgs = newArgs; return true; } - } - - internal static bool IsClientArgsOption(string arg, string optionName, out bool hasValue, out string optionValue) - { - hasValue = false; - optionValue = null; - if (!arg.StartsWith(optionName, StringComparison.OrdinalIgnoreCase)) + bool isClientArgsOption(string arg, string optionName, out bool hasValue, out string optionValue) { - return false; - } + hasValue = false; + optionValue = null; - if (arg.Length > optionName.Length && !(arg[optionName.Length] == ':' || arg[optionName.Length] == '=')) - { - return false; - } + if (arg.Length == 0 || !(arg[0] == '/' || arg[0] == '-')) + { + return false; + } + + arg = arg.Substring(1); + if (!arg.StartsWith(optionName, StringComparison.OrdinalIgnoreCase)) + { + return false; + } - if (arg.Length > optionName.Length) - { - hasValue = true; - optionValue = arg.Substring(optionName.Length + 1).Trim('"'); - } + if (arg.Length > optionName.Length) + { + if (!(arg[optionName.Length] == ':' || arg[optionName.Length] == '=')) + { + return false; + } - return true; + hasValue = true; + optionValue = arg.Substring(optionName.Length + 1).Trim('"'); + } + + return true; + } } internal static string MismatchedVersionErrorText => CodeAnalysisResources.MismatchedVersion; diff --git a/src/Compilers/Core/Portable/FileSystem/FileUtilities.cs b/src/Compilers/Core/Portable/FileSystem/FileUtilities.cs index 5ca6bdbebff30..cbfedf22b4ebc 100644 --- a/src/Compilers/Core/Portable/FileSystem/FileUtilities.cs +++ b/src/Compilers/Core/Portable/FileSystem/FileUtilities.cs @@ -405,13 +405,12 @@ internal static Stream OpenFileStream(string path) { throw; } - catch (IOException e) + catch (DirectoryNotFoundException e) + { + throw new FileNotFoundException(e.Message, path, e); + } + catch (IOException) { - if (e.GetType().Name == "DirectoryNotFoundException") - { - throw new FileNotFoundException(e.Message, path, e); - } - throw; } catch (Exception e) diff --git a/src/Compilers/Core/Portable/Microsoft.CodeAnalysis.csproj b/src/Compilers/Core/Portable/Microsoft.CodeAnalysis.csproj index b104ca537609a..513c2e340f950 100644 --- a/src/Compilers/Core/Portable/Microsoft.CodeAnalysis.csproj +++ b/src/Compilers/Core/Portable/Microsoft.CodeAnalysis.csproj @@ -7,7 +7,7 @@ Library Microsoft.CodeAnalysis true - netstandard1.3 + netstandard2.0 $(DefineConstants);COMPILERCORE ..\CodeAnalysisRules.ruleset true @@ -56,14 +56,10 @@ - - - - - + diff --git a/src/Compilers/Core/Portable/PublicAPI.Unshipped.txt b/src/Compilers/Core/Portable/PublicAPI.Unshipped.txt index a292f757d3041..c979701bfdb01 100644 --- a/src/Compilers/Core/Portable/PublicAPI.Unshipped.txt +++ b/src/Compilers/Core/Portable/PublicAPI.Unshipped.txt @@ -1,4 +1,5 @@ *REMOVED*Microsoft.CodeAnalysis.Operations.IEventAssignmentOperation.EventReference.get -> Microsoft.CodeAnalysis.Operations.IEventReferenceOperation +Microsoft.CodeAnalysis.IFieldSymbol.IsFixedSizeBuffer.get -> bool Microsoft.CodeAnalysis.OperationKind.Binary = 32 -> Microsoft.CodeAnalysis.OperationKind Microsoft.CodeAnalysis.OperationKind.ConstructorBody = 89 -> Microsoft.CodeAnalysis.OperationKind Microsoft.CodeAnalysis.OperationKind.FromEndIndex = 100 -> Microsoft.CodeAnalysis.OperationKind diff --git a/src/Compilers/Core/Portable/Symbols/IFieldSymbol.cs b/src/Compilers/Core/Portable/Symbols/IFieldSymbol.cs index 2d4d2cc66283e..d58abea7553ed 100644 --- a/src/Compilers/Core/Portable/Symbols/IFieldSymbol.cs +++ b/src/Compilers/Core/Portable/Symbols/IFieldSymbol.cs @@ -39,6 +39,13 @@ public interface IFieldSymbol : ISymbol /// bool IsVolatile { get; } + /// + /// Returns true if this field was declared as "fixed". + /// Note that for a fixed-size buffer declaration, this.Type will be a pointer type, of which + /// the pointed-to type will be the declared element type of the fixed-size buffer. + /// + bool IsFixedSizeBuffer { get; } + /// /// Gets the type of this field. /// diff --git a/src/Compilers/Core/Portable/Symbols/TypeCompareKind.cs b/src/Compilers/Core/Portable/Symbols/TypeCompareKind.cs index c0250a26151ed..ec31a54ad2558 100644 --- a/src/Compilers/Core/Portable/Symbols/TypeCompareKind.cs +++ b/src/Compilers/Core/Portable/Symbols/TypeCompareKind.cs @@ -16,34 +16,11 @@ internal enum TypeCompareKind IgnoreTupleNames = 4, IgnoreDynamicAndTupleNames = IgnoreDynamic | IgnoreTupleNames, - /// - /// Note: comparisons with nullability-related options pull on NonNullTypes, which can cause cycles. - /// - CompareNullableModifiersForReferenceTypes = 8, - - /// - /// Has no impact without CompareNullableModifiersForReferenceTypes. - /// + IgnoreNullableModifiersForReferenceTypes = 8, UnknownNullableModifierMatchesAny = 16, - AllIgnoreOptions = IgnoreCustomModifiersAndArraySizesAndLowerBounds | IgnoreDynamic | IgnoreTupleNames, - AllIgnoreOptionsForVB = IgnoreCustomModifiersAndArraySizesAndLowerBounds | IgnoreTupleNames - } - internal static class TypeCompareKindExtension - { - public static TypeCompareKind AddIgnoreCustomModifiersAndArraySizesAndLowerBounds(this TypeCompareKind self, bool condition) - { - return condition ? (self | TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds) : self; - } - - public static TypeCompareKind AddIgnoreDynamic(this TypeCompareKind self, bool condition) - { - return condition ? (self | TypeCompareKind.IgnoreDynamic) : self; - } - - public static TypeCompareKind AddIgnoreTupleNames(this TypeCompareKind self, bool condition) - { - return condition ? (self | TypeCompareKind.IgnoreTupleNames) : self; - } + AllNullableIgnoreOptions = IgnoreNullableModifiersForReferenceTypes | UnknownNullableModifierMatchesAny, + AllIgnoreOptions = IgnoreCustomModifiersAndArraySizesAndLowerBounds | IgnoreDynamic | IgnoreTupleNames | AllNullableIgnoreOptions, + AllIgnoreOptionsForVB = IgnoreCustomModifiersAndArraySizesAndLowerBounds | IgnoreTupleNames } } diff --git a/src/Compilers/Extension/AssemblyRedirects.cs b/src/Compilers/Extension/AssemblyRedirects.cs index 336b8b61fb85f..c653dd3701b06 100644 --- a/src/Compilers/Extension/AssemblyRedirects.cs +++ b/src/Compilers/Extension/AssemblyRedirects.cs @@ -5,18 +5,3 @@ [assembly: ProvideRoslynBindingRedirection("Microsoft.Build.Tasks.CodeAnalysis.dll")] [assembly: ProvideRoslynBindingRedirection("Roslyn.Compilers.Extension.dll")] - -[assembly: ProvideCodeBase(CodeBase = "$PackageFolder$\\System.AppContext.dll")] -[assembly: ProvideCodeBase(CodeBase = "$PackageFolder$\\System.Console.dll")] -[assembly: ProvideCodeBase(CodeBase = "$PackageFolder$\\System.Diagnostics.FileVersionInfo.dll")] -[assembly: ProvideCodeBase(CodeBase = "$PackageFolder$\\System.IO.Compression.dll")] -[assembly: ProvideCodeBase(CodeBase = "$PackageFolder$\\System.IO.FileSystem.dll")] -[assembly: ProvideCodeBase(CodeBase = "$PackageFolder$\\System.IO.FileSystem.Primitives.dll")] -[assembly: ProvideCodeBase(CodeBase = "$PackageFolder$\\System.Security.Cryptography.Algorithms.dll")] -[assembly: ProvideCodeBase(CodeBase = "$PackageFolder$\\System.Security.Cryptography.Encoding.dll")] -[assembly: ProvideCodeBase(CodeBase = "$PackageFolder$\\System.Security.Cryptography.Primitives.dll")] -[assembly: ProvideCodeBase(CodeBase = "$PackageFolder$\\System.Security.Cryptography.X509Certificates.dll")] -[assembly: ProvideCodeBase(CodeBase = "$PackageFolder$\\System.Text.Encoding.CodePages.dll")] -[assembly: ProvideCodeBase(CodeBase = "$PackageFolder$\\System.Xml.XmlDocument.dll")] -[assembly: ProvideCodeBase(CodeBase = "$PackageFolder$\\System.Xml.XPath.dll")] -[assembly: ProvideCodeBase(CodeBase = "$PackageFolder$\\System.Xml.XPath.XDocument.dll")] diff --git a/src/Compilers/Extension/Roslyn.Compilers.Extension.csproj b/src/Compilers/Extension/Roslyn.Compilers.Extension.csproj index 943ea5ba6ef9e..3f65a5aa8b280 100644 --- a/src/Compilers/Extension/Roslyn.Compilers.Extension.csproj +++ b/src/Compilers/Extension/Roslyn.Compilers.Extension.csproj @@ -6,7 +6,7 @@ AnyCPU Library Roslyn.Compilers.Extension - net46 + net472 Vsix @@ -30,51 +30,10 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -96,7 +55,7 @@ BuiltProjectOutputGroup%3bGetCopyToOutputDirectoryItems DebugSymbolsProjectOutputGroup%3b true - TargetFramework=net46 + TargetFramework=net472 BuiltProjectOutputGroup @@ -108,13 +67,13 @@ DebugSymbolsProjectOutputGroup%3b true - TargetFramework=net46 + TargetFramework=net472 BuiltProjectOutputGroup%3bGetCopyToOutputDirectoryItems DebugSymbolsProjectOutputGroup%3b true - TargetFramework=net46 + TargetFramework=net472 BuiltProjectOutputGroup @@ -130,7 +89,7 @@ BuiltProjectOutputGroup%3bGetCopyToOutputDirectoryItems DebugSymbolsProjectOutputGroup%3b true - TargetFramework=net46 + TargetFramework=net472 @@ -145,6 +104,6 @@ - + \ No newline at end of file diff --git a/src/Compilers/Extension/source.extension.vsixmanifest b/src/Compilers/Extension/source.extension.vsixmanifest index f94cbe5c42f90..f48a7ddd87a56 100644 --- a/src/Compilers/Extension/source.extension.vsixmanifest +++ b/src/Compilers/Extension/source.extension.vsixmanifest @@ -9,7 +9,7 @@ - + diff --git a/src/Compilers/Server/VBCSCompiler/App.config b/src/Compilers/Server/VBCSCompiler/App.config index 7db1af7cfaef3..3ca9c0445ce84 100644 --- a/src/Compilers/Server/VBCSCompiler/App.config +++ b/src/Compilers/Server/VBCSCompiler/App.config @@ -3,7 +3,7 @@ - + diff --git a/src/Compilers/Server/VBCSCompiler/NamedPipeClientConnection.cs b/src/Compilers/Server/VBCSCompiler/NamedPipeClientConnection.cs index 6edd014ccc95a..dc0bf5d79bb63 100644 --- a/src/Compilers/Server/VBCSCompiler/NamedPipeClientConnection.cs +++ b/src/Compilers/Server/VBCSCompiler/NamedPipeClientConnection.cs @@ -72,21 +72,39 @@ private NamedPipeServerStream ConstructPipe(string pipeName) { CompilerServerLogger.Log("Constructing pipe '{0}'.", pipeName); -#if NET46 - SecurityIdentifier identifier = WindowsIdentity.GetCurrent().Owner; - PipeSecurity security = new PipeSecurity(); +#if NET472 + PipeSecurity security; + PipeOptions pipeOptions = PipeOptions.Asynchronous | PipeOptions.WriteThrough; - // Restrict access to just this account. - PipeAccessRule rule = new PipeAccessRule(identifier, PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance, AccessControlType.Allow); - security.AddAccessRule(rule); - security.SetOwner(identifier); + if (!PlatformInformation.IsRunningOnMono) + { + security = new PipeSecurity(); + SecurityIdentifier identifier = WindowsIdentity.GetCurrent().Owner; + + // Restrict access to just this account. + PipeAccessRule rule = new PipeAccessRule(identifier, PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance, AccessControlType.Allow); + security.AddAccessRule(rule); + security.SetOwner(identifier); + } + else + { + // Pipe security and additional access rights constructor arguments + // are not supported by Mono + // https://github.com/dotnet/roslyn/pull/30810 + // https://github.com/mono/mono/issues/11406 + security = null; + // This enum value is implemented by Mono to restrict pipe access to + // the current user + const int CurrentUserOnly = unchecked((int)0x20000000); + pipeOptions |= (PipeOptions)CurrentUserOnly; + } NamedPipeServerStream pipeStream = new NamedPipeServerStream( pipeName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, // Maximum connections. PipeTransmissionMode.Byte, - PipeOptions.Asynchronous | PipeOptions.WriteThrough, + pipeOptions, PipeBufferSize, // Default input buffer PipeBufferSize, // Default output buffer security, diff --git a/src/Compilers/Server/VBCSCompiler/VBCSCompiler.cs b/src/Compilers/Server/VBCSCompiler/VBCSCompiler.cs index eaf8c7b701900..edd6ebc630aff 100644 --- a/src/Compilers/Server/VBCSCompiler/VBCSCompiler.cs +++ b/src/Compilers/Server/VBCSCompiler/VBCSCompiler.cs @@ -14,7 +14,7 @@ public static int Main(string[] args) NameValueCollection appSettings; try { -#if NET46 +#if NET472 appSettings = System.Configuration.ConfigurationManager.AppSettings; #else // Do not use AppSettings on non-desktop platforms diff --git a/src/Compilers/Server/VBCSCompilerTests/CompilerServerTests.cs b/src/Compilers/Server/VBCSCompilerTests/CompilerServerTests.cs index 10d3451ca5f8e..123c5e13ae7bd 100644 --- a/src/Compilers/Server/VBCSCompilerTests/CompilerServerTests.cs +++ b/src/Compilers/Server/VBCSCompilerTests/CompilerServerTests.cs @@ -101,7 +101,7 @@ private static void CheckForBadShared(List arguments) private static void ReferenceNetstandardDllIfCoreClr(TempDirectory currentDirectory, List arguments) { -#if !NET46 +#if !NET472 var filePath = Path.Combine(currentDirectory.Path, "netstandard.dll"); File.WriteAllBytes(filePath, TestResources.NetFX.netstandard20.netstandard); arguments.Add("/nostdlib"); @@ -232,7 +232,7 @@ private static void RunCompilerOutput(TempFile file, string expectedOutput) private static void VerifyResult((int ExitCode, string Output) result) { - Assert.Equal("", result.Output); + AssertEx.AssertEqualToleratingWhitespaceDifferences("", result.Output); Assert.Equal(0, result.ExitCode); } @@ -388,6 +388,18 @@ public async Task HelloWorldCS() } } + [Fact] + [Trait(Traits.Environment, Traits.Environments.VSProductInstall)] + public async Task HelloWorldCSDashShared() + { + using (var serverData = ServerUtil.CreateServer()) + { + var result = RunCommandLineCompiler(CSharpCompilerClientExecutable, $"-shared:{serverData.PipeName} /nologo hello.cs", _tempDirectory, s_helloWorldSrcCs); + VerifyResultAndOutput(result, _tempDirectory, "Hello, world."); + await serverData.Verify(connections: 1, completed: 1).ConfigureAwait(true); + } + } + [ConditionalFact(typeof(DesktopOnly))] [WorkItem(946954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/946954")] public void CompilerBinariesAreNotX86() diff --git a/src/Compilers/Server/VBCSCompilerTests/DesktopBuildClientTests.cs b/src/Compilers/Server/VBCSCompilerTests/DesktopBuildClientTests.cs index 2224fd8a9110e..29cd8f272bb90 100644 --- a/src/Compilers/Server/VBCSCompilerTests/DesktopBuildClientTests.cs +++ b/src/Compilers/Server/VBCSCompilerTests/DesktopBuildClientTests.cs @@ -147,7 +147,7 @@ public void ConnectToServerFails() } } -#if NET46 +#if NET472 [Fact] public void TestMutexConstructorException() { @@ -287,99 +287,115 @@ private bool Parse(params string[] args) out _errorMessage); } - [Fact] - public void Shared() + [Theory] + [InlineData('-')] + [InlineData('/')] + public void Shared(char optionPrefix) { - Assert.True(Parse("/shared", "test.cs")); + Assert.True(Parse(optionPrefix + "shared", "test.cs")); Assert.True(_hasShared); Assert.Null(_sessionKey); Assert.Equal(new[] { "test.cs" }, _parsedArgs); } - [Fact] - public void SharedWithSessionKey() + [Theory] + [InlineData('-')] + [InlineData('/')] + public void SharedWithSessionKey(char optionPrefix) { - Assert.True(Parse("/shared:pipe", "test.cs")); + Assert.True(Parse(optionPrefix + "shared:pipe", "test.cs")); Assert.True(_hasShared); Assert.Equal("pipe", _sessionKey); Assert.Equal(new[] { "test.cs" }, _parsedArgs); - Assert.True(Parse("/shared:1:2", "test.cs")); + Assert.True(Parse(optionPrefix + "shared:1:2", "test.cs")); Assert.True(_hasShared); Assert.Equal("1:2", _sessionKey); Assert.Equal(new[] { "test.cs" }, _parsedArgs); - Assert.True(Parse("/shared=1:2", "test.cs")); + Assert.True(Parse(optionPrefix + "shared=1:2", "test.cs")); Assert.True(_hasShared); Assert.Equal("1:2", _sessionKey); Assert.Equal(new[] { "test.cs" }, _parsedArgs); } - [Fact] - public void SharedWithEmptySessionKey() + [Theory] + [InlineData('-')] + [InlineData('/')] + public void SharedWithEmptySessionKey(char optionPrefix) { - Assert.False(Parse("/shared:", "test.cs")); + Assert.False(Parse(optionPrefix + "shared:", "test.cs")); Assert.False(_hasShared); Assert.Equal(CodeAnalysisResources.SharedArgumentMissing, _errorMessage); } - [Fact] - public void SharedPrefix() + [Theory] + [InlineData('-')] + [InlineData('/')] + public void SharedPrefix(char optionPrefix) { - Assert.True(Parse("/sharedstart", "test.cs")); + Assert.True(Parse(optionPrefix + "sharedstart", "test.cs")); Assert.False(_hasShared); - Assert.Equal(new[] { "/sharedstart", "test.cs" }, _parsedArgs); + Assert.Equal(new[] { optionPrefix + "sharedstart", "test.cs" }, _parsedArgs); } - [Fact] - public void Basic() + [Theory] + [InlineData('-')] + [InlineData('/')] + public void Basic(char optionPrefix) { Assert.True(Parse("test.cs")); Assert.False(_hasShared); Assert.Null(_sessionKey); Assert.Equal(new[] { "test.cs" }, _parsedArgs); - Assert.True(Parse("/keepalive:100", "/shared", "test.cs")); + Assert.True(Parse(optionPrefix + "keepalive:100", "/shared", "test.cs")); Assert.True(_hasShared); Assert.Null(_sessionKey); Assert.Equal("100", _keepAlive); Assert.Equal(new[] { "test.cs" }, _parsedArgs); } - [Fact] - public void KeepAliveBad() + [Theory] + [InlineData('-')] + [InlineData('/')] + public void KeepAliveBad(char optionPrefix) { - Assert.False(Parse("/keepalive", "test.cs")); + Assert.False(Parse(optionPrefix + "keepalive", "test.cs")); Assert.Equal(CodeAnalysisResources.MissingKeepAlive, _errorMessage); - Assert.False(Parse("/keepalive:", "test.cs")); + Assert.False(Parse(optionPrefix + "keepalive:", "test.cs")); Assert.Equal(CodeAnalysisResources.MissingKeepAlive, _errorMessage); - Assert.False(Parse("/keepalive:-100", "test.cs")); + Assert.False(Parse(optionPrefix + "keepalive:-100", "test.cs")); Assert.Equal(CodeAnalysisResources.KeepAliveIsTooSmall, _errorMessage); - Assert.False(Parse("/keepalive:100", "test.cs")); + Assert.False(Parse(optionPrefix + "keepalive:100", "test.cs")); Assert.Equal(CodeAnalysisResources.KeepAliveWithoutShared, _errorMessage); } - [Fact] - public void KeepAlivePrefix() + [Theory] + [InlineData('-')] + [InlineData('/')] + public void KeepAlivePrefix(char optionPrefix) { - Assert.True(Parse("/keepalivestart", "test.cs")); + Assert.True(Parse(optionPrefix + "keepalivestart", "test.cs")); Assert.Null(_keepAlive); - Assert.Equal(new[] { "/keepalivestart", "test.cs" }, _parsedArgs); + Assert.Equal(new[] { optionPrefix + "keepalivestart", "test.cs" }, _parsedArgs); } - [Fact] - public void KeepAlive() + [Theory] + [InlineData('-')] + [InlineData('/')] + public void KeepAlive(char optionPrefix) { - Assert.True(Parse("/keepalive:100", "/shared", "test.cs")); + Assert.True(Parse(optionPrefix + "keepalive:100", optionPrefix + "shared", "test.cs")); Assert.Equal("100", _keepAlive); Assert.Equal(new[] { "test.cs" }, _parsedArgs); Assert.True(_hasShared); Assert.Null(_sessionKey); - Assert.True(Parse("/keepalive=100", "/shared", "test.cs")); + Assert.True(Parse(optionPrefix + "keepalive=100", optionPrefix + "shared", "test.cs")); Assert.Equal("100", _keepAlive); Assert.Equal(new[] { "test.cs" }, _parsedArgs); Assert.True(_hasShared); diff --git a/src/Compilers/Shared/BuildClient.cs b/src/Compilers/Shared/BuildClient.cs index 84d0295278550..7280f557f13ef 100644 --- a/src/Compilers/Shared/BuildClient.cs +++ b/src/Compilers/Shared/BuildClient.cs @@ -6,7 +6,7 @@ using System.IO; using System.Linq; using System.Reflection; -#if NET46 +#if NET472 using System.Runtime; #else using System.Runtime.Loader; @@ -118,7 +118,7 @@ private static bool TryEnableMulticoreJitting(out string errorMessage) var assemblyName = Assembly.GetExecutingAssembly().GetName(); var profileName = assemblyName.Name + assemblyName.Version + ".profile"; Directory.CreateDirectory(profileRoot); -#if NET46 +#if NET472 ProfileOptimization.SetProfileRoot(profileRoot); ProfileOptimization.StartProfile(profileName); #else diff --git a/src/Compilers/Shared/BuildServerConnection.cs b/src/Compilers/Shared/BuildServerConnection.cs index 3fa040253c232..7a3a658a4409a 100644 --- a/src/Compilers/Shared/BuildServerConnection.cs +++ b/src/Compilers/Shared/BuildServerConnection.cs @@ -505,7 +505,7 @@ private static bool CheckPipeConnectionOwnership(NamedPipeClientStream pipeStrea } } -#if NET46 +#if NET472 internal static bool CheckIdentityUnix(PipeStream stream) { // Identity verification is unavailable in the MSBuild task, diff --git a/src/Compilers/Shared/DesktopAnalyzerAssemblyLoader.cs b/src/Compilers/Shared/DesktopAnalyzerAssemblyLoader.cs index 2690031572d61..88373622595a4 100644 --- a/src/Compilers/Shared/DesktopAnalyzerAssemblyLoader.cs +++ b/src/Compilers/Shared/DesktopAnalyzerAssemblyLoader.cs @@ -1,7 +1,5 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -#if NET46 - using System; using System.Reflection; using System.Threading; @@ -48,5 +46,3 @@ private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs a } } } - -#endif diff --git a/src/Compilers/Shared/GlobalAssemblyCacheHelpers/ClrGlobalAssemblyCache.cs b/src/Compilers/Shared/GlobalAssemblyCacheHelpers/ClrGlobalAssemblyCache.cs index 39a40afb0595d..2f23f1d602102 100644 --- a/src/Compilers/Shared/GlobalAssemblyCacheHelpers/ClrGlobalAssemblyCache.cs +++ b/src/Compilers/Shared/GlobalAssemblyCacheHelpers/ClrGlobalAssemblyCache.cs @@ -158,7 +158,7 @@ private static IEnumerable GetAssemblyIdentities( #if SCRIPTING throw new ArgumentException(Microsoft.CodeAnalysis.Scripting.ScriptingResources.InvalidAssemblyName); #else - throw new ArgumentException(Microsoft.CodeAnalysis.WorkspaceDesktopResources.Invalid_assembly_name); + throw new ArgumentException(Editor.EditorFeaturesResources.Invalid_assembly_name); #endif } } diff --git a/src/Compilers/Shared/GlobalAssemblyCacheHelpers/FusionAssemblyIdentity.cs b/src/Compilers/Shared/GlobalAssemblyCacheHelpers/FusionAssemblyIdentity.cs index cf345dc91ba4a..f8a4ecc47ecd2 100644 --- a/src/Compilers/Shared/GlobalAssemblyCacheHelpers/FusionAssemblyIdentity.cs +++ b/src/Compilers/Shared/GlobalAssemblyCacheHelpers/FusionAssemblyIdentity.cs @@ -438,15 +438,10 @@ internal static IAssemblyName ToAssemblyNameObject(AssemblyName name) if (assemblyName.IndexOf('\0') >= 0) { #if SCRIPTING - throw new ArgumentException(Scripting.ScriptingResources.InvalidCharactersInAssemblyName, nameof(name)); - -#elif WORKSPACE_DESKTOP || EDITOR_FEATURES - - throw new ArgumentException(Microsoft.CodeAnalysis.WorkspaceDesktopResources.Invalid_characters_in_assembly_name, nameof(name)); - +#elif EDITOR_FEATURES + throw new ArgumentException(Microsoft.CodeAnalysis.Editor.EditorFeaturesResources.Invalid_characters_in_assembly_name, nameof(name)); #else - throw new ArgumentException(Microsoft.CodeAnalysis.CodeAnalysisResources.InvalidCharactersInAssemblyName, nameof(name)); #endif } @@ -468,15 +463,10 @@ internal static IAssemblyName ToAssemblyNameObject(AssemblyName name) if (cultureName.IndexOf('\0') >= 0) { #if SCRIPTING - throw new ArgumentException(Microsoft.CodeAnalysis.Scripting.ScriptingResources.InvalidCharactersInAssemblyName, nameof(name)); - -#elif WORKSPACE_DESKTOP || EDITOR_FEATURES - - throw new ArgumentException(Microsoft.CodeAnalysis.WorkspaceDesktopResources.Invalid_characters_in_assembly_name, nameof(name)); - +#elif EDITOR_FEATURES + throw new ArgumentException(Microsoft.CodeAnalysis.Editor.EditorFeaturesResources.Invalid_characters_in_assembly_name, nameof(name)); #else - throw new ArgumentException(Microsoft.CodeAnalysis.CodeAnalysisResources.InvalidCharactersInAssemblyName, nameof(name)); #endif } diff --git a/src/Compilers/Shared/ShadowCopyAnalyzerAssemblyLoader.cs b/src/Compilers/Shared/ShadowCopyAnalyzerAssemblyLoader.cs index b66d554ed3b52..525110261fe9a 100644 --- a/src/Compilers/Shared/ShadowCopyAnalyzerAssemblyLoader.cs +++ b/src/Compilers/Shared/ShadowCopyAnalyzerAssemblyLoader.cs @@ -10,7 +10,7 @@ namespace Microsoft.CodeAnalysis { internal sealed class ShadowCopyAnalyzerAssemblyLoader : -#if NET46 +#if NET472 DesktopAnalyzerAssemblyLoader #else CoreClrAnalyzerAssemblyLoader diff --git a/src/Compilers/Test/Resources/Core/Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj b/src/Compilers/Test/Resources/Core/Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj index 03bc3346a29e4..331022ac84664 100644 --- a/src/Compilers/Test/Resources/Core/Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj +++ b/src/Compilers/Test/Resources/Core/Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj @@ -5,7 +5,7 @@ AnyCPU AnyCPU Library - netstandard1.3 + netstandard2.0 false false @@ -397,6 +397,5 @@ - \ No newline at end of file diff --git a/src/Compilers/Test/Utilities/CSharp/Microsoft.CodeAnalysis.CSharp.Test.Utilities.csproj b/src/Compilers/Test/Utilities/CSharp/Microsoft.CodeAnalysis.CSharp.Test.Utilities.csproj index a2664366621dc..72374fe20bf0b 100644 --- a/src/Compilers/Test/Utilities/CSharp/Microsoft.CodeAnalysis.CSharp.Test.Utilities.csproj +++ b/src/Compilers/Test/Utilities/CSharp/Microsoft.CodeAnalysis.CSharp.Test.Utilities.csproj @@ -8,7 +8,7 @@ Library Microsoft.CodeAnalysis.CSharp.Test.Utilities en-US - netstandard1.3 + netstandard2.0 true true false @@ -38,9 +38,6 @@ - - - diff --git a/src/Compilers/Test/Utilities/VisualBasic/Microsoft.CodeAnalysis.VisualBasic.Test.Utilities.vbproj b/src/Compilers/Test/Utilities/VisualBasic/Microsoft.CodeAnalysis.VisualBasic.Test.Utilities.vbproj index df4afa9592570..8e180e18c278d 100644 --- a/src/Compilers/Test/Utilities/VisualBasic/Microsoft.CodeAnalysis.VisualBasic.Test.Utilities.vbproj +++ b/src/Compilers/Test/Utilities/VisualBasic/Microsoft.CodeAnalysis.VisualBasic.Test.Utilities.vbproj @@ -7,7 +7,7 @@ Library Microsoft.CodeAnalysis.VisualBasic.UnitTests $(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 - netstandard1.3 + netstandard2.0 false @@ -42,9 +42,6 @@ - - - diff --git a/src/Compilers/VisualBasic/Portable/Compilation/ClsComplianceChecker.vb b/src/Compilers/VisualBasic/Portable/Compilation/ClsComplianceChecker.vb index 95f45aed877a3..485e00e5fa743 100644 --- a/src/Compilers/VisualBasic/Portable/Compilation/ClsComplianceChecker.vb +++ b/src/Compilers/VisualBasic/Portable/Compilation/ClsComplianceChecker.vb @@ -777,10 +777,10 @@ Namespace Microsoft.CodeAnalysis.VisualBasic Private Function GetDeclaredComplianceHelper(symbol As Symbol, ByRef attributeLocation As Location, ByRef isAttributeInherited As Boolean) As Boolean? attributeLocation = Nothing isAttributeInherited = False - For Each data In symbol.GetAttributes() + For Each attributeData In symbol.GetAttributes() ' Check signature before HasErrors to avoid realizing symbols for other attributes. - If data.IsTargetAttribute(symbol, AttributeDescription.CLSCompliantAttribute) Then - Dim attributeClass = data.AttributeClass + If attributeData.IsTargetAttribute(symbol, AttributeDescription.CLSCompliantAttribute) Then + Dim attributeClass = attributeData.AttributeClass If attributeClass IsNot Nothing Then Dim info = attributeClass.GetUseSiteErrorInfo() If info IsNot Nothing Then @@ -790,15 +790,15 @@ Namespace Microsoft.CodeAnalysis.VisualBasic End If End If - If Not data.HasErrors Then - If Not TryGetAttributeWarningLocation(data, attributeLocation) Then + If Not attributeData.HasErrors Then + If Not TryGetAttributeWarningLocation(attributeData, attributeLocation) Then attributeLocation = Nothing End If - Debug.Assert(Not data.AttributeClass.IsErrorType(), "Already checked HasErrors.") - isAttributeInherited = data.AttributeClass.GetAttributeUsageInfo().Inherited + Debug.Assert(Not attributeData.AttributeClass.IsErrorType(), "Already checked HasErrors.") + isAttributeInherited = attributeData.AttributeClass.GetAttributeUsageInfo().Inherited - Dim args As ImmutableArray(Of TypedConstant) = data.CommonConstructorArguments + Dim args As ImmutableArray(Of TypedConstant) = attributeData.CommonConstructorArguments Debug.Assert(args.Length = 1, "We already checked the signature and HasErrors.") ' Duplicates are reported elsewhere - we only care about the first (error-free) occurrence. diff --git a/src/Compilers/VisualBasic/Portable/Microsoft.CodeAnalysis.VisualBasic.vbproj b/src/Compilers/VisualBasic/Portable/Microsoft.CodeAnalysis.VisualBasic.vbproj index 695bd938c045c..cc1d413273ac7 100644 --- a/src/Compilers/VisualBasic/Portable/Microsoft.CodeAnalysis.VisualBasic.vbproj +++ b/src/Compilers/VisualBasic/Portable/Microsoft.CodeAnalysis.VisualBasic.vbproj @@ -5,7 +5,7 @@ AnyCPU AnyCPU Library - netstandard1.3 + netstandard2.0 $(NoWarn);42014 ..\BasicCodeAnalysisRules.ruleset true @@ -98,8 +98,5 @@ Designer - - - \ No newline at end of file diff --git a/src/Compilers/VisualBasic/Portable/Symbols/FieldSymbol.vb b/src/Compilers/VisualBasic/Portable/Symbols/FieldSymbol.vb index 9469eb1cdf085..ee12a0fa8abbd 100644 --- a/src/Compilers/VisualBasic/Portable/Symbols/FieldSymbol.vb +++ b/src/Compilers/VisualBasic/Portable/Symbols/FieldSymbol.vb @@ -412,6 +412,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols End Get End Property + Private ReadOnly Property IFieldSymbol_IsFixedSizeBuffer As Boolean Implements IFieldSymbol.IsFixedSizeBuffer + Get + Return False + End Get + End Property + Private ReadOnly Property IFieldSymbol_Type As ITypeSymbol Implements IFieldSymbol.Type Get Return Me.Type diff --git a/src/Compilers/VisualBasic/Test/CommandLine/Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests.vbproj b/src/Compilers/VisualBasic/Test/CommandLine/Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests.vbproj index 81228590fe378..c2d5461e9197e 100644 --- a/src/Compilers/VisualBasic/Test/CommandLine/Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests.vbproj +++ b/src/Compilers/VisualBasic/Test/CommandLine/Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests.vbproj @@ -5,7 +5,7 @@ AnyCPU AnyCPU Library - net46 + net472 $(RoslynDesktopRuntimeIdentifier) UnitTest diff --git a/src/Compilers/VisualBasic/Test/Emit/Attributes/InternalsVisibleToAndStrongNameTests.vb b/src/Compilers/VisualBasic/Test/Emit/Attributes/InternalsVisibleToAndStrongNameTests.vb index b723a5431a5b7..56990c6379e19 100644 --- a/src/Compilers/VisualBasic/Test/Emit/Attributes/InternalsVisibleToAndStrongNameTests.vb +++ b/src/Compilers/VisualBasic/Test/Emit/Attributes/InternalsVisibleToAndStrongNameTests.vb @@ -1,5 +1,5 @@ ' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -#If NOT NETCOREAPP2_1 +#If NET472 Imports System.Collections.Immutable Imports System.IO diff --git a/src/Compilers/VisualBasic/Test/Emit/Emit/FieldInitializerTests.vb b/src/Compilers/VisualBasic/Test/Emit/Emit/FieldInitializerTests.vb index e0a7a37806c21..dce988ebc287f 100644 --- a/src/Compilers/VisualBasic/Test/Emit/Emit/FieldInitializerTests.vb +++ b/src/Compilers/VisualBasic/Test/Emit/Emit/FieldInitializerTests.vb @@ -583,7 +583,7 @@ BC30424: Constants must be of an intrinsic or enumerated type, not a class, stru ) End Sub -#If NOT NETCOREAPP2_1 Then +#If NET472 Then Public Sub ChrChrWAscAscWAreConst() Dim source = diff --git a/src/Compilers/VisualBasic/Test/Emit/Microsoft.CodeAnalysis.VisualBasic.Emit.UnitTests.vbproj b/src/Compilers/VisualBasic/Test/Emit/Microsoft.CodeAnalysis.VisualBasic.Emit.UnitTests.vbproj index eea96a57658fb..2efe11261e479 100644 --- a/src/Compilers/VisualBasic/Test/Emit/Microsoft.CodeAnalysis.VisualBasic.Emit.UnitTests.vbproj +++ b/src/Compilers/VisualBasic/Test/Emit/Microsoft.CodeAnalysis.VisualBasic.Emit.UnitTests.vbproj @@ -12,7 +12,7 @@ Current version of the SDK doesn't emit constants properly for VB https://github.com/dotnet/sdk/pull/2117 --> - $(FinalDefineConstants),NET46=-1 + $(FinalDefineConstants),NET472=-1 $(FinalDefineConstants),NETCOREAPP2_1=-1 diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/PEParameterSymbolTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/PEParameterSymbolTests.vb index 706d70c0b824a..b80a9af07f638 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/PEParameterSymbolTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/PEParameterSymbolTests.vb @@ -1,5 +1,5 @@ ' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -#If NET46 Then +#If NET472 Then Imports System.Reflection Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.Desktop diff --git a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/FieldTests.vb b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/FieldTests.vb index d7a402392ccd2..ed30e2353cdff 100644 --- a/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/FieldTests.vb +++ b/src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/FieldTests.vb @@ -538,6 +538,24 @@ End Class Assert.Equal(substitutedProperty, substitutedField.AssociatedSymbol) End Sub + + + Public Sub FixedSizeBufferFalse() + Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( + + +Public Structure S + Private goo as Byte +End Structure + +) + Dim globalNS = compilation.SourceModule.GlobalNamespace + Dim s = globalNS.GetMember(Of NamedTypeSymbol)("S") + Dim goo = DirectCast(s.GetMember(Of FieldSymbol)("goo"), IFieldSymbol) + + Assert.False(goo.IsFixedSizeBuffer) + End Sub + End Class End Namespace diff --git a/src/Compilers/VisualBasic/Test/Syntax/Parser/ParserRegressionTests.vb b/src/Compilers/VisualBasic/Test/Syntax/Parser/ParserRegressionTests.vb index 50035ec4d5966..fe3934e877f46 100644 --- a/src/Compilers/VisualBasic/Test/Syntax/Parser/ParserRegressionTests.vb +++ b/src/Compilers/VisualBasic/Test/Syntax/Parser/ParserRegressionTests.vb @@ -746,7 +746,7 @@ End Select VisualBasicSyntaxTree.ParseText(text) End Sub - + Public Sub ParseFileOnBinaryFile() ' This is doing the same thing as ParseFile, but using a MemoryStream diff --git a/src/Compilers/VisualBasic/vbc/App.config b/src/Compilers/VisualBasic/vbc/App.config index 0b8bc41dc17f4..7472b129cb6f9 100644 --- a/src/Compilers/VisualBasic/vbc/App.config +++ b/src/Compilers/VisualBasic/vbc/App.config @@ -3,7 +3,7 @@ - + diff --git a/src/Compilers/VisualBasic/vbc/Program.cs b/src/Compilers/VisualBasic/vbc/Program.cs index c33e3aaf1a157..ba2710fee0753 100644 --- a/src/Compilers/VisualBasic/vbc/Program.cs +++ b/src/Compilers/VisualBasic/vbc/Program.cs @@ -25,7 +25,7 @@ public static int Main(string[] args) private static int MainCore(string[] args) { -#if NET46 +#if NET472 var loader = new DesktopAnalyzerAssemblyLoader(); #else var loader = new CoreClrAnalyzerAssemblyLoader(); diff --git a/src/Compilers/VisualBasic/vbc/vbc.csproj b/src/Compilers/VisualBasic/vbc/vbc.csproj index 765a2dc4bd84c..1ed430e4cf33c 100644 --- a/src/Compilers/VisualBasic/vbc/vbc.csproj +++ b/src/Compilers/VisualBasic/vbc/vbc.csproj @@ -54,7 +54,7 @@ - + PreserveNewest diff --git a/src/Deployment/DeployToolsetCompiler/DeployToolsetCompiler.csproj b/src/Deployment/DeployToolsetCompiler/DeployToolsetCompiler.csproj index 77225700bb390..5d417fcc77cf8 100644 --- a/src/Deployment/DeployToolsetCompiler/DeployToolsetCompiler.csproj +++ b/src/Deployment/DeployToolsetCompiler/DeployToolsetCompiler.csproj @@ -9,7 +9,7 @@ Exe DeployToolsetCompiler DeployToolsetCompiler_DoNotUse - v4.6 + v4.7.2 true diff --git a/src/Deployment/RoslynDeployment.csproj b/src/Deployment/RoslynDeployment.csproj index af66351f8841c..4ff8e20b54c70 100644 --- a/src/Deployment/RoslynDeployment.csproj +++ b/src/Deployment/RoslynDeployment.csproj @@ -5,7 +5,7 @@ AnyCPU AnyCPU Library - net46 + net472 Vsix false diff --git a/src/EditorFeatures/CSharp/CSharpEditorResources.Designer.cs b/src/EditorFeatures/CSharp/CSharpEditorResources.Designer.cs index 28d709117a03e..12ec92cb5d794 100644 --- a/src/EditorFeatures/CSharp/CSharpEditorResources.Designer.cs +++ b/src/EditorFeatures/CSharp/CSharpEditorResources.Designer.cs @@ -60,6 +60,15 @@ internal CSharpEditorResources() { } } + /// + /// Looks up a localized string similar to Fix interpolated verbatim string. + /// + internal static string Fix_interpolated_verbatim_string { + get { + return ResourceManager.GetString("Fix_interpolated_verbatim_string", resourceCulture); + } + } + /// /// Looks up a localized string similar to (Press TAB to insert). /// diff --git a/src/EditorFeatures/CSharp/CSharpEditorResources.resx b/src/EditorFeatures/CSharp/CSharpEditorResources.resx index d27291f3f75f3..e8650f88e00c1 100644 --- a/src/EditorFeatures/CSharp/CSharpEditorResources.resx +++ b/src/EditorFeatures/CSharp/CSharpEditorResources.resx @@ -117,6 +117,9 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + Fix interpolated verbatim string + (Press TAB to insert) diff --git a/src/EditorFeatures/CSharp/DecompiledSource/AssemblyResolver.cs b/src/EditorFeatures/CSharp/DecompiledSource/AssemblyResolver.cs new file mode 100644 index 0000000000000..ede9ce90b2ded --- /dev/null +++ b/src/EditorFeatures/CSharp/DecompiledSource/AssemblyResolver.cs @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.IO; +using System.Linq; +using System.Reflection.PortableExecutable; +using ICSharpCode.Decompiler.Metadata; +using Microsoft.CodeAnalysis.Shared.Extensions; + +namespace Microsoft.CodeAnalysis.Editor.CSharp.DecompiledSource +{ + internal class AssemblyResolver : IAssemblyResolver + { + private readonly Compilation parentCompilation; + private static readonly Version zeroVersion = new Version(0, 0, 0, 0); + + public AssemblyResolver(Compilation parentCompilation) + { + this.parentCompilation = parentCompilation; + } + + public PEFile Resolve(IAssemblyReference name) + { + foreach (var assembly in parentCompilation.GetReferencedAssemblySymbols()) + { + // First, find the correct IAssemblySymbol by name and PublicKeyToken. + if (assembly.Identity.Name != name.Name + || !assembly.Identity.PublicKeyToken.SequenceEqual(name.PublicKeyToken ?? Array.Empty())) + { + continue; + } + + // Normally we skip versions that do not match, except if the reference is "mscorlib" (see comments below) + // or if the name.Version is '0.0.0.0'. This is because we require the metadata of all transitive references + // and modules, to achieve best decompilation results. + // In the case of .NET Standard projects for example, the 'netstandard' reference contains no references + // with actual versions. All versions are '0.0.0.0', therefore we have to ignore those version numbers, + // and can just use the references provided by Roslyn instead. + if (assembly.Identity.Version != name.Version && name.Version != zeroVersion + && !string.Equals("mscorlib", assembly.Identity.Name, StringComparison.OrdinalIgnoreCase)) + { + // MSBuild treats mscorlib special for the purpose of assembly resolution/unification, where all + // versions of the assembly are considered equal. The same policy is adopted here. + continue; + } + + // reference assemblies should be fine here, we only need the metadata of references. + var reference = parentCompilation.GetMetadataReference(assembly); + return new PEFile(reference.Display, PEStreamOptions.PrefetchMetadata); + } + + // not found + return null; + } + + public PEFile ResolveModule(PEFile mainModule, string moduleName) + { + // Primitive implementation to support multi-module assemblies + // where all modules are located next to the main module. + string baseDirectory = Path.GetDirectoryName(mainModule.FileName); + string moduleFileName = Path.Combine(baseDirectory, moduleName); + if (!File.Exists(moduleFileName)) + { + return null; + } + + return new PEFile(moduleFileName, PEStreamOptions.PrefetchMetadata); + } + } + +} diff --git a/src/EditorFeatures/CSharp/DecompiledSource/CSharpDecompiledSourceService.cs b/src/EditorFeatures/CSharp/DecompiledSource/CSharpDecompiledSourceService.cs new file mode 100644 index 0000000000000..f65663adff739 --- /dev/null +++ b/src/EditorFeatures/CSharp/DecompiledSource/CSharpDecompiledSourceService.cs @@ -0,0 +1,161 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Linq; +using System.Reflection.PortableExecutable; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; + +using ICSharpCode.Decompiler; +using ICSharpCode.Decompiler.CSharp; +using ICSharpCode.Decompiler.CSharp.Transforms; +using ICSharpCode.Decompiler.Metadata; +using ICSharpCode.Decompiler.TypeSystem; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.DocumentationComments; +using Microsoft.CodeAnalysis.DocumentationComments; +using Microsoft.CodeAnalysis.ErrorReporting; +using Microsoft.CodeAnalysis.Formatting; +using Microsoft.CodeAnalysis.Host; +using Microsoft.CodeAnalysis.MetadataAsSource; +using Microsoft.CodeAnalysis.Shared.Extensions; +using Microsoft.CodeAnalysis.Text; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.Editor.CSharp.DecompiledSource +{ + internal class CSharpDecompiledSourceService : IDecompiledSourceService + { + private readonly HostLanguageServices provider; + private static readonly FileVersionInfo decompilerVersion = FileVersionInfo.GetVersionInfo(typeof(CSharpDecompiler).Assembly.Location); + + public CSharpDecompiledSourceService(HostLanguageServices provider) + { + this.provider = provider; + } + + public async Task AddSourceToAsync(Document document, ISymbol symbol, CancellationToken cancellationToken) + { + // Get the name of the type the symbol is in + var containingOrThis = symbol.GetContainingTypeOrThis(); + var fullName = GetFullReflectionName(containingOrThis); + + var compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); + + string assemblyLocation = null; + var isReferenceAssembly = symbol.ContainingAssembly.GetAttributes().Any(attribute => attribute.AttributeClass.Name == nameof(ReferenceAssemblyAttribute) + && attribute.AttributeClass.ToNameDisplayString() == typeof(ReferenceAssemblyAttribute).FullName); + if (isReferenceAssembly) + { + try + { + var fullAssemblyName = symbol.ContainingAssembly.Identity.GetDisplayName(); + GlobalAssemblyCache.Instance.ResolvePartialName(fullAssemblyName, out assemblyLocation, preferredCulture: CultureInfo.CurrentCulture); + } + catch (Exception e) when (FatalError.ReportWithoutCrash(e)) + { + } + } + + if (assemblyLocation == null) + { + var reference = compilation.GetMetadataReference(symbol.ContainingAssembly); + assemblyLocation = (reference as PortableExecutableReference)?.FilePath; + if (assemblyLocation == null) + { + throw new NotSupportedException(EditorFeaturesResources.Cannot_navigate_to_the_symbol_under_the_caret); + } + } + + // Decompile + document = PerformDecompilation(document, fullName, compilation, assemblyLocation); + + document = await AddAssemblyInfoRegionAsync(document, symbol, cancellationToken); + + // Convert XML doc comments to regular comments, just like MAS + var docCommentFormattingService = document.GetLanguageService(); + document = await ConvertDocCommentsToRegularCommentsAsync(document, docCommentFormattingService, cancellationToken); + + var node = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + + // Apply formatting rules + document = await Formatter.FormatAsync( + document, SpecializedCollections.SingletonEnumerable(node.FullSpan), + options: null, Formatter.GetDefaultFormattingRules(document), cancellationToken).ConfigureAwait(false); + + return document; + } + + private Document PerformDecompilation(Document document, string fullName, Compilation compilation, string assemblyLocation) + { + // Load the assembly. + var file = new PEFile(assemblyLocation, PEStreamOptions.PrefetchEntireImage); + + // Initialize a decompiler with default settings. + var decompiler = new CSharpDecompiler(file, new AssemblyResolver(compilation), new DecompilerSettings()); + // Escape invalid identifiers to prevent Roslyn from failing to parse the generated code. + // (This happens for example, when there is compiler-generated code that is not yet recognized/transformed by the decompiler.) + decompiler.AstTransforms.Add(new EscapeInvalidIdentifiers()); + + var fullTypeName = new FullTypeName(fullName); + + // Try to decompile; if an exception is thrown the caller will handle it + var text = decompiler.DecompileTypeAsString(fullTypeName); + return document.WithText(SourceText.From(text)); + } + + private async Task AddAssemblyInfoRegionAsync(Document document, ISymbol symbol, CancellationToken cancellationToken) + { + string assemblyInfo = MetadataAsSourceHelpers.GetAssemblyInfo(symbol.ContainingAssembly); + var compilation = await document.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); + string assemblyPath = MetadataAsSourceHelpers.GetAssemblyDisplay(compilation, symbol.ContainingAssembly); + + var regionTrivia = SyntaxFactory.RegionDirectiveTrivia(true) + .WithTrailingTrivia(new[] { SyntaxFactory.Space, SyntaxFactory.PreprocessingMessage(assemblyInfo) }); + + var oldRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + var newRoot = oldRoot.WithLeadingTrivia(new[] + { + SyntaxFactory.Trivia(regionTrivia), + SyntaxFactory.CarriageReturnLineFeed, + SyntaxFactory.Comment("// " + assemblyPath), + SyntaxFactory.CarriageReturnLineFeed, + SyntaxFactory.Comment($"// Decompiled with ICSharpCode.Decompiler {decompilerVersion.FileVersion}"), + SyntaxFactory.CarriageReturnLineFeed, + SyntaxFactory.Trivia(SyntaxFactory.EndRegionDirectiveTrivia(true)), + SyntaxFactory.CarriageReturnLineFeed, + SyntaxFactory.CarriageReturnLineFeed + }); + + return document.WithSyntaxRoot(newRoot); + } + + private async Task ConvertDocCommentsToRegularCommentsAsync(Document document, IDocumentationCommentFormattingService docCommentFormattingService, CancellationToken cancellationToken) + { + var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + + var newSyntaxRoot = DocCommentConverter.ConvertToRegularComments(syntaxRoot, docCommentFormattingService, cancellationToken); + + return document.WithSyntaxRoot(newSyntaxRoot); + } + + private string GetFullReflectionName(INamedTypeSymbol containingType) + { + var stack = new Stack(); + stack.Push(containingType.MetadataName); + var ns = containingType.ContainingNamespace; + do + { + stack.Push(ns.Name); + ns = ns.ContainingNamespace; + } + while (ns != null && !ns.IsGlobalNamespace); + + return string.Join(".", stack); + } + } +} diff --git a/src/EditorFeatures/CSharp/DecompiledSource/CSharpDecompiledSourceServiceFactory.cs b/src/EditorFeatures/CSharp/DecompiledSource/CSharpDecompiledSourceServiceFactory.cs new file mode 100644 index 0000000000000..197c516c0ffe7 --- /dev/null +++ b/src/EditorFeatures/CSharp/DecompiledSource/CSharpDecompiledSourceServiceFactory.cs @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Composition; +using Microsoft.CodeAnalysis.Host; +using Microsoft.CodeAnalysis.Host.Mef; + +namespace Microsoft.CodeAnalysis.Editor.CSharp.DecompiledSource +{ + [ExportLanguageServiceFactory(typeof(IDecompiledSourceService), LanguageNames.CSharp), Shared] + internal partial class CSharpDecompiledSourceServiceFactory : ILanguageServiceFactory + { + public ILanguageService CreateLanguageService(HostLanguageServices provider) + { + return new CSharpDecompiledSourceService(provider); + } + } +} diff --git a/src/EditorFeatures/CSharp/FixInterpolatedVerbatimString/FixInterpolatedVerbatimStringCommandHandler.cs b/src/EditorFeatures/CSharp/FixInterpolatedVerbatimString/FixInterpolatedVerbatimStringCommandHandler.cs new file mode 100644 index 0000000000000..653220727825e --- /dev/null +++ b/src/EditorFeatures/CSharp/FixInterpolatedVerbatimString/FixInterpolatedVerbatimStringCommandHandler.cs @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.ComponentModel.Composition; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Editor.Shared.Extensions; +using Microsoft.CodeAnalysis.Text; +using Microsoft.VisualStudio.Commanding; +using Microsoft.VisualStudio.Text; +using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; +using Microsoft.VisualStudio.Utilities; +using VSCommanding = Microsoft.VisualStudio.Commanding; + +namespace Microsoft.CodeAnalysis.Editor.CSharp.FixInterpolatedVerbatimString +{ + /// + /// Replaces @$" with $@", which is the preferred and until C# 8.0 the only supported form + /// of an interpolated verbatim string start token. In C# 8.0 we still auto-correct to this form for consistency. + /// + [Export(typeof(VSCommanding.ICommandHandler))] + [ContentType(ContentTypeNames.CSharpContentType)] + [Name(nameof(FixInterpolatedVerbatimStringCommandHandler))] + internal sealed class FixInterpolatedVerbatimStringCommandHandler : IChainedCommandHandler + { + public string DisplayName => CSharpEditorResources.Fix_interpolated_verbatim_string; + + public void ExecuteCommand(TypeCharCommandArgs args, Action nextCommandHandler, CommandExecutionContext executionContext) + { + // We need to check for the token *after* the opening quote is typed, so defer to the editor first + nextCommandHandler(); + + if (args.TypedChar == '"') + { + var caret = args.TextView.GetCaretPoint(args.SubjectBuffer); + if (caret != null) + { + var position = caret.Value.Position; + var snapshot = caret.Value.Snapshot; + + if (position >= 3 && + snapshot[position - 1] == '"' && + snapshot[position - 2] == '$' && + snapshot[position - 3] == '@') + { + var document = snapshot.GetOpenDocumentInCurrentContextWithChanges(); + if (document != null) + { + var root = document.GetSyntaxRootSynchronously(executionContext.OperationContext.UserCancellationToken); + var token = root.FindToken(position - 3); + if (token.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken)) + { + args.SubjectBuffer.Replace(new Span(position - 3, 2), "$@"); + } + } + } + } + } + } + + public VSCommanding.CommandState GetCommandState(TypeCharCommandArgs args, Func nextCommandHandler) + => nextCommandHandler(); + } +} diff --git a/src/EditorFeatures/CSharp/Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj b/src/EditorFeatures/CSharp/Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj index cf09c3739bb84..99c683d71fde3 100644 --- a/src/EditorFeatures/CSharp/Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj +++ b/src/EditorFeatures/CSharp/Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj @@ -6,7 +6,7 @@ AnyCPU Library Microsoft.CodeAnalysis.Editor.CSharp - net46 + net472 true @@ -48,6 +48,7 @@ + diff --git a/src/EditorFeatures/CSharp/SplitStringLiteral/SplitStringLiteralCommandHandler.cs b/src/EditorFeatures/CSharp/SplitStringLiteral/SplitStringLiteralCommandHandler.cs index c31092dba7431..3af3564a9dab6 100644 --- a/src/EditorFeatures/CSharp/SplitStringLiteral/SplitStringLiteralCommandHandler.cs +++ b/src/EditorFeatures/CSharp/SplitStringLiteral/SplitStringLiteralCommandHandler.cs @@ -1,4 +1,6 @@ -using System.ComponentModel.Composition; +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.ComponentModel.Composition; using System.Threading; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; diff --git a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.cs.xlf b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.cs.xlf index a17aebf9f66c4..3391d2c1f867c 100644 --- a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.cs.xlf +++ b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.cs.xlf @@ -2,6 +2,11 @@ + + Fix interpolated verbatim string + Fix interpolated verbatim string + + (Press TAB to insert) (Pro vložení stiskněte TAB.) diff --git a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.de.xlf b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.de.xlf index 50d22d4cbf64f..a66e264a4e40b 100644 --- a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.de.xlf +++ b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.de.xlf @@ -2,6 +2,11 @@ + + Fix interpolated verbatim string + Fix interpolated verbatim string + + (Press TAB to insert) (Zum Einfügen TAB-TASTE drücken) diff --git a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.es.xlf b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.es.xlf index c3a1bcdb8c245..5bfe2078450de 100644 --- a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.es.xlf +++ b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.es.xlf @@ -2,6 +2,11 @@ + + Fix interpolated verbatim string + Fix interpolated verbatim string + + (Press TAB to insert) (Presione TAB para insertar) diff --git a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.fr.xlf b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.fr.xlf index 371e6847a1650..760cd1f717c28 100644 --- a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.fr.xlf +++ b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.fr.xlf @@ -2,6 +2,11 @@ + + Fix interpolated verbatim string + Fix interpolated verbatim string + + (Press TAB to insert) (Appuyez sur TAB pour insérer) diff --git a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.it.xlf b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.it.xlf index 3f705fc00cd62..70a6be74b8402 100644 --- a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.it.xlf +++ b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.it.xlf @@ -2,6 +2,11 @@ + + Fix interpolated verbatim string + Fix interpolated verbatim string + + (Press TAB to insert) (Premere TAB per inserire) diff --git a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.ja.xlf b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.ja.xlf index 79836dd659f25..4e941b8e6e616 100644 --- a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.ja.xlf +++ b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.ja.xlf @@ -2,6 +2,11 @@ + + Fix interpolated verbatim string + Fix interpolated verbatim string + + (Press TAB to insert) (Tab キーを押して挿入) diff --git a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.ko.xlf b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.ko.xlf index 4f37904a65657..34d816961e3a5 100644 --- a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.ko.xlf +++ b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.ko.xlf @@ -2,6 +2,11 @@ + + Fix interpolated verbatim string + Fix interpolated verbatim string + + (Press TAB to insert) (삽입하려면 <Tab> 키 누름) diff --git a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.pl.xlf b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.pl.xlf index 8357da8a9bcb6..00308e0a7fa2b 100644 --- a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.pl.xlf +++ b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.pl.xlf @@ -2,6 +2,11 @@ + + Fix interpolated verbatim string + Fix interpolated verbatim string + + (Press TAB to insert) (Naciśnij klawisz TAB, aby wstawić) diff --git a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.pt-BR.xlf b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.pt-BR.xlf index 62ccf9cbe2aa7..110f9897ee18d 100644 --- a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.pt-BR.xlf +++ b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.pt-BR.xlf @@ -2,6 +2,11 @@ + + Fix interpolated verbatim string + Fix interpolated verbatim string + + (Press TAB to insert) (Pressione TAB para inserir) diff --git a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.ru.xlf b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.ru.xlf index c863054ae8617..cb77ad446dd9b 100644 --- a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.ru.xlf +++ b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.ru.xlf @@ -2,6 +2,11 @@ + + Fix interpolated verbatim string + Fix interpolated verbatim string + + (Press TAB to insert) (Нажмите клавишу TAB для вставки) diff --git a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.tr.xlf b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.tr.xlf index 68e2ef9108775..348464115430b 100644 --- a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.tr.xlf +++ b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.tr.xlf @@ -2,6 +2,11 @@ + + Fix interpolated verbatim string + Fix interpolated verbatim string + + (Press TAB to insert) (Eklemek için TAB tuşuna basın) diff --git a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.zh-Hans.xlf b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.zh-Hans.xlf index eebbc0d6aa141..6c8ff00750991 100644 --- a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.zh-Hans.xlf +++ b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.zh-Hans.xlf @@ -2,6 +2,11 @@ + + Fix interpolated verbatim string + Fix interpolated verbatim string + + (Press TAB to insert) (按 Tab 插入) diff --git a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.zh-Hant.xlf b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.zh-Hant.xlf index dca16e32a211a..4bf9b233bf860 100644 --- a/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.zh-Hant.xlf +++ b/src/EditorFeatures/CSharp/xlf/CSharpEditorResources.zh-Hant.xlf @@ -2,6 +2,11 @@ + + Fix interpolated verbatim string + Fix interpolated verbatim string + + (Press TAB to insert) (按 TAB 鍵插入) diff --git a/src/EditorFeatures/CSharpTest/ConvertForEachToFor/ConvertForEachToForTests.cs b/src/EditorFeatures/CSharpTest/ConvertForEachToFor/ConvertForEachToForTests.cs index 9b7b848f9ec2f..8d93645463d63 100644 --- a/src/EditorFeatures/CSharpTest/ConvertForEachToFor/ConvertForEachToForTests.cs +++ b/src/EditorFeatures/CSharpTest/ConvertForEachToFor/ConvertForEachToForTests.cs @@ -917,7 +917,7 @@ class List : IList await TestInRegularAndScriptAsync(text, expected); } - [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] + [Fact(Skip = "https://github.com/dotnet/roslyn/issues/29740"), Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)] public async Task ImmutableArray() { var text = @" diff --git a/src/EditorFeatures/CSharpTest/FixInterpolatedVerbatimString/FixInterpolatedVerbatimStringCommandHandlerTests.cs b/src/EditorFeatures/CSharpTest/FixInterpolatedVerbatimString/FixInterpolatedVerbatimStringCommandHandlerTests.cs new file mode 100644 index 0000000000000..5ce65c0be709a --- /dev/null +++ b/src/EditorFeatures/CSharpTest/FixInterpolatedVerbatimString/FixInterpolatedVerbatimStringCommandHandlerTests.cs @@ -0,0 +1,315 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Immutable; +using System.Linq; +using Microsoft.CodeAnalysis.Editor.CSharp.FixInterpolatedVerbatimString; +using Microsoft.CodeAnalysis.Editor.Shared.Extensions; +using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; +using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; +using Microsoft.CodeAnalysis.Test.Utilities; +using Microsoft.CodeAnalysis.Text; +using Microsoft.CodeAnalysis.Text.Shared.Extensions; +using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; +using Microsoft.VisualStudio.Text.Operations; +using Roslyn.Test.Utilities; +using Xunit; + +namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.FixInterpolatedVerbatimString +{ + [UseExportProvider] + public class FixInterpolatedVerbatimStringCommandHandlerTests + { + private static TestWorkspace CreateTestWorkspace(string inputMarkup) + { + var workspace = TestWorkspace.CreateCSharp(inputMarkup); + var document = workspace.Documents.Single(); + var view = document.GetTextView(); + view.SetSelection(document.SelectedSpans.Single().ToSnapshotSpan(view.TextBuffer.CurrentSnapshot)); + return workspace; + } + + private static (string quoteCharSnapshotText, int quoteCharCaretPosition) TypeQuoteChar(TestWorkspace workspace) + { + var view = workspace.Documents.Single().GetTextView(); + var commandHandler = new FixInterpolatedVerbatimStringCommandHandler(); + + string quoteCharSnapshotText = default; + int quoteCharCaretPosition = default; + + commandHandler.ExecuteCommand(new TypeCharCommandArgs(view, view.TextBuffer, '"'), + () => + { + var editorOperations = workspace.GetService().GetEditorOperations(view); + editorOperations.InsertText("\""); + + quoteCharSnapshotText = view.TextBuffer.CurrentSnapshot.GetText(); + quoteCharCaretPosition = view.Caret.Position.BufferPosition.Position; + + }, TestCommandExecutionContext.Create()); + + return (quoteCharSnapshotText, quoteCharCaretPosition); + } + + private static void TestHandled(string inputMarkup, string expectedOutputMarkup) + { + using (var workspace = CreateTestWorkspace(inputMarkup)) + { + var (quoteCharSnapshotText, quoteCharCaretPosition) = TypeQuoteChar(workspace); + var view = workspace.Documents.Single().GetTextView(); + + MarkupTestFile.GetSpans(expectedOutputMarkup, + out var expectedOutput, out ImmutableArray expectedSpans); + + Assert.Equal(expectedOutput, view.TextBuffer.CurrentSnapshot.GetText()); + Assert.Equal(expectedSpans.Single().Start, view.Caret.Position.BufferPosition.Position); + + var history = workspace.GetService().GetHistory(view.TextBuffer); + history.Undo(count: 1); + + // Ensure that after undo, the ordering fix is undone but the quote remains inserted + Assert.Equal(quoteCharSnapshotText, view.TextBuffer.CurrentSnapshot.GetText()); + Assert.Equal(quoteCharCaretPosition, view.Caret.Position.BufferPosition.Position); + } + } + + private static void TestNotHandled(string inputMarkup) + { + using (var workspace = CreateTestWorkspace(inputMarkup)) + { + var originalView = workspace.Documents.Single().GetTextView(); + var originalSnapshotText = originalView.TextBuffer.CurrentSnapshot.GetText(); + var originalCaretPosition = originalView.Caret.Position.BufferPosition.Position; + + var (quoteCharSnapshotText, quoteCharCaretPosition) = TypeQuoteChar(workspace); + var view = workspace.Documents.Single().GetTextView(); + + Assert.Equal(quoteCharSnapshotText, view.TextBuffer.CurrentSnapshot.GetText()); + Assert.Equal(quoteCharCaretPosition, view.Caret.Position.BufferPosition.Position); + + var history = workspace.GetService().GetHistory(view.TextBuffer); + history.Undo(count: 1); + + // Ensure that after undo, the quote is removed because the command made no changes + Assert.Equal(originalSnapshotText, view.TextBuffer.CurrentSnapshot.GetText()); + Assert.Equal(originalCaretPosition, view.Caret.Position.BufferPosition.Position); + } + } + + [WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)] + public void TestAfterAtSignDollarSign() + { + TestHandled( +@"class C +{ + void M() + { + var v = @$[||] + } +}", +@"class C +{ + void M() + { + var v = $@""[||] + } +}"); + } + + [WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)] + public void TestMissingAfterDollarSignAtSign() + { + TestNotHandled( +@"class C +{ + void M() + { + var v = $@[||] + } +}"); + } + + [WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)] + public void TestMissingAfterAtSign() + { + TestNotHandled( +@"class C +{ + void M() + { + var v = @[||] + } +}"); + } + + [WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)] + public void TestMissingAfterDollarSign() + { + TestNotHandled( +@"class C +{ + void M() + { + var v = $[||] + } +}"); + } + + [WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)] + public void TestMissingInEmptyFileAfterAtSignDollarSign() + { + TestNotHandled(@"@$[||]"); + } + + [WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)] + public void TestMissingInEmptyFileAfterDollarSign() + { + TestNotHandled(@"$[||]"); + } + + [WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)] + public void TestMissingInEmptyFile() + { + TestNotHandled(@"[||]"); + } + + [WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)] + public void TestAfterAtSignDollarSignEndOfFile() + { + TestHandled( +@"class C +{ + void M() + { + var v = @$[||]", +@"class C +{ + void M() + { + var v = $@""[||]"); + } + + [WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)] + public void TestMissingInClassDeclaration() + { + TestNotHandled( +@"class C +{ + @$[||] +}"); + } + + [WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)] + public void TestMissingInComment1() + { + TestNotHandled( +@"class C +{ + void M() + { + var v = // @$[||] + } +}"); + } + + [WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)] + public void TestMissingInComment2() + { + TestNotHandled( +@"class C +{ + void M() + { + var v = /* @$[||] + } +}"); + } + + [WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)] + public void TestMissingInString() + { + TestNotHandled( +@"class C +{ + void M() + { + var v = ""@$[||] + } +}"); + } + + [WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)] + public void TestMissingInVerbatimString() + { + TestNotHandled( +@"class C +{ + void M() + { + var v = @""@$[||] + } +}"); + } + + [WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)] + public void TestMissingInInterpolatedString() + { + TestNotHandled( +@"class C +{ + void M() + { + var v = $""@$[||] + } +}"); + } + + [WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)] + public void TestMissingInInterpolatedVerbatimString1() + { + TestNotHandled( +@"class C +{ + void M() + { + var v = $@""@$[||] + } +}"); + } + + [WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)] + public void TestMissingInInterpolatedVerbatimString2() + { + TestNotHandled( +@"class C +{ + void M() + { + var v = @$""@$[||] + } +}"); + } + + [WpfFact, Trait(Traits.Feature, Traits.Features.FixInterpolatedVerbatimString)] + public void TestTrivia() + { + TestHandled( +@"class C +{ + void M() + { + var v = // a + /* b */ @$[||] // c + } +}", +@"class C +{ + void M() + { + var v = // a + /* b */ $@""[||] // c + } +}"); + } + } +} diff --git a/src/EditorFeatures/CSharpTest/IntroduceUsingStatement/IntroduceUsingStatementTests.cs b/src/EditorFeatures/CSharpTest/IntroduceUsingStatement/IntroduceUsingStatementTests.cs new file mode 100644 index 0000000000000..d078adafc320d --- /dev/null +++ b/src/EditorFeatures/CSharpTest/IntroduceUsingStatement/IntroduceUsingStatementTests.cs @@ -0,0 +1,519 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CodeRefactorings; +using Microsoft.CodeAnalysis.CSharp.IntroduceUsingStatement; +using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; +using Microsoft.CodeAnalysis.Test.Utilities; +using Xunit; + +namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.IntroduceUsingStatement +{ + [Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceUsingStatement)] + public sealed class IntroduceUsingStatementTests : AbstractCSharpCodeActionTest + { + protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) + => new CSharpIntroduceUsingStatementCodeRefactoringProvider(); + + [Theory] + [InlineData("v[||]ar name = disposable;")] + [InlineData("var[||] name = disposable;")] + [InlineData("var [||]name = disposable;")] + [InlineData("var na[||]me = disposable;")] + [InlineData("var name[||] = disposable;")] + [InlineData("var name [||]= disposable;")] + [InlineData("var name =[||] disposable;")] + [InlineData("var name = [||]disposable;")] + [InlineData("[|var name = disposable;|]")] + [InlineData("var name = disposable[||];")] + [InlineData("var name = disposable;[||]")] + [InlineData("var name = disposable[||]")] + public async Task RefactoringIsAvailableForSelection(string declaration) + { + await TestInRegularAndScriptAsync( +@"class C +{ + void M(System.IDisposable disposable) + { + " + declaration + @" + } +}", +@"class C +{ + void M(System.IDisposable disposable) + { + using (var name = disposable) + { + } + } +}"); + } + + [Fact] + public async Task RefactoringIsAvailableForVerticalSelection() + { + await TestInRegularAndScriptAsync( +@"class C +{ + void M(System.IDisposable disposable) + { [| " + @" + var name = disposable; |] + } +}", +@"class C +{ + void M(System.IDisposable disposable) + { + using (var name = disposable) + { + } + } +}"); + } + + [Fact] + public async Task RefactoringIsAvailableForSelectionAtStartOfStatementWithPrecedingDeclaration() + { + await TestInRegularAndScriptAsync( +@"class C +{ + void M(System.IDisposable disposable) + { + var ignore = disposable; + [||]var name = disposable; + } +}", +@"class C +{ + void M(System.IDisposable disposable) + { + var ignore = disposable; + using (var name = disposable) + { + } + } +}"); + } + + [Fact] + public async Task RefactoringIsAvailableForSelectionAtStartOfLineWithPrecedingDeclaration() + { + await TestInRegularAndScriptAsync( +@"class C +{ + void M(System.IDisposable disposable) + { + var ignore = disposable; +[||] var name = disposable; + } +}", +@"class C +{ + void M(System.IDisposable disposable) + { + var ignore = disposable; + using (var name = disposable) + { + } + } +}"); + } + + [Fact] + public async Task RefactoringIsAvailableForSelectionAtEndOfStatementWithFollowingDeclaration() + { + await TestInRegularAndScriptAsync( +@"class C +{ + void M(System.IDisposable disposable) + { + var name = disposable;[||] + var ignore = disposable; + } +}", +@"class C +{ + void M(System.IDisposable disposable) + { + using (var name = disposable) + { + } + var ignore = disposable; + } +}"); + } + + [Fact] + public async Task RefactoringIsAvailableForSelectionAtEndOfLineWithFollowingDeclaration() + { + await TestInRegularAndScriptAsync( +@"class C +{ + void M(System.IDisposable disposable) + { + var name = disposable; [||] + var ignore = disposable; + } +}", +@"class C +{ + void M(System.IDisposable disposable) + { + using (var name = disposable) + { + } + var ignore = disposable; + } +}"); + } + + [Theory] + [InlineData("var name = d[||]isposable;")] + [InlineData("var name = disposabl[||]e;")] + [InlineData("var name=[|disposable|];")] + public async Task RefactoringIsNotAvailableForSelection(string declaration) + { + await TestMissingInRegularAndScriptAsync( +@"class C +{ + void M(System.IDisposable disposable) + { + " + declaration + @" + } +}"); + } + + [Fact] + public async Task RefactoringIsNotAvailableForDeclarationMissingInitializerExpression() + { + await TestMissingInRegularAndScriptAsync( +@"class C +{ + void M(System.IDisposable disposable) + { + System.IDisposable name =[||] + } +}"); + } + + [Fact] + public async Task RefactoringIsNotAvailableForUsingStatementDeclaration() + { + await TestMissingInRegularAndScriptAsync( +@"class C +{ + void M(System.IDisposable disposable) + { + using ([||]var name = disposable) + { + } + } +}"); + } + + [Theory] + [InlineData("[||]System.IDisposable x = disposable, y = disposable;")] + [InlineData("System.IDisposable [||]x = disposable, y = disposable;")] + [InlineData("System.IDisposable x = disposable, [||]y = disposable;")] + [InlineData("System.IDisposable x = disposable, y = disposable;[||]")] + public async Task RefactoringIsNotAvailableForMultiVariableDeclaration(string declaration) + { + await TestMissingInRegularAndScriptAsync( +@"class C +{ + void M(System.IDisposable disposable) + { + " + declaration + @" + } +}"); + } + + [Fact] + public async Task RefactoringIsAvailableForConstrainedGenericTypeParameter() + { + await TestInRegularAndScriptAsync( +@"class C where T : System.IDisposable +{ + void M(T disposable) + { + var x = disposable;[||] + } +}", +@"class C where T : System.IDisposable +{ + void M(T disposable) + { + using (var x = disposable) + { + } + } +}"); + } + + [Fact] + public async Task RefactoringIsNotAvailableForUnconstrainedGenericTypeParameter() + { + await TestMissingAsync( +@"class C +{ + void M(T disposable) + { + var x = disposable;[||] + } +}"); + } + + [Fact] + public async Task LeadingCommentTriviaIsPlacedOnUsingStatement() + { + await TestInRegularAndScriptAsync( +@"class C +{ + void M(System.IDisposable disposable) + { + // Comment + var x = disposable;[||] + } +}", +@"class C +{ + void M(System.IDisposable disposable) + { + // Comment + using (var x = disposable) + { + } + } +}"); + } + + [Fact] + public async Task CommentOnTheSameLineStaysOnTheSameLine() + { + await TestInRegularAndScriptAsync( +@"class C +{ + void M(System.IDisposable disposable) + { + var x = disposable;[||] // Comment + } +}", +@"class C +{ + void M(System.IDisposable disposable) + { + using (var x = disposable) // Comment + { + } + } +}"); + } + + [Fact] + public async Task TrailingCommentTriviaOnNextLineGoesAfterBlock() + { + await TestInRegularAndScriptAsync( +@"class C +{ + void M(System.IDisposable disposable) + { + var x = disposable;[||] + // Comment + } +}", +@"class C +{ + void M(System.IDisposable disposable) + { + using (var x = disposable) + { + } + // Comment + } +}"); + } + + [Fact] + public async Task ValidPreprocessorStaysValid() + { + await TestInRegularAndScriptAsync( +@"class C +{ + void M(System.IDisposable disposable) + { +#if true + var x = disposable;[||] +#endif + } +}", +@"class C +{ + void M(System.IDisposable disposable) + { +#if true + using (var x = disposable) + { + } +#endif + } +}"); + } + + [Fact] + public async Task InvalidPreprocessorStaysInvalid() + { + await TestInRegularAndScriptAsync( +@"class C +{ + void M(System.IDisposable disposable) + { +#if true + var x = disposable;[||] +#endif + _ = x; + } +}", +@"class C +{ + void M(System.IDisposable disposable) + { +#if true + using (var x = disposable) + { +#endif + _ = x; + } + } +}"); + } + + [Fact] + public async Task StatementsAreSurroundedByMinimalScope() + { + await TestInRegularAndScriptAsync( +@"class C +{ + void M(System.IDisposable disposable) + { + M(null); + var x = disposable;[||] + M(null); + M(x); + M(null); + } +}", +@"class C +{ + void M(System.IDisposable disposable) + { + M(null); + using (var x = disposable) + { + M(null); + M(x); + } + M(null); + } +}"); + } + + [Fact] + public async Task CommentsAreSurroundedExceptLinesFollowingLastUsage() + { + await TestInRegularAndScriptAsync( +@"class C +{ + void M(System.IDisposable disposable) + { + var x = disposable;[||] + // A + M(x); // B + // C + } +}", +@"class C +{ + void M(System.IDisposable disposable) + { + using (var x = disposable) + { + // A + M(x); // B + } + // C + } +}"); + } + + [Fact] + public async Task WorksInSwitchSections() + { + await TestInRegularAndScriptAsync( +@"class C +{ + void M(System.IDisposable disposable) + { + switch (disposable) + { + default: + var x = disposable;[||] + M(x); + break; + } + } +}", +@"class C +{ + void M(System.IDisposable disposable) + { + switch (disposable) + { + default: + using (var x = disposable) + { + M(x); + } + break; + } + } +}"); + } + + [Fact] + public async Task WorksOnStatementWithInvalidEmbeddingInIf() + { + await TestInRegularAndScriptAsync( +@"class C +{ + void M(System.IDisposable disposable) + { + if (disposable != null) + var x = disposable;[||] + } +}", +@"class C +{ + void M(System.IDisposable disposable) + { + if (disposable != null) + using (var x = disposable) + { + } + } +}"); + } + + [Fact] + public async Task RefactoringIsNotAvailableOnStatementWithInvalidEmbeddingInLambda() + { + await TestMissingInRegularAndScriptAsync( +@"class C +{ + void M(System.IDisposable disposable) + { + new Action(() => var x = disposable[||]); + } +}"); + } + } +} diff --git a/src/EditorFeatures/CSharpTest/MakeFieldReadonly/MakeFieldReadonlyTests.cs b/src/EditorFeatures/CSharpTest/MakeFieldReadonly/MakeFieldReadonlyTests.cs index 3f20f36bada2f..d45e7f06791aa 100644 --- a/src/EditorFeatures/CSharpTest/MakeFieldReadonly/MakeFieldReadonlyTests.cs +++ b/src/EditorFeatures/CSharpTest/MakeFieldReadonly/MakeFieldReadonlyTests.cs @@ -1104,6 +1104,17 @@ void M() void M() { } +}"); + } + + [WorkItem(26364, "https://github.com/dotnet/roslyn/issues/26364")] + [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeFieldReadonly)] + public async Task FieldIsFixed() + { + await TestMissingInRegularAndScriptAsync( +@"unsafe struct S +{ + [|private fixed byte b[8];|] }"); } } diff --git a/src/EditorFeatures/CSharpTest/Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests.csproj b/src/EditorFeatures/CSharpTest/Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests.csproj index 4e94ed8c1e474..8e39574a334b1 100644 --- a/src/EditorFeatures/CSharpTest/Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests.csproj +++ b/src/EditorFeatures/CSharpTest/Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests.csproj @@ -3,7 +3,7 @@ - net46 + net472 $(RoslynDesktopRuntimeIdentifier) AnyCPU AnyCPU @@ -17,8 +17,6 @@ - - diff --git a/src/EditorFeatures/CSharpTest/MoveDeclarationNearReference/MoveDeclarationNearReferenceTests.cs b/src/EditorFeatures/CSharpTest/MoveDeclarationNearReference/MoveDeclarationNearReferenceTests.cs index 66d9d8d663f96..df5f39878dc35 100644 --- a/src/EditorFeatures/CSharpTest/MoveDeclarationNearReference/MoveDeclarationNearReferenceTests.cs +++ b/src/EditorFeatures/CSharpTest/MoveDeclarationNearReference/MoveDeclarationNearReferenceTests.cs @@ -2,8 +2,8 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; -using Microsoft.CodeAnalysis.CSharp.MoveDeclarationNearReference; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; +using Microsoft.CodeAnalysis.MoveDeclarationNearReference; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; @@ -13,7 +13,7 @@ namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.MoveDeclarationNearRefe public class MoveDeclarationNearReferenceTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) - => new CSharpMoveDeclarationNearReferenceCodeRefactoringProvider(); + => new MoveDeclarationNearReferenceCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestMove1() diff --git a/src/EditorFeatures/CSharpTest/RemoveUnusedVariable/RemoveUnusedVariableTests.cs b/src/EditorFeatures/CSharpTest/RemoveUnusedVariable/RemoveUnusedVariableTests.cs index 4fdaf6789ff95..6c5a7ef2aa38d 100644 --- a/src/EditorFeatures/CSharpTest/RemoveUnusedVariable/RemoveUnusedVariableTests.cs +++ b/src/EditorFeatures/CSharpTest/RemoveUnusedVariable/RemoveUnusedVariableTests.cs @@ -213,7 +213,7 @@ public async Task LeadingDirectives() { await TestInRegularAndScriptAsync( @" -#define NET46 +#define DIRECTIVE1 using System; @@ -223,9 +223,9 @@ public class Class1 { public static string GetText() { -#if NET46 +#if DIRECTIVE1 return ""Hello from "" + Environment.OSVersion; -#elif NETSTANDARD1_4 +#elif DIRECTIVE2 return ""Hello from .NET Standard""; #else #error Unknown platform @@ -235,7 +235,7 @@ public static string GetText() } }", @" -#define NET46 +#define DIRECTIVE1 using System; @@ -245,9 +245,9 @@ public class Class1 { public static string GetText() { -#if NET46 +#if DIRECTIVE1 return ""Hello from "" + Environment.OSVersion; -#elif NETSTANDARD1_4 +#elif DIRECTIVE2 return ""Hello from .NET Standard""; #else #error Unknown platform diff --git a/src/EditorFeatures/CSharpTest/ReplaceDefaultLiteral/ReplaceDefaultLiteralTests.cs b/src/EditorFeatures/CSharpTest/ReplaceDefaultLiteral/ReplaceDefaultLiteralTests.cs new file mode 100644 index 0000000000000..877610036b885 --- /dev/null +++ b/src/EditorFeatures/CSharpTest/ReplaceDefaultLiteral/ReplaceDefaultLiteralTests.cs @@ -0,0 +1,856 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Collections.Immutable; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.ReplaceDefaultLiteral; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; +using Microsoft.CodeAnalysis.Test.Utilities; +using Xunit; + +namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ReplaceDefaultLiteral +{ + [Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDefaultLiteral)] + public sealed class ReplaceDefaultLiteralTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest + { + internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) + => (null, new CSharpReplaceDefaultLiteralCodeFixProvider()); + + private static readonly ImmutableArray s_csharp7_1above = + ImmutableArray.Create( + LanguageVersion.CSharp7_1, + LanguageVersion.Latest); + + private static readonly ImmutableArray s_csharp7below = + ImmutableArray.Create( + LanguageVersion.CSharp7, + LanguageVersion.CSharp6, + LanguageVersion.CSharp5, + LanguageVersion.CSharp4, + LanguageVersion.CSharp3, + LanguageVersion.CSharp2, + LanguageVersion.CSharp1); + + private async Task TestWithLanguageVersionsAsync(string initialMarkup, string expectedMarkup, ImmutableArray versions) + { + foreach (var version in versions) + { + await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, + parseOptions: CSharpParseOptions.Default.WithLanguageVersion(version)); + } + } + + private async Task TestMissingWithLanguageVersionsAsync(string initialMarkup, ImmutableArray versions) + { + foreach (var version in versions) + { + await TestMissingInRegularAndScriptAsync(initialMarkup, + new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(version))); + } + } + + [Fact] + public async Task TestCSharp7_1_InCaseSwitchLabel_Int() + { + await TestWithLanguageVersionsAsync( +@"class C +{ + void M() + { + switch (1) { case [||]default: } + } +}", +@"class C +{ + void M() + { + switch (1) { case 0: } + } +}", s_csharp7_1above); + } + + [Fact] + public async Task TestCSharp7_1_InCaseSwitchLabel_Int_InParentheses() + { + await TestWithLanguageVersionsAsync( +@"class C +{ + void M() + { + switch (1) { case ([||]default): } + } +}", +@"class C +{ + void M() + { + switch (1) { case (0): } + } +}", s_csharp7_1above); + } + + [Fact] + public async Task TestCSharp7_1_InCaseSwitchLabel_Int_NotInsideCast() + { + await TestMissingWithLanguageVersionsAsync( +@"class C +{ + void M() + { + switch (1) { case (int)[||]default: } + } +}", s_csharp7_1above); + } + + [Fact] + public async Task TestCSharp7_1_InCaseSwitchLabel_Int_NotOnDefaultExpression() + { + await TestMissingWithLanguageVersionsAsync( +@"class C +{ + void M() + { + switch (1) { case [||]default(int): } + } +}", s_csharp7_1above); + } + + [Fact] + public async Task TestCSharp7_1_InCaseSwitchLabel_Int_NotOnNumericLiteral() + { + await TestMissingWithLanguageVersionsAsync( +@"class C +{ + void M() + { + switch (1) { case [||]0: } + } +}", s_csharp7_1above); + } + + [Fact] + public async Task TestCSharp7_1_InCaseSwitchLabel_DateTime() + { + // Note that the default value of a struct type is not a constant, so this code is incorrect. + await TestWithLanguageVersionsAsync( +@"class C +{ + void M() + { + switch (System.DateTime.Now) { case [||]default: } + } +}", +@"class C +{ + void M() + { + switch (System.DateTime.Now) { case default(System.DateTime): } + } +}", s_csharp7_1above); + } + + [Fact] + public async Task TestCSharp7_1_InCaseSwitchLabel_TupleType() + { + // Note that the default value of a tuple type is not a constant, so this code is incorrect. + await TestWithLanguageVersionsAsync( +@"class C +{ + void M() + { + switch ((0, true)) { case [||]default: } + } +}", +@"class C +{ + void M() + { + switch ((0, true)) { case default((int, bool)): } + } +}", s_csharp7_1above); + } + + [Theory] + [InlineData("value")] + [InlineData("null")] + [InlineData("default")] + [InlineData("() => { }")] + [InlineData("")] + public async Task TestCSharp7_1_InCaseSwitchLabel_NotForInvalidType(string expression) + { + await TestMissingWithLanguageVersionsAsync( +$@"class C +{{ + void M() + {{ + switch ({expression}) {{ case [||]default: }} + }} +}}", s_csharp7_1above); + } + + [Fact] + public async Task TestCSharp7_1_InCasePatternSwitchLabel_Int() + { + await TestWithLanguageVersionsAsync( +@"class C +{ + void M() + { + switch (1) { case [||]default when true: } + } +}", +@"class C +{ + void M() + { + switch (1) { case 0 when true: } + } +}", s_csharp7_1above); + } + + [Fact] + public async Task TestCSharp7_1_InCasePatternSwitchLabel_Int_InParentheses() + { + await TestWithLanguageVersionsAsync( +@"class C +{ + void M() + { + switch (1) { case ([||]default) when true: } + } +}", +@"class C +{ + void M() + { + switch (1) { case (0) when true: } + } +}", s_csharp7_1above); + } + + [Fact] + public async Task TestCSharp7_1_InCasePatternSwitchLabel_Int_NotInsideCast() + { + await TestMissingWithLanguageVersionsAsync( +@"class C +{ + void M() + { + switch (1) { case (int)[||]default when true: } + } +}", s_csharp7_1above); + } + + [Fact] + public async Task TestCSharp7_1_InCasePatternSwitchLabel_Int_NotOnDefaultExpression() + { + await TestMissingWithLanguageVersionsAsync( +@"class C +{ + void M() + { + switch (1) { case [||]default(int) when true: } + } +}", s_csharp7_1above); + } + + [Fact] + public async Task TestCSharp7_1_InCasePatternSwitchLabel_Int_NotOnNumericLiteral() + { + await TestMissingWithLanguageVersionsAsync( +@"class C +{ + void M() + { + switch (1) { case [||]0 when true: } + } +}", s_csharp7_1above); + } + + [Fact] + public async Task TestCSharp7_1_InCasePatternSwitchLabel_DateTime() + { + // Note that the default value of a struct type is not a constant, so this code is incorrect. + await TestWithLanguageVersionsAsync( +@"class C +{ + void M() + { + switch (System.DateTime.Now) { case [||]default when true: } + } +}", +@"class C +{ + void M() + { + switch (System.DateTime.Now) { case default(System.DateTime) when true: } + } +}", s_csharp7_1above); + } + + [Fact] + public async Task TestCSharp7_1_InCasePatternSwitchLabel_TupleType() + { + // Note that the default value of a tuple type is not a constant, so this code is incorrect. + await TestWithLanguageVersionsAsync( +@"class C +{ + void M() + { + switch ((0, true)) { case [||]default when true: } + } +}", +@"class C +{ + void M() + { + switch ((0, true)) { case default((int, bool)) when true: } + } +}", s_csharp7_1above); + } + + [Theory] + [InlineData("value")] + [InlineData("null")] + [InlineData("default")] + [InlineData("() => { }")] + [InlineData("")] + public async Task TestCSharp7_1_InCasePatternSwitchLabel_NotForInvalidType(string expression) + { + await TestMissingWithLanguageVersionsAsync( +$@"class C +{{ + void M() + {{ + switch ({expression}) {{ case [||]default when true: }} + }} +}}", s_csharp7_1above); + } + + [Fact] + public async Task TestCSharp7_1_InIsPattern_Bool() + { + await TestWithLanguageVersionsAsync( +@"class C +{ + void M() + { + if (true is [||]default) { } + } +}", +@"class C +{ + void M() + { + if (true is false) { } + } +}", s_csharp7_1above); + } + + [Fact] + public async Task TestCSharp7_1_InIsPattern_Bool_InParentheses() + { + await TestWithLanguageVersionsAsync( +@"class C +{ + void M() + { + if (true is ([||]default)) { } + } +}", +@"class C +{ + void M() + { + if (true is (false)) { } + } +}", s_csharp7_1above); + } + + [Fact] + public async Task TestCSharp7_1_InIsPattern_Bool_NotInsideCast() + { + await TestMissingWithLanguageVersionsAsync( +@"class C +{ + void M() + { + if (true is (bool)[||]default) { } + } +}", s_csharp7_1above); + } + + [Fact] + public async Task TestCSharp7_1_InIsPattern_Bool_NotOnDefaultExpression() + { + await TestMissingWithLanguageVersionsAsync( +@"class C +{ + void M() + { + if (true is [||]default(bool)) { } + } +}", s_csharp7_1above); + } + + [Fact] + public async Task TestCSharp7_1_InIsPattern_Bool_NotOnFalseLiteral() + { + await TestMissingWithLanguageVersionsAsync( +@"class C +{ + void M() + { + if (true is [||]false) { } + } +}", s_csharp7_1above); + } + + [Theory] + [InlineData("int", "0")] + [InlineData("uint", "0U")] + [InlineData("byte", "0")] + [InlineData("sbyte", "0")] + [InlineData("short", "0")] + [InlineData("ushort", "0")] + [InlineData("long", "0L")] + [InlineData("ulong", "0UL")] + [InlineData("float", "0F")] + [InlineData("double", "0D")] + [InlineData("decimal", "0M")] + [InlineData("char", "'\\0'")] + [InlineData("string", "null")] + [InlineData("object", "null")] + public async Task TestCSharp7_1_InIsPattern_BuiltInType(string type, string expectedLiteral) + { + await TestWithLanguageVersionsAsync( +$@"class C +{{ + void M({type} value) + {{ + if (value is [||]default) {{ }} + }} +}}", +$@"class C +{{ + void M({type} value) + {{ + if (value is {expectedLiteral}) {{ }} + }} +}}", s_csharp7_1above); + } + + [Fact] + public async Task TestCSharp7_1_InIsPattern_DateTime() + { + // Note that the default value of a struct type is not a constant, so this code is incorrect. + await TestWithLanguageVersionsAsync( +@"class C +{ + void M() + { + if (System.DateTime.Now is [||]default) { } + } +}", +@"class C +{ + void M() + { + if (System.DateTime.Now is default(System.DateTime)) { } + } +}", s_csharp7_1above); + } + + [Fact] + public async Task TestCSharp7_1_InIsPattern_TupleType() + { + // Note that the default value of a tuple type is not a constant, so this code is incorrect. + await TestWithLanguageVersionsAsync( +@"class C +{ + void M() + { + if ((0, true) is [||]default) { } + } +}", +@"class C +{ + void M() + { + if ((0, true) is default((int, bool))) { } + } +}", s_csharp7_1above); + } + + [Theory] + [InlineData("class Type { }")] + [InlineData("interface Type { }")] + [InlineData("delegate void Type();")] + public async Task TestCSharp7_1_InIsPattern_CustomReferenceType(string typeDeclaration) + { + await TestWithLanguageVersionsAsync( +$@"class C +{{ + {typeDeclaration} + void M() + {{ + if (new Type() is [||]default) {{ }} + }} +}}", +$@"class C +{{ + {typeDeclaration} + void M() + {{ + if (new Type() is null) {{ }} + }} +}}", s_csharp7_1above); + } + + [Theory] + [InlineData("enum Enum { }")] + [InlineData("enum Enum { None = 0 }")] + [InlineData("[Flags] enum Enum { None = 0 }")] + [InlineData("[System.Flags] enum Enum { None = 1 }")] + [InlineData("[System.Flags] enum Enum { None = 1, None = 0 }")] + [InlineData("[System.Flags] enum Enum { Some = 0 }")] + public async Task TestCSharp7_1_InIsPattern_CustomEnum_WithoutSpecialMember(string enumDeclaration) + { + await TestWithLanguageVersionsAsync( +$@"class C +{{ + {enumDeclaration} + void M() + {{ + if (new Enum() is [||]default) {{ }} + }} +}}", +$@"class C +{{ + {enumDeclaration} + void M() + {{ + if (new Enum() is 0) {{ }} + }} +}}", s_csharp7_1above); + } + + [Theory] + [InlineData("[System.Flags] enum Enum : int { None = 0 }")] + [InlineData("[System.Flags] enum Enum : uint { None = 0 }")] + [InlineData("[System.Flags] enum Enum : byte { None = 0 }")] + [InlineData("[System.Flags] enum Enum : sbyte { None = 0 }")] + [InlineData("[System.Flags] enum Enum : short { None = 0 }")] + [InlineData("[System.Flags] enum Enum : ushort { None = 0 }")] + [InlineData("[System.Flags] enum Enum : long { None = 0 }")] + [InlineData("[System.Flags] enum Enum : ulong { None = 0 }")] + [InlineData("[System.Flags] enum Enum { None = default }")] + [InlineData("[System.Flags] enum Enum { Some = 1, None = 0 }")] + [InlineData("[System.FlagsAttribute] enum Enum { None = 0, Some = 1 }")] + public async Task TestCSharp7_1_InIsPattern_CustomEnum_WithSpecialMember(string enumDeclaration) + { + await TestWithLanguageVersionsAsync( +$@"class C +{{ + {enumDeclaration} + void M() + {{ + if (new Enum() is [||]default) {{ }} + }} +}}", +$@"class C +{{ + {enumDeclaration} + void M() + {{ + if (new Enum() is Enum.None) {{ }} + }} +}}", s_csharp7_1above); + } + + [Fact] + public async Task TestCSharp7_1_InIsPattern_CustomStruct() + { + // Note that the default value of a struct type is not a constant, so this code is incorrect. + await TestWithLanguageVersionsAsync( +@"class C +{ + struct Struct { } + void M() + { + if (new Struct() is [||]default) { } + } +}", +@"class C +{ + struct Struct { } + void M() + { + if (new Struct() is default(Struct)) { } + } +}", s_csharp7_1above); + } + + [Fact] + public async Task TestCSharp7_1_InIsPattern_AnonymousType() + { + await TestWithLanguageVersionsAsync( +@"class C +{ + void M() + { + if (new { a = 0 } is [||]default) { } + } +}", +@"class C +{ + void M() + { + if (new { a = 0 } is null) { } + } +}", s_csharp7_1above); + } + + [Theory] + [InlineData("class Container { }")] + [InlineData("interface Container { }")] + [InlineData("delegate void Container();")] + public async Task TestCSharp7_1_InIsPattern_CustomReferenceTypeOfAnonymousType(string typeDeclaration) + { + await TestWithLanguageVersionsAsync( +$@"class C +{{ + {typeDeclaration} + Container ToContainer(T value) => new Container(); + void M() + {{ + if (ToContainer(new {{ x = 0 }}) is [||]default) {{ }} + }} +}}", +$@"class C +{{ + {typeDeclaration} + Container ToContainer(T value) => new Container(); + void M() + {{ + if (ToContainer(new {{ x = 0 }}) is null) {{ }} + }} +}}", s_csharp7_1above); + } + + [Fact] + public async Task TestCSharp7_1_InIsPattern_NotForCustomStructOfAnonymousType() + { + await TestMissingWithLanguageVersionsAsync( +@"class C +{ + struct Container { } + Container ToContainer(T value) => new Container(); + void M() + { + if (ToContainer(new { x = 0 }) is [||]default) { } + } +}", s_csharp7_1above); + } + + [Theory] + [InlineData("System.Threading", "CancellationToken", "None")] + [InlineData("System", "IntPtr", "Zero")] + [InlineData("System", "UIntPtr", "Zero")] + public async Task TestCSharp7_1_InIsPattern_SpecialTypeQualified(string @namespace, string type, string member) + { + await TestWithLanguageVersionsAsync( +$@"class C +{{ + void M() + {{ + if (default({@namespace}.{type}) is [||]default) {{ }} + }} +}}", +$@"class C +{{ + void M() + {{ + if (default({@namespace}.{type}) is {@namespace}.{type}.{member}) {{ }} + }} +}}", s_csharp7_1above); + } + + [Theory] + [InlineData("System.Threading", "CancellationToken", "None")] + [InlineData("System", "IntPtr", "Zero")] + [InlineData("System", "UIntPtr", "Zero")] + public async Task TestCSharp7_1_InIsPattern_SpecialTypeUnqualifiedWithUsing(string @namespace, string type, string member) + { + await TestWithLanguageVersionsAsync( +$@"using {@namespace}; +class C +{{ + void M() + {{ + if (default({type}) is [||]default) {{ }} + }} +}}", +$@"using {@namespace}; +class C +{{ + void M() + {{ + if (default({type}) is {type}.{member}) {{ }} + }} +}}", s_csharp7_1above); + } + + [Theory] + [InlineData("CancellationToken")] + [InlineData("IntPtr")] + [InlineData("UIntPtr")] + public async Task TestCSharp7_1_InIsPattern_NotForSpecialTypeUnqualifiedWithoutUsing(string type) + { + await TestMissingWithLanguageVersionsAsync( +$@"class C +{{ + void M() + {{ + if (default({type}) is [||]default) {{ }} + }} +}}", s_csharp7_1above); + } + + [Fact] + public async Task TestCSharp7_1_InIsPattern_NotForInvalidType1() + { + await TestMissingWithLanguageVersionsAsync( +@"class C +{ + void M() + { + var value; + if (value is [||]default) { } + } +}", s_csharp7_1above); + } + + [Theory] + [InlineData("value")] + [InlineData("null")] + [InlineData("default")] + [InlineData("() => { }")] + [InlineData("")] + public async Task TestCSharp7_1_InIsPattern_NotForInvalidType2(string expression) + { + await TestMissingWithLanguageVersionsAsync( +$@"class C +{{ + void M() + {{ + var value = {expression}; + if (value is [||]default) {{ }} + }} +}}", s_csharp7_1above); + } + + [Theory] + [InlineData("value")] + [InlineData("null")] + [InlineData("default")] + [InlineData("() => { }")] + [InlineData("")] + public async Task TestCSharp7_1_InIsPattern_NotForInvalidType3(string expression) + { + await TestMissingWithLanguageVersionsAsync( +$@"class C +{{ + void M() + {{ + if ({expression} is [||]default) {{ }} + }} +}}", s_csharp7_1above); + } + + [Fact] + public async Task TestCSharp7_1_InIsPattern_Bool_Trivia() + { + await TestWithLanguageVersionsAsync( +@"class C +{ + void M() + { + if (true is + /*a*/ [||]default /*b*/) { } + } +}", +@"class C +{ + void M() + { + if (true is + /*a*/ false /*b*/) { } + } +}", s_csharp7_1above); + } + + [Fact] + public async Task TestCSharp7_1_InIsPattern_DateTime_Trivia() + { + await TestWithLanguageVersionsAsync( +@"class C +{ + void M() + { + if (System.DateTime.Now is + /*a*/ [||]default /*b*/) { } + } +}", +@"class C +{ + void M() + { + if (System.DateTime.Now is + /*a*/ default(System.DateTime) /*b*/) { } + } +}", s_csharp7_1above); + } + + [Fact] + public async Task TestCSharp7_1_NotInsideExpression() + { + await TestMissingWithLanguageVersionsAsync( +@"class C +{ + void M() + { + int i = [||]default; + } +}", s_csharp7_1above); + } + + [Fact] + public async Task TestCSharp7_1_NotInsideExpression_InvalidType() + { + await TestMissingWithLanguageVersionsAsync( +@"class C +{ + void M() + { + var v = [||]default; + } +}", s_csharp7_1above); + } + + [Fact] + public async Task TestCSharp7Lower_NotInsideExpression() + { + await TestMissingWithLanguageVersionsAsync( +@"class C +{ + void M() + { + int i = [||]default; + } +}", s_csharp7below); + } + } +} diff --git a/src/EditorFeatures/CSharpTest/SplitStringLiteral/SplitStringLiteralCommandHandlerTests.cs b/src/EditorFeatures/CSharpTest/SplitStringLiteral/SplitStringLiteralCommandHandlerTests.cs index 395c30f3e1a7c..595aba796f67a 100644 --- a/src/EditorFeatures/CSharpTest/SplitStringLiteral/SplitStringLiteralCommandHandlerTests.cs +++ b/src/EditorFeatures/CSharpTest/SplitStringLiteral/SplitStringLiteralCommandHandlerTests.cs @@ -1,4 +1,6 @@ -using System; +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Editor.CSharp.SplitStringLiteral; diff --git a/src/EditorFeatures/CSharpTest2/Microsoft.CodeAnalysis.CSharp.EditorFeatures2.UnitTests.csproj b/src/EditorFeatures/CSharpTest2/Microsoft.CodeAnalysis.CSharp.EditorFeatures2.UnitTests.csproj index b2218b8579a47..fc20d384eb159 100644 --- a/src/EditorFeatures/CSharpTest2/Microsoft.CodeAnalysis.CSharp.EditorFeatures2.UnitTests.csproj +++ b/src/EditorFeatures/CSharpTest2/Microsoft.CodeAnalysis.CSharp.EditorFeatures2.UnitTests.csproj @@ -3,7 +3,7 @@ - net46 + net472 $(RoslynDesktopRuntimeIdentifier) AnyCPU AnyCPU @@ -16,8 +16,6 @@ - - diff --git a/src/EditorFeatures/Core.Wpf/Microsoft.CodeAnalysis.EditorFeatures.Wpf.csproj b/src/EditorFeatures/Core.Wpf/Microsoft.CodeAnalysis.EditorFeatures.Wpf.csproj index a82babce5b3e5..6c84624cbe6db 100644 --- a/src/EditorFeatures/Core.Wpf/Microsoft.CodeAnalysis.EditorFeatures.Wpf.csproj +++ b/src/EditorFeatures/Core.Wpf/Microsoft.CodeAnalysis.EditorFeatures.Wpf.csproj @@ -6,7 +6,7 @@ AnyCPU Library Microsoft.CodeAnalysis.Editor - net46 + net472 true @@ -17,8 +17,6 @@ - - diff --git a/src/EditorFeatures/Core/EditorFeaturesResources.Designer.cs b/src/EditorFeatures/Core/EditorFeaturesResources.Designer.cs index bcbf2d0a279f0..80c7fed73bf63 100644 --- a/src/EditorFeatures/Core/EditorFeaturesResources.Designer.cs +++ b/src/EditorFeatures/Core/EditorFeaturesResources.Designer.cs @@ -1142,6 +1142,24 @@ internal static string Interface_Parts { } } + /// + /// Looks up a localized string similar to Invalid assembly name. + /// + internal static string Invalid_assembly_name { + get { + return ResourceManager.GetString("Invalid_assembly_name", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid characters in assembly name. + /// + internal static string Invalid_characters_in_assembly_name { + get { + return ResourceManager.GetString("Invalid_characters_in_assembly_name", resourceCulture); + } + } + /// /// Looks up a localized string similar to Light bulb session is already dismissed.. /// diff --git a/src/EditorFeatures/Core/IDecompiledSourceService.cs b/src/EditorFeatures/Core/IDecompiledSourceService.cs new file mode 100644 index 0000000000000..838478c289910 --- /dev/null +++ b/src/EditorFeatures/Core/IDecompiledSourceService.cs @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Host; + +namespace Microsoft.CodeAnalysis.Editor +{ + internal interface IDecompiledSourceService : ILanguageService + { + /// + /// Generates formatted source code containing general information about the symbol's + /// containing assembly and the decompiled source code which the given ISymbol is or is a part of + /// into the given document + /// + /// The document to generate source into + /// The symbol to generate source for + /// To cancel document operations + /// The updated document + Task AddSourceToAsync(Document document, ISymbol symbol, CancellationToken cancellationToken); + } +} diff --git a/src/EditorFeatures/Core/Implementation/MetadataAsSource/MetadataAsSourceFileService.cs b/src/EditorFeatures/Core/Implementation/MetadataAsSource/MetadataAsSourceFileService.cs index a669a37648eb7..474a1ec9937bd 100644 --- a/src/EditorFeatures/Core/Implementation/MetadataAsSource/MetadataAsSourceFileService.cs +++ b/src/EditorFeatures/Core/Implementation/MetadataAsSource/MetadataAsSourceFileService.cs @@ -3,19 +3,11 @@ using System; using System.Collections.Generic; using System.ComponentModel.Composition; -using System.Diagnostics; -using System.Globalization; using System.IO; using System.Linq; -using System.Reflection.PortableExecutable; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; -using ICSharpCode.Decompiler; -using ICSharpCode.Decompiler.CSharp; -using ICSharpCode.Decompiler.CSharp.Transforms; -using ICSharpCode.Decompiler.Metadata; -using ICSharpCode.Decompiler.TypeSystem; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Shared.Extensions; @@ -128,7 +120,15 @@ public async Task GetGeneratedFileAsync(Project project, I { try { - temporaryDocument = await DecompileSymbolAsync(temporaryDocument, symbol, cancellationToken).ConfigureAwait(false); + var decompiledSourceService = temporaryDocument.GetLanguageService(); + if (decompiledSourceService != null) + { + temporaryDocument = await decompiledSourceService.AddSourceToAsync(temporaryDocument, symbol, cancellationToken).ConfigureAwait(false); + } + else + { + useDecompiler = false; + } } catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceled(e)) { @@ -191,136 +191,6 @@ public async Task GetGeneratedFileAsync(Project project, I return new MetadataAsSourceFile(fileInfo.TemporaryFilePath, navigateLocation, documentName, documentTooltip); } - private async Task DecompileSymbolAsync(Document temporaryDocument, ISymbol symbol, CancellationToken cancellationToken) - { - // Get the name of the type the symbol is in - var containingOrThis = symbol.GetContainingTypeOrThis(); - var fullName = GetFullReflectionName(containingOrThis); - - var compilation = await temporaryDocument.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); - - string assemblyLocation = null; - var isReferenceAssembly = symbol.ContainingAssembly.GetAttributes().Any(attribute => attribute.AttributeClass.Name == nameof(ReferenceAssemblyAttribute) - && attribute.AttributeClass.ToNameDisplayString() == typeof(ReferenceAssemblyAttribute).FullName); - if (isReferenceAssembly) - { - try - { - var fullAssemblyName = symbol.ContainingAssembly.Identity.GetDisplayName(); - GlobalAssemblyCache.Instance.ResolvePartialName(fullAssemblyName, out assemblyLocation, preferredCulture: CultureInfo.CurrentCulture); - } - catch (Exception e) when (FatalError.ReportWithoutCrash(e)) - { - } - } - - if (assemblyLocation == null) - { - var reference = compilation.GetMetadataReference(symbol.ContainingAssembly); - assemblyLocation = (reference as PortableExecutableReference)?.FilePath; - if (assemblyLocation == null) - { - throw new NotSupportedException(EditorFeaturesResources.Cannot_navigate_to_the_symbol_under_the_caret); - } - } - - // Load the assembly. - var pefile = new PEFile(assemblyLocation, PEStreamOptions.PrefetchEntireImage); - - // Initialize a decompiler with default settings. - var settings = new DecompilerSettings(LanguageVersion.Latest); - var decompiler = new CSharpDecompiler(pefile, new RoslynAssemblyResolver(compilation), settings); - // Escape invalid identifiers to prevent Roslyn from failing to parse the generated code. - // (This happens for example, when there is compiler-generated code that is not yet recognized/transformed by the decompiler.) - decompiler.AstTransforms.Add(new EscapeInvalidIdentifiers()); - - var fullTypeName = new FullTypeName(fullName); - - var decompilerVersion = FileVersionInfo.GetVersionInfo(typeof(CSharpDecompiler).Assembly.Location); - - // Add header to match output of metadata-only view. - // (This also makes debugging easier, because you can see which assembly was decompiled inside VS.) - var header = $"#region {FeaturesResources.Assembly} {pefile.FullName}" + Environment.NewLine - + $"// {assemblyLocation}" + Environment.NewLine - + $"// Decompiled with ICSharpCode.Decompiler {decompilerVersion.FileVersion}" + Environment.NewLine - + "#endregion" + Environment.NewLine; - - // Try to decompile; if an exception is thrown the caller will handle it - var text = decompiler.DecompileTypeAsString(fullTypeName); - return temporaryDocument.WithText(SourceText.From(header + text)); - } - - private class RoslynAssemblyResolver : IAssemblyResolver - { - private readonly Compilation parentCompilation; - private static readonly Version zeroVersion = new Version(0, 0, 0, 0); - - public RoslynAssemblyResolver(Compilation parentCompilation) - { - this.parentCompilation = parentCompilation; - } - - public PEFile Resolve(IAssemblyReference name) - { - foreach (var assembly in parentCompilation.GetReferencedAssemblySymbols()) - { - // First, find the correct IAssemblySymbol by name and PublicKeyToken. - if (assembly.Identity.Name != name.Name - || !assembly.Identity.PublicKeyToken.SequenceEqual(name.PublicKeyToken ?? Array.Empty())) - { - continue; - } - - // Normally we skip versions that do not match, except if the reference is "mscorlib" (see comments below) - // or if the name.Version is '0.0.0.0'. This is because we require the metadata of all transitive references - // and modules, to achieve best decompilation results. - // In the case of .NET Standard projects for example, the 'netstandard' reference contains no references - // with actual versions. All versions are '0.0.0.0', therefore we have to ignore those version numbers, - // and can just use the references provided by Roslyn instead. - if (assembly.Identity.Version != name.Version && name.Version != zeroVersion - && !string.Equals("mscorlib", assembly.Identity.Name, StringComparison.OrdinalIgnoreCase)) - { - // MSBuild treats mscorlib special for the purpose of assembly resolution/unification, where all - // versions of the assembly are considered equal. The same policy is adopted here. - continue; - } - - // reference assemblies should be fine here, we only need the metadata of references. - var reference = parentCompilation.GetMetadataReference(assembly); - return new PEFile(reference.Display, PEStreamOptions.PrefetchMetadata); - } - - // not found - return null; - } - - public PEFile ResolveModule(PEFile mainModule, string moduleName) - { - // Primitive implementation to support multi-module assemblies - // where all modules are located next to the main module. - string baseDirectory = Path.GetDirectoryName(mainModule.FileName); - string moduleFileName = Path.Combine(baseDirectory, moduleName); - if (!File.Exists(moduleFileName)) - return null; - return new PEFile(moduleFileName, PEStreamOptions.PrefetchMetadata); - } - } - - private string GetFullReflectionName(INamedTypeSymbol containingType) - { - var stack = new Stack(); - stack.Push(containingType.MetadataName); - var ns = containingType.ContainingNamespace; - do - { - stack.Push(ns.Name); - ns = ns.ContainingNamespace; - } - while (ns != null && !ns.IsGlobalNamespace); - - return string.Join(".", stack); - } - private async Task RelocateSymbol_NoLock(MetadataAsSourceGeneratedFileInfo fileInfo, SymbolKey symbolId, CancellationToken cancellationToken) { // We need to relocate the symbol in the already existing file. If the file is open, we can just diff --git a/src/EditorFeatures/Core/Microsoft.CodeAnalysis.EditorFeatures.csproj b/src/EditorFeatures/Core/Microsoft.CodeAnalysis.EditorFeatures.csproj index c31ea671f1f36..14e85a5f1f3a5 100644 --- a/src/EditorFeatures/Core/Microsoft.CodeAnalysis.EditorFeatures.csproj +++ b/src/EditorFeatures/Core/Microsoft.CodeAnalysis.EditorFeatures.csproj @@ -6,7 +6,7 @@ AnyCPU Library Microsoft.CodeAnalysis.Editor - net46 + net472 true $(DefineConstants);EDITOR_FEATURES @@ -19,8 +19,6 @@ - - @@ -37,7 +35,6 @@ - @@ -104,6 +101,7 @@ + diff --git a/src/EditorFeatures/Test/CodeGeneration/AbstractCodeGenerationTests.cs b/src/EditorFeatures/Test/CodeGeneration/AbstractCodeGenerationTests.cs index a0e298371f63e..a61a0e061d493 100644 --- a/src/EditorFeatures/Test/CodeGeneration/AbstractCodeGenerationTests.cs +++ b/src/EditorFeatures/Test/CodeGeneration/AbstractCodeGenerationTests.cs @@ -10,6 +10,7 @@ using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.VisualBasic.Syntax; using Microsoft.VisualStudio.Composition; +using Microsoft.VisualStudio.LanguageServices; using Roslyn.Test.Utilities; using Xunit; @@ -71,7 +72,7 @@ internal void Test( Assert.True(cs != null || csSimple != null || vb != null || vbSimple != null, $"At least one of {nameof(cs)}, {nameof(csSimple)}, {nameof(vb)}, {nameof(vbSimple)} must be provided"); - var hostServices = MefV1HostServices.Create(TestExportProvider.ExportProviderWithCSharpAndVisualBasic.AsExportProvider()); + var hostServices = VisualStudioMefHostServices.Create(TestExportProvider.ExportProviderWithCSharpAndVisualBasic); var workspace = new AdhocWorkspace(hostServices); if (cs != null || csSimple != null) diff --git a/src/EditorFeatures/Test/Diagnostics/DiagnosticAnalyzerServiceTests.cs b/src/EditorFeatures/Test/Diagnostics/DiagnosticAnalyzerServiceTests.cs index 932ceed2d83b7..a4204d84a9a44 100644 --- a/src/EditorFeatures/Test/Diagnostics/DiagnosticAnalyzerServiceTests.cs +++ b/src/EditorFeatures/Test/Diagnostics/DiagnosticAnalyzerServiceTests.cs @@ -16,6 +16,7 @@ using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Composition; +using Microsoft.VisualStudio.LanguageServices; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; @@ -184,7 +185,7 @@ public async Task TestOpenFileOnlyAnalyzerDiagnostics() [Fact] public async Task TestSynchronizeWithBuild() { - var workspace = new AdhocWorkspace(MefV1HostServices.Create(TestExportProvider.ExportProviderWithCSharpAndVisualBasic.AsExportProvider())); + var workspace = new AdhocWorkspace(VisualStudioMefHostServices.Create(TestExportProvider.ExportProviderWithCSharpAndVisualBasic)); var language = Workspaces.NoCompilationConstants.LanguageName; @@ -249,7 +250,7 @@ await service.SynchronizeWithBuildAsync( [Fact] public void TestHostAnalyzerOrdering() { - var workspace = new AdhocWorkspace(MefV1HostServices.Create(TestExportProvider.ExportProviderWithCSharpAndVisualBasic.AsExportProvider())); + var workspace = new AdhocWorkspace(VisualStudioMefHostServices.Create(TestExportProvider.ExportProviderWithCSharpAndVisualBasic)); var project = workspace.AddProject( ProjectInfo.Create( diff --git a/src/EditorFeatures/Test/Microsoft.CodeAnalysis.EditorFeatures.UnitTests.csproj b/src/EditorFeatures/Test/Microsoft.CodeAnalysis.EditorFeatures.UnitTests.csproj index 52bd2824bab1f..1e36effdffca4 100644 --- a/src/EditorFeatures/Test/Microsoft.CodeAnalysis.EditorFeatures.UnitTests.csproj +++ b/src/EditorFeatures/Test/Microsoft.CodeAnalysis.EditorFeatures.UnitTests.csproj @@ -6,7 +6,7 @@ AnyCPU Library Microsoft.CodeAnalysis.Editor.UnitTests - net46 + net472 $(RoslynDesktopRuntimeIdentifier) UnitTest @@ -20,7 +20,6 @@ - diff --git a/src/EditorFeatures/Test/Preview/PreviewWorkspaceTests.cs b/src/EditorFeatures/Test/Preview/PreviewWorkspaceTests.cs index 24a93db930634..d5ce9d7523221 100644 --- a/src/EditorFeatures/Test/Preview/PreviewWorkspaceTests.cs +++ b/src/EditorFeatures/Test/Preview/PreviewWorkspaceTests.cs @@ -21,6 +21,7 @@ using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Composition; +using Microsoft.VisualStudio.LanguageServices; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Test.Utilities; using Roslyn.Utilities; @@ -132,7 +133,7 @@ public void TestPreviewOpenCloseFile() [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewServices() { - using (var previewWorkspace = new PreviewWorkspace(MefV1HostServices.Create(EditorServicesUtil.ExportProvider.AsExportProvider()))) + using (var previewWorkspace = new PreviewWorkspace(VisualStudioMefHostServices.Create(EditorServicesUtil.ExportProvider))) { var service = previewWorkspace.Services.GetService(); Assert.True(service is PreviewSolutionCrawlerRegistrationServiceFactory.Service); @@ -154,7 +155,7 @@ public void TestPreviewDiagnostic() var taskSource = new TaskCompletionSource(); diagnosticService.DiagnosticsUpdated += (s, a) => taskSource.TrySetResult(a); - using (var previewWorkspace = new PreviewWorkspace(MefV1HostServices.Create(EditorServicesUtil.ExportProvider.AsExportProvider()))) + using (var previewWorkspace = new PreviewWorkspace(VisualStudioMefHostServices.Create(EditorServicesUtil.ExportProvider))) { var solution = previewWorkspace.CurrentSolution .AddProject("project", "project.dll", LanguageNames.CSharp) diff --git a/src/EditorFeatures/Test/SolutionCrawler/WorkCoordinatorTests.cs b/src/EditorFeatures/Test/SolutionCrawler/WorkCoordinatorTests.cs index bae4f54ab75ae..7db4cad25dcb9 100644 --- a/src/EditorFeatures/Test/SolutionCrawler/WorkCoordinatorTests.cs +++ b/src/EditorFeatures/Test/SolutionCrawler/WorkCoordinatorTests.cs @@ -252,6 +252,23 @@ public async Task Project_AssemblyName_Change() } } + [Fact] + public async Task Project_DefaultNamespace_Change() + { + using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) + { + var solutionInfo = GetInitialSolutionInfo_2Projects_10Documents(workspace); + workspace.OnSolutionAdded(solutionInfo); + await WaitWaiterAsync(workspace.ExportProvider); + + var project = workspace.CurrentSolution.Projects.First(p => p.Name == "P1").WithDefaultNamespace("newNamespace"); + var worker = await ExecuteOperation(workspace, w => w.ChangeProject(project.Id, project.Solution)); + + Assert.Equal(5, worker.SyntaxDocumentIds.Count); + Assert.Equal(5, worker.DocumentIds.Count); + } + } + [Fact] public async Task Project_AnalyzerOptions_Change() { diff --git a/src/EditorFeatures/Test2/Microsoft.CodeAnalysis.EditorFeatures2.UnitTests.vbproj b/src/EditorFeatures/Test2/Microsoft.CodeAnalysis.EditorFeatures2.UnitTests.vbproj index 12548f908628d..f858a42e5c20b 100644 --- a/src/EditorFeatures/Test2/Microsoft.CodeAnalysis.EditorFeatures2.UnitTests.vbproj +++ b/src/EditorFeatures/Test2/Microsoft.CodeAnalysis.EditorFeatures2.UnitTests.vbproj @@ -6,7 +6,7 @@ AnyCPU Library Off - net46 + net472 $(RoslynDesktopRuntimeIdentifier) UnitTest @@ -19,7 +19,6 @@ - diff --git a/src/EditorFeatures/TestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest.cs b/src/EditorFeatures/TestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest.cs index 62340cbd572c8..f24dd333a1c3c 100644 --- a/src/EditorFeatures/TestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest.cs +++ b/src/EditorFeatures/TestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest.cs @@ -429,7 +429,7 @@ protected async Task> TestOperationsAsync( // To help when a user just writes a test (and supplied no 'expectedText') just print // out the entire 'actualText' (without any trimming). in the case that we have both, - // call the normal Assert helper which will print out a good trimmed diff. + // call the normal Assert helper which will print out a good trimmed diff. if (expectedText == "") { Assert.Equal((object)expectedText, actualText); @@ -517,7 +517,8 @@ private static async Task VerifyAgainstWorkspaceDefinitionAsync(string expectedT internal static Task> VerifyActionAndGetOperationsAsync( CodeAction action, TestParameters parameters) { - Assert.NotNull(action); + Assert.False(action is null, "No action was offered when one was expected."); + if (parameters.priority != null) { Assert.Equal(parameters.priority.Value, action.Priority); diff --git a/src/EditorFeatures/TestUtilities/Roslyn.Services.Test.Utilities.csproj b/src/EditorFeatures/TestUtilities/Roslyn.Services.Test.Utilities.csproj index 9893bd7893c43..f71fc3426f90d 100644 --- a/src/EditorFeatures/TestUtilities/Roslyn.Services.Test.Utilities.csproj +++ b/src/EditorFeatures/TestUtilities/Roslyn.Services.Test.Utilities.csproj @@ -6,7 +6,7 @@ AnyCPU Library Microsoft.CodeAnalysis.Test.Utilities - net46 + net472 true false @@ -23,7 +23,6 @@ - global,WORKSPACES diff --git a/src/EditorFeatures/TestUtilities/Workspaces/TestWorkspace.cs b/src/EditorFeatures/TestUtilities/Workspaces/TestWorkspace.cs index d67eb05a78d23..80994c2c4bf07 100644 --- a/src/EditorFeatures/TestUtilities/Workspaces/TestWorkspace.cs +++ b/src/EditorFeatures/TestUtilities/Workspaces/TestWorkspace.cs @@ -19,6 +19,7 @@ using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Composition; +using Microsoft.VisualStudio.LanguageServices; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Projection; using Microsoft.VisualStudio.Threading; @@ -49,7 +50,7 @@ public TestWorkspace() } public TestWorkspace(ExportProvider exportProvider, string workspaceKind = null, bool disablePartialSolutions = true) - : base(MefV1HostServices.Create(exportProvider.AsExportProvider()), workspaceKind ?? WorkspaceKind.Test) + : base(VisualStudioMefHostServices.Create(exportProvider), workspaceKind ?? WorkspaceKind.Test) { this.TestHookPartialSolutionsDisabled = disablePartialSolutions; this.ExportProvider = exportProvider; diff --git a/src/EditorFeatures/TestUtilities2/Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.vbproj b/src/EditorFeatures/TestUtilities2/Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.vbproj index 251791dd5930c..91fad6d1abcc3 100644 --- a/src/EditorFeatures/TestUtilities2/Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.vbproj +++ b/src/EditorFeatures/TestUtilities2/Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.vbproj @@ -5,7 +5,7 @@ AnyCPU AnyCPU Library - net46 + net472 $(RoslynDesktopRuntimeIdentifier) false @@ -18,7 +18,6 @@ - diff --git a/src/EditorFeatures/Text/Microsoft.CodeAnalysis.EditorFeatures.Text.csproj b/src/EditorFeatures/Text/Microsoft.CodeAnalysis.EditorFeatures.Text.csproj index 70d8029d188c6..0256f604dcd00 100644 --- a/src/EditorFeatures/Text/Microsoft.CodeAnalysis.EditorFeatures.Text.csproj +++ b/src/EditorFeatures/Text/Microsoft.CodeAnalysis.EditorFeatures.Text.csproj @@ -6,7 +6,7 @@ AnyCPU Library Microsoft.CodeAnalysis.Text - net46 + net472 true diff --git a/src/EditorFeatures/VisualBasic/Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj b/src/EditorFeatures/VisualBasic/Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj index fd12b32686da3..16aad2fe62284 100644 --- a/src/EditorFeatures/VisualBasic/Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj +++ b/src/EditorFeatures/VisualBasic/Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj @@ -5,7 +5,7 @@ AnyCPU AnyCPU Library - net46 + net472 diff --git a/src/EditorFeatures/VisualBasicTest/Diagnostics/OverloadBase/OverloadBaseTests.vb b/src/EditorFeatures/VisualBasicTest/Diagnostics/OverloadBase/OverloadBaseTests.vb index dd586a9b05c63..86909b4bd98d6 100644 --- a/src/EditorFeatures/VisualBasicTest/Diagnostics/OverloadBase/OverloadBaseTests.vb +++ b/src/EditorFeatures/VisualBasicTest/Diagnostics/OverloadBase/OverloadBaseTests.vb @@ -74,6 +74,65 @@ End Class Class App : Inherits Application Overloads Shared Sub Test() End Sub +End Class") + End Function + + + Public Async Function TestAddShadowsToProperty() As Task + Await TestInRegularAndScriptAsync( +"Class Application + Shared Sub Current() + End Sub +End Class +Class App : Inherits Application + [|Shared Property Current As App|] +End Class", +"Class Application + Shared Sub Current() + End Sub +End Class +Class App : Inherits Application + Shared Shadows Property Current As App +End Class") + End Function + + + Public Async Function TestAddShadowsToFunction() As Task + Await TestInRegularAndScriptAsync( +"Class Application + Shared Property Test As Integer +End Class +Class App : Inherits Application + [|Shared Function Test() As Integer + Return 2 + End Function|] +End Class", +"Class Application + Shared Property Test As Integer +End Class +Class App : Inherits Application + Shared Shadows Function Test() As Integer + Return 2 + End Function +End Class") + End Function + + + Public Async Function TestAddShadowsToSub() As Task + Await TestInRegularAndScriptAsync( +"Class Application + Shared Property Test As Integer +End Class +Class App : Inherits Application + [|Shared Sub Test() + End Sub|] +End Class", +"Class Application + Shared Property Test As Integer +End Class +Class App : Inherits Application + Shared Shadows Sub Test() + End Sub End Class") End Function End Class diff --git a/src/EditorFeatures/VisualBasicTest/IntroduceUsingStatement/IntroduceUsingStatementTests.vb b/src/EditorFeatures/VisualBasicTest/IntroduceUsingStatement/IntroduceUsingStatementTests.vb new file mode 100644 index 0000000000000..89b364a3c5c84 --- /dev/null +++ b/src/EditorFeatures/VisualBasicTest/IntroduceUsingStatement/IntroduceUsingStatementTests.vb @@ -0,0 +1,360 @@ +Imports Microsoft.CodeAnalysis.CodeRefactorings +Imports Microsoft.CodeAnalysis.VisualBasic.IntroduceUsingStatement +Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings + +Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.IntroduceUsingStatement + + + Public NotInheritable Class IntroduceUsingStatementTests + Inherits AbstractVisualBasicCodeActionTest + + Protected Overrides Function CreateCodeRefactoringProvider(ByVal workspace As Workspace, ByVal parameters As TestParameters) As CodeRefactoringProvider + Return New VisualBasicIntroduceUsingStatementCodeRefactoringProvider + End Function + + + + + + + + + + + + + + Public Async Function RefactoringIsAvailableForSelection(ByVal declaration As String) As Task + Await TestInRegularAndScriptAsync("Class C + Sub M(disposable As System.IDisposable) + " & declaration & " + End Sub +End Class", "Class C + Sub M(disposable As System.IDisposable) + Using name = disposable + End Using + End Sub +End Class") + End Function + + + Public Async Function RefactoringIsAvailableForVerticalSelection() As Task + Await TestInRegularAndScriptAsync("Class C + Sub M(disposable As System.IDisposable) [| " & " + Dim name = disposable |] + End Sub +End Class", "Class C + Sub M(disposable As System.IDisposable) + Using name = disposable + End Using + End Sub +End Class") + End Function + + + Public Async Function RefactoringIsAvailableForSelectionAtStartOfStatementWithPrecedingDeclaration() As Task + Await TestInRegularAndScriptAsync("Class C + Sub M(disposable As System.IDisposable) + Dim ignore = disposable + [||]Dim name = disposable + End Sub +End Class", "Class C + Sub M(disposable As System.IDisposable) + Dim ignore = disposable + Using name = disposable + End Using + End Sub +End Class") + End Function + + + Public Async Function RefactoringIsAvailableForSelectionAtStartOfLineWithPrecedingDeclaration() As Task + Await TestInRegularAndScriptAsync("Class C + Sub M(disposable As System.IDisposable) + Dim ignore = disposable +[||] Dim name = disposable + End Sub +End Class", "Class C + Sub M(disposable As System.IDisposable) + Dim ignore = disposable + Using name = disposable + End Using + End Sub +End Class") + End Function + + + Public Async Function RefactoringIsAvailableForSelectionAtEndOfStatementWithFollowingDeclaration() As Task + Await TestInRegularAndScriptAsync("Class C + Sub M(disposable As System.IDisposable) + Dim name = disposable[||] + Dim ignore = disposable + End Sub +End Class", "Class C + Sub M(disposable As System.IDisposable) + Using name = disposable + End Using + Dim ignore = disposable + End Sub +End Class") + End Function + + + Public Async Function RefactoringIsAvailableForSelectionAtEndOfLineWithFollowingDeclaration() As Task + Await TestInRegularAndScriptAsync("Class C + Sub M(disposable As System.IDisposable) + Dim name = disposable [||] + Dim ignore = disposable + End Sub +End Class", "Class C + Sub M(disposable As System.IDisposable) + Using name = disposable + End Using + Dim ignore = disposable + End Sub +End Class") + End Function + + + + + + Public Async Function RefactoringIsNotAvailableForSelection(ByVal declaration As String) As Task + Await TestMissingInRegularAndScriptAsync("Class C + Sub M(disposable As System.IDisposable) + " & declaration & " + End Sub +End Class") + End Function + + + Public Async Function RefactoringIsNotAvailableForDeclarationMissingInitializerExpression() As Task + Await TestMissingInRegularAndScriptAsync("Class C + Sub M(disposable As System.IDisposable) + Dim name As System.IDisposable =[||] + End Sub +End Class") + End Function + + + Public Async Function RefactoringIsNotAvailableForUsingStatementDeclaration() As Task + Await TestMissingInRegularAndScriptAsync("Class C + Sub M(disposable As System.IDisposable) + Using [||]name = disposable + End Using + End Sub +End Class") + End Function + + + + + + + Public Async Function RefactoringIsNotAvailableForMultiVariableDeclaration(ByVal declaration As String) As Task + Await TestMissingInRegularAndScriptAsync("Class C + Sub M(disposable As System.IDisposable) + " & declaration & " + End Sub +End Class") + End Function + + + Public Async Function RefactoringIsAvailableForConstrainedGenericTypeParameter() As Task + Await TestInRegularAndScriptAsync("Class C(Of T As System.IDisposable) + Sub M(disposable As T) + Dim x = disposable[||] + End Sub +End Class", "Class C(Of T As System.IDisposable) + Sub M(disposable As T) + Using x = disposable + End Using + End Sub +End Class") + End Function + + + Public Async Function RefactoringIsNotAvailableForUnconstrainedGenericTypeParameter() As Task + Await TestMissingAsync("Class C(Of T) + Sub M(disposable as T) + Dim x = disposable[||] + End Sub +End Class") + End Function + + + Public Async Function LeadingCommentTriviaIsPlacedOnUsingStatement() As Task + Await TestInRegularAndScriptAsync("Class C + Sub M(disposable As System.IDisposable) + ' Comment + Dim x = disposable[||] + End Sub +End Class", "Class C + Sub M(disposable As System.IDisposable) + ' Comment + Using x = disposable + End Using + End Sub +End Class") + End Function + + + Public Async Function CommentOnTheSameLineStaysOnTheSameLine() As Task + Await TestInRegularAndScriptAsync("Class C + Sub M(disposable As System.IDisposable) + Dim x = disposable[||] ' Comment + End Sub +End Class", "Class C + Sub M(disposable As System.IDisposable) + Using x = disposable ' Comment + End Using + End Sub +End Class") + End Function + + + Public Async Function TrailingCommentTriviaOnNextLineGoesAfterBlock() As Task + Await TestInRegularAndScriptAsync("Class C + Sub M(disposable As System.IDisposable) + Dim x = disposable[||] + ' Comment + End Sub +End Class", "Class C + Sub M(disposable As System.IDisposable) + Using x = disposable + End Using + ' Comment + End Sub +End Class") + End Function + + + Public Async Function ValidPreprocessorStaysValid() As Task + Await TestInRegularAndScriptAsync("Class C + Sub M(disposable As System.IDisposable) +#If True Then + Dim x = disposable[||] +#End If + End Sub +End Class", "Class C + Sub M(disposable As System.IDisposable) +#If True Then + Using x = disposable + End Using +#End If + End Sub +End Class") + End Function + + + Public Async Function InvalidPreprocessorStaysInvalid() As Task + Await TestInRegularAndScriptAsync("Class C + Sub M(disposable As System.IDisposable) +#If True Then + Dim x = disposable[||] +#End If + Dim discard = x + End Sub +End Class", "Class C + Sub M(disposable As System.IDisposable) +#If True Then + Using x = disposable +#End If + Dim discard = x + End Using + End Sub +End Class") + End Function + + + Public Async Function StatementsAreSurroundedByMinimalScope() As Task + Await TestInRegularAndScriptAsync("Class C + Sub M(disposable As System.IDisposable) + M(null) + Dim x = disposable[||] + M(null) + M(x) + M(null) + End Sub +End Class", "Class C + Sub M(disposable As System.IDisposable) + M(null) + Using x = disposable + M(null) + M(x) + End Using + M(null) + End Sub +End Class") + End Function + + + Public Async Function CommentsAreSurroundedExceptLinesFollowingLastUsage() As Task + Await TestInRegularAndScriptAsync("Class C + Sub M(disposable As System.IDisposable) + Dim x = disposable[||] + ' A + M(x) ' B + ' C + End Sub +End Class", "Class C + Sub M(disposable As System.IDisposable) + Using x = disposable + ' A + M(x) ' B + End Using + ' C + End Sub +End Class") + End Function + + + Public Async Function WorksInSelectCases() As Task + Await TestInRegularAndScriptAsync("Class C + Sub M(disposable As System.IDisposable) + Select Case disposable + Case Else + Dim x = disposable[||] + M(x) + End Select + End Sub +End Class", "Class C + Sub M(disposable As System.IDisposable) + Select Case disposable + Case Else + Using x = disposable + M(x) + End Using + End Select + End Sub +End Class") + End Function + + + Public Async Function RefactoringIsNotAvailableOnSingleLineIfStatements() As Task + Await TestMissingInRegularAndScriptAsync("Class C + Sub M(disposable As System.IDisposable) + If disposable IsNot Nothing Then Dim x = disposable[||] + End Sub +End Class") + End Function + + + Public Async Function RefactoringIsNotAvailableOnSingleLineIfElseClauses() As Task + Await TestMissingInRegularAndScriptAsync("Class C + Sub M(disposable As System.IDisposable) + If disposable IsNot Nothing Then Else Dim x = disposable[||] + End Sub +End Class") + End Function + + + Public Async Function RefactoringIsNotAvailableOnSingleLineLambda() As Task + Await TestMissingInRegularAndScriptAsync("Class C + Sub M(disposable As System.IDisposable) + New Action(Function() Dim x = disposable[||]) + End Sub +End Class") + End Function + End Class +End Namespace diff --git a/src/EditorFeatures/VisualBasicTest/Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests.vbproj b/src/EditorFeatures/VisualBasicTest/Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests.vbproj index 24cb61a8c1667..d81a65320dee2 100644 --- a/src/EditorFeatures/VisualBasicTest/Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests.vbproj +++ b/src/EditorFeatures/VisualBasicTest/Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests.vbproj @@ -7,7 +7,7 @@ Library Off Default - net46 + net472 $(RoslynDesktopRuntimeIdentifier) UnitTest @@ -30,7 +30,6 @@ - diff --git a/src/EditorFeatures/VisualBasicTest/MoveDeclarationNearReference/MoveDeclarationNearReferenceTests.vb b/src/EditorFeatures/VisualBasicTest/MoveDeclarationNearReference/MoveDeclarationNearReferenceTests.vb index eec1204444f46..a7b9916e70e82 100644 --- a/src/EditorFeatures/VisualBasicTest/MoveDeclarationNearReference/MoveDeclarationNearReferenceTests.vb +++ b/src/EditorFeatures/VisualBasicTest/MoveDeclarationNearReference/MoveDeclarationNearReferenceTests.vb @@ -2,14 +2,14 @@ Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings -Imports Microsoft.CodeAnalysis.VisualBasic.MoveDeclarationNearReference +Imports Microsoft.CodeAnalysis.MoveDeclarationNearReference Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.MoveDeclarationNearReference Public Class MoveDeclarationNearReferenceTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider - Return New VisualBasicMoveDeclarationNearReferenceCodeRefactoringProvider() + Return New MoveDeclarationNearReferenceCodeRefactoringProvider() End Function diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Microsoft.CodeAnalysis.CSharp.ExpressionCompiler.csproj b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Microsoft.CodeAnalysis.CSharp.ExpressionCompiler.csproj index cf716ff30d421..17259e4b0db0d 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Microsoft.CodeAnalysis.CSharp.ExpressionCompiler.csproj +++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Microsoft.CodeAnalysis.CSharp.ExpressionCompiler.csproj @@ -8,7 +8,7 @@ Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ExpressionCompiler true - netstandard1.3 + netstandard2.0 diff --git a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Rewriters/CapturedVariableRewriter.cs b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Rewriters/CapturedVariableRewriter.cs index a3c3732aea72a..2bf32d382771c 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Rewriters/CapturedVariableRewriter.cs +++ b/src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Rewriters/CapturedVariableRewriter.cs @@ -81,7 +81,7 @@ public override BoundNode VisitMethodGroup(BoundMethodGroup node) public override BoundNode VisitThisReference(BoundThisReference node) { var rewrittenThis = GenerateThisReference(node); - Debug.Assert(rewrittenThis.Type.Equals(node.Type, TypeCompareKind.IgnoreDynamicAndTupleNames)); + Debug.Assert(rewrittenThis.Type.Equals(node.Type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); return rewrittenThis; } diff --git a/src/ExpressionEvaluator/CSharp/Source/ResultProvider/Portable/Microsoft.CodeAnalysis.CSharp.ResultProvider.csproj b/src/ExpressionEvaluator/CSharp/Source/ResultProvider/Portable/Microsoft.CodeAnalysis.CSharp.ResultProvider.csproj index a2e345e4bf4d9..4cb9ff6922786 100644 --- a/src/ExpressionEvaluator/CSharp/Source/ResultProvider/Portable/Microsoft.CodeAnalysis.CSharp.ResultProvider.csproj +++ b/src/ExpressionEvaluator/CSharp/Source/ResultProvider/Portable/Microsoft.CodeAnalysis.CSharp.ResultProvider.csproj @@ -7,6 +7,7 @@ Library Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ResultProvider + netstandard1.3 diff --git a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ExpressionCompilerTests.cs b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ExpressionCompilerTests.cs index fa80d2e0d149a..d817951a836bd 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ExpressionCompilerTests.cs +++ b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/ExpressionCompilerTests.cs @@ -3116,6 +3116,94 @@ .locals init (B.<>c__DisplayClass2_0 V_0, //CS$<>8__locals0 }); } + [Fact(Skip = "https://github.com/dotnet/roslyn/issues/30767")] + [WorkItem(30767, "https://github.com/dotnet/roslyn/issues/30767")] + public void EvaluateCapturedLocalsOutsideLambda_PlusNullable() + { + var source = +@"class A +{ + internal virtual object F(object o) + { + return 1; + } +} +class B : A +{ + internal override object F(object o) + { + return 2; + } + static void F(System.Func f) + { + f(); + } + void M(object x) where T : A, new() + { + F(() => this.F(x)); + if (x != null) + { +#line 999 + var y = new T(); + var z = 1; + F(() => base.F(y)); + } + else + { + var w = 2; + F(() => w); + } + } +}"; + var compilation0 = CreateCompilation(source, options: WithNonNullTypesTrue(TestOptions.DebugDll)); + + WithRuntimeInstance(compilation0, runtime => + { + var context = CreateMethodContext(runtime, methodName: "B.M", atLineNumber: 999); + + string error; + var testData = new CompilationTestData(); + context.CompileExpression("this.F(y)", out error, testData); + + testData.GetMethodData("<>x.<>m0").VerifyIL(@" +{ + // Code size 23 (0x17) + .maxstack 2 + .locals init (B.<>c__DisplayClass2_0 V_0, //CS$<>8__locals0 + bool V_1, + B.<>c__DisplayClass2_1 V_2, //CS$<>8__locals1 + int V_3, //z + B.<>c__DisplayClass2_2 V_4) + IL_0000: ldloc.0 + IL_0001: ldfld ""B B.<>c__DisplayClass2_0.<>4__this"" + IL_0006: ldloc.2 + IL_0007: ldfld ""T B.<>c__DisplayClass2_1.y"" + IL_000c: box ""T"" + IL_0011: callvirt ""object B.F(object)"" + IL_0016: ret +}"); + testData = new CompilationTestData(); + context.CompileExpression("base.F(x)", out error, testData); + + testData.GetMethodData("<>x.<>m0").VerifyIL( + @"{ + // Code size 18 (0x12) + .maxstack 2 + .locals init (B.<>c__DisplayClass2_0 V_0, //CS$<>8__locals0 + bool V_1, + B.<>c__DisplayClass2_1 V_2, //CS$<>8__locals1 + int V_3, //z + B.<>c__DisplayClass2_2 V_4) + IL_0000: ldloc.0 + IL_0001: ldfld ""B B.<>c__DisplayClass2_0.<>4__this"" + IL_0006: ldloc.0 + IL_0007: ldfld ""object B.<>c__DisplayClass2_0.x"" + IL_000c: call ""object A.F(object)"" + IL_0011: ret +}"); + }); + } + [Fact] public void EvaluateCapturedLocalsInsideLambda() { diff --git a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/Microsoft.CodeAnalysis.CSharp.ExpressionCompiler.UnitTests.csproj b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/Microsoft.CodeAnalysis.CSharp.ExpressionCompiler.UnitTests.csproj index 07f132583f02f..13e43e5e212fc 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/Microsoft.CodeAnalysis.CSharp.ExpressionCompiler.UnitTests.csproj +++ b/src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/Microsoft.CodeAnalysis.CSharp.ExpressionCompiler.UnitTests.csproj @@ -7,7 +7,7 @@ Library Microsoft.CodeAnalysis.CSharp.UnitTests Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ExpressionCompiler.UnitTests - net46 + net472 $(RoslynDesktopRuntimeIdentifier) UnitTest true diff --git a/src/ExpressionEvaluator/CSharp/Test/ResultProvider/Microsoft.CodeAnalysis.CSharp.ResultProvider.UnitTests.csproj b/src/ExpressionEvaluator/CSharp/Test/ResultProvider/Microsoft.CodeAnalysis.CSharp.ResultProvider.UnitTests.csproj index 6047dc1558b58..78ad6ac8d48db 100644 --- a/src/ExpressionEvaluator/CSharp/Test/ResultProvider/Microsoft.CodeAnalysis.CSharp.ResultProvider.UnitTests.csproj +++ b/src/ExpressionEvaluator/CSharp/Test/ResultProvider/Microsoft.CodeAnalysis.CSharp.ResultProvider.UnitTests.csproj @@ -7,7 +7,7 @@ Library Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ResultProvider.UnitTests - net46 + net472 $(RoslynDesktopRuntimeIdentifier) UnitTest true diff --git a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/Microsoft.CodeAnalysis.ExpressionCompiler.csproj b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/Microsoft.CodeAnalysis.ExpressionCompiler.csproj index eb27b2dc1a52e..fe6660e8ffbe3 100644 --- a/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/Microsoft.CodeAnalysis.ExpressionCompiler.csproj +++ b/src/ExpressionEvaluator/Core/Source/ExpressionCompiler/Microsoft.CodeAnalysis.ExpressionCompiler.csproj @@ -8,7 +8,7 @@ Microsoft.CodeAnalysis.ExpressionEvaluator Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler true - netstandard1.3 + netstandard2.0 $(DefineConstants);EXPRESSIONCOMPILER diff --git a/src/ExpressionEvaluator/Core/Source/FunctionResolver/Microsoft.CodeAnalysis.FunctionResolver.csproj b/src/ExpressionEvaluator/Core/Source/FunctionResolver/Microsoft.CodeAnalysis.FunctionResolver.csproj index d5a79a12ccda1..6df08d60fbd03 100644 --- a/src/ExpressionEvaluator/Core/Source/FunctionResolver/Microsoft.CodeAnalysis.FunctionResolver.csproj +++ b/src/ExpressionEvaluator/Core/Source/FunctionResolver/Microsoft.CodeAnalysis.FunctionResolver.csproj @@ -8,7 +8,8 @@ Microsoft.CodeAnalysis.ExpressionEvaluator Microsoft.CodeAnalysis.ExpressionEvaluator.FunctionResolver true - netstandard1.3 + + net45;netstandard1.3 diff --git a/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/Microsoft.CodeAnalysis.ResultProvider.csproj b/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/Microsoft.CodeAnalysis.ResultProvider.csproj index 5f34b6079a02a..d2beb219e58b0 100644 --- a/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/Microsoft.CodeAnalysis.ResultProvider.csproj +++ b/src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/Microsoft.CodeAnalysis.ResultProvider.csproj @@ -7,6 +7,7 @@ Library Microsoft.CodeAnalysis.ExpressionEvaluator Microsoft.CodeAnalysis.ExpressionEvaluator.ResultProvider + netstandard1.3 diff --git a/src/ExpressionEvaluator/Core/Test/ExpressionCompiler/Microsoft.CodeAnalysis.ExpressionCompiler.Utilities.csproj b/src/ExpressionEvaluator/Core/Test/ExpressionCompiler/Microsoft.CodeAnalysis.ExpressionCompiler.Utilities.csproj index f2b96d9b7dbd5..18c6b01329d0b 100644 --- a/src/ExpressionEvaluator/Core/Test/ExpressionCompiler/Microsoft.CodeAnalysis.ExpressionCompiler.Utilities.csproj +++ b/src/ExpressionEvaluator/Core/Test/ExpressionCompiler/Microsoft.CodeAnalysis.ExpressionCompiler.Utilities.csproj @@ -8,7 +8,7 @@ Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.Utilities true - net46 + net472 false diff --git a/src/ExpressionEvaluator/Core/Test/FunctionResolver/Microsoft.CodeAnalysis.FunctionResolver.UnitTests.csproj b/src/ExpressionEvaluator/Core/Test/FunctionResolver/Microsoft.CodeAnalysis.FunctionResolver.UnitTests.csproj index f6a9b1d4c7679..325d426a851c3 100644 --- a/src/ExpressionEvaluator/Core/Test/FunctionResolver/Microsoft.CodeAnalysis.FunctionResolver.UnitTests.csproj +++ b/src/ExpressionEvaluator/Core/Test/FunctionResolver/Microsoft.CodeAnalysis.FunctionResolver.UnitTests.csproj @@ -8,7 +8,7 @@ Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests Microsoft.CodeAnalysis.ExpressionEvaluator.FunctionResolver.UnitTests true - net46 + net472 $(RoslynDesktopRuntimeIdentifier) UnitTest diff --git a/src/ExpressionEvaluator/Core/Test/ResultProvider/Microsoft.CodeAnalysis.ResultProvider.Utilities.csproj b/src/ExpressionEvaluator/Core/Test/ResultProvider/Microsoft.CodeAnalysis.ResultProvider.Utilities.csproj index 0056ed8421068..989ccdd08dbab 100644 --- a/src/ExpressionEvaluator/Core/Test/ResultProvider/Microsoft.CodeAnalysis.ResultProvider.Utilities.csproj +++ b/src/ExpressionEvaluator/Core/Test/ResultProvider/Microsoft.CodeAnalysis.ResultProvider.Utilities.csproj @@ -8,7 +8,7 @@ Microsoft.CodeAnalysis.ExpressionEvaluator Microsoft.CodeAnalysis.ExpressionEvaluator.ResultProvider.Utilities true - net46 + net472 false diff --git a/src/ExpressionEvaluator/Package/ExpressionEvaluatorPackage.csproj b/src/ExpressionEvaluator/Package/ExpressionEvaluatorPackage.csproj index 108fbc0ffa062..06d27a5a6e573 100644 --- a/src/ExpressionEvaluator/Package/ExpressionEvaluatorPackage.csproj +++ b/src/ExpressionEvaluator/Package/ExpressionEvaluatorPackage.csproj @@ -6,7 +6,7 @@ AnyCPU Library Vsix - net46 + net472 true @@ -36,6 +36,7 @@ BuiltProjectOutputGroup%3bVsdConfigOutputGroup DebugSymbolsProjectOutputGroup true + TargetFramework=netstandard1.3 ResultProvider.Portable @@ -81,6 +82,8 @@ + + diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Microsoft.CodeAnalysis.VisualBasic.ExpressionCompiler.vbproj b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Microsoft.CodeAnalysis.VisualBasic.ExpressionCompiler.vbproj index 83dc7b473bcc7..951df45876921 100644 --- a/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Microsoft.CodeAnalysis.VisualBasic.ExpressionCompiler.vbproj +++ b/src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Microsoft.CodeAnalysis.VisualBasic.ExpressionCompiler.vbproj @@ -6,7 +6,7 @@ AnyCPU Library Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ExpressionCompiler - netstandard1.3 + netstandard2.0 diff --git a/src/ExpressionEvaluator/VisualBasic/Source/ResultProvider/Portable/Microsoft.CodeAnalysis.VisualBasic.ResultProvider.vbproj b/src/ExpressionEvaluator/VisualBasic/Source/ResultProvider/Portable/Microsoft.CodeAnalysis.VisualBasic.ResultProvider.vbproj index 33a4891c7670e..6bd32a43d8733 100644 --- a/src/ExpressionEvaluator/VisualBasic/Source/ResultProvider/Portable/Microsoft.CodeAnalysis.VisualBasic.ResultProvider.vbproj +++ b/src/ExpressionEvaluator/VisualBasic/Source/ResultProvider/Portable/Microsoft.CodeAnalysis.VisualBasic.ResultProvider.vbproj @@ -6,6 +6,7 @@ AnyCPU Library Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ResultProvider + netstandard1.3 diff --git a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/Microsoft.CodeAnalysis.VisualBasic.ExpressionCompiler.UnitTests.vbproj b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/Microsoft.CodeAnalysis.VisualBasic.ExpressionCompiler.UnitTests.vbproj index 8e7b2b3775393..bd2d5a8459011 100644 --- a/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/Microsoft.CodeAnalysis.VisualBasic.ExpressionCompiler.UnitTests.vbproj +++ b/src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/Microsoft.CodeAnalysis.VisualBasic.ExpressionCompiler.UnitTests.vbproj @@ -6,7 +6,7 @@ AnyCPU Library Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ExpressionCompiler.UnitTests - net46 + net472 $(RoslynDesktopRuntimeIdentifier) UnitTest diff --git a/src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/Microsoft.CodeAnalysis.VisualBasic.ResultProvider.UnitTests.vbproj b/src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/Microsoft.CodeAnalysis.VisualBasic.ResultProvider.UnitTests.vbproj index 0885fa5713a4b..a13dfca20aa63 100644 --- a/src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/Microsoft.CodeAnalysis.VisualBasic.ResultProvider.UnitTests.vbproj +++ b/src/ExpressionEvaluator/VisualBasic/Test/ResultProvider/Microsoft.CodeAnalysis.VisualBasic.ResultProvider.UnitTests.vbproj @@ -6,7 +6,7 @@ AnyCPU Library Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ResultProvider.UnitTests - net46 + net472 $(RoslynDesktopRuntimeIdentifier) Default UnitTest diff --git a/src/Features/CSharp/Portable/CSharpFeaturesResources.Designer.cs b/src/Features/CSharp/Portable/CSharpFeaturesResources.Designer.cs index cfcf8a09ddedf..938ee807f618b 100644 --- a/src/Features/CSharp/Portable/CSharpFeaturesResources.Designer.cs +++ b/src/Features/CSharp/Portable/CSharpFeaturesResources.Designer.cs @@ -665,6 +665,15 @@ internal static string into_clause { } } + /// + /// Looks up a localized string similar to Introduce 'using' statement. + /// + internal static string Introduce_using_statement { + get { + return ResourceManager.GetString("Introduce_using_statement", resourceCulture); + } + } + /// /// Looks up a localized string similar to Invalid selection.. /// @@ -1252,6 +1261,15 @@ internal static string Upgrade_this_project_to_csharp_language_version_0 { } } + /// + /// Looks up a localized string similar to Use '{0}'. + /// + internal static string Use_0 { + get { + return ResourceManager.GetString("Use_0", resourceCulture); + } + } + /// /// Looks up a localized string similar to Use explicit type. /// diff --git a/src/Features/CSharp/Portable/CSharpFeaturesResources.resx b/src/Features/CSharp/Portable/CSharpFeaturesResources.resx index bd5d29c1b15d6..8d809ecf3af72 100644 --- a/src/Features/CSharp/Portable/CSharpFeaturesResources.resx +++ b/src/Features/CSharp/Portable/CSharpFeaturesResources.resx @@ -572,8 +572,15 @@ Remove unused variables + + Use '{0}' + Add missing usings {Locked="using"} "using" is a C# keyword and should not be localized. + + Introduce 'using' statement + {Locked="using"} "using" is a C# keyword and should not be localized. + \ No newline at end of file diff --git a/src/Features/CSharp/Portable/DocumentationComments/DocCommentConverter.cs b/src/Features/CSharp/Portable/DocumentationComments/DocCommentConverter.cs new file mode 100644 index 0000000000000..1d898e3695318 --- /dev/null +++ b/src/Features/CSharp/Portable/DocumentationComments/DocCommentConverter.cs @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Collections.Generic; +using System.Threading; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.DocumentationComments; +using Microsoft.CodeAnalysis.MetadataAsSource; +using Microsoft.CodeAnalysis.Shared.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.DocumentationComments +{ + internal class DocCommentConverter : CSharpSyntaxRewriter + { + private readonly IDocumentationCommentFormattingService _formattingService; + private readonly CancellationToken _cancellationToken; + + public static SyntaxNode ConvertToRegularComments(SyntaxNode node, IDocumentationCommentFormattingService formattingService, CancellationToken cancellationToken) + { + var converter = new DocCommentConverter(formattingService, cancellationToken); + + return converter.Visit(node); + } + + private DocCommentConverter(IDocumentationCommentFormattingService formattingService, CancellationToken cancellationToken) + : base(visitIntoStructuredTrivia: false) + { + _formattingService = formattingService; + _cancellationToken = cancellationToken; + } + + public override SyntaxNode Visit(SyntaxNode node) + { + _cancellationToken.ThrowIfCancellationRequested(); + + if (node == null) + { + return node; + } + + // Process children first + node = base.Visit(node); + + // Check the leading trivia for doc comments. + if (node.GetLeadingTrivia().Any(SyntaxKind.SingleLineDocumentationCommentTrivia)) + { + var newLeadingTrivia = new List(); + + foreach (var trivia in node.GetLeadingTrivia()) + { + if (trivia.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia) + { + newLeadingTrivia.Add(SyntaxFactory.Comment("//")); + newLeadingTrivia.Add(SyntaxFactory.ElasticCarriageReturnLineFeed); + + var structuredTrivia = (DocumentationCommentTriviaSyntax)trivia.GetStructure(); + newLeadingTrivia.AddRange(ConvertDocCommentToRegularComment(structuredTrivia)); + } + else + { + newLeadingTrivia.Add(trivia); + } + } + + node = node.WithLeadingTrivia(newLeadingTrivia); + } + + return node; + } + + private IEnumerable ConvertDocCommentToRegularComment(DocumentationCommentTriviaSyntax structuredTrivia) + { + var xmlFragment = DocumentationCommentUtilities.ExtractXMLFragment(structuredTrivia.ToFullString(), "///"); + + var docComment = DocumentationComment.FromXmlFragment(xmlFragment); + + var commentLines = AbstractMetadataAsSourceService.DocCommentFormatter.Format(_formattingService, docComment); + + foreach (var line in commentLines) + { + if (!string.IsNullOrWhiteSpace(line)) + { + yield return SyntaxFactory.Comment("// " + line); + } + else + { + yield return SyntaxFactory.Comment("//"); + } + + yield return SyntaxFactory.ElasticCarriageReturnLineFeed; + } + } + } +} diff --git a/src/Features/CSharp/Portable/IntroduceUsingStatement/CSharpIntroduceUsingStatementCodeRefactoringProvider.cs b/src/Features/CSharp/Portable/IntroduceUsingStatement/CSharpIntroduceUsingStatementCodeRefactoringProvider.cs new file mode 100644 index 0000000000000..60e4df6d817f1 --- /dev/null +++ b/src/Features/CSharp/Portable/IntroduceUsingStatement/CSharpIntroduceUsingStatementCodeRefactoringProvider.cs @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Composition; +using Microsoft.CodeAnalysis.CodeRefactorings; +using Microsoft.CodeAnalysis.CSharp.Extensions; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.IntroduceUsingStatement; +using Roslyn.Utilities; + +namespace Microsoft.CodeAnalysis.CSharp.IntroduceUsingStatement +{ + [ExtensionOrder(Before = PredefinedCodeRefactoringProviderNames.IntroduceVariable)] + [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.IntroduceUsingStatement), Shared] + internal sealed class CSharpIntroduceUsingStatementCodeRefactoringProvider + : AbstractIntroduceUsingStatementCodeRefactoringProvider + { + protected override string CodeActionTitle => CSharpFeaturesResources.Introduce_using_statement; + + protected override bool CanRefactorToContainBlockStatements(SyntaxNode parent) + { + return parent is BlockSyntax || parent is SwitchSectionSyntax || parent.IsEmbeddedStatementOwner(); + } + + protected override SyntaxList GetStatements(SyntaxNode parentOfStatementsToSurround) + { + return + parentOfStatementsToSurround is BlockSyntax block ? block.Statements : + parentOfStatementsToSurround is SwitchSectionSyntax switchSection ? switchSection.Statements : + throw ExceptionUtilities.UnexpectedValue(parentOfStatementsToSurround); + } + + protected override SyntaxNode WithStatements(SyntaxNode parentOfStatementsToSurround, SyntaxList statements) + { + return + parentOfStatementsToSurround is BlockSyntax block ? block.WithStatements(statements) as SyntaxNode : + parentOfStatementsToSurround is SwitchSectionSyntax switchSection ? switchSection.WithStatements(statements) : + throw ExceptionUtilities.UnexpectedValue(parentOfStatementsToSurround); + } + + protected override StatementSyntax CreateUsingStatement(LocalDeclarationStatementSyntax declarationStatement, SyntaxTriviaList sameLineTrivia, SyntaxList statementsToSurround) + { + var usingStatement = SyntaxFactory.UsingStatement( + declaration: declarationStatement.Declaration.WithoutTrivia(), + expression: null, // Declaration already has equals token and expression + statement: SyntaxFactory.Block(statementsToSurround)); + + return usingStatement + .WithCloseParenToken(usingStatement.CloseParenToken + .WithTrailingTrivia(sameLineTrivia)); + } + } +} diff --git a/src/Features/CSharp/Portable/MetadataAsSource/CSharpMetadataAsSourceService.cs b/src/Features/CSharp/Portable/MetadataAsSource/CSharpMetadataAsSourceService.cs index c5520cf337af0..7f2cf2481345c 100644 --- a/src/Features/CSharp/Portable/MetadataAsSource/CSharpMetadataAsSourceService.cs +++ b/src/Features/CSharp/Portable/MetadataAsSource/CSharpMetadataAsSourceService.cs @@ -6,6 +6,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; +using Microsoft.CodeAnalysis.CSharp.DocumentationComments; using Microsoft.CodeAnalysis.CSharp.Simplification; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; @@ -127,87 +128,5 @@ protected override bool IsNewLine(char c) return SyntaxFacts.IsNewLine(c); } } - - private class DocCommentConverter : CSharpSyntaxRewriter - { - private readonly IDocumentationCommentFormattingService _formattingService; - private readonly CancellationToken _cancellationToken; - - public static SyntaxNode ConvertToRegularComments(SyntaxNode node, IDocumentationCommentFormattingService formattingService, CancellationToken cancellationToken) - { - var converter = new DocCommentConverter(formattingService, cancellationToken); - - return converter.Visit(node); - } - - private DocCommentConverter(IDocumentationCommentFormattingService formattingService, CancellationToken cancellationToken) - : base(visitIntoStructuredTrivia: false) - { - _formattingService = formattingService; - _cancellationToken = cancellationToken; - } - - public override SyntaxNode Visit(SyntaxNode node) - { - _cancellationToken.ThrowIfCancellationRequested(); - - if (node == null) - { - return node; - } - - // Process children first - node = base.Visit(node); - - // Check the leading trivia for doc comments. - if (node.GetLeadingTrivia().Any(SyntaxKind.SingleLineDocumentationCommentTrivia)) - { - var newLeadingTrivia = new List(); - - foreach (var trivia in node.GetLeadingTrivia()) - { - if (trivia.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia) - { - newLeadingTrivia.Add(SyntaxFactory.Comment("//")); - newLeadingTrivia.Add(SyntaxFactory.ElasticCarriageReturnLineFeed); - - var structuredTrivia = (DocumentationCommentTriviaSyntax)trivia.GetStructure(); - newLeadingTrivia.AddRange(ConvertDocCommentToRegularComment(structuredTrivia)); - } - else - { - newLeadingTrivia.Add(trivia); - } - } - - node = node.WithLeadingTrivia(newLeadingTrivia); - } - - return node; - } - - private IEnumerable ConvertDocCommentToRegularComment(DocumentationCommentTriviaSyntax structuredTrivia) - { - var xmlFragment = DocumentationCommentUtilities.ExtractXMLFragment(structuredTrivia.ToFullString(), "///"); - - var docComment = DocumentationComment.FromXmlFragment(xmlFragment); - - var commentLines = AbstractMetadataAsSourceService.DocCommentFormatter.Format(_formattingService, docComment); - - foreach (var line in commentLines) - { - if (!string.IsNullOrWhiteSpace(line)) - { - yield return SyntaxFactory.Comment("// " + line); - } - else - { - yield return SyntaxFactory.Comment("//"); - } - - yield return SyntaxFactory.ElasticCarriageReturnLineFeed; - } - } - } } } diff --git a/src/Features/CSharp/Portable/Microsoft.CodeAnalysis.CSharp.Features.csproj b/src/Features/CSharp/Portable/Microsoft.CodeAnalysis.CSharp.Features.csproj index 973bf8194159c..f2a0f0ce1acd3 100644 --- a/src/Features/CSharp/Portable/Microsoft.CodeAnalysis.CSharp.Features.csproj +++ b/src/Features/CSharp/Portable/Microsoft.CodeAnalysis.CSharp.Features.csproj @@ -6,7 +6,7 @@ AnyCPU Library Microsoft.CodeAnalysis.CSharp - netstandard1.3 + netstandard2.0 true @@ -65,7 +65,6 @@ - diff --git a/src/Features/CSharp/Portable/MoveDeclarationNearReference/CSharpMoveDeclarationNearReferenceCodeRefactoringProvider.cs b/src/Features/CSharp/Portable/MoveDeclarationNearReference/CSharpMoveDeclarationNearReferenceService.cs similarity index 82% rename from src/Features/CSharp/Portable/MoveDeclarationNearReference/CSharpMoveDeclarationNearReferenceCodeRefactoringProvider.cs rename to src/Features/CSharp/Portable/MoveDeclarationNearReference/CSharpMoveDeclarationNearReferenceService.cs index 9138d6e2afd42..6e2ba6a230195 100644 --- a/src/Features/CSharp/Portable/MoveDeclarationNearReference/CSharpMoveDeclarationNearReferenceCodeRefactoringProvider.cs +++ b/src/Features/CSharp/Portable/MoveDeclarationNearReference/CSharpMoveDeclarationNearReferenceService.cs @@ -1,21 +1,19 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Composition; -using System.Linq; using System.Threading; using System.Threading.Tasks; -using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MoveDeclarationNearReference; namespace Microsoft.CodeAnalysis.CSharp.MoveDeclarationNearReference { - [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.MoveDeclarationNearReference), Shared] - [ExtensionOrder(After = PredefinedCodeRefactoringProviderNames.InlineTemporary)] - internal partial class CSharpMoveDeclarationNearReferenceCodeRefactoringProvider : - AbstractMoveDeclarationNearReferenceCodeRefactoringProvider< - CSharpMoveDeclarationNearReferenceCodeRefactoringProvider, + [ExportLanguageService(typeof(IMoveDeclarationNearReferenceService), LanguageNames.CSharp), Shared] + internal partial class CSharpMoveDeclarationNearReferenceService : + AbstractMoveDeclarationNearReferenceService< + CSharpMoveDeclarationNearReferenceService, StatementSyntax, LocalDeclarationStatementSyntax, VariableDeclaratorSyntax> diff --git a/src/Features/CSharp/Portable/ReplaceDefaultLiteral/CSharpReplaceDefaultLiteralCodeFixProvider.cs b/src/Features/CSharp/Portable/ReplaceDefaultLiteral/CSharpReplaceDefaultLiteralCodeFixProvider.cs new file mode 100644 index 0000000000000..8a658e0570f7f --- /dev/null +++ b/src/Features/CSharp/Portable/ReplaceDefaultLiteral/CSharpReplaceDefaultLiteralCodeFixProvider.cs @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Immutable; +using System.Composition; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CSharp.Extensions; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Editing; +using Microsoft.CodeAnalysis.Shared.Extensions; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.CSharp.ReplaceDefaultLiteral +{ + [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.ReplaceDefaultLiteral), Shared] + internal sealed class CSharpReplaceDefaultLiteralCodeFixProvider : CodeFixProvider + { + private const string CS8313 = nameof(CS8313); // A default literal 'default' is not valid as a case constant. Use another literal (e.g. '0' or 'null') as appropriate. If you intended to write the default label, use 'default:' without 'case'. + private const string CS8363 = nameof(CS8363); // A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern 'var _'. + + public override ImmutableArray FixableDiagnosticIds { get; } = + ImmutableArray.Create(CS8313, CS8363); + + public override FixAllProvider GetFixAllProvider() + { + // This code fix addresses very specific compiler errors. It's unlikely there will be more than 1 of them at a time. + return null; + } + + public override async Task RegisterCodeFixesAsync(CodeFixContext context) + { + var syntaxRoot = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); + var token = syntaxRoot.FindToken(context.Span.Start); + + if (token.Span == context.Span && + token.IsKind(SyntaxKind.DefaultKeyword) && + token.Parent.IsKind(SyntaxKind.DefaultLiteralExpression)) + { + var defaultLiteral = (LiteralExpressionSyntax)token.Parent; + var semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false); + + var (newExpression, displayText) = GetReplacementExpressionAndText( + context.Document, semanticModel, defaultLiteral, context.CancellationToken); + + if (newExpression != null) + { + context.RegisterCodeFix( + new MyCodeAction( + c => ReplaceAsync(context.Document, context.Span, newExpression, c), + displayText), + context.Diagnostics); + } + } + } + + private static async Task ReplaceAsync( + Document document, TextSpan span, SyntaxNode newExpression, CancellationToken cancellationToken) + { + var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + + var defaultToken = syntaxRoot.FindToken(span.Start); + var defaultLiteral = (LiteralExpressionSyntax)defaultToken.Parent; + + var newRoot = syntaxRoot.ReplaceNode(defaultLiteral, newExpression.WithTriviaFrom(defaultLiteral)); + return document.WithSyntaxRoot(newRoot); + } + + private static (SyntaxNode newExpression, string displayText) GetReplacementExpressionAndText( + Document document, + SemanticModel semanticModel, + LiteralExpressionSyntax defaultLiteral, + CancellationToken cancellationToken) + { + var generator = SyntaxGenerator.GetGenerator(document); + + var type = semanticModel.GetTypeInfo(defaultLiteral, cancellationToken).ConvertedType; + if (type != null && type.TypeKind != TypeKind.Error) + { + if (IsFlagsEnum(type, semanticModel.Compilation) && + type.GetMembers("None").FirstOrDefault() is IFieldSymbol field && IsZero(field.ConstantValue)) + { + return GenerateMemberAccess("None"); + } + else if (type.Equals(semanticModel.Compilation.GetTypeByMetadataName(typeof(CancellationToken).FullName))) + { + return GenerateMemberAccess(nameof(CancellationToken.None)); + } + else if (type.SpecialType == SpecialType.System_IntPtr || type.SpecialType == SpecialType.System_UIntPtr) + { + return GenerateMemberAccess(nameof(IntPtr.Zero)); + } + else if (semanticModel.GetConstantValue(defaultLiteral, cancellationToken) is var constant && constant.HasValue) + { + var newLiteral = generator.LiteralExpression(constant.Value); + return (newLiteral, newLiteral.ToString()); + } + else if (!type.ContainsAnonymousType()) + { + var defaultExpression = generator.DefaultExpression(type); + return (defaultExpression, $"default({type.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)})"); + } + } + + return default; + + (SyntaxNode newExpression, string displayText) GenerateMemberAccess(string memberName) + { + var memberAccess = generator.MemberAccessExpression(generator.TypeExpression(type), memberName); + return (memberAccess, $"{type.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)}.{memberName}"); + } + } + + private static bool IsFlagsEnum(ITypeSymbol type, Compilation compilation) + { + var flagsAttribute = compilation.GetTypeByMetadataName(typeof(FlagsAttribute).FullName); + return type.TypeKind == TypeKind.Enum && + type.GetAttributes().Any(attribute => attribute.AttributeClass.Equals(flagsAttribute)); + } + + private static bool IsZero(object o) + { + switch (o) + { + case default(int): + case default(uint): + case default(byte): + case default(sbyte): + case default(short): + case default(ushort): + case default(long): + case default(ulong): + return true; + default: + return false; + } + } + + private sealed class MyCodeAction : CodeAction.DocumentChangeAction + { + public MyCodeAction(Func> createChangedDocument, string literal) + : base(string.Format(CSharpFeaturesResources.Use_0, literal), createChangedDocument, CSharpFeaturesResources.Use_0) + { + } + } + } +} diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.cs.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.cs.xlf index a4f24203d4f2f..b0d9115111505 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.cs.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.cs.xlf @@ -77,6 +77,11 @@ Zjistily se konflikty. + + Introduce 'using' statement + Introduce 'using' statement + {Locked="using"} "using" is a C# keyword and should not be localized. + Make private fields readonly when possible Make private fields readonly when possible @@ -112,6 +117,11 @@ Sort accessibility modifiers + + Use '{0}' + Use '{0}' + + 'if' statement can be simplified 'if' statement can be simplified diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.de.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.de.xlf index 28547a3d5c397..742a2721524aa 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.de.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.de.xlf @@ -77,6 +77,11 @@ Konflikt(e) erkannt. + + Introduce 'using' statement + Introduce 'using' statement + {Locked="using"} "using" is a C# keyword and should not be localized. + Make private fields readonly when possible Make private fields readonly when possible @@ -112,6 +117,11 @@ Sort accessibility modifiers + + Use '{0}' + Use '{0}' + + 'if' statement can be simplified 'if' statement can be simplified diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.es.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.es.xlf index 83b371aa29412..ea9ec47916e5c 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.es.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.es.xlf @@ -77,6 +77,11 @@ Conflicto(s) detectado(s). + + Introduce 'using' statement + Introduce 'using' statement + {Locked="using"} "using" is a C# keyword and should not be localized. + Make private fields readonly when possible Make private fields readonly when possible @@ -112,6 +117,11 @@ Sort accessibility modifiers + + Use '{0}' + Use '{0}' + + 'if' statement can be simplified 'if' statement can be simplified diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.fr.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.fr.xlf index 8f2f5170be41e..997b51e8aa1be 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.fr.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.fr.xlf @@ -77,6 +77,11 @@ Conflit(s) détecté(s). + + Introduce 'using' statement + Introduce 'using' statement + {Locked="using"} "using" is a C# keyword and should not be localized. + Make private fields readonly when possible Make private fields readonly when possible @@ -112,6 +117,11 @@ Sort accessibility modifiers + + Use '{0}' + Use '{0}' + + 'if' statement can be simplified 'if' statement can be simplified diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.it.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.it.xlf index a7b91e7bcab13..0b83245d4b62b 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.it.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.it.xlf @@ -77,6 +77,11 @@ Sono stati rilevati conflitti + + Introduce 'using' statement + Introduce 'using' statement + {Locked="using"} "using" is a C# keyword and should not be localized. + Make private fields readonly when possible Make private fields readonly when possible @@ -112,6 +117,11 @@ Sort accessibility modifiers + + Use '{0}' + Use '{0}' + + 'if' statement can be simplified 'if' statement can be simplified diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ja.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ja.xlf index b1baeeaea48b6..65f501f65215d 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ja.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ja.xlf @@ -77,6 +77,11 @@ 競合が検出されました。 + + Introduce 'using' statement + Introduce 'using' statement + {Locked="using"} "using" is a C# keyword and should not be localized. + Make private fields readonly when possible Make private fields readonly when possible @@ -112,6 +117,11 @@ Sort accessibility modifiers + + Use '{0}' + Use '{0}' + + 'if' statement can be simplified 'if' statement can be simplified diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ko.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ko.xlf index f486e558fc3fd..e7959149a2c03 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ko.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ko.xlf @@ -77,6 +77,11 @@ 충돌이 감지되었습니다. + + Introduce 'using' statement + Introduce 'using' statement + {Locked="using"} "using" is a C# keyword and should not be localized. + Make private fields readonly when possible Make private fields readonly when possible @@ -112,6 +117,11 @@ Sort accessibility modifiers + + Use '{0}' + Use '{0}' + + 'if' statement can be simplified 'if' statement can be simplified diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.pl.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.pl.xlf index e253fc3f27f59..98f63185b371c 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.pl.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.pl.xlf @@ -77,6 +77,11 @@ Wykryto konflikty. + + Introduce 'using' statement + Introduce 'using' statement + {Locked="using"} "using" is a C# keyword and should not be localized. + Make private fields readonly when possible Make private fields readonly when possible @@ -112,6 +117,11 @@ Sort accessibility modifiers + + Use '{0}' + Use '{0}' + + 'if' statement can be simplified 'if' statement can be simplified diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.pt-BR.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.pt-BR.xlf index ac9595dfc6001..726a184c2d913 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.pt-BR.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.pt-BR.xlf @@ -77,6 +77,11 @@ Conflito(s) detectado(s). + + Introduce 'using' statement + Introduce 'using' statement + {Locked="using"} "using" is a C# keyword and should not be localized. + Make private fields readonly when possible Make private fields readonly when possible @@ -112,6 +117,11 @@ Sort accessibility modifiers + + Use '{0}' + Use '{0}' + + 'if' statement can be simplified 'if' statement can be simplified diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ru.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ru.xlf index 5aa8fe5a314f5..f08c4e6538344 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ru.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.ru.xlf @@ -77,6 +77,11 @@ Обнаружены конфликты. + + Introduce 'using' statement + Introduce 'using' statement + {Locked="using"} "using" is a C# keyword and should not be localized. + Make private fields readonly when possible Make private fields readonly when possible @@ -112,6 +117,11 @@ Sort accessibility modifiers + + Use '{0}' + Use '{0}' + + 'if' statement can be simplified 'if' statement can be simplified diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.tr.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.tr.xlf index 066f1d407a23d..a90572b227a6b 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.tr.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.tr.xlf @@ -77,6 +77,11 @@ Çakışmalar algılandı. + + Introduce 'using' statement + Introduce 'using' statement + {Locked="using"} "using" is a C# keyword and should not be localized. + Make private fields readonly when possible Make private fields readonly when possible @@ -112,6 +117,11 @@ Sort accessibility modifiers + + Use '{0}' + Use '{0}' + + 'if' statement can be simplified 'if' statement can be simplified diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.zh-Hans.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.zh-Hans.xlf index b1f47ceb70269..136829077e826 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.zh-Hans.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.zh-Hans.xlf @@ -77,6 +77,11 @@ 检测到冲突。 + + Introduce 'using' statement + Introduce 'using' statement + {Locked="using"} "using" is a C# keyword and should not be localized. + Make private fields readonly when possible Make private fields readonly when possible @@ -112,6 +117,11 @@ Sort accessibility modifiers + + Use '{0}' + Use '{0}' + + 'if' statement can be simplified 'if' statement can be simplified diff --git a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.zh-Hant.xlf b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.zh-Hant.xlf index 04724b3c1f582..8107b45a09402 100644 --- a/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.zh-Hant.xlf +++ b/src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.zh-Hant.xlf @@ -77,6 +77,11 @@ 偵測到衝突。 + + Introduce 'using' statement + Introduce 'using' statement + {Locked="using"} "using" is a C# keyword and should not be localized. + Make private fields readonly when possible Make private fields readonly when possible @@ -112,6 +117,11 @@ Sort accessibility modifiers + + Use '{0}' + Use '{0}' + + 'if' statement can be simplified 'if' statement can be simplified diff --git a/src/Features/Core/Portable/CodeFixes/PredefinedCodeFixProviderNames.cs b/src/Features/Core/Portable/CodeFixes/PredefinedCodeFixProviderNames.cs index 9009f056dcb88..2e52e425d5cb5 100644 --- a/src/Features/Core/Portable/CodeFixes/PredefinedCodeFixProviderNames.cs +++ b/src/Features/Core/Portable/CodeFixes/PredefinedCodeFixProviderNames.cs @@ -41,6 +41,7 @@ internal static class PredefinedCodeFixProviderNames public const string MoveToTopOfFile = nameof(MoveToTopOfFile); public const string PopulateSwitch = nameof(PopulateSwitch); public const string QualifyMemberAccess = nameof(QualifyMemberAccess); + public const string ReplaceDefaultLiteral = nameof(ReplaceDefaultLiteral); public const string RemoveUnnecessaryCast = nameof(RemoveUnnecessaryCast); public const string DeclareAsNullable = nameof(DeclareAsNullable); public const string RemoveUnnecessaryImports = nameof(RemoveUnnecessaryImports); diff --git a/src/Features/Core/Portable/CodeRefactoringHelpers.cs b/src/Features/Core/Portable/CodeRefactoringHelpers.cs new file mode 100644 index 0000000000000..76f450a52e0fc --- /dev/null +++ b/src/Features/Core/Portable/CodeRefactoringHelpers.cs @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Collections.Immutable; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis +{ + internal static class CodeRefactoringHelpers + { + public static Task RefactoringSelectionIsValidAsync( + Document document, TextSpan selection, SyntaxNode node, CancellationToken cancellation) + { + return RefactoringSelectionIsValidAsync(document, selection, node, ImmutableArray.Empty, cancellation); + } + + /// + /// + /// Determines if a refactoring should be offered for a given node, given the specified selection in a document. + /// The refactoring is offered either if the selection is zero-width and not inside one of the specified holes + /// or if the selection contains the entire node and perhaps some whitespace. + /// + /// + /// Note: this function considers the span containing the node to start at the earliest preceding whitespace + /// (including up to one newline) before the node’s and up through the last + /// whitespace following the ’s . + /// + /// + /// For the , the position is considered invalid if it is *within* the hole, not if it + /// is touching the hole edges. + /// + /// + public static async Task RefactoringSelectionIsValidAsync( + Document document, + TextSpan selection, + SyntaxNode node, + ImmutableArray holes, + CancellationToken cancellationToken) + { + if (selection.Length == 0) + { + return await RefactoringPositionIsValidAsync( + document, selection.Start, node, holes, cancellationToken).ConfigureAwait(false); + } + + // If we have a selection, it needs to be selecting at least the full node. We allow the selection to start + // in whitespace (including up to one newline) before the start of the node, and we allow it to end after + // the end of the node and the end of the line the node ends on. + var expandedSpan = await GetExpandedNodeSpan(document, node, cancellationToken).ConfigureAwait(false); + if ((selection.Start >= expandedSpan.Start && selection.Start <= node.SpanStart) && + (selection.End >= node.Span.End && selection.End <= expandedSpan.End)) + { + return true; + } + + return false; + } + + /// + /// + /// Determines if a refactoring should be offered for a given node, given the specified position in a document. + /// The refactoring is offered if the position is somewhere on the span containing the node and not in any of + /// the specified to avoid. + /// + /// + /// Note: this function considers the span containing the node to start at the earliest preceding whitespace + /// (including up to one newline) before the node’s and up through the last + /// whitespace following the ’s . + /// + /// + /// For the , the position is considered invalid if it is *within* the hole, not if it + /// is touching the hole edges. + /// + /// + public static async Task RefactoringPositionIsValidAsync( + Document document, + int position, + SyntaxNode node, + ImmutableArray holes, + CancellationToken cancellationToken) + { + var expandedSpan = await GetExpandedNodeSpan(document, node, cancellationToken).ConfigureAwait(false); + if (!expandedSpan.IntersectsWith(position)) + { + // Position isn’t within the node’s widened span. Definitely not valid here. + return false; + } + + foreach (var hole in holes) + { + if (position > hole.Span.Start && position < hole.Span.End) + { + // Position was in one of the holes. Not valid here. + return false; + } + } + + return true; + } + + private static async Task GetExpandedNodeSpan( + Document document, + SyntaxNode node, + CancellationToken cancellationToken) + { + var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); + + var nodeStartLine = sourceText.Lines.GetLineFromPosition(node.SpanStart); + + // Enable vertical selections that catch the previous line break and perhaps some whitespace. + if (nodeStartLine.LineNumber != 0) + { + nodeStartLine = sourceText.Lines[nodeStartLine.LineNumber - 1]; + } + + var nodeEndLine = sourceText.Lines.GetLineFromPosition(node.Span.End); + + var start = node.SpanStart; + var end = node.Span.End; + + while (start > nodeStartLine.Start && char.IsWhiteSpace(sourceText[start - 1])) + { + start--; + } + + while (end < nodeEndLine.End && char.IsWhiteSpace(sourceText[end])) + { + end++; + } + + return TextSpan.FromBounds(start, end); + } + } +} diff --git a/src/Features/Core/Portable/CodeRefactorings/PredefinedCodeRefactoringProviderNames.cs b/src/Features/Core/Portable/CodeRefactorings/PredefinedCodeRefactoringProviderNames.cs index 7de928a49bfb5..8184ee2aae646 100644 --- a/src/Features/Core/Portable/CodeRefactorings/PredefinedCodeRefactoringProviderNames.cs +++ b/src/Features/Core/Portable/CodeRefactorings/PredefinedCodeRefactoringProviderNames.cs @@ -19,6 +19,7 @@ internal static class PredefinedCodeRefactoringProviderNames public const string GenerateEqualsAndGetHashCodeFromMembers = "Generate Equals and GetHashCode Code Action Provider"; public const string GenerateOverrides = "Generate Overrides Code Action Provider"; public const string InlineTemporary = "Inline Temporary Code Action Provider"; + public const string IntroduceUsingStatement = "Introduce Using Statement Code Action Provider"; public const string IntroduceVariable = "Introduce Variable Code Action Provider"; public const string InvertConditional = "Invert Conditional Code Action Provider"; public const string InvertIf = "Invert If Code Action Provider"; diff --git a/src/Features/Core/Portable/IntroduceUsingStatement/AbstractIntroduceUsingStatementCodeRefactoringProvider.cs b/src/Features/Core/Portable/IntroduceUsingStatement/AbstractIntroduceUsingStatementCodeRefactoringProvider.cs new file mode 100644 index 0000000000000..cdcdf76d90068 --- /dev/null +++ b/src/Features/Core/Portable/IntroduceUsingStatement/AbstractIntroduceUsingStatementCodeRefactoringProvider.cs @@ -0,0 +1,295 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CodeRefactorings; +using Microsoft.CodeAnalysis.Formatting; +using Microsoft.CodeAnalysis.LanguageServices; +using Microsoft.CodeAnalysis.Operations; +using Microsoft.CodeAnalysis.Shared.Extensions; +using Microsoft.CodeAnalysis.Text; +using Microsoft.CodeAnalysis.Utilities; +using Roslyn.Utilities; +using static Microsoft.CodeAnalysis.CodeActions.CodeAction; + +namespace Microsoft.CodeAnalysis.IntroduceUsingStatement +{ + internal abstract class AbstractIntroduceUsingStatementCodeRefactoringProvider : CodeRefactoringProvider + where TStatementSyntax : SyntaxNode + where TLocalDeclarationSyntax : TStatementSyntax + { + protected abstract string CodeActionTitle { get; } + + protected abstract bool CanRefactorToContainBlockStatements(SyntaxNode parent); + protected abstract SyntaxList GetStatements(SyntaxNode parentOfStatementsToSurround); + protected abstract SyntaxNode WithStatements(SyntaxNode parentOfStatementsToSurround, SyntaxList statements); + + protected abstract TStatementSyntax CreateUsingStatement(TLocalDeclarationSyntax declarationStatement, SyntaxTriviaList sameLineTrivia, SyntaxList statementsToSurround); + + public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) + { + var document = context.Document; + var span = context.Span; + + var (declarationSyntax, _) = + await FindDisposableLocalDeclaration(document, span, context.CancellationToken).ConfigureAwait(false); + + if (declarationSyntax != null) + { + context.RegisterRefactoring(new MyCodeAction( + CodeActionTitle, + cancellationToken => IntroduceUsingStatementAsync(document, span, cancellationToken))); + } + } + + private async Task<(TLocalDeclarationSyntax, ILocalSymbol)> FindDisposableLocalDeclaration(Document document, TextSpan selection, CancellationToken cancellationToken) + { + var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + + var declarationSyntax = + root.FindNode(selection)?.GetAncestorOrThis() + ?? root.FindTokenOnLeftOfPosition(selection.End).GetAncestor(); + + if (declarationSyntax is null || !CanRefactorToContainBlockStatements(declarationSyntax.Parent)) + { + return default; + } + + var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); + + var disposableType = semanticModel.Compilation.GetSpecialType(SpecialType.System_IDisposable); + if (disposableType is null) + { + return default; + } + + var operation = semanticModel.GetOperation(declarationSyntax, cancellationToken) as IVariableDeclarationGroupOperation; + if (operation?.Declarations.Length != 1) + { + return default; + } + + var localDeclaration = operation.Declarations[0]; + if (localDeclaration.Declarators.Length != 1) + { + return default; + } + + var declarator = localDeclaration.Declarators[0]; + + var localType = declarator.Symbol?.Type; + if (localType is null) + { + return default; + } + + var initializer = (localDeclaration.Initializer ?? declarator.Initializer)?.Value; + + // Initializer kind is invalid when incomplete declaration syntax ends in an equals token. + if (initializer is null || initializer.Kind == OperationKind.Invalid) + { + return default; + } + + // Infer the intent of the selection. Offer the refactoring only if the selection + // appears to be aimed at the declaration statement but not at its initializer expression. + var isValidSelection = await CodeRefactoringHelpers.RefactoringSelectionIsValidAsync( + document, + selection, + node: declarationSyntax, + holes: ImmutableArray.Create(initializer.Syntax), + cancellationToken).ConfigureAwait(false); + + if (!isValidSelection) + { + return default; + } + + if (!IsLegalUsingStatementType(semanticModel.Compilation, disposableType, localType)) + { + return default; + } + + return (declarationSyntax, declarator.Symbol); + } + + /// + /// Up to date with C# 7.3. Pattern-based disposal is likely to be added to C# 8.0, + /// in which case accessible instance and extension methods will need to be detected. + /// + private static bool IsLegalUsingStatementType(Compilation compilation, ITypeSymbol disposableType, ITypeSymbol type) + { + if (disposableType == null) + { + return false; + } + + // CS1674: type used in a using statement must be implicitly convertible to 'System.IDisposable' + return compilation.ClassifyCommonConversion(type, disposableType).IsImplicit; + } + + private async Task IntroduceUsingStatementAsync( + Document document, + TextSpan span, + CancellationToken cancellationToken) + { + var (declarationStatement, localVariable) = await FindDisposableLocalDeclaration(document, span, cancellationToken).ConfigureAwait(false); + + var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); + + var syntaxFactsService = document.GetLanguageService(); + + var statementsToSurround = GetStatementsToSurround(declarationStatement, localVariable, semanticModel, syntaxFactsService, cancellationToken); + + // Separate the newline from the trivia that is going on the using declaration line. + var trailingTrivia = SplitTrailingTrivia(declarationStatement, syntaxFactsService); + + var usingStatement = + CreateUsingStatement( + declarationStatement, + trailingTrivia.sameLine, + statementsToSurround) + .WithLeadingTrivia(declarationStatement.GetLeadingTrivia()) + .WithTrailingTrivia(trailingTrivia.endOfLine); + + if (statementsToSurround.Any()) + { + var parentStatements = GetStatements(declarationStatement.Parent); + var declarationStatementIndex = parentStatements.IndexOf(declarationStatement); + + var newParent = WithStatements( + declarationStatement.Parent, + new SyntaxList(parentStatements + .Take(declarationStatementIndex) + .Concat(usingStatement) + .Concat(parentStatements.Skip(declarationStatementIndex + 1 + statementsToSurround.Count)))); + + return document.WithSyntaxRoot(root.ReplaceNode( + declarationStatement.Parent, + newParent.WithAdditionalAnnotations(Formatter.Annotation))); + } + else + { + // Either the parent is not blocklike, meaning WithStatements can’t be used as in the other branch, + // or there’s just no need to replace more than the statement itself because no following statements + // will be surrounded. + return document.WithSyntaxRoot(root.ReplaceNode( + declarationStatement, + usingStatement.WithAdditionalAnnotations(Formatter.Annotation))); + } + } + + private SyntaxList GetStatementsToSurround( + TLocalDeclarationSyntax declarationStatement, + ILocalSymbol localVariable, + SemanticModel semanticModel, + ISyntaxFactsService syntaxFactsService, + CancellationToken cancellationToken) + { + // Find the minimal number of statements to move into the using block + // in order to not break existing references to the local. + var lastUsageStatement = FindSiblingStatementContainingLastUsage( + declarationStatement, + localVariable, + semanticModel, + syntaxFactsService, + cancellationToken); + + if (lastUsageStatement == null) + { + return default; + } + + var parentStatements = GetStatements(declarationStatement.Parent); + var declarationStatementIndex = parentStatements.IndexOf(declarationStatement); + var lastUsageStatementIndex = parentStatements.IndexOf(lastUsageStatement, declarationStatementIndex + 1); + + return new SyntaxList(parentStatements + .Take(lastUsageStatementIndex + 1) + .Skip(declarationStatementIndex + 1)); + } + + private static (SyntaxTriviaList sameLine, SyntaxTriviaList endOfLine) SplitTrailingTrivia(SyntaxNode node, ISyntaxFactsService syntaxFactsService) + { + var trailingTrivia = node.GetTrailingTrivia(); + var lastIndex = trailingTrivia.Count - 1; + + return lastIndex != -1 && syntaxFactsService.IsEndOfLineTrivia(trailingTrivia[lastIndex]) + ? (sameLine: trailingTrivia.RemoveAt(lastIndex), endOfLine: new SyntaxTriviaList(trailingTrivia[lastIndex])) + : (sameLine: trailingTrivia, endOfLine: SyntaxTriviaList.Empty); + } + + private static TStatementSyntax FindSiblingStatementContainingLastUsage( + TStatementSyntax declarationSyntax, + ILocalSymbol localVariable, + SemanticModel semanticModel, + ISyntaxFactsService syntaxFactsService, + CancellationToken cancellationToken) + { + foreach (var nodeOrToken in declarationSyntax.Parent.ChildNodesAndTokens().Reverse()) + { + var node = (TStatementSyntax)nodeOrToken.AsNode(); + if (node is null) + { + continue; + } + + if (node == declarationSyntax) + { + break; // Ignore the declaration and usages prior to the declaration + } + + if (ContainsReference(node, localVariable, semanticModel, syntaxFactsService, cancellationToken)) + { + return node; + } + } + + return null; + } + + private static bool ContainsReference( + SyntaxNode node, + ILocalSymbol localVariable, + SemanticModel semanticModel, + ISyntaxFactsService syntaxFactsService, + CancellationToken cancellationToken) + { + if (syntaxFactsService.IsIdentifierName(node)) + { + var identifierName = syntaxFactsService.GetIdentifierOfSimpleName(node).ValueText; + + return syntaxFactsService.StringComparer.Equals(localVariable.Name, identifierName) && + localVariable.Equals(semanticModel.GetSymbolInfo(node).Symbol); + } + + foreach (var nodeOrToken in node.ChildNodesAndTokens()) + { + var childNode = nodeOrToken.AsNode(); + if (childNode is null) + { + continue; + } + + if (ContainsReference(childNode, localVariable, semanticModel, syntaxFactsService, cancellationToken)) + { + return true; + } + } + + return false; + } + + private sealed class MyCodeAction : DocumentChangeAction + { + public MyCodeAction(string title, Func> createChangedDocument) + : base(title, createChangedDocument) + { + } + } + } +} diff --git a/src/Features/Core/Portable/MakeFieldReadonly/MakeFieldReadonlyDiagnosticAnalyzer.cs b/src/Features/Core/Portable/MakeFieldReadonly/MakeFieldReadonlyDiagnosticAnalyzer.cs index 314a8b751a23f..bb1863eebc925 100644 --- a/src/Features/Core/Portable/MakeFieldReadonly/MakeFieldReadonlyDiagnosticAnalyzer.cs +++ b/src/Features/Core/Portable/MakeFieldReadonly/MakeFieldReadonlyDiagnosticAnalyzer.cs @@ -107,7 +107,8 @@ bool IsCandidateField(IFieldSymbol symbol) => !symbol.IsConst && !symbol.IsImplicitlyDeclared && symbol.Locations.Length == 1 && - symbol.Type.IsMutableValueType() == false; + symbol.Type.IsMutableValueType() == false && + !symbol.IsFixedSizeBuffer; // Method to update the field state for a candidate field written outside constructor and field initializer. void UpdateFieldStateOnWrite(IFieldSymbol field) diff --git a/src/Features/Core/Portable/MetadataAsSource/AbstractMetadataAsSourceService.WrappedFieldSymbol.cs b/src/Features/Core/Portable/MetadataAsSource/AbstractMetadataAsSourceService.WrappedFieldSymbol.cs index 4c88c72d9ca3e..6341fd70086fa 100644 --- a/src/Features/Core/Portable/MetadataAsSource/AbstractMetadataAsSourceService.WrappedFieldSymbol.cs +++ b/src/Features/Core/Portable/MetadataAsSource/AbstractMetadataAsSourceService.WrappedFieldSymbol.cs @@ -35,6 +35,8 @@ public WrappedFieldSymbol(IFieldSymbol fieldSymbol, IDocumentationCommentFormatt public bool IsVolatile => _symbol.IsVolatile; + public bool IsFixedSizeBuffer => _symbol.IsFixedSizeBuffer; + public ITypeSymbol Type => _symbol.Type; } } diff --git a/src/Features/Core/Portable/Microsoft.CodeAnalysis.Features.csproj b/src/Features/Core/Portable/Microsoft.CodeAnalysis.Features.csproj index 5221aaa1c7ec5..00ae1c69b60ac 100644 --- a/src/Features/Core/Portable/Microsoft.CodeAnalysis.Features.csproj +++ b/src/Features/Core/Portable/Microsoft.CodeAnalysis.Features.csproj @@ -6,7 +6,7 @@ AnyCPU Library Microsoft.CodeAnalysis - netstandard1.3 + netstandard2.0 true diff --git a/src/Features/Core/Portable/MoveDeclarationNearReference/AbstractMoveDeclarationNearReferenceCodeRefactoringProvider.State.cs b/src/Features/Core/Portable/MoveDeclarationNearReference/AbstractMoveDeclarationNearReferenceService.State.cs similarity index 98% rename from src/Features/Core/Portable/MoveDeclarationNearReference/AbstractMoveDeclarationNearReferenceCodeRefactoringProvider.State.cs rename to src/Features/Core/Portable/MoveDeclarationNearReference/AbstractMoveDeclarationNearReferenceService.State.cs index 8bb34a99fc6cb..50cb065473920 100644 --- a/src/Features/Core/Portable/MoveDeclarationNearReference/AbstractMoveDeclarationNearReferenceCodeRefactoringProvider.State.cs +++ b/src/Features/Core/Portable/MoveDeclarationNearReference/AbstractMoveDeclarationNearReferenceService.State.cs @@ -12,7 +12,7 @@ namespace Microsoft.CodeAnalysis.MoveDeclarationNearReference { - internal partial class AbstractMoveDeclarationNearReferenceCodeRefactoringProvider< + internal partial class AbstractMoveDeclarationNearReferenceService< TService, TStatementSyntax, TLocalDeclarationStatementSyntax, diff --git a/src/Features/Core/Portable/MoveDeclarationNearReference/AbstractMoveDeclarationNearReferenceCodeRefactoringProvider.cs b/src/Features/Core/Portable/MoveDeclarationNearReference/AbstractMoveDeclarationNearReferenceService.cs similarity index 84% rename from src/Features/Core/Portable/MoveDeclarationNearReference/AbstractMoveDeclarationNearReferenceCodeRefactoringProvider.cs rename to src/Features/Core/Portable/MoveDeclarationNearReference/AbstractMoveDeclarationNearReferenceService.cs index 032ef85f33f06..3fe097150d717 100644 --- a/src/Features/Core/Portable/MoveDeclarationNearReference/AbstractMoveDeclarationNearReferenceCodeRefactoringProvider.cs +++ b/src/Features/Core/Portable/MoveDeclarationNearReference/AbstractMoveDeclarationNearReferenceService.cs @@ -1,28 +1,25 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; -using System.Collections.Generic; using System.Collections.Immutable; -using System.Linq; +using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; -using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; -using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.MoveDeclarationNearReference { - internal abstract partial class AbstractMoveDeclarationNearReferenceCodeRefactoringProvider< + internal abstract partial class AbstractMoveDeclarationNearReferenceService< TService, TStatementSyntax, TLocalDeclarationStatementSyntax, - TVariableDeclaratorSyntax> : CodeRefactoringProvider - where TService : AbstractMoveDeclarationNearReferenceCodeRefactoringProvider + TVariableDeclaratorSyntax> : IMoveDeclarationNearReferenceService + where TService : AbstractMoveDeclarationNearReferenceService where TStatementSyntax : SyntaxNode where TLocalDeclarationStatementSyntax : TStatementSyntax where TVariableDeclaratorSyntax : SyntaxNode @@ -34,55 +31,43 @@ internal abstract partial class AbstractMoveDeclarationNearReferenceCodeRefactor protected abstract SyntaxToken GetIdentifierOfVariableDeclarator(TVariableDeclaratorSyntax variableDeclarator); protected abstract Task TypesAreCompatibleAsync(Document document, ILocalSymbol localSymbol, TLocalDeclarationStatementSyntax declarationStatement, SyntaxNode right, CancellationToken cancellationToken); - public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) + public async Task CanMoveDeclarationNearReferenceAsync(Document document, SyntaxNode node, CancellationToken cancellationToken) { - var document = context.Document; - var textSpan = context.Span; - var cancellationToken = context.CancellationToken; - - if (!textSpan.IsEmpty) - { - return; - } + var state = await ComputeStateAsync(document, node, cancellationToken).ConfigureAwait(false); + return state != null; + } - var position = textSpan.Start; - var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - var statement = root.FindToken(position).GetAncestor(); - if (statement == null) + private async Task ComputeStateAsync(Document document, SyntaxNode node, CancellationToken cancellationToken) + { + if (!(node is TLocalDeclarationStatementSyntax statement)) { - return; + return null; } var state = await State.GenerateAsync((TService)this, document, statement, cancellationToken).ConfigureAwait(false); if (state == null) { - return; + return null; } if (!CanMoveToBlock(state.LocalSymbol, state.OutermostBlock, state.InnermostBlock)) { - return; + return null; } - // Don't offer the refactoring inside the initializer for the variable. - var syntaxFacts = document.GetLanguageService(); - var initializer = syntaxFacts.GetInitializerOfVariableDeclarator(state.VariableDeclarator); - var applicableSpan = initializer == null - ? statement.Span - : TextSpan.FromBounds(statement.SpanStart, initializer.SpanStart); + return state; + } - if (!applicableSpan.IntersectsWith(position)) + public async Task MoveDeclarationNearReferenceAsync( + Document document, SyntaxNode localDeclarationStatement, CancellationToken cancellationToken) + { + var state = await ComputeStateAsync(document, localDeclarationStatement, cancellationToken); + if (state == null) { - return; + return document; } - context.RegisterRefactoring( - new MyCodeAction(c => MoveDeclarationNearReferenceAsync(document, state, root, c))); - } - - private async Task MoveDeclarationNearReferenceAsync( - Document document, State state, SyntaxNode root, CancellationToken cancellationToken) - { + var root = await document.GetSyntaxRootAsync(cancellationToken); var editor = new SyntaxEditor(root, document.Project.Solution.Workspace); var crossesMeaningfulBlock = CrossesMeaningfulBlock(state); diff --git a/src/Features/Core/Portable/MoveDeclarationNearReference/IMoveDeclarationNearReferenceService.cs b/src/Features/Core/Portable/MoveDeclarationNearReference/IMoveDeclarationNearReferenceService.cs new file mode 100644 index 0000000000000..fa37e94459444 --- /dev/null +++ b/src/Features/Core/Portable/MoveDeclarationNearReference/IMoveDeclarationNearReferenceService.cs @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Host; + +namespace Microsoft.CodeAnalysis.MoveDeclarationNearReference +{ + internal interface IMoveDeclarationNearReferenceService : ILanguageService + { + /// + /// Returns true if is local declaration statement + /// that can be moved forward to be closer to its first reference. + /// + Task CanMoveDeclarationNearReferenceAsync(Document document, SyntaxNode localDeclarationStatement, CancellationToken cancellationToken); + + /// + /// Moves closer to its first reference. Only + /// applicable if returned + /// true. If not, then the original document will be returned unchanged. + /// + Task MoveDeclarationNearReferenceAsync(Document document, SyntaxNode localDeclarationStatement, CancellationToken cancellationToken); + } +} diff --git a/src/Features/Core/Portable/MoveDeclarationNearReference/MoveDeclarationNearReferenceCodeRefactoringProvider.cs b/src/Features/Core/Portable/MoveDeclarationNearReference/MoveDeclarationNearReferenceCodeRefactoringProvider.cs new file mode 100644 index 0000000000000..2f3e99bed9bae --- /dev/null +++ b/src/Features/Core/Portable/MoveDeclarationNearReference/MoveDeclarationNearReferenceCodeRefactoringProvider.cs @@ -0,0 +1,96 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Composition; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.CodeRefactorings; +using Microsoft.CodeAnalysis.LanguageServices; +using Microsoft.CodeAnalysis.Shared.Extensions; +using Microsoft.CodeAnalysis.Text; + +namespace Microsoft.CodeAnalysis.MoveDeclarationNearReference +{ + [ExportCodeRefactoringProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeRefactoringProviderNames.MoveDeclarationNearReference), Shared] + [ExtensionOrder(After = PredefinedCodeRefactoringProviderNames.InlineTemporary)] + internal sealed class MoveDeclarationNearReferenceCodeRefactoringProvider : CodeRefactoringProvider + { + public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) + { + var document = context.Document; + var textSpan = context.Span; + var cancellationToken = context.CancellationToken; + + if (!textSpan.IsEmpty) + { + return; + } + + var statement = await GetLocalDeclarationStatementAsync(document, textSpan, cancellationToken).ConfigureAwait(false); + if (statement == null) + { + return; + } + + var syntaxFacts = document.GetLanguageService(); + var variables = syntaxFacts.GetVariablesOfLocalDeclarationStatement(statement); + if (variables.Count != 1) + { + return; + } + + // Don't offer the refactoring inside the initializer for the variable. + var initializer = syntaxFacts.GetInitializerOfVariableDeclarator(variables[0]); + var applicableSpan = initializer == null + ? statement.Span + : TextSpan.FromBounds(statement.SpanStart, initializer.SpanStart); + + if (!applicableSpan.IntersectsWith(textSpan.Start)) + { + return; + } + + var service = document.GetLanguageService(); + if (!await service.CanMoveDeclarationNearReferenceAsync( + document, statement, cancellationToken)) + { + return; + } + + context.RegisterRefactoring( + new MyCodeAction(c => MoveDeclarationNearReferenceAsync(document, textSpan, c))); + } + + private async Task GetLocalDeclarationStatementAsync( + Document document, TextSpan textSpan, CancellationToken cancellationToken) + { + var syntaxFacts = document.GetLanguageService(); + + var position = textSpan.Start; + var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + var statement = root.FindToken(position).Parent.Ancestors().FirstOrDefault(n => syntaxFacts.IsLocalDeclarationStatement(n)); + return statement; + } + + private async Task MoveDeclarationNearReferenceAsync( + Document document, TextSpan span, CancellationToken cancellationToken) + { + var statement = await GetLocalDeclarationStatementAsync(document, span, cancellationToken).ConfigureAwait(false); + var service = document.GetLanguageService(); + + return await service.MoveDeclarationNearReferenceAsync(document, statement, cancellationToken); + } + + private class MyCodeAction : CodeAction.DocumentChangeAction + { + public MyCodeAction(Func> createChangedDocument) + : base(FeaturesResources.Move_declaration_near_reference, createChangedDocument) + { + } + + internal override CodeActionPriority Priority => CodeActionPriority.Low; + } + } +} diff --git a/src/Features/Core/Portable/SignatureHelp/AbstractSignatureHelpProvider.cs b/src/Features/Core/Portable/SignatureHelp/AbstractSignatureHelpProvider.cs index 87a1a95830a8f..7c357d48ad803 100644 --- a/src/Features/Core/Portable/SignatureHelp/AbstractSignatureHelpProvider.cs +++ b/src/Features/Core/Portable/SignatureHelp/AbstractSignatureHelpProvider.cs @@ -34,6 +34,15 @@ protected AbstractSignatureHelpProvider() protected abstract Task GetItemsWorkerAsync(Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken); + /// + /// This overload is required for compatibility with existing extensions. + /// + protected static SignatureHelpItems CreateSignatureHelpItems( + IList items, TextSpan applicableSpan, SignatureHelpState state) + { + return CreateSignatureHelpItems(items, applicableSpan, state, selectedItem: null); + } + protected static SignatureHelpItems CreateSignatureHelpItems( IList items, TextSpan applicableSpan, SignatureHelpState state, int? selectedItem) { diff --git a/src/Features/Core/Portable/SolutionCrawler/WorkCoordinator.cs b/src/Features/Core/Portable/SolutionCrawler/WorkCoordinator.cs index f8f2e9f5c80c5..d529fef348129 100644 --- a/src/Features/Core/Portable/SolutionCrawler/WorkCoordinator.cs +++ b/src/Features/Core/Portable/SolutionCrawler/WorkCoordinator.cs @@ -505,7 +505,8 @@ private async Task EnqueueProjectConfigurationChangeWorkItemAsync(ProjectChanges !object.Equals(oldProject.CompilationOptions, newProject.CompilationOptions) || !object.Equals(oldProject.AssemblyName, newProject.AssemblyName) || !object.Equals(oldProject.Name, newProject.Name) || - !object.Equals(oldProject.AnalyzerOptions, newProject.AnalyzerOptions)) + !object.Equals(oldProject.AnalyzerOptions, newProject.AnalyzerOptions) || + !object.Equals(oldProject.DefaultNamespace, newProject.DefaultNamespace)) { projectConfigurationChange = projectConfigurationChange.With(InvocationReasons.ProjectConfigurationChanged); } diff --git a/src/Features/VisualBasic/Portable/CodeFixes/OverloadBase/OverloadBaseCodeFixProvider.AddOverloads.vb b/src/Features/VisualBasic/Portable/CodeFixes/OverloadBase/OverloadBaseCodeFixProvider.AddKeywordAction.vb similarity index 89% rename from src/Features/VisualBasic/Portable/CodeFixes/OverloadBase/OverloadBaseCodeFixProvider.AddOverloads.vb rename to src/Features/VisualBasic/Portable/CodeFixes/OverloadBase/OverloadBaseCodeFixProvider.AddKeywordAction.vb index 44362449caa3f..e87768ae72b7c 100644 --- a/src/Features/VisualBasic/Portable/CodeFixes/OverloadBase/OverloadBaseCodeFixProvider.AddOverloads.vb +++ b/src/Features/VisualBasic/Portable/CodeFixes/OverloadBase/OverloadBaseCodeFixProvider.AddKeywordAction.vb @@ -11,27 +11,31 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.OverloadBase #Disable Warning RS1016 ' Code fix providers should provide FixAll support. https://github.com/dotnet/roslyn/issues/23528 Partial Friend Class OverloadBaseCodeFixProvider #Enable Warning RS1016 - Private Class AddOverloadsKeywordAction + Private Class AddKeywordAction Inherits CodeAction Private ReadOnly _document As Document Private ReadOnly _node As SyntaxNode + Private ReadOnly _title As String + Private ReadOnly _modifier As SyntaxKind Public Overrides ReadOnly Property Title As String Get - Return VBFeaturesResources.Add_Overloads + Return _title End Get End Property Public Overrides ReadOnly Property EquivalenceKey As String Get - Return VBFeaturesResources.Add_Overloads + Return _title End Get End Property - Public Sub New(document As Document, node As SyntaxNode) + Public Sub New(document As Document, node As SyntaxNode, title As String, modifier As SyntaxKind) _document = document _node = node + _title = title + _modifier = modifier End Sub Protected Overrides Async Function GetChangedDocumentAsync(cancellationToken As CancellationToken) As Task(Of Document) @@ -48,12 +52,12 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.OverloadBase Dim propertyStatement = TryCast(node, PropertyStatementSyntax) If propertyStatement IsNot Nothing Then - newNode = propertyStatement.AddModifiers(SyntaxFactory.Token(SyntaxKind.OverloadsKeyword)) + newNode = propertyStatement.AddModifiers(SyntaxFactory.Token(_modifier)) End If Dim methodStatement = TryCast(node, MethodStatementSyntax) If methodStatement IsNot Nothing Then - newNode = methodStatement.AddModifiers(SyntaxFactory.Token(SyntaxKind.OverloadsKeyword)) + newNode = methodStatement.AddModifiers(SyntaxFactory.Token(_modifier)) End If 'Make sure we preserve any trivia from the original node diff --git a/src/Features/VisualBasic/Portable/CodeFixes/OverloadBase/OverloadBaseCodeFixProvider.vb b/src/Features/VisualBasic/Portable/CodeFixes/OverloadBase/OverloadBaseCodeFixProvider.vb index d30d84e6ccfe8..d5f8c5d68ca15 100644 --- a/src/Features/VisualBasic/Portable/CodeFixes/OverloadBase/OverloadBaseCodeFixProvider.vb +++ b/src/Features/VisualBasic/Portable/CodeFixes/OverloadBase/OverloadBaseCodeFixProvider.vb @@ -11,10 +11,11 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.OverloadBase Inherits CodeFixProvider Friend Const BC40003 As String = "BC40003" ' '{0} '{1}' shadows an overloadable member declared in the base class '{2}'. If you want to overload the base method, this method must be declared 'Overloads'. + Friend Const BC40004 As String = "BC40004" ' '{0} '{1}' overloads an overloadable member declared in the base class '{2}'. If you want to shadow the base method, this method must be declared 'Shadows'. Public Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) Get - Return ImmutableArray.Create(BC40003) + Return ImmutableArray.Create(BC40003, BC40004) End Get End Property @@ -30,7 +31,11 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.OverloadBase Return End If - context.RegisterCodeFix(New AddOverloadsKeywordAction(context.Document, token.Parent), context.Diagnostics) + If diagnostic.Descriptor.Id = BC40003 Then + context.RegisterCodeFix(New AddKeywordAction(context.Document, token.Parent, VBFeaturesResources.Add_Overloads, SyntaxKind.OverloadsKeyword), context.Diagnostics) + ElseIf diagnostic.Descriptor.Id = BC40004 Then + context.RegisterCodeFix(New AddKeywordAction(context.Document, token.Parent, VBFeaturesResources.Add_Shadows, SyntaxKind.ShadowsKeyword), context.Diagnostics) + End If End Function End Class End Namespace diff --git a/src/Features/VisualBasic/Portable/IntroduceUsingStatement/VisualBasicIntroduceUsingStatementCodeRefactoringProvider.vb b/src/Features/VisualBasic/Portable/IntroduceUsingStatement/VisualBasicIntroduceUsingStatementCodeRefactoringProvider.vb new file mode 100644 index 0000000000000..87cde0ae0905b --- /dev/null +++ b/src/Features/VisualBasic/Portable/IntroduceUsingStatement/VisualBasicIntroduceUsingStatementCodeRefactoringProvider.vb @@ -0,0 +1,43 @@ +' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +Imports System.Composition +Imports Microsoft.CodeAnalysis.CodeRefactorings +Imports Microsoft.CodeAnalysis.IntroduceUsingStatement +Imports Microsoft.CodeAnalysis.VisualBasic.Syntax + +Namespace Microsoft.CodeAnalysis.VisualBasic.IntroduceUsingStatement + + + + Friend NotInheritable Class VisualBasicIntroduceUsingStatementCodeRefactoringProvider + Inherits AbstractIntroduceUsingStatementCodeRefactoringProvider(Of StatementSyntax, LocalDeclarationStatementSyntax) + + Protected Overrides ReadOnly Property CodeActionTitle As String = VBFeaturesResources.Introduce_Using_statement + + Protected Overrides Function CanRefactorToContainBlockStatements(parent As SyntaxNode) As Boolean + ' We don’t care enough about declarations in single-line If, Else, lambdas, etc, to support them. + Return parent.IsMultiLineExecutableBlock() + End Function + + Protected Overrides Function GetStatements(parentOfStatementsToSurround As SyntaxNode) As SyntaxList(Of StatementSyntax) + Return parentOfStatementsToSurround.GetExecutableBlockStatements() + End Function + + Protected Overrides Function WithStatements(parentOfStatementsToSurround As SyntaxNode, statements As SyntaxList(Of StatementSyntax)) As SyntaxNode + Return parentOfStatementsToSurround.ReplaceStatements(statements) + End Function + + Protected Overrides Function CreateUsingStatement(declarationStatement As LocalDeclarationStatementSyntax, sameLineTrivia As SyntaxTriviaList, statementsToSurround As SyntaxList(Of StatementSyntax)) As StatementSyntax + Dim usingStatement = + SyntaxFactory.UsingStatement( + expression:=Nothing, + variables:=declarationStatement.Declarators) + + If sameLineTrivia.Any Then + usingStatement = usingStatement.WithTrailingTrivia(sameLineTrivia) + End If + + Return SyntaxFactory.UsingBlock(usingStatement, statementsToSurround) + End Function + End Class +End Namespace diff --git a/src/Features/VisualBasic/Portable/Microsoft.CodeAnalysis.VisualBasic.Features.vbproj b/src/Features/VisualBasic/Portable/Microsoft.CodeAnalysis.VisualBasic.Features.vbproj index 7a4d17171b4f9..bf9feac65e11c 100644 --- a/src/Features/VisualBasic/Portable/Microsoft.CodeAnalysis.VisualBasic.Features.vbproj +++ b/src/Features/VisualBasic/Portable/Microsoft.CodeAnalysis.VisualBasic.Features.vbproj @@ -5,7 +5,7 @@ AnyCPU AnyCPU Library - netstandard1.3 + netstandard2.0 diff --git a/src/Features/VisualBasic/Portable/MoveDeclarationNearReference/VisualBasicMoveDeclarationNearReferenceCodeRefactoringProvider.vb b/src/Features/VisualBasic/Portable/MoveDeclarationNearReference/VisualBasicMoveDeclarationNearReferenceService.vb similarity index 80% rename from src/Features/VisualBasic/Portable/MoveDeclarationNearReference/VisualBasicMoveDeclarationNearReferenceCodeRefactoringProvider.vb rename to src/Features/VisualBasic/Portable/MoveDeclarationNearReference/VisualBasicMoveDeclarationNearReferenceService.vb index 1e299829e7f91..f595c3289e7e3 100644 --- a/src/Features/VisualBasic/Portable/MoveDeclarationNearReference/VisualBasicMoveDeclarationNearReferenceCodeRefactoringProvider.vb +++ b/src/Features/VisualBasic/Portable/MoveDeclarationNearReference/VisualBasicMoveDeclarationNearReferenceService.vb @@ -2,16 +2,15 @@ Imports System.Composition Imports System.Threading -Imports Microsoft.CodeAnalysis.CodeRefactorings +Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.MoveDeclarationNearReference Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.MoveDeclarationNearReference - - - Friend Class VisualBasicMoveDeclarationNearReferenceCodeRefactoringProvider - Inherits AbstractMoveDeclarationNearReferenceCodeRefactoringProvider(Of - VisualBasicMoveDeclarationNearReferenceCodeRefactoringProvider, + + Friend Class VisualBasicMoveDeclarationNearReferenceService + Inherits AbstractMoveDeclarationNearReferenceService(Of + VisualBasicMoveDeclarationNearReferenceService, StatementSyntax, LocalDeclarationStatementSyntax, VariableDeclaratorSyntax) diff --git a/src/Features/VisualBasic/Portable/VBFeaturesResources.Designer.vb b/src/Features/VisualBasic/Portable/VBFeaturesResources.Designer.vb index 72ded7458b1bc..788bcd2573f31 100644 --- a/src/Features/VisualBasic/Portable/VBFeaturesResources.Designer.vb +++ b/src/Features/VisualBasic/Portable/VBFeaturesResources.Designer.vb @@ -130,7 +130,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.VBFeaturesResources End Property ''' - ''' Looks up a localized string similar to Add Overloads. + ''' Looks up a localized string similar to Add 'Overloads'. ''' Friend ReadOnly Property Add_Overloads() As String Get @@ -138,6 +138,15 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.VBFeaturesResources End Get End Property + ''' + ''' Looks up a localized string similar to Add 'Shadows'. + ''' + Friend ReadOnly Property Add_Shadows() As String + Get + Return ResourceManager.GetString("Add_Shadows", resourceCulture) + End Get + End Property + ''' ''' Looks up a localized string similar to AddHandler statement. ''' @@ -1382,6 +1391,15 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.VBFeaturesResources End Get End Property + ''' + ''' Looks up a localized string similar to Introduce 'Using' statement. + ''' + Friend ReadOnly Property Introduce_Using_statement() As String + Get + Return ResourceManager.GetString("Introduce_Using_statement", resourceCulture) + End Get + End Property + ''' ''' Looks up a localized string similar to Introduces a clause that identifies the external file (DLL or code resource) containing an external procedure.. ''' diff --git a/src/Features/VisualBasic/Portable/VBFeaturesResources.resx b/src/Features/VisualBasic/Portable/VBFeaturesResources.resx index 97709b57d3488..131b4bf56503f 100644 --- a/src/Features/VisualBasic/Portable/VBFeaturesResources.resx +++ b/src/Features/VisualBasic/Portable/VBFeaturesResources.resx @@ -1175,7 +1175,8 @@ Sub(<parameterList>) <statement> Type '{0}' is not defined. - Add Overloads + Add 'Overloads' + {Locked="Overloads"} "Overloads" is a VB keyword and should not be localized. Add a metadata reference to specified assembly and all its dependencies, e.g. #r "myLib.dll". @@ -1263,4 +1264,12 @@ Sub(<parameterList>) <statement> Add missing Imports {Locked="Import"} "Import" is a VB keyword and should not be localized. + + Add 'Shadows' + {Locked="Shadows"} "Shadows" is a VB keyword and should not be localized. + + + Introduce 'Using' statement + {Locked="Using"} "Using" is a VB keyword and should not be localized. + \ No newline at end of file diff --git a/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.cs.xlf b/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.cs.xlf index e5107d71b6173..e61f3b1f3e677 100644 --- a/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.cs.xlf +++ b/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.cs.xlf @@ -17,6 +17,11 @@ Add missing Imports {Locked="Import"} "Import" is a VB keyword and should not be localized. + + Add 'Shadows' + Add 'Shadows' + {Locked="Shadows"} "Shadows" is a VB keyword and should not be localized. + 'If' statement can be simplified Příkaz if lze zjednodušit. @@ -57,6 +62,11 @@ Zjistily se konflikty. + + Introduce 'Using' statement + Introduce 'Using' statement + {Locked="Using"} "Using" is a VB keyword and should not be localized. + Move the '{0}' statement to line {1}. Přesuňte příkaz {0} na řádek {1}. @@ -1713,9 +1723,9 @@ Sub(<seznam_parametrů>) <výraz> - Add Overloads - Přidat přetížení - + Add 'Overloads' + Přidat přetížení + {Locked="Overloads"} "Overloads" is a VB keyword and should not be localized. Add a metadata reference to specified assembly and all its dependencies, e.g. #r "myLib.dll". diff --git a/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.de.xlf b/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.de.xlf index ea4a4fec3af41..5cc7b79ea5a79 100644 --- a/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.de.xlf +++ b/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.de.xlf @@ -17,6 +17,11 @@ Add missing Imports {Locked="Import"} "Import" is a VB keyword and should not be localized. + + Add 'Shadows' + Add 'Shadows' + {Locked="Shadows"} "Shadows" is a VB keyword and should not be localized. + 'If' statement can be simplified Die If-Anweisung kann vereinfacht werden. @@ -57,6 +62,11 @@ Konflikt(e) erkannt. + + Introduce 'Using' statement + Introduce 'Using' statement + {Locked="Using"} "Using" is a VB keyword and should not be localized. + Move the '{0}' statement to line {1}. Verschieben Sie die "{0}"-Anweisung zu Zeile {1}. @@ -1713,9 +1723,9 @@ Sub(<Parameterliste>) <Ausdruck> - Add Overloads - Überladungen hinzufügen - + Add 'Overloads' + Überladungen hinzufügen + {Locked="Overloads"} "Overloads" is a VB keyword and should not be localized. Add a metadata reference to specified assembly and all its dependencies, e.g. #r "myLib.dll". diff --git a/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.es.xlf b/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.es.xlf index 4ecdc0a613e07..652b39c3e34b2 100644 --- a/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.es.xlf +++ b/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.es.xlf @@ -17,6 +17,11 @@ Add missing Imports {Locked="Import"} "Import" is a VB keyword and should not be localized. + + Add 'Shadows' + Add 'Shadows' + {Locked="Shadows"} "Shadows" is a VB keyword and should not be localized. + 'If' statement can be simplified La instrucción "if" se puede simplificar @@ -57,6 +62,11 @@ Conflicto(s) detectado(s). + + Introduce 'Using' statement + Introduce 'Using' statement + {Locked="Using"} "Using" is a VB keyword and should not be localized. + Move the '{0}' statement to line {1}. Mueva la instrucción '{0}' a la línea {1}. @@ -1713,9 +1723,9 @@ Sub(<listaDeParámetros>) <instrucción> - Add Overloads - Agregar sobrecargas - + Add 'Overloads' + Agregar sobrecargas + {Locked="Overloads"} "Overloads" is a VB keyword and should not be localized. Add a metadata reference to specified assembly and all its dependencies, e.g. #r "myLib.dll". diff --git a/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.fr.xlf b/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.fr.xlf index bee398f140eb8..50154bc4586bf 100644 --- a/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.fr.xlf +++ b/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.fr.xlf @@ -17,6 +17,11 @@ Add missing Imports {Locked="Import"} "Import" is a VB keyword and should not be localized. + + Add 'Shadows' + Add 'Shadows' + {Locked="Shadows"} "Shadows" is a VB keyword and should not be localized. + 'If' statement can be simplified L'instruction 'If' peut être simplifiée @@ -57,6 +62,11 @@ Conflit(s) détecté(s). + + Introduce 'Using' statement + Introduce 'Using' statement + {Locked="Using"} "Using" is a VB keyword and should not be localized. + Move the '{0}' statement to line {1}. Déplacez l'instruction '{0}' à la ligne {1}. @@ -1713,9 +1723,9 @@ Sub(<parameterList>) <statement> - Add Overloads - Ajouter des surcharges - + Add 'Overloads' + Ajouter des surcharges + {Locked="Overloads"} "Overloads" is a VB keyword and should not be localized. Add a metadata reference to specified assembly and all its dependencies, e.g. #r "myLib.dll". diff --git a/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.it.xlf b/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.it.xlf index d1b39b5106bf1..65038f47cb104 100644 --- a/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.it.xlf +++ b/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.it.xlf @@ -17,6 +17,11 @@ Add missing Imports {Locked="Import"} "Import" is a VB keyword and should not be localized. + + Add 'Shadows' + Add 'Shadows' + {Locked="Shadows"} "Shadows" is a VB keyword and should not be localized. + 'If' statement can be simplified L'istruzione 'If' può essere semplificata @@ -57,6 +62,11 @@ Sono stati rilevati conflitti + + Introduce 'Using' statement + Introduce 'Using' statement + {Locked="Using"} "Using" is a VB keyword and should not be localized. + Move the '{0}' statement to line {1}. Spostare l'istruzione '{0}' alla riga {1}. @@ -1713,9 +1723,9 @@ Sub(<elencoParametri>) <istruzione> - Add Overloads - Aggiungi overload - + Add 'Overloads' + Aggiungi overload + {Locked="Overloads"} "Overloads" is a VB keyword and should not be localized. Add a metadata reference to specified assembly and all its dependencies, e.g. #r "myLib.dll". diff --git a/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.ja.xlf b/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.ja.xlf index 3b506b1573dd3..a9746c45131fc 100644 --- a/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.ja.xlf +++ b/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.ja.xlf @@ -17,6 +17,11 @@ Add missing Imports {Locked="Import"} "Import" is a VB keyword and should not be localized. + + Add 'Shadows' + Add 'Shadows' + {Locked="Shadows"} "Shadows" is a VB keyword and should not be localized. + 'If' statement can be simplified 'if' ステートメントは簡素化できます @@ -57,6 +62,11 @@ 競合が検出されました。 + + Introduce 'Using' statement + Introduce 'Using' statement + {Locked="Using"} "Using" is a VB keyword and should not be localized. + Move the '{0}' statement to line {1}. {0}' ステートメントを行 {1} に移動します。 @@ -1712,9 +1722,9 @@ Sub(<parameterList>) <statement> - Add Overloads - オーバーロードを追加します - + Add 'Overloads' + オーバーロードを追加します + {Locked="Overloads"} "Overloads" is a VB keyword and should not be localized. Add a metadata reference to specified assembly and all its dependencies, e.g. #r "myLib.dll". diff --git a/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.ko.xlf b/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.ko.xlf index 7a4bb92db0f51..6660c98815ea9 100644 --- a/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.ko.xlf +++ b/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.ko.xlf @@ -17,6 +17,11 @@ Add missing Imports {Locked="Import"} "Import" is a VB keyword and should not be localized. + + Add 'Shadows' + Add 'Shadows' + {Locked="Shadows"} "Shadows" is a VB keyword and should not be localized. + 'If' statement can be simplified 'if' 문을 간단하게 줄일 수 있습니다. @@ -57,6 +62,11 @@ 충돌이 감지되었습니다. + + Introduce 'Using' statement + Introduce 'Using' statement + {Locked="Using"} "Using" is a VB keyword and should not be localized. + Move the '{0}' statement to line {1}. {0}' 문을 {1} 줄로 이동합니다. @@ -1713,9 +1723,9 @@ Sub(<parameterList>) <statement> - Add Overloads - 오버로드 추가 - + Add 'Overloads' + 오버로드 추가 + {Locked="Overloads"} "Overloads" is a VB keyword and should not be localized. Add a metadata reference to specified assembly and all its dependencies, e.g. #r "myLib.dll". diff --git a/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.pl.xlf b/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.pl.xlf index df76fb3f2fdfa..9f76acb7892f7 100644 --- a/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.pl.xlf +++ b/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.pl.xlf @@ -17,6 +17,11 @@ Add missing Imports {Locked="Import"} "Import" is a VB keyword and should not be localized. + + Add 'Shadows' + Add 'Shadows' + {Locked="Shadows"} "Shadows" is a VB keyword and should not be localized. + 'If' statement can be simplified Instrukcja „if” może zostać uproszczona @@ -57,6 +62,11 @@ Wykryto konflikty. + + Introduce 'Using' statement + Introduce 'Using' statement + {Locked="Using"} "Using" is a VB keyword and should not be localized. + Move the '{0}' statement to line {1}. Przenieś instrukcję „{0}” do wiersza {1}. @@ -1713,9 +1723,9 @@ Sub(<listaParametrów>) <instrukcja> - Add Overloads - Dodaj przeciążenia - + Add 'Overloads' + Dodaj przeciążenia + {Locked="Overloads"} "Overloads" is a VB keyword and should not be localized. Add a metadata reference to specified assembly and all its dependencies, e.g. #r "myLib.dll". diff --git a/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.pt-BR.xlf b/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.pt-BR.xlf index a9c7b61ed6037..059fa552c5230 100644 --- a/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.pt-BR.xlf +++ b/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.pt-BR.xlf @@ -17,6 +17,11 @@ Add missing Imports {Locked="Import"} "Import" is a VB keyword and should not be localized. + + Add 'Shadows' + Add 'Shadows' + {Locked="Shadows"} "Shadows" is a VB keyword and should not be localized. + 'If' statement can be simplified A instrução 'If' pode ser simplificada @@ -57,6 +62,11 @@ Conflito(s) detectado(s). + + Introduce 'Using' statement + Introduce 'Using' statement + {Locked="Using"} "Using" is a VB keyword and should not be localized. + Move the '{0}' statement to line {1}. Mova a instrução "{0}" para a linha {1}. @@ -1713,9 +1723,9 @@ Sub(<parameterList>) <statement> - Add Overloads - Adicionar Sobrecargas - + Add 'Overloads' + Adicionar Sobrecargas + {Locked="Overloads"} "Overloads" is a VB keyword and should not be localized. Add a metadata reference to specified assembly and all its dependencies, e.g. #r "myLib.dll". diff --git a/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.ru.xlf b/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.ru.xlf index 06b29795bbfe7..f37c9f3cdff0b 100644 --- a/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.ru.xlf +++ b/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.ru.xlf @@ -17,6 +17,11 @@ Add missing Imports {Locked="Import"} "Import" is a VB keyword and should not be localized. + + Add 'Shadows' + Add 'Shadows' + {Locked="Shadows"} "Shadows" is a VB keyword and should not be localized. + 'If' statement can be simplified Оператор if можно упростить @@ -57,6 +62,11 @@ Обнаружены конфликты. + + Introduce 'Using' statement + Introduce 'Using' statement + {Locked="Using"} "Using" is a VB keyword and should not be localized. + Move the '{0}' statement to line {1}. Перемещение оператора "{0}" в строку {1}. @@ -1713,9 +1723,9 @@ Sub(<parameterList>) <statement> - Add Overloads - Добавить перегрузки - + Add 'Overloads' + Добавить перегрузки + {Locked="Overloads"} "Overloads" is a VB keyword and should not be localized. Add a metadata reference to specified assembly and all its dependencies, e.g. #r "myLib.dll". diff --git a/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.tr.xlf b/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.tr.xlf index 02682e1455e80..e4e08d6615026 100644 --- a/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.tr.xlf +++ b/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.tr.xlf @@ -17,6 +17,11 @@ Add missing Imports {Locked="Import"} "Import" is a VB keyword and should not be localized. + + Add 'Shadows' + Add 'Shadows' + {Locked="Shadows"} "Shadows" is a VB keyword and should not be localized. + 'If' statement can be simplified 'If' deyimi basitleştirilebilir @@ -57,6 +62,11 @@ Çakışmalar algılandı. + + Introduce 'Using' statement + Introduce 'Using' statement + {Locked="Using"} "Using" is a VB keyword and should not be localized. + Move the '{0}' statement to line {1}. {0}' deyimini {1} satırına taşıyın. @@ -1713,9 +1723,9 @@ Sub(<parameterList>) <statement> - Add Overloads - Aşırı Yükleme Ekle - + Add 'Overloads' + Aşırı Yükleme Ekle + {Locked="Overloads"} "Overloads" is a VB keyword and should not be localized. Add a metadata reference to specified assembly and all its dependencies, e.g. #r "myLib.dll". diff --git a/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.zh-Hans.xlf b/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.zh-Hans.xlf index 137c552a89a88..99d76ed8f7890 100644 --- a/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.zh-Hans.xlf +++ b/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.zh-Hans.xlf @@ -17,6 +17,11 @@ Add missing Imports {Locked="Import"} "Import" is a VB keyword and should not be localized. + + Add 'Shadows' + Add 'Shadows' + {Locked="Shadows"} "Shadows" is a VB keyword and should not be localized. + 'If' statement can be simplified 可简化“If”语句 @@ -57,6 +62,11 @@ 检测到冲突。 + + Introduce 'Using' statement + Introduce 'Using' statement + {Locked="Using"} "Using" is a VB keyword and should not be localized. + Move the '{0}' statement to line {1}. 将“{0}”语句移动到第 {1} 行。 @@ -1713,9 +1723,9 @@ Sub(<parameterList>) <statement> - Add Overloads - 添加重载 - + Add 'Overloads' + 添加重载 + {Locked="Overloads"} "Overloads" is a VB keyword and should not be localized. Add a metadata reference to specified assembly and all its dependencies, e.g. #r "myLib.dll". diff --git a/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.zh-Hant.xlf b/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.zh-Hant.xlf index a87c7d357db11..3e72affb9b500 100644 --- a/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.zh-Hant.xlf +++ b/src/Features/VisualBasic/Portable/xlf/VBFeaturesResources.zh-Hant.xlf @@ -17,6 +17,11 @@ Add missing Imports {Locked="Import"} "Import" is a VB keyword and should not be localized. + + Add 'Shadows' + Add 'Shadows' + {Locked="Shadows"} "Shadows" is a VB keyword and should not be localized. + 'If' statement can be simplified 'If' 陳述式可簡化 @@ -57,6 +62,11 @@ 偵測到衝突。 + + Introduce 'Using' statement + Introduce 'Using' statement + {Locked="Using"} "Using" is a VB keyword and should not be localized. + Move the '{0}' statement to line {1}. 將 '{0}' 陳述式移至行 {1}。 @@ -1713,9 +1723,9 @@ Sub(<parameterList>) <statement> - Add Overloads - 加入多載 - + Add 'Overloads' + 加入多載 + {Locked="Overloads"} "Overloads" is a VB keyword and should not be localized. Add a metadata reference to specified assembly and all its dependencies, e.g. #r "myLib.dll". diff --git a/src/Interactive/EditorFeatures/CSharp/Microsoft.CodeAnalysis.CSharp.InteractiveEditorFeatures.csproj b/src/Interactive/EditorFeatures/CSharp/Microsoft.CodeAnalysis.CSharp.InteractiveEditorFeatures.csproj index 97623fd110f42..5b7fc096ecc99 100644 --- a/src/Interactive/EditorFeatures/CSharp/Microsoft.CodeAnalysis.CSharp.InteractiveEditorFeatures.csproj +++ b/src/Interactive/EditorFeatures/CSharp/Microsoft.CodeAnalysis.CSharp.InteractiveEditorFeatures.csproj @@ -6,7 +6,7 @@ AnyCPU Library Microsoft.CodeAnalysis.Editor.CSharp - net46 + net472 diff --git a/src/Interactive/EditorFeatures/Core/Microsoft.CodeAnalysis.InteractiveEditorFeatures.csproj b/src/Interactive/EditorFeatures/Core/Microsoft.CodeAnalysis.InteractiveEditorFeatures.csproj index afca19e1a422d..8a5219a773d32 100644 --- a/src/Interactive/EditorFeatures/Core/Microsoft.CodeAnalysis.InteractiveEditorFeatures.csproj +++ b/src/Interactive/EditorFeatures/Core/Microsoft.CodeAnalysis.InteractiveEditorFeatures.csproj @@ -6,11 +6,10 @@ AnyCPU Library Microsoft.CodeAnalysis.Editor - net46 + net472 - global,Scripting diff --git a/src/Interactive/EditorFeatures/VisualBasic/Microsoft.CodeAnalysis.VisualBasic.InteractiveEditorFeatures.vbproj b/src/Interactive/EditorFeatures/VisualBasic/Microsoft.CodeAnalysis.VisualBasic.InteractiveEditorFeatures.vbproj index bc104844e5efa..d1f0f71d68c30 100644 --- a/src/Interactive/EditorFeatures/VisualBasic/Microsoft.CodeAnalysis.VisualBasic.InteractiveEditorFeatures.vbproj +++ b/src/Interactive/EditorFeatures/VisualBasic/Microsoft.CodeAnalysis.VisualBasic.InteractiveEditorFeatures.vbproj @@ -5,7 +5,7 @@ AnyCPU AnyCPU Library - net46 + net472 diff --git a/src/Interactive/Features/Microsoft.CodeAnalysis.InteractiveFeatures.csproj b/src/Interactive/Features/Microsoft.CodeAnalysis.InteractiveFeatures.csproj index f56f12712dce9..adff8d9f48ee4 100644 --- a/src/Interactive/Features/Microsoft.CodeAnalysis.InteractiveFeatures.csproj +++ b/src/Interactive/Features/Microsoft.CodeAnalysis.InteractiveFeatures.csproj @@ -6,11 +6,10 @@ AnyCPU Library Microsoft.CodeAnalysis - net46 + net472 - global,Scripting diff --git a/src/Interactive/Host/InteractiveHost32.csproj b/src/Interactive/Host/InteractiveHost32.csproj index 597c540109c8e..681a26f919a43 100644 --- a/src/Interactive/Host/InteractiveHost32.csproj +++ b/src/Interactive/Host/InteractiveHost32.csproj @@ -7,13 +7,12 @@ AnyCPU true Exe - net46 + net472 $(RoslynDesktopRuntimeIdentifier) - diff --git a/src/Interactive/Host/InteractiveHost64.csproj b/src/Interactive/Host/InteractiveHost64.csproj index e3b9fc1a793de..ca2d1cd686147 100644 --- a/src/Interactive/Host/InteractiveHost64.csproj +++ b/src/Interactive/Host/InteractiveHost64.csproj @@ -7,13 +7,12 @@ AnyCPU false Exe - net46 + net472 $(RoslynDesktopRuntimeIdentifier) - diff --git a/src/Interactive/HostTest/InteractiveHost.UnitTests.csproj b/src/Interactive/HostTest/InteractiveHost.UnitTests.csproj index 9512d905f6b5c..58399a528cb50 100644 --- a/src/Interactive/HostTest/InteractiveHost.UnitTests.csproj +++ b/src/Interactive/HostTest/InteractiveHost.UnitTests.csproj @@ -6,7 +6,7 @@ AnyCPU Library Roslyn.InteractiveHost.UnitTests - net46 + net472 UnitTest @@ -16,7 +16,6 @@ - diff --git a/src/Interactive/csi/App.config b/src/Interactive/csi/App.config index 442bfd2d9b621..18b356da3f3be 100644 --- a/src/Interactive/csi/App.config +++ b/src/Interactive/csi/App.config @@ -3,6 +3,6 @@ - + diff --git a/src/Interactive/csi/csi.coreclr.rsp b/src/Interactive/csi/csi.coreclr.rsp index be91c8d9e3aab..d22fba87434ca 100644 --- a/src/Interactive/csi/csi.coreclr.rsp +++ b/src/Interactive/csi/csi.coreclr.rsp @@ -23,11 +23,11 @@ /r:System.Threading.Tasks.Parallel /r:System.Threading.Thread # extra references +/r:System.Dynamic.Runtime /r:System.Linq /r:System.Linq.Expressions /r:System.Runtime.Numerics -/r:System.Dynamic.Runtime -/r:System.ValueTuple.dll +/r:System.ValueTuple /r:Microsoft.CSharp # imports /u:System diff --git a/src/Interactive/csi/csi.csproj b/src/Interactive/csi/csi.csproj index 9e76c2ee297a0..0845995afc53a 100644 --- a/src/Interactive/csi/csi.csproj +++ b/src/Interactive/csi/csi.csproj @@ -19,7 +19,6 @@ - diff --git a/src/Interactive/csi/csi.desktop.rsp b/src/Interactive/csi/csi.desktop.rsp index 2ec6fc9b4069b..96e81d8fec43b 100644 --- a/src/Interactive/csi/csi.desktop.rsp +++ b/src/Interactive/csi/csi.desktop.rsp @@ -1,7 +1,6 @@ /r:System /r:System.Core /r:Microsoft.CSharp -/r:System.ValueTuple.dll /u:System /u:System.IO /u:System.Collections.Generic diff --git a/src/Interactive/vbi/App.config b/src/Interactive/vbi/App.config index 442bfd2d9b621..18b356da3f3be 100644 --- a/src/Interactive/vbi/App.config +++ b/src/Interactive/vbi/App.config @@ -3,6 +3,6 @@ - + diff --git a/src/Interactive/vbi/vbi.coreclr.rsp b/src/Interactive/vbi/vbi.coreclr.rsp index 7d73a5397dea5..79fcb57e05300 100644 --- a/src/Interactive/vbi/vbi.coreclr.rsp +++ b/src/Interactive/vbi/vbi.coreclr.rsp @@ -25,11 +25,11 @@ /r:System.Threading.Tasks.Parallel /r:System.Threading.Thread # extra references +/r:System.Dynamic.Runtime /r:System.Linq /r:System.Linq.Expressions /r:System.Runtime.Numerics -/r:System.Dynamic.Runtime -/r:System.ValueTuple.dll +/r:System.ValueTuple # imports /u:System /u:System.IO diff --git a/src/Interactive/vbi/vbi.desktop.rsp b/src/Interactive/vbi/vbi.desktop.rsp index 1d4c65da51116..714fbdf12c4a1 100644 --- a/src/Interactive/vbi/vbi.desktop.rsp +++ b/src/Interactive/vbi/vbi.desktop.rsp @@ -1,6 +1,5 @@ /r:System /r:System.Core -/r:System.ValueTuple.dll /Imports:System /Imports:System.IO /Imports:System.Collections.Generic diff --git a/src/Interactive/vbi/vbi.vbproj b/src/Interactive/vbi/vbi.vbproj index 5b3fedd8dfe51..a71b753b7d85a 100644 --- a/src/Interactive/vbi/vbi.vbproj +++ b/src/Interactive/vbi/vbi.vbproj @@ -20,7 +20,6 @@ - diff --git a/src/NuGet/Microsoft.CodeAnalysis.Compilers.Package.csproj b/src/NuGet/Microsoft.CodeAnalysis.Compilers.Package.csproj index ca4d1b6635c06..c49a750b02117 100644 --- a/src/NuGet/Microsoft.CodeAnalysis.Compilers.Package.csproj +++ b/src/NuGet/Microsoft.CodeAnalysis.Compilers.Package.csproj @@ -1,7 +1,7 @@  - netstandard1.3 + netstandard2.0 Custom diff --git a/src/NuGet/Microsoft.CodeAnalysis.EditorFeatures.Package.csproj b/src/NuGet/Microsoft.CodeAnalysis.EditorFeatures.Package.csproj index 0c32c1888687d..4df664f73c24a 100644 --- a/src/NuGet/Microsoft.CodeAnalysis.EditorFeatures.Package.csproj +++ b/src/NuGet/Microsoft.CodeAnalysis.EditorFeatures.Package.csproj @@ -1,7 +1,7 @@  - net46 + net472 Custom diff --git a/src/NuGet/Microsoft.CodeAnalysis.Package.csproj b/src/NuGet/Microsoft.CodeAnalysis.Package.csproj index 5c0e4e1120b09..c5eb55786df88 100644 --- a/src/NuGet/Microsoft.CodeAnalysis.Package.csproj +++ b/src/NuGet/Microsoft.CodeAnalysis.Package.csproj @@ -1,7 +1,7 @@  - net46;netstandard1.3 + net472;netstandard2.0 Custom diff --git a/src/NuGet/Microsoft.CodeAnalysis.Scripting.Package.csproj b/src/NuGet/Microsoft.CodeAnalysis.Scripting.Package.csproj index b3d7465a9e912..bce805e370e5e 100644 --- a/src/NuGet/Microsoft.CodeAnalysis.Scripting.Package.csproj +++ b/src/NuGet/Microsoft.CodeAnalysis.Scripting.Package.csproj @@ -1,7 +1,7 @@  - netstandard1.3 + netstandard2.0 Custom diff --git a/src/NuGet/Microsoft.Net.Compilers/CompilerArtifacts.targets b/src/NuGet/Microsoft.Net.Compilers/CompilerArtifacts.targets index 328a48391c4d6..279a869b35e87 100644 --- a/src/NuGet/Microsoft.Net.Compilers/CompilerArtifacts.targets +++ b/src/NuGet/Microsoft.Net.Compilers/CompilerArtifacts.targets @@ -17,6 +17,10 @@ Ngen* attributes indicate how VS should NGEN the assemblies that are distributed by VS Setup. NgenApplication is relative to the Roslyn install directory within MSBuild (i.e. MSBuild\15.0\Bin\Roslyn). + + Set OverwriteOptimizationData to true to replace optimization data already embedded in the assembly with data retrieved from VS training scenarios. + We only need to specify this for assemblies built outside or Roslyn repo since the projects in Roslyn repo are responsible for embedding + VS training data to the assemblies they produce. --> @@ -29,44 +33,31 @@ - - - - - - - - - - - - - - - - - - + - - - - - + \ No newline at end of file diff --git a/src/NuGet/Microsoft.Net.Compilers/Microsoft.Net.Compilers.Package.csproj b/src/NuGet/Microsoft.Net.Compilers/Microsoft.Net.Compilers.Package.csproj index 8469f85cfab96..a296c69824e21 100644 --- a/src/NuGet/Microsoft.Net.Compilers/Microsoft.Net.Compilers.Package.csproj +++ b/src/NuGet/Microsoft.Net.Compilers/Microsoft.Net.Compilers.Package.csproj @@ -1,7 +1,7 @@  - net46 + net472 Custom true @@ -12,7 +12,7 @@ .NET Compilers package. Referencing this package will cause the project to be built using the specific version of the C# and Visual Basic compilers contained in the package, as opposed to any system installed version. - This package can be used to compile code targeting any platform, but can only be run using the desktop .NET 4.6+ Full Framework. + This package can be used to compile code targeting any platform, but can only be run using the desktop .NET 4.7.2+ Full Framework. $(RoslynPackageDescriptionDetails) $(TargetsForTfmSpecificContentInPackage);_GetFilesToPackage @@ -38,7 +38,7 @@ <_File Include="$(ArtifactsConfigurationDir)Dlls\Microsoft.CodeAnalysis.Scripting\**\Microsoft.CodeAnalysis.Scripting.resources.dll" TargetDir="tools" /> <_File Include="$(ArtifactsConfigurationDir)Dlls\Microsoft.CodeAnalysis.CSharp.Scripting\**\Microsoft.CodeAnalysis.CSharp.Scripting.resources.dll" TargetDir="tools" /> <_File Include="$(ArtifactsConfigurationDir)Dlls\Microsoft.CodeAnalysis.VisualBasic\**\Microsoft.CodeAnalysis.VisualBasic.resources.dll" TargetDir="tools" /> - <_File Include="$(ArtifactsConfigurationDir)Dlls\Microsoft.Build.Tasks.CodeAnalysis\net46\**\Microsoft.Build.Tasks.CodeAnalysis.resources.dll" TargetDir="tools" /> + <_File Include="$(ArtifactsConfigurationDir)Dlls\Microsoft.Build.Tasks.CodeAnalysis\net472\**\Microsoft.Build.Tasks.CodeAnalysis.resources.dll" TargetDir="tools" /> diff --git a/src/NuGet/VisualStudio/VS.ExternalAPIs.Roslyn.Package.csproj b/src/NuGet/VisualStudio/VS.ExternalAPIs.Roslyn.Package.csproj index be5e0e9309af3..f30e5d6013b30 100644 --- a/src/NuGet/VisualStudio/VS.ExternalAPIs.Roslyn.Package.csproj +++ b/src/NuGet/VisualStudio/VS.ExternalAPIs.Roslyn.Package.csproj @@ -1,7 +1,7 @@  - net46 + net472 Custom @@ -84,9 +84,9 @@ <_File Include="$(_Dlls)Microsoft.CodeAnalysis.VisualBasic.Features\Microsoft.CodeAnalysis.VisualBasic.Features.dll" TargetDir="" /> <_File Include="$(_Dlls)Microsoft.CodeAnalysis.VisualBasic.Workspaces\Microsoft.CodeAnalysis.VisualBasic.Workspaces.dll" TargetDir="" /> <_File Include="$(_Dlls)Microsoft.CodeAnalysis.VisualBasic\Microsoft.CodeAnalysis.VisualBasic.dll" TargetDir="" /> - <_File Include="$(_Dlls)Microsoft.CodeAnalysis.Workspaces.Desktop\Microsoft.CodeAnalysis.Workspaces.Desktop.dll" TargetDir="" /> - <_File Include="$(_Dlls)Microsoft.CodeAnalysis.Workspaces.MSBuild\net46\Microsoft.CodeAnalysis.Workspaces.MSBuild.dll" TargetDir="" /> + <_File Include="$(_Dlls)Microsoft.CodeAnalysis.Workspaces.MSBuild\net472\Microsoft.CodeAnalysis.Workspaces.MSBuild.dll" TargetDir="" /> <_File Include="$(_Dlls)Microsoft.CodeAnalysis.Workspaces\Microsoft.CodeAnalysis.Workspaces.dll" TargetDir="" /> + <_File Include="$(_Dlls)Microsoft.CodeAnalysis.Workspaces.Desktop\Microsoft.CodeAnalysis.Workspaces.Desktop.dll" TargetDir="" /> <_File Include="$(_Dlls)Microsoft.VisualStudio.LanguageServices.CSharp\Microsoft.VisualStudio.LanguageServices.CSharp.dll" TargetDir="" /> <_File Include="$(_Dlls)Microsoft.VisualStudio.LanguageServices.Implementation\Microsoft.VisualStudio.LanguageServices.Implementation.dll" TargetDir="" /> <_File Include="$(_Dlls)Microsoft.VisualStudio.LanguageServices.Razor.RemoteClient\Microsoft.VisualStudio.LanguageServices.Razor.RemoteClient.dll" TargetDir="" /> @@ -98,20 +98,21 @@ <_File Include="$(_Dlls)Microsoft.CodeAnalysis.ResultProvider\Microsoft.CodeAnalysis.ExpressionEvaluator.ResultProvider.dll" TargetDir="" /> <_File Include="$(_Dlls)Microsoft.CodeAnalysis.CSharp.ResultProvider\Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ResultProvider.dll" TargetDir="" /> <_File Include="$(_Dlls)Microsoft.CodeAnalysis.VisualBasic.ResultProvider\Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ResultProvider.dll" TargetDir="" /> - <_File Include="$(_Dlls)Microsoft.CodeAnalysis.FunctionResolver\Microsoft.CodeAnalysis.ExpressionEvaluator.FunctionResolver.dll" TargetDir="" /> + <_File Include="$(_Dlls)Microsoft.CodeAnalysis.FunctionResolver\netstandard1.3\Microsoft.CodeAnalysis.ExpressionEvaluator.FunctionResolver.dll" TargetDir="" /> <_File Include="$(_Dlls)Microsoft.CodeAnalysis.VisualBasic.ExpressionCompiler\Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ExpressionCompiler.dll" TargetDir="" /> <_File Include="$(_Dlls)Microsoft.CodeAnalysis.CSharp.ExpressionCompiler\Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ExpressionCompiler.dll" TargetDir="" /> <_File Include="$(_Dlls)Microsoft.CodeAnalysis.ExpressionCompiler\Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.dll" TargetDir="" /> - <_File Include="$(_Dlls)BasicResultProvider.NetFX20\Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ResultProvider.dll" TargetDir="Dlls\BasicResultProvider.NetFX20" /> - <_File Include="$(_Dlls)CSharpResultProvider.NetFX20\Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ResultProvider.dll" TargetDir="Dlls\CSharpResultProvider.NetFX20" /> - <_File Include="$(_Dlls)ResultProvider.NetFX20\Microsoft.CodeAnalysis.ExpressionEvaluator.ResultProvider.dll" TargetDir="Dlls\ResultProvider.NetFX20" /> + <_File Include="$(_Dlls)BasicResultProvider.NetFX20\Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ResultProvider.dll" TargetDir="RemoteDebugger\net20" /> + <_File Include="$(_Dlls)CSharpResultProvider.NetFX20\Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ResultProvider.dll" TargetDir="RemoteDebugger\net20" /> + <_File Include="$(_Dlls)ResultProvider.NetFX20\Microsoft.CodeAnalysis.ExpressionEvaluator.ResultProvider.dll" TargetDir="RemoteDebugger\net20" /> + <_File Include="$(_Dlls)Microsoft.CodeAnalysis.FunctionResolver\net45\Microsoft.CodeAnalysis.ExpressionEvaluator.FunctionResolver.dll" TargetDir="RemoteDebugger\net45" /> <_File Include="$(_Dlls)Microsoft.CodeAnalysis.CSharp.ResultProvider\Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ResultProvider.vsdconfig" TargetDir="LanguageServiceRegistration\ExpressionEvaluatorPackage" /> <_File Include="$(_Dlls)Microsoft.CodeAnalysis.CSharp.ExpressionCompiler\Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ExpressionCompiler.vsdconfig" TargetDir="LanguageServiceRegistration\ExpressionEvaluatorPackage" /> <_File Include="$(_Dlls)Microsoft.CodeAnalysis.VisualBasic.ResultProvider\Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ResultProvider.vsdconfig" TargetDir="LanguageServiceRegistration\ExpressionEvaluatorPackage" /> <_File Include="$(_Dlls)Microsoft.VisualStudio.LanguageServices\Microsoft.VisualStudio.LanguageServices.vsdconfig" TargetDir="LanguageServiceRegistration\ExpressionEvaluatorPackage" /> - <_File Include="$(_Dlls)Microsoft.CodeAnalysis.FunctionResolver\Microsoft.CodeAnalysis.ExpressionEvaluator.FunctionResolver.vsdconfig" TargetDir="LanguageServiceRegistration\ExpressionEvaluatorPackage" /> + <_File Include="$(_Dlls)Microsoft.CodeAnalysis.FunctionResolver\netstandard1.3\Microsoft.CodeAnalysis.ExpressionEvaluator.FunctionResolver.vsdconfig" TargetDir="LanguageServiceRegistration\ExpressionEvaluatorPackage" /> <_File Include="$(_Dlls)Microsoft.CodeAnalysis.VisualBasic.ExpressionCompiler\Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ExpressionCompiler.vsdconfig" TargetDir="LanguageServiceRegistration\ExpressionEvaluatorPackage" /> - net46 + net472 Custom @@ -35,7 +35,7 @@ <_File Include="$(MSBuildProjectDirectory)\Init.cmd" TargetDir="" /> - <_File Remove="$(ArtifactsConfigurationDir)Exes\csc\net46\csc.exe"/> + <_File Remove="$(ArtifactsConfigurationDir)Exes\csc\net472\csc.exe"/> <_File Include="$(IntermediateOutputPath)csc.exe"/> @@ -49,10 +49,10 @@ - + diff --git a/src/Scripting/CSharp/Hosting/ObjectFormatter/CSharpObjectFormatterImpl.cs b/src/Scripting/CSharp/Hosting/ObjectFormatter/CSharpObjectFormatterImpl.cs index e1ebd3602a652..91a07875a89e7 100644 --- a/src/Scripting/CSharp/Hosting/ObjectFormatter/CSharpObjectFormatterImpl.cs +++ b/src/Scripting/CSharp/Hosting/ObjectFormatter/CSharpObjectFormatterImpl.cs @@ -2,6 +2,7 @@ using System.Reflection; using Microsoft.CodeAnalysis.Scripting.Hosting; +using MemberFilter = Microsoft.CodeAnalysis.Scripting.Hosting.MemberFilter; namespace Microsoft.CodeAnalysis.CSharp.Scripting.Hosting { diff --git a/src/Scripting/CSharp/Microsoft.CodeAnalysis.CSharp.Scripting.csproj b/src/Scripting/CSharp/Microsoft.CodeAnalysis.CSharp.Scripting.csproj index d1e4561d5fb40..facbedf401b0c 100644 --- a/src/Scripting/CSharp/Microsoft.CodeAnalysis.CSharp.Scripting.csproj +++ b/src/Scripting/CSharp/Microsoft.CodeAnalysis.CSharp.Scripting.csproj @@ -6,7 +6,7 @@ AnyCPU Library Microsoft.CodeAnalysis.CSharp.Scripting - netstandard1.3 + netstandard2.0 true diff --git a/src/Scripting/CSharpTest.Desktop/Microsoft.CodeAnalysis.CSharp.Scripting.Desktop.UnitTests.csproj b/src/Scripting/CSharpTest.Desktop/Microsoft.CodeAnalysis.CSharp.Scripting.Desktop.UnitTests.csproj index eaa2422f50238..b9a4429b4c728 100644 --- a/src/Scripting/CSharpTest.Desktop/Microsoft.CodeAnalysis.CSharp.Scripting.Desktop.UnitTests.csproj +++ b/src/Scripting/CSharpTest.Desktop/Microsoft.CodeAnalysis.CSharp.Scripting.Desktop.UnitTests.csproj @@ -7,7 +7,7 @@ Library Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests true - net46 + net472 $(RoslynDesktopRuntimeIdentifier) UnitTest diff --git a/src/Scripting/CSharpTest/CommandLineRunnerTests.cs b/src/Scripting/CSharpTest/CommandLineRunnerTests.cs index cef91abc4d142..10b8fd8c13ac4 100644 --- a/src/Scripting/CSharpTest/CommandLineRunnerTests.cs +++ b/src/Scripting/CSharpTest/CommandLineRunnerTests.cs @@ -23,7 +23,8 @@ public class CommandLineRunnerTests : TestBase { private static readonly string s_compilerVersion = typeof(CSharpInteractiveCompiler).GetTypeInfo().Assembly.GetCustomAttribute().Version; - private static readonly string s_logoAndHelpPrompt = $@"{ string.Format(CSharpScriptingResources.LogoLine1, s_compilerVersion) } + + private string LogoAndHelpPrompt => $@"{ string.Format(CSharpScriptingResources.LogoLine1, s_compilerVersion) } {CSharpScriptingResources.LogoLine2} {ScriptingResources.HelpPrompt}"; @@ -43,7 +44,6 @@ private static IEnumerable GetReferences() yield return "System"; yield return "System.Core"; yield return "Microsoft.CSharp"; - yield return "System.ValueTuple.dll"; } else { @@ -76,7 +76,6 @@ private static IEnumerable GetReferences() yield return "System.Linq.Expressions"; yield return "System.Runtime.Numerics"; yield return "System.Dynamic.Runtime"; - yield return "System.ValueTuple"; yield return "Microsoft.CSharp"; } } @@ -119,7 +118,7 @@ select x * x runner.RunInteractive(); AssertEx.AssertEqualToleratingWhitespaceDifferences( -$@"{s_logoAndHelpPrompt} +$@"{LogoAndHelpPrompt} > async Task GetStuffAsync() . {{ . return new int[] {{ 1, 2, 3, 4, 5 }}; @@ -170,7 +169,7 @@ public void TestDisplayResultsWithCurrentUICulture1() >", runner.Console.Out.ToString()); } - [Fact(Skip = "https://github.com/dotnet/roslyn/issues/17043")] + [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/dotnet/roslyn/issues/30924")] [WorkItem(7133, "http://github.com/dotnet/roslyn/issues/7133")] public void TestDisplayResultsWithCurrentUICulture2() { @@ -216,7 +215,7 @@ public void Void() runner.RunInteractive(); AssertEx.AssertEqualToleratingWhitespaceDifferences( -$@"{s_logoAndHelpPrompt} +$@"{LogoAndHelpPrompt} > Print(1); 1 > Print(2) @@ -224,7 +223,7 @@ public void Void() > ", runner.Console.Out.ToString()); } - [Fact(Skip = "https://github.com/dotnet/roslyn/issues/18479")] + [Fact] [WorkItem(18479, "https://github.com/dotnet/roslyn/issues/18479")] public void Tuples() { @@ -232,7 +231,7 @@ public void Tuples() runner.RunInteractive(); AssertEx.AssertEqualToleratingWhitespaceDifferences( -$@"{s_logoAndHelpPrompt} +$@"{LogoAndHelpPrompt} > (1,2) [(1, 2)] > ", runner.Console.Out.ToString()); @@ -249,7 +248,7 @@ public void Exception() Assert.Equal(0, runner.RunInteractive()); Assert.Equal( -$@"{s_logoAndHelpPrompt} +$@"{LogoAndHelpPrompt} > int div(int a, int b) => a/b; > div(10, 2) 5 @@ -277,7 +276,7 @@ public void ExceptionInGeneric() Assert.Equal(0, runner.RunInteractive()); Assert.Equal( -$@"{s_logoAndHelpPrompt} +$@"{LogoAndHelpPrompt} > static class C {{ public static int div(int a, int b) => a/b; }} > C.div(10, 2) 5 @@ -304,7 +303,7 @@ public void Args_Interactive1() runner.RunInteractive(); Assert.Equal( -$@"{s_logoAndHelpPrompt} +$@"{LogoAndHelpPrompt} > 1+1 2 > ", runner.Console.Out.ToString()); @@ -533,7 +532,7 @@ public void Script_NoHostNamespaces() runner.RunInteractive(); AssertEx.AssertEqualToleratingWhitespaceDifferences( -$@"{s_logoAndHelpPrompt} +$@"{LogoAndHelpPrompt} > nameof(Microsoft.Missing) «Red» (1,8): error CS0234: { string.Format(CSharpResources.ERR_DottedTypeNameNotFoundInNS, "Missing", "Microsoft") } @@ -648,7 +647,7 @@ public void SourceSearchPaths_Change1() runner.RunInteractive(); AssertEx.AssertEqualToleratingWhitespaceDifferences($@" -{s_logoAndHelpPrompt} +{LogoAndHelpPrompt} > SourcePaths SearchPaths {{ }} > #load ""a.csx"" @@ -684,7 +683,7 @@ public void ReferenceSearchPaths_Change1() runner.RunInteractive(); AssertEx.AssertEqualToleratingWhitespaceDifferences($@" -{s_logoAndHelpPrompt} +{LogoAndHelpPrompt} > ReferencePaths SearchPaths {{ }} > #r ""C.dll"" @@ -796,7 +795,7 @@ public void HelpCommand() runner.RunInteractive(); Assert.Equal( -$@"{s_logoAndHelpPrompt} +$@"{LogoAndHelpPrompt} > #help { ScriptingResources.HelpText } > ", runner.Console.Out.ToString()); @@ -860,7 +859,7 @@ public class Lib2 runner.RunInteractive(); AssertEx.AssertEqualToleratingWhitespaceDifferences( -$@"{s_logoAndHelpPrompt} +$@"{LogoAndHelpPrompt} > #r ""{file1.Path}"" > var l1 = new Lib1(); > #r ""{file2.Path}"" @@ -883,7 +882,7 @@ public void PreservingDeclarationsOnException() runner.RunInteractive(); AssertEx.AssertEqualToleratingWhitespaceDifferences( -$@"{s_logoAndHelpPrompt} +$@"{LogoAndHelpPrompt} > int i = 100; > int j = 20; throw new System.Exception(""Bang!""); int k = 3; «Yellow» @@ -912,7 +911,7 @@ public void DefaultLiteral() runner.RunInteractive(); AssertEx.AssertEqualToleratingWhitespaceDifferences( -$@"{s_logoAndHelpPrompt} +$@"{LogoAndHelpPrompt} > int i = default; > Print(i); 0 diff --git a/src/Scripting/CSharpTest/Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests.csproj b/src/Scripting/CSharpTest/Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests.csproj index 7b68b1cdb0159..b83327ad668ef 100644 --- a/src/Scripting/CSharpTest/Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests.csproj +++ b/src/Scripting/CSharpTest/Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests.csproj @@ -30,7 +30,4 @@ - - - \ No newline at end of file diff --git a/src/Scripting/Core/Hosting/ObjectFormatter/CommonObjectFormatter.cs b/src/Scripting/Core/Hosting/ObjectFormatter/CommonObjectFormatter.cs index 097c57979f2dc..bab8aa1b68d83 100644 --- a/src/Scripting/Core/Hosting/ObjectFormatter/CommonObjectFormatter.cs +++ b/src/Scripting/Core/Hosting/ObjectFormatter/CommonObjectFormatter.cs @@ -67,7 +67,7 @@ public override string FormatException(Exception e) builder.AppendLine(e.Message); - var trace = new StackTrace(e, needFileInfo: true); + var trace = new StackTrace(e, fNeedFileInfo: true); foreach (var frame in trace.GetFrames()) { if (!Filter.Include(frame)) diff --git a/src/Scripting/Core/Microsoft.CodeAnalysis.Scripting.csproj b/src/Scripting/Core/Microsoft.CodeAnalysis.Scripting.csproj index fda45f221d412..00e035671a0ce 100644 --- a/src/Scripting/Core/Microsoft.CodeAnalysis.Scripting.csproj +++ b/src/Scripting/Core/Microsoft.CodeAnalysis.Scripting.csproj @@ -7,7 +7,7 @@ Library Microsoft.CodeAnalysis.Scripting true - netstandard1.3 + netstandard2.0 $(DefineConstants);SCRIPTING @@ -32,7 +32,6 @@ is .NET Core. --> - diff --git a/src/Scripting/Core/ScriptOptions.cs b/src/Scripting/Core/ScriptOptions.cs index d1ec0fbf4fad6..36b631ddcf626 100644 --- a/src/Scripting/Core/ScriptOptions.cs +++ b/src/Scripting/Core/ScriptOptions.cs @@ -63,6 +63,7 @@ private static ImmutableArray GetDefaultMetadataReferences() "System.Threading.Tasks", "System.Threading.Tasks.Parallel", "System.Threading.Thread", + "System.ValueTuple", }; return ImmutableArray.CreateRange(files.Select(CreateUnresolvedReference)); diff --git a/src/Scripting/CoreTest.Desktop/Microsoft.CodeAnalysis.Scripting.Desktop.UnitTests.csproj b/src/Scripting/CoreTest.Desktop/Microsoft.CodeAnalysis.Scripting.Desktop.UnitTests.csproj index bbb5aa9e19761..f0379cab72f3a 100644 --- a/src/Scripting/CoreTest.Desktop/Microsoft.CodeAnalysis.Scripting.Desktop.UnitTests.csproj +++ b/src/Scripting/CoreTest.Desktop/Microsoft.CodeAnalysis.Scripting.Desktop.UnitTests.csproj @@ -7,7 +7,7 @@ Library Microsoft.CodeAnalysis.Scripting.Test true - net46 + net472 $(RoslynDesktopRuntimeIdentifier) UnitTest diff --git a/src/Scripting/CoreTest/ScriptOptionsTests.cs b/src/Scripting/CoreTest/ScriptOptionsTests.cs index 4aad123fd2f43..88bddc11b8e5c 100644 --- a/src/Scripting/CoreTest/ScriptOptionsTests.cs +++ b/src/Scripting/CoreTest/ScriptOptionsTests.cs @@ -24,7 +24,7 @@ public void AddReferences() AddReferences("System.Linq"). AddReferences("System.Linq"); - Assert.Equal(GacFileResolver.IsAvailable ? 5 : 29, options.MetadataReferences.Length); + Assert.Equal(GacFileResolver.IsAvailable ? 5 : 30, options.MetadataReferences.Length); } [Fact] diff --git a/src/Scripting/CoreTestUtilities/Microsoft.CodeAnalysis.Scripting.TestUtilities.csproj b/src/Scripting/CoreTestUtilities/Microsoft.CodeAnalysis.Scripting.TestUtilities.csproj index e0f5e8bae156f..2b49cfadf684c 100644 --- a/src/Scripting/CoreTestUtilities/Microsoft.CodeAnalysis.Scripting.TestUtilities.csproj +++ b/src/Scripting/CoreTestUtilities/Microsoft.CodeAnalysis.Scripting.TestUtilities.csproj @@ -6,7 +6,7 @@ AnyCPU Library true - netstandard1.3 + netstandard2.0 true false diff --git a/src/Scripting/VisualBasic/Hosting/ObjectFormatter/VisualBasicObjectFormatterImpl.vb b/src/Scripting/VisualBasic/Hosting/ObjectFormatter/VisualBasicObjectFormatterImpl.vb index 29283b6c848a9..11502a83c8888 100644 --- a/src/Scripting/VisualBasic/Hosting/ObjectFormatter/VisualBasicObjectFormatterImpl.vb +++ b/src/Scripting/VisualBasic/Hosting/ObjectFormatter/VisualBasicObjectFormatterImpl.vb @@ -2,6 +2,7 @@ Imports System.Reflection Imports Microsoft.CodeAnalysis.Scripting.Hosting +Imports MemberFilter = Microsoft.CodeAnalysis.Scripting.Hosting.MemberFilter Namespace Microsoft.CodeAnalysis.VisualBasic.Scripting.Hosting diff --git a/src/Scripting/VisualBasic/Microsoft.CodeAnalysis.VisualBasic.Scripting.vbproj b/src/Scripting/VisualBasic/Microsoft.CodeAnalysis.VisualBasic.Scripting.vbproj index e7981e3efbc46..566f133d55226 100644 --- a/src/Scripting/VisualBasic/Microsoft.CodeAnalysis.VisualBasic.Scripting.vbproj +++ b/src/Scripting/VisualBasic/Microsoft.CodeAnalysis.VisualBasic.Scripting.vbproj @@ -5,7 +5,7 @@ AnyCPU AnyCPU Library - netstandard1.3 + netstandard2.0 diff --git a/src/Scripting/VisualBasicTest.Desktop/Microsoft.CodeAnalysis.VisualBasic.Scripting.Desktop.UnitTests.vbproj b/src/Scripting/VisualBasicTest.Desktop/Microsoft.CodeAnalysis.VisualBasic.Scripting.Desktop.UnitTests.vbproj index 14c82482ce637..2ff7d37d42d03 100644 --- a/src/Scripting/VisualBasicTest.Desktop/Microsoft.CodeAnalysis.VisualBasic.Scripting.Desktop.UnitTests.vbproj +++ b/src/Scripting/VisualBasicTest.Desktop/Microsoft.CodeAnalysis.VisualBasic.Scripting.Desktop.UnitTests.vbproj @@ -7,7 +7,7 @@ Library Properties true - net46 + net472 $(RoslynDesktopRuntimeIdentifier) UnitTest diff --git a/src/Scripting/VisualBasicTest/Microsoft.CodeAnalysis.VisualBasic.Scripting.UnitTests.vbproj b/src/Scripting/VisualBasicTest/Microsoft.CodeAnalysis.VisualBasic.Scripting.UnitTests.vbproj index c4921fd81a30d..7aea3b2eabb0f 100644 --- a/src/Scripting/VisualBasicTest/Microsoft.CodeAnalysis.VisualBasic.Scripting.UnitTests.vbproj +++ b/src/Scripting/VisualBasicTest/Microsoft.CodeAnalysis.VisualBasic.Scripting.UnitTests.vbproj @@ -5,7 +5,7 @@ AnyCPU AnyCPU Library - net46 + net472 UnitTest diff --git a/src/Setup/DevDivInsertionFiles/App.config b/src/Setup/DevDivInsertionFiles/App.config deleted file mode 100644 index 9c05822ff533f..0000000000000 --- a/src/Setup/DevDivInsertionFiles/App.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/src/Setup/DevDivInsertionFiles/BuildDevDivInsertionFiles.vb b/src/Setup/DevDivInsertionFiles/BuildDevDivInsertionFiles.vb deleted file mode 100644 index 1c33664472068..0000000000000 --- a/src/Setup/DevDivInsertionFiles/BuildDevDivInsertionFiles.vb +++ /dev/null @@ -1,266 +0,0 @@ -Imports System.IO -Imports System.Threading -Imports Newtonsoft.Json -Imports Newtonsoft.Json.Linq -Imports System.Reflection.PortableExecutable -Imports System.Reflection.Metadata - -Public Class BuildDevDivInsertionFiles - Private Const DevDivInsertionFilesDirName = "DevDivInsertionFiles" - Private Const DevDivPackagesDirName = "DevDivPackages" - - Private ReadOnly _binDirectory As String - Private ReadOnly _outputDirectory As String - Private ReadOnly _outputPackageDirectory As String - Private ReadOnly _nugetPackageRoot As String - - Private Sub New(args As String()) - _binDirectory = Path.GetFullPath(args(0)) - _nugetPackageRoot = Path.GetFullPath(args(1)) - _outputDirectory = Path.Combine(_binDirectory, DevDivInsertionFilesDirName) - _outputPackageDirectory = Path.Combine(_binDirectory, DevDivPackagesDirName) - End Sub - - Public Shared Function Main(args As String()) As Integer - If args.Length < 2 Then - Console.WriteLine("Expected arguments: ") - Console.WriteLine($"Actual argument count is {args.Length}") - Return 1 - End If - - Try - Call New BuildDevDivInsertionFiles(args).Execute() - Return 0 - Catch ex As Exception - Console.Error.WriteLine(ex.ToString()) - Return 1 - End Try - End Function - - Private Sub DeleteDirContents(dir As String) - If Directory.Exists(dir) Then - ' Delete everything within it. We'll keep the top-level one around. - For Each file In New DirectoryInfo(dir).GetFiles() - file.Delete() - Next - - For Each directory In New DirectoryInfo(dir).GetDirectories() - directory.Delete(recursive:=True) - Next - End If - End Sub - - Public Sub Execute() - Retry(Sub() - DeleteDirContents(_outputDirectory) - DeleteDirContents(Path.Combine(_outputPackageDirectory, "NativeDependencies")) - DeleteDirContents(Path.Combine(_outputPackageDirectory, "ManagedDependencies")) - End Sub) - - ' Build a dependency map - Dim dependencies = BuildDependencyMap(_binDirectory) - GenerateContractsListMsbuild(dependencies) - GenerateAssemblyVersionList(dependencies) - CopyDependencies(dependencies) - End Sub - - Private Class DependencyInfo - ' For example, "ref/net46" - Public ContractDir As String - - ' For example, "lib/net46" - Public ImplementationDir As String - - ' For example, "System.AppContext" - Public PackageName As String - - ' For example, "4.1.0" - Public PackageVersion As String - - Public IsNative As Boolean - Public IsFacade As Boolean - - Sub New(contractDir As String, implementationDir As String, packageName As String, packageVersion As String, isNative As Boolean, isFacade As Boolean) - Me.ContractDir = contractDir - Me.ImplementationDir = implementationDir - Me.PackageName = packageName - Me.PackageVersion = packageVersion - Me.IsNative = isNative - Me.IsFacade = isFacade - End Sub - End Class - - Private Function BuildDependencyMap(inputDirectory As String) As Dictionary(Of String, DependencyInfo) - Dim result = New Dictionary(Of String, DependencyInfo) - Dim objDir = Path.Combine(Path.GetDirectoryName(_binDirectory.TrimEnd(Path.DirectorySeparatorChar)), "Obj") - Dim files = New List(Of String) - files.Add(Path.Combine(objDir, "Roslyn.Compilers.Extension\project.assets.json")) - files.Add(Path.Combine(objDir, "Roslyn.VisualStudio.Setup.Dependencies\project.assets.json")) - - For Each projectLockJson In files - Dim items = DirectCast(JsonConvert.DeserializeObject(File.ReadAllText(projectLockJson)), JObject) - Const targetFx = ".NETFramework,Version=v4.6" - - Dim targets = DirectCast(items.Property("targets")?.Value, JObject) - If targets Is Nothing Then - Throw New InvalidDataException($"Invalid format for '{projectLockJson}': missing 'targets' property") - End If - - Dim targetObj = DirectCast(targets.Property(targetFx)?.Value, JObject) - If targetObj Is Nothing Then - Dim availablePlatforms = String.Join(",", targets.Properties.Select(Function(p) $"'{p.Name}'")) - Throw New InvalidDataException($"Expected platform not found in '{projectLockJson}': '{targetFx}'. Available platforms: {availablePlatforms}") - End If - - For Each targetProperty In targetObj.Properties - Dim packageNameAndVersion = targetProperty.Name.Split("/"c) - Dim packageName = packageNameAndVersion(0) - Dim packageVersion = packageNameAndVersion(1) - Dim packageObj = DirectCast(targetProperty.Value, JObject) - - If packageObj.Property("type").Value.Value(Of String) = "project" Then - Continue For - End If - - Dim contracts = DirectCast(packageObj.Property("compile")?.Value, JObject) - Dim runtime = DirectCast(packageObj.Property("runtime")?.Value, JObject) - Dim native = DirectCast(packageObj.Property("native")?.Value, JObject) - Dim frameworkAssemblies = packageObj.Property("frameworkAssemblies")?.Value - - Dim implementations = If(runtime, native) - If implementations Is Nothing Then - Continue For - End If - - ' No need to insert Visual Studio packages back into the repository itself - If packageName.StartsWith("Microsoft.VisualStudio.") OrElse - packageName = "EnvDTE" OrElse - packageName = "stdole" OrElse - packageName.StartsWith("Microsoft.Build") OrElse - packageName = "Microsoft.Composition" OrElse - packageName = "System.Net.Http" OrElse - packageName = "System.Diagnostics.DiagnosticSource" OrElse - packageName = "StreamJsonRpc" OrElse - packageName = "Newtonsoft.Json" Then - Continue For - End If - - For Each assemblyProperty In implementations.Properties() - Dim fileName = Path.GetFileName(assemblyProperty.Name) - If fileName <> "_._" Then - - Dim existingDependency As DependencyInfo = Nothing - If result.TryGetValue(fileName, existingDependency) Then - - If existingDependency.PackageVersion <> packageVersion Then - Throw New InvalidOperationException($"Found multiple versions of package '{existingDependency.PackageName}': {existingDependency.PackageVersion} and {packageVersion}") - End If - - Continue For - End If - - Dim runtimeTarget = Path.GetDirectoryName(assemblyProperty.Name) - - Dim compileDll = contracts?.Properties().Select(Function(p) p.Name).Where(Function(n) Path.GetFileName(n) = fileName).SingleOrDefault() - Dim compileTarget = If(compileDll IsNot Nothing, Path.GetDirectoryName(compileDll), Nothing) - - result.Add(fileName, New DependencyInfo(compileTarget, - runtimeTarget, - packageName, - packageVersion, - isNative:=native IsNot Nothing, - isFacade:=(frameworkAssemblies IsNot Nothing AndAlso - packageName <> "Microsoft.Build" AndAlso - packageName <> "Microsoft.DiaSymReader") OrElse - packageName = "System.IO.Pipes.AccessControl")) - End If - Next - Next - Next - - Return result - End Function - - Private Sub GenerateContractsListMsbuild(dependencies As IReadOnlyDictionary(Of String, DependencyInfo)) - Using writer = New StreamWriter(GetAbsolutePathInOutputDirectory("ProductData\ContractAssemblies.props")) - writer.WriteLine("") - writer.WriteLine("") - writer.WriteLine(" ") - writer.WriteLine(" ") - - For Each entry In GetContracts(dependencies) - writer.WriteLine($" <{entry.Key}>{entry.Value}") - Next - - writer.WriteLine(" ") - writer.WriteLine("") - End Using - End Sub - - Private Iterator Function GetContracts(dependencies As IReadOnlyDictionary(Of String, DependencyInfo)) As IEnumerable(Of KeyValuePair(Of String, String)) - For Each entry In dependencies.OrderBy(Function(e) e.Key) - Dim fileName = entry.Key - Dim dependency = entry.Value - If dependency.ContractDir IsNot Nothing Then - Dim variableName = "FXContract_" + Path.GetFileNameWithoutExtension(fileName).Replace(".", "_") - Dim dir = Path.Combine(dependency.PackageName, dependency.ContractDir) - Yield New KeyValuePair(Of String, String)(variableName, Path.Combine(dir, fileName)) - End If - Next - End Function - - Private Sub GenerateAssemblyVersionList(dependencies As IReadOnlyDictionary(Of String, DependencyInfo)) - Using writer = New StreamWriter(GetAbsolutePathInOutputDirectory("DependentAssemblyVersions.csv")) - For Each entry In dependencies.OrderBy(Function(e) e.Key) - Dim fileName = entry.Key - Dim dependency = entry.Value - If Not dependency.IsNative Then - - Dim version As Version - Dim dllPath = Path.Combine(_nugetPackageRoot, dependency.PackageName, dependency.PackageVersion, dependency.ImplementationDir, fileName) - - Using peReader = New PEReader(File.OpenRead(dllPath)) - version = peReader.GetMetadataReader().GetAssemblyDefinition().Version - End Using - - writer.WriteLine($"{Path.GetFileNameWithoutExtension(fileName)},{version}") - End If - Next - End Using - End Sub - - Private Sub CopyDependencies(dependencies As IReadOnlyDictionary(Of String, DependencyInfo)) - For Each dependency In dependencies.Values - Dim nupkg = $"{dependency.PackageName}.{dependency.PackageVersion}.nupkg" - Dim srcPath = Path.Combine(_nugetPackageRoot, dependency.PackageName, dependency.PackageVersion, nupkg) - Dim dstDir = Path.Combine(_outputPackageDirectory, If(dependency.IsNative, "NativeDependencies", "ManagedDependencies")) - Dim dstPath = Path.Combine(dstDir, nupkg) - - Directory.CreateDirectory(dstDir) - File.Copy(srcPath, dstPath, overwrite:=True) - Next - End Sub - - ''' - ''' A simple method to retry an operation. Helpful if some file locking is going on and you want to just try the operation again. - ''' - Private Sub Retry(action As Action) - For i = 1 To 10 - Try - action() - Return - Catch ex As Exception - Thread.Sleep(100) - End Try - Next - End Sub - - Private Function GetAbsolutePathInOutputDirectory(relativePath As String) As String - Dim absolutePath = Path.Combine(_outputDirectory, relativePath) - - ' Ensure that the parent directories are all created - Directory.CreateDirectory(Path.GetDirectoryName(absolutePath)) - - Return absolutePath - End Function -End Class diff --git a/src/Setup/DevDivInsertionFiles/DevDivInsertionFiles.csproj b/src/Setup/DevDivInsertionFiles/DevDivInsertionFiles.csproj new file mode 100644 index 0000000000000..9606bbe95238e --- /dev/null +++ b/src/Setup/DevDivInsertionFiles/DevDivInsertionFiles.csproj @@ -0,0 +1,194 @@ + + + + + + <_NuGetRepackAssembly Condition="'$(MSBuildRuntimeType)' != 'Core'">$(NuGetPackageRoot)roslyntools.nugetrepack.buildtasks\$(RoslynToolsNuGetRepackVersion)\tools\net472\RoslynTools.NuGetRepack.BuildTasks.dll + <_NuGetRepackAssembly Condition="'$(MSBuildRuntimeType)' == 'Core'">$(NuGetPackageRoot)roslyntools.nugetrepack.buildtasks\$(RoslynToolsNuGetRepackVersion)\tools\netcoreapp2.1\RoslynTools.NuGetRepack.BuildTasks.dll + + + + + + + + + net472 + Library + + + + + + + + + + + <_DevDivInsertionFilesDir>$(ArtifactsConfigurationDir)DevDivInsertionFiles\ + <_DependentAssemblyVersionsFile>$(_DevDivInsertionFilesDir)DependentAssemblyVersions.csv + <_ManagedDependenciesDir>$(ArtifactsConfigurationDir)DevDivPackages\ManagedDependencies\ + <_OptimizedDependenciesDir>$(ArtifactsTmpDir)OptimizedDependencies\ + <_OptimizedNuGetPackageVersionSuffix Condition="'$(OfficialBuild)' != 'true'">vs-ci + <_OptimizedNuGetPackageVersionSuffix Condition="'$(OfficialBuild)' == 'true'">vs-$(VersionSuffixDateStamp)-$(VersionSuffixBuildOfTheDayPadded) + + + + + + + + + + + + + + + + + + + + + <_Dependency Include="@(ReferencePath->'%(NuGetPackageId)')" + Condition="'%(ReferencePath.FrameworkFile)' != 'true' and + '%(ReferencePath.NuGetPackageId)' != '' and + '%(ReferencePath.ReferenceSourceTarget)' != 'ProjectReference'" /> + + + <_CopyLocalDependency Include="@(ReferenceCopyLocalPaths->'%(NuGetPackageId)')" + Exclude="@(_Dependency)" + Condition="'%(ReferenceCopyLocalPaths.Culture)' == ''"> + <_AssemblyPath>%(ReferenceCopyLocalPaths.Identity) + + + + + + + + + + <_Dependency Remove="@(_Dependency)" Condition="$([MSBuild]::ValueOrDefault('%(Identity)', '').StartsWith('Microsoft.VisualStudio.'))"/> + <_Dependency Remove="@(_Dependency)" Condition="$([MSBuild]::ValueOrDefault('%(Identity)', '').StartsWith('System.Composition.'))"/> + <_Dependency Remove="@(_Dependency)" Condition="$([MSBuild]::ValueOrDefault('%(Identity)', '').StartsWith('Microsoft.Internal.VisualStudio.'))"/> + <_Dependency Remove="EnvDTE"/> + <_Dependency Remove="EnvDTE80"/> + <_Dependency Remove="Microsoft.Build"/> + <_Dependency Remove="Microsoft.Build.Framework"/> + <_Dependency Remove="Microsoft.MSXML"/> + <_Dependency Remove="Newtonsoft.Json"/> + <_Dependency Remove="stdole"/> + <_Dependency Remove="StreamJsonRpc"/> + <_Dependency Remove="System.Threading.Tasks.Dataflow"/> + + + + + <_Dependency> + <_AssemblyName>$([MSBuild]::ValueOrDefault('%(_Dependency.FusionName)', '').Split(',')[0]) + <_AssemblyVersion>$([MSBuild]::ValueOrDefault('%(_Dependency.FusionName)', '').Split(',')[1]) + <_NuGetPackageFileName>%(_Dependency.NuGetPackageId).%(_Dependency.NuGetPackageVersion).nupkg + <_NuGetPackageDir>$(NuGetPackageRoot)$([MSBuild]::ValueOrDefault('%(_Dependency.NuGetPackageId)', '').ToLower())\%(_Dependency.NuGetPackageVersion)\ + + + + + + <_RemainingDependency Include="@(_Dependency)" Exclude="@(ExpectedDependency)"/> + <_UninsertedExpectedDependency Include="@(ExpectedDependency)" Exclude="@(_Dependency)"/> + + + + + + + + + + + + <_DependencyWithExpectedMetadata> + <_UnpackDir>$(_OptimizedDependenciesDir)%(_DependencyWithExpectedMetadata.Identity)\ + <_OptimizeAssembly>$(_OptimizedDependenciesDir)%(_DependencyWithExpectedMetadata.Identity)\%(_DependencyWithExpectedMetadata.DevEnvLib) + <_PreviousOptimizedFile>$([System.IO.Path]::Combine($(IbcOptimizationDataDir), '$([System.IO.Path]::GetFileNameWithoutExtension(%(_DependencyWithExpectedMetadata.DevEnvLib))).pgo')) + + + <_DependencyWithOptimizationData Include="@(_DependencyWithExpectedMetadata)" Condition="'%(_DependencyWithExpectedMetadata.Optimize)' != 'false' and Exists(%(_DependencyWithExpectedMetadata._PreviousOptimizedFile))" /> + <_DependencyWithoutOptimizationData Include="@(_Dependency)" Exclude="@(_DependencyWithOptimizationData)"/> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Setup/DevDivInsertionFiles/Directory.Build.targets b/src/Setup/DevDivInsertionFiles/Directory.Build.targets new file mode 100644 index 0000000000000..399381dca7064 --- /dev/null +++ b/src/Setup/DevDivInsertionFiles/Directory.Build.targets @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/src/Setup/DevDivInsertionFiles/My Project/launchSettings.json b/src/Setup/DevDivInsertionFiles/My Project/launchSettings.json deleted file mode 100644 index 6d7f07b79bffa..0000000000000 --- a/src/Setup/DevDivInsertionFiles/My Project/launchSettings.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "profiles": { - "DevDivInsertionFiles": { - "commandName": "Project", - "commandLineArgs": "E:\\code\\roslyn\\Binaries\\Debug E:\\code\\roslyn e:\\nuget" - } - } -} \ No newline at end of file diff --git a/src/Setup/DevDivInsertionFiles/Roslyn.BuildDevDivInsertionFiles.vbproj b/src/Setup/DevDivInsertionFiles/Roslyn.BuildDevDivInsertionFiles.vbproj deleted file mode 100644 index 1ccbcc8a9c89d..0000000000000 --- a/src/Setup/DevDivInsertionFiles/Roslyn.BuildDevDivInsertionFiles.vbproj +++ /dev/null @@ -1,41 +0,0 @@ - - - - - AnyCPU - AnyCPU - Exe - Sub Main - Roslyn.BuildDevDivInsertionFiles - net46 - $(RoslynDesktopRuntimeIdentifier) - $(RoslynDesktopRuntimeIdentifier) - true - Off - false - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Setup/DevDivPackages/Debugger/DevDivPackagesDebugger_DoNotUse.csproj b/src/Setup/DevDivPackages/Debugger/DevDivPackagesDebugger_DoNotUse.csproj deleted file mode 100644 index d4c827fb76679..0000000000000 --- a/src/Setup/DevDivPackages/Debugger/DevDivPackagesDebugger_DoNotUse.csproj +++ /dev/null @@ -1,36 +0,0 @@ - - - - - AnyCPU - AnyCPU - Exe - DevDivPackagesDebugger - net46 - win - true - false - true - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Setup/DevDivPackages/Debugger/Program.cs b/src/Setup/DevDivPackages/Debugger/Program.cs deleted file mode 100644 index 3859fe1967c75..0000000000000 --- a/src/Setup/DevDivPackages/Debugger/Program.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; - -namespace DoNotUse -{ - public class Program - { - private static void Main(string[] args) - { - throw new Exception("Do not use"); - } - } -} diff --git a/src/Setup/DevDivVsix/CompilersPackage/Microsoft.CodeAnalysis.Compilers.Setup.csproj b/src/Setup/DevDivVsix/CompilersPackage/Microsoft.CodeAnalysis.Compilers.Setup.csproj index 064521d092ac7..c573d0aa6a25e 100644 --- a/src/Setup/DevDivVsix/CompilersPackage/Microsoft.CodeAnalysis.Compilers.Setup.csproj +++ b/src/Setup/DevDivVsix/CompilersPackage/Microsoft.CodeAnalysis.Compilers.Setup.csproj @@ -1,7 +1,7 @@ - net46 + net472 Custom @@ -22,23 +22,60 @@ <_SwrFilePath>$(IntermediateOutputPath)Microsoft.CodeAnalysis.Compilers.swr + + + + + + + <_PreviousOptimizedFile>$([System.IO.Path]::Combine($(IbcOptimizationDataDir), '$([System.IO.Path]::GetFileNameWithoutExtension(%(CompilerArtifact.Identity))).pgo')) + <_OptimizeAssembly>$(IntermediateOutputPath)optimized\$([System.IO.Path]::GetFileName(%(CompilerArtifact.Identity))) + + + + <_PreviousOptimizedFile/> + <_OptimizeAssembly/> + + + + + + + + + + + + + <_File Include="@(CompilerArtifact)"> + %(CompilerArtifact.Identity) + %(CompilerArtifact._OptimizeAssembly) vs.file.ngenArchitecture=%(CompilerArtifact.NgenArchitecture) vs.file.ngenPriority=%(CompilerArtifact.NGenPriority) vs.file.ngenApplication="[installDir]\MSBuild\15.0\Bin\Roslyn\%(CompilerArtifact.NGenApplication)" - - - - <_FileEntries Include='file source="%(_File.Identity)"%(_File.NGenArchitectureString)%(_File.NGenPriorityString)%(_File.NGenApplicationString)'/> + + <_FileEntries Include='file source="%(_File.Path)"%(_File.NGenArchitectureString)%(_File.NGenPriorityString)%(_File.NGenApplicationString)'/> @@ -49,7 +86,7 @@ package name=$(VisualStudioInsertionComponent) version=$(VsixVersion) vs.dependencies - vs.dependency id=Microsoft.Net.PackageGroup.4.6.1.Redist + vs.dependency id=Microsoft.Net.PackageGroup.4.7.2.Redist vs.nonCriticalProcesses vs.nonCriticalProcess name="VBCSCompiler" @@ -70,6 +107,6 @@ folder InstallDir:\Common7\Tools\vsdevcmd\ext - + \ No newline at end of file diff --git a/src/Setup/DevDivVsix/PortableFacades/PortableFacades.Setup.csproj b/src/Setup/DevDivVsix/PortableFacades/PortableFacades.Setup.csproj deleted file mode 100644 index 2fecd0ab79ff2..0000000000000 --- a/src/Setup/DevDivVsix/PortableFacades/PortableFacades.Setup.csproj +++ /dev/null @@ -1,81 +0,0 @@ - - - - net46 - Custom - 1.11.0.0 - - - PortableFacades.vsix - PortableFacades - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <_SwrFilePath>$(IntermediateOutputPath)$(TargetVsixContainerName).swr - - - - - - - <_FileEntries Include='file source="%(RuntimeCopyLocalItems.Identity)" vs.file.ngen=yes'/> - - - - <_Lines> - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Setup/Installer/Installer.Package.csproj b/src/Setup/Installer/Installer.Package.csproj index f97c157167773..9c12cdf89fdd5 100644 --- a/src/Setup/Installer/Installer.Package.csproj +++ b/src/Setup/Installer/Installer.Package.csproj @@ -1,7 +1,7 @@ - net46 + net472 Custom diff --git a/src/Test/Diagnostics/Roslyn.Hosting.Diagnostics.csproj b/src/Test/Diagnostics/Roslyn.Hosting.Diagnostics.csproj index 66db6a99aff49..1f77aa9f108c9 100644 --- a/src/Test/Diagnostics/Roslyn.Hosting.Diagnostics.csproj +++ b/src/Test/Diagnostics/Roslyn.Hosting.Diagnostics.csproj @@ -6,14 +6,13 @@ AnyCPU Library Roslyn.Hosting.Diagnostics - net46 + net472 - diff --git a/src/Test/PdbUtilities/Roslyn.Test.PdbUtilities.csproj b/src/Test/PdbUtilities/Roslyn.Test.PdbUtilities.csproj index 30a02f6c518ca..268eedf8b1849 100644 --- a/src/Test/PdbUtilities/Roslyn.Test.PdbUtilities.csproj +++ b/src/Test/PdbUtilities/Roslyn.Test.PdbUtilities.csproj @@ -6,7 +6,7 @@ AnyCPU Library Roslyn.Test.PdbUtilities - netstandard1.3 + netstandard2.0 14.0 true false @@ -49,9 +49,17 @@ - + + + + + + diff --git a/src/Test/Perf/StackDepthTest/StackDepthTest.csproj b/src/Test/Perf/StackDepthTest/StackDepthTest.csproj index 4a3ac1e7103fd..d759441941e73 100644 --- a/src/Test/Perf/StackDepthTest/StackDepthTest.csproj +++ b/src/Test/Perf/StackDepthTest/StackDepthTest.csproj @@ -4,7 +4,7 @@ AnyCPU AnyCPU Exe - net46 + net472 $(RoslynDesktopRuntimeIdentifier) true false diff --git a/src/Test/Perf/Utilities/Roslyn.Test.Performance.Utilities.csproj b/src/Test/Perf/Utilities/Roslyn.Test.Performance.Utilities.csproj index e23061acc10fe..dc7496499313b 100644 --- a/src/Test/Perf/Utilities/Roslyn.Test.Performance.Utilities.csproj +++ b/src/Test/Perf/Utilities/Roslyn.Test.Performance.Utilities.csproj @@ -6,7 +6,7 @@ AnyCPU Library Roslyn.Test.Performance.Utilities - net46 + net472 false diff --git a/src/Test/Perf/tests/Roslyn.Test.Performance.Tests.csproj b/src/Test/Perf/tests/Roslyn.Test.Performance.Tests.csproj index 1999df7ef8e0e..76d44786a0934 100644 --- a/src/Test/Perf/tests/Roslyn.Test.Performance.Tests.csproj +++ b/src/Test/Perf/tests/Roslyn.Test.Performance.Tests.csproj @@ -6,7 +6,7 @@ AnyCPU Library Roslyn.Test.Performance.Tests - net46 + net472 true false diff --git a/src/Test/Utilities/Portable/Assert/UseCultureAttribute.cs b/src/Test/Utilities/Portable/Assert/UseCultureAttribute.cs index e4a2177c5d8de..dad0250403354 100644 --- a/src/Test/Utilities/Portable/Assert/UseCultureAttribute.cs +++ b/src/Test/Utilities/Portable/Assert/UseCultureAttribute.cs @@ -51,7 +51,7 @@ public UseCultureAttribute(string culture) /// The name of the UI culture. public UseCultureAttribute(string culture, string uiCulture) { -#if NET46 +#if NET472 _culture = new Lazy(() => new CultureInfo(culture, useUserOverride: false)); _uiCulture = new Lazy(() => new CultureInfo(uiCulture, useUserOverride: false)); #elif NETCOREAPP2_1 @@ -83,11 +83,11 @@ public override void Before(MethodInfo methodUnderTest) _originalCulture = CultureInfo.CurrentCulture; _originalUICulture = CultureInfo.CurrentUICulture; -#if NET46 || NETCOREAPP2_1 +#if NET472 || NETCOREAPP2_1 CultureInfo.CurrentCulture = Culture; CultureInfo.CurrentUICulture = UICulture; -#if NET46 +#if NET472 CultureInfo.CurrentCulture.ClearCachedData(); CultureInfo.CurrentUICulture.ClearCachedData(); #endif @@ -103,11 +103,11 @@ public override void Before(MethodInfo methodUnderTest) /// The method under test public override void After(MethodInfo methodUnderTest) { -#if NET46 || NETCOREAPP2_1 +#if NET472 || NETCOREAPP2_1 CultureInfo.CurrentCulture = _originalCulture; CultureInfo.CurrentUICulture = _originalUICulture; -#if NET46 +#if NET472 CultureInfo.CurrentCulture.ClearCachedData(); CultureInfo.CurrentUICulture.ClearCachedData(); #endif diff --git a/src/Test/Utilities/Portable/Compilation/RuntimeUtilities.cs b/src/Test/Utilities/Portable/Compilation/RuntimeUtilities.cs index 81305131c1817..795d2e2710a76 100644 --- a/src/Test/Utilities/Portable/Compilation/RuntimeUtilities.cs +++ b/src/Test/Utilities/Portable/Compilation/RuntimeUtilities.cs @@ -1,4 +1,6 @@ -using System; +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; using System.Collections.Generic; using System.IO; using System.Reflection; @@ -16,7 +18,7 @@ public static partial class RuntimeUtilities internal static BuildPaths CreateBuildPaths(string workingDirectory, string sdkDirectory = null, string tempDirectory = null) { tempDirectory = tempDirectory ?? Path.GetTempPath(); -#if NET46 +#if NET472 return new BuildPaths( clientDir: Path.GetDirectoryName(typeof(BuildPathsUtil).Assembly.Location), workingDir: workingDirectory, @@ -33,11 +35,11 @@ internal static BuildPaths CreateBuildPaths(string workingDirectory, string sdkD internal static IRuntimeEnvironmentFactory GetRuntimeEnvironmentFactory() { -#if NET46 +#if NET472 return new Roslyn.Test.Utilities.Desktop.DesktopRuntimeEnvironmentFactory(); #elif NETCOREAPP2_1 return new Roslyn.Test.Utilities.CoreClr.CoreCLRRuntimeEnvironmentFactory(); -#elif NETSTANDARD1_3 +#elif NETSTANDARD2_0 throw new PlatformNotSupportedException(); #else #error Unsupported configuration @@ -46,11 +48,11 @@ internal static IRuntimeEnvironmentFactory GetRuntimeEnvironmentFactory() internal static AnalyzerAssemblyLoader CreateAnalyzerAssemblyLoader() { -#if NET46 +#if NET472 return new DesktopAnalyzerAssemblyLoader(); #elif NETCOREAPP2_1 return new CoreClrAnalyzerAssemblyLoader(); -#elif NETSTANDARD1_3 +#elif NETSTANDARD2_0 return new ThrowingAnalyzerAssemblyLoader(); #else #error Unsupported configuration @@ -62,13 +64,7 @@ internal static AnalyzerAssemblyLoader CreateAnalyzerAssemblyLoader() /// internal static string GetAssemblyLocation(Type type) { -#if NET46 || NETCOREAPP2_1 return type.GetTypeInfo().Assembly.Location; -#elif NETSTANDARD1_3 - throw new PlatformNotSupportedException(); -#else -#error Unsupported configuration -#endif } } } diff --git a/src/Test/Utilities/Portable/CompilationVerifier.cs b/src/Test/Utilities/Portable/CompilationVerifier.cs index 1318f2dbfec04..4ff99abc52eda 100644 --- a/src/Test/Utilities/Portable/CompilationVerifier.cs +++ b/src/Test/Utilities/Portable/CompilationVerifier.cs @@ -79,7 +79,6 @@ internal Metadata GetMetadata() } } -#if NET46 public string Dump(string methodName = null) { using (var testEnvironment = RuntimeEnvironmentFactory.Create(_dependencies)) @@ -151,7 +150,6 @@ void listMethodsInType(ICSharpCode.Decompiler.TypeSystem.ITypeDefinition type, D } } } -#endif public void Emit(string expectedOutput, int? expectedReturnCode, string[] args, IEnumerable manifestResources, EmitOptions emitOptions, Verification peVerify, SignatureDescription[] expectedSignatures) { diff --git a/src/Test/Utilities/Portable/FX/EnsureEnglishUICulture.cs b/src/Test/Utilities/Portable/FX/EnsureEnglishUICulture.cs index 756a9498edb5a..4f49b634ea649 100644 --- a/src/Test/Utilities/Portable/FX/EnsureEnglishUICulture.cs +++ b/src/Test/Utilities/Portable/FX/EnsureEnglishUICulture.cs @@ -37,11 +37,7 @@ public EnsureEnglishUICulture() _threadUICulture = CultureInfo.CurrentUICulture; _needToRestore = true; -#if DNX CultureInfo.CurrentUICulture = preferred; -#else - System.Threading.Thread.CurrentThread.CurrentUICulture = preferred; -#endif } } @@ -52,11 +48,7 @@ public void Dispose() if (_needToRestore && _threadId == Thread.CurrentThread.ManagedThreadId) { _needToRestore = false; -#if DNX CultureInfo.CurrentUICulture = _threadUICulture; -#else - System.Threading.Thread.CurrentThread.CurrentUICulture = _threadUICulture; -#endif } } } diff --git a/src/Test/Utilities/Portable/FX/EnsureInvariantCulture.cs b/src/Test/Utilities/Portable/FX/EnsureInvariantCulture.cs index d40122d6e10fd..0f0c99592a057 100644 --- a/src/Test/Utilities/Portable/FX/EnsureInvariantCulture.cs +++ b/src/Test/Utilities/Portable/FX/EnsureInvariantCulture.cs @@ -17,11 +17,7 @@ public EnsureInvariantCulture() _threadId = Thread.CurrentThread.ManagedThreadId; _threadCulture = CultureInfo.CurrentCulture; -#if DNX CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; -#else - Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; -#endif } public void Dispose() @@ -30,11 +26,7 @@ public void Dispose() if (_threadId == Thread.CurrentThread.ManagedThreadId) { -#if DNX CultureInfo.CurrentCulture = _threadCulture; -#else - Thread.CurrentThread.CurrentCulture = _threadCulture; -#endif } } } diff --git a/src/Test/Utilities/Portable/Platform/Custom/MetadataSignatureHelper.cs b/src/Test/Utilities/Portable/Platform/Custom/MetadataSignatureHelper.cs index 9f4bec956af67..82fb91d327890 100644 --- a/src/Test/Utilities/Portable/Platform/Custom/MetadataSignatureHelper.cs +++ b/src/Test/Utilities/Portable/Platform/Custom/MetadataSignatureHelper.cs @@ -1,5 +1,4 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -#if !NETSTANDARD1_3 using System; using System.Collections.Generic; using System.Globalization; @@ -686,5 +685,3 @@ static public IEnumerable GetMemberSignatures(System.Reflection.Assembly } } } - -#endif diff --git a/src/Test/Utilities/Portable/Platform/Custom/OSVersion.cs b/src/Test/Utilities/Portable/Platform/Custom/OSVersion.cs index a01c4d2b60956..aa9f2892eb9bf 100644 --- a/src/Test/Utilities/Portable/Platform/Custom/OSVersion.cs +++ b/src/Test/Utilities/Portable/Platform/Custom/OSVersion.cs @@ -1,9 +1,5 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -using System; -using System.Collections.Generic; -using System.Text; - namespace Roslyn.Test.Utilities { public static class OSVersion @@ -12,10 +8,6 @@ public static class OSVersion /// True when the operating system is at least Windows version 8 /// public static bool IsWin8 => -#if NET46 || NETCOREAPP2_1 System.Environment.OSVersion.Version.Build >= 9200; -#else - throw new PlatformNotSupportedException(); -#endif } } diff --git a/src/Test/Utilities/Portable/Platform/Custom/SigningTestHelpers.cs b/src/Test/Utilities/Portable/Platform/Custom/SigningTestHelpers.cs index 47385e805345a..74b1a7017894e 100644 --- a/src/Test/Utilities/Portable/Platform/Custom/SigningTestHelpers.cs +++ b/src/Test/Utilities/Portable/Platform/Custom/SigningTestHelpers.cs @@ -1,6 +1,6 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -#if !NETSTANDARD1_3 +#if !NETSTANDARD2_0 using System; using System.Collections.Immutable; using System.IO; diff --git a/src/Test/Utilities/Portable/Platform/Desktop/AppDomainAssemblyCache.cs b/src/Test/Utilities/Portable/Platform/Desktop/AppDomainAssemblyCache.cs index 0327380279f43..0d9321abe2711 100644 --- a/src/Test/Utilities/Portable/Platform/Desktop/AppDomainAssemblyCache.cs +++ b/src/Test/Utilities/Portable/Platform/Desktop/AppDomainAssemblyCache.cs @@ -1,6 +1,6 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -#if NET46 +#if NET472 using System; using System.Collections.Concurrent; diff --git a/src/Test/Utilities/Portable/Platform/Desktop/AppDomainUtils.cs b/src/Test/Utilities/Portable/Platform/Desktop/AppDomainUtils.cs index 27d89ad49fad2..a53421d750a0e 100644 --- a/src/Test/Utilities/Portable/Platform/Desktop/AppDomainUtils.cs +++ b/src/Test/Utilities/Portable/Platform/Desktop/AppDomainUtils.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -#if NET46 +#if NET472 using System; using System.IO; using System.Reflection; diff --git a/src/Test/Utilities/Portable/Platform/Desktop/CLRHelpers.cs b/src/Test/Utilities/Portable/Platform/Desktop/CLRHelpers.cs index 29eabe54ee056..9821f6b0fe24e 100644 --- a/src/Test/Utilities/Portable/Platform/Desktop/CLRHelpers.cs +++ b/src/Test/Utilities/Portable/Platform/Desktop/CLRHelpers.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -#if NET46 +#if NET472 using System; using System.Collections.Generic; diff --git a/src/Test/Utilities/Portable/Platform/Desktop/DesktopRuntimeEnvironment.cs b/src/Test/Utilities/Portable/Platform/Desktop/DesktopRuntimeEnvironment.cs index e5b6381cbc093..85a3c951aad90 100644 --- a/src/Test/Utilities/Portable/Platform/Desktop/DesktopRuntimeEnvironment.cs +++ b/src/Test/Utilities/Portable/Platform/Desktop/DesktopRuntimeEnvironment.cs @@ -1,6 +1,6 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -#if NET46 +#if NET472 using System; using System.Collections.Generic; diff --git a/src/Test/Utilities/Portable/Platform/Desktop/DesktopRuntimeEnvironmentFactory.cs b/src/Test/Utilities/Portable/Platform/Desktop/DesktopRuntimeEnvironmentFactory.cs index 59d30bd77476e..46c2a6ff56bf8 100644 --- a/src/Test/Utilities/Portable/Platform/Desktop/DesktopRuntimeEnvironmentFactory.cs +++ b/src/Test/Utilities/Portable/Platform/Desktop/DesktopRuntimeEnvironmentFactory.cs @@ -1,4 +1,4 @@ -#if NET46 +#if NET472 using System.Collections.Generic; using Roslyn.Test.Utilities; diff --git a/src/Test/Utilities/Portable/Platform/Desktop/DesktopRuntimeUtil.cs b/src/Test/Utilities/Portable/Platform/Desktop/DesktopRuntimeUtil.cs index 33ee2dc9a719d..6ccf5568b0fe7 100644 --- a/src/Test/Utilities/Portable/Platform/Desktop/DesktopRuntimeUtil.cs +++ b/src/Test/Utilities/Portable/Platform/Desktop/DesktopRuntimeUtil.cs @@ -1,4 +1,4 @@ -#if NET46 +#if NET472 using System; using System.Collections.Generic; using System.Collections.Immutable; diff --git a/src/Test/Utilities/Portable/Platform/Desktop/ErrorDiagnostics.cs b/src/Test/Utilities/Portable/Platform/Desktop/ErrorDiagnostics.cs index 765c600de6173..309d57070083f 100644 --- a/src/Test/Utilities/Portable/Platform/Desktop/ErrorDiagnostics.cs +++ b/src/Test/Utilities/Portable/Platform/Desktop/ErrorDiagnostics.cs @@ -1,6 +1,6 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -#if NET46 +#if NET472 using System; using System.Collections.Generic; using System.Linq; diff --git a/src/Test/Utilities/Portable/Platform/Desktop/Exceptions.cs b/src/Test/Utilities/Portable/Platform/Desktop/Exceptions.cs index d2a20d17ab1dd..d712708f2f1f1 100644 --- a/src/Test/Utilities/Portable/Platform/Desktop/Exceptions.cs +++ b/src/Test/Utilities/Portable/Platform/Desktop/Exceptions.cs @@ -1,6 +1,6 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -#if NET46 +#if NET472 using System; using System.Collections.Generic; using System.Runtime.Serialization; diff --git a/src/Test/Utilities/Portable/Platform/Desktop/Extensions.cs b/src/Test/Utilities/Portable/Platform/Desktop/Extensions.cs index b46ecff573254..64d3d9f2b9272 100644 --- a/src/Test/Utilities/Portable/Platform/Desktop/Extensions.cs +++ b/src/Test/Utilities/Portable/Platform/Desktop/Extensions.cs @@ -1,6 +1,6 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -#if NET46 +#if NET472 using System; using System.Collections.Concurrent; using System.Collections.Generic; diff --git a/src/Test/Utilities/Portable/Platform/Desktop/RuntimeAssemblyManager.cs b/src/Test/Utilities/Portable/Platform/Desktop/RuntimeAssemblyManager.cs index 4397d6a28325d..d19edcb19e6f6 100644 --- a/src/Test/Utilities/Portable/Platform/Desktop/RuntimeAssemblyManager.cs +++ b/src/Test/Utilities/Portable/Platform/Desktop/RuntimeAssemblyManager.cs @@ -1,6 +1,6 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -#if NET46 +#if NET472 using System; using System.Collections.Generic; using System.Collections.Immutable; diff --git a/src/Test/Utilities/Portable/Platform/Desktop/RuntimeModuleData.cs b/src/Test/Utilities/Portable/Platform/Desktop/RuntimeModuleData.cs index ef7e73ecc9805..c6ddceb07d85d 100644 --- a/src/Test/Utilities/Portable/Platform/Desktop/RuntimeModuleData.cs +++ b/src/Test/Utilities/Portable/Platform/Desktop/RuntimeModuleData.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -#if NET46 +#if NET472 using System; using System.Collections.Concurrent; diff --git a/src/Test/Utilities/Portable/Platform/Desktop/TestHelpers.cs b/src/Test/Utilities/Portable/Platform/Desktop/TestHelpers.cs index c853cdcaa4a03..8d12ce8a45019 100644 --- a/src/Test/Utilities/Portable/Platform/Desktop/TestHelpers.cs +++ b/src/Test/Utilities/Portable/Platform/Desktop/TestHelpers.cs @@ -1,4 +1,4 @@ -#if NET46 +#if NET472 using System; using System.Collections.Generic; using System.Collections.Immutable; @@ -67,14 +67,14 @@ public class TestAnalyzer : DiagnosticAnalyzer dir.CopyFile(typeof(System.Reflection.Metadata.MetadataReader).Assembly.Location); var immutable = dir.CopyFile(typeof(ImmutableArray).Assembly.Location); var analyzer = dir.CopyFile(typeof(DiagnosticAnalyzer).Assembly.Location); - dir.CopyFile(Path.Combine(Path.GetDirectoryName(typeof(CSharpCompilation).Assembly.Location), "System.IO.FileSystem.dll")); var analyzerCompilation = CSharpCompilation.Create( assemblyName, new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree(analyzerSource) }, new MetadataReference[] { - TestReferences.NetStandard13.SystemRuntime, + TestReferences.NetStandard20.NetStandard, + TestReferences.NetStandard20.SystemRuntimeRef, MetadataReference.CreateFromFile(immutable.Path), MetadataReference.CreateFromFile(analyzer.Path) }, @@ -82,6 +82,196 @@ public class TestAnalyzer : DiagnosticAnalyzer return dir.CreateFile(assemblyName + ".dll").WriteAllBytes(analyzerCompilation.EmitToArray()); } + + public static ImmutableArray CreateCSharpAnalyzerNetStandard13(string analyzerAssemblyName) + { + var minSystemCollectionsImmutableSource = @" +[assembly: System.Reflection.AssemblyVersion(""1.2.3.0"")] + +namespace System.Collections.Immutable +{ + public struct ImmutableArray + { + } +} +"; + + var minCodeAnalysisSource = @" +using System; + +[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] + +namespace Microsoft.CodeAnalysis.Diagnostics +{ + [AttributeUsage(AttributeTargets.Class)] + public sealed class DiagnosticAnalyzerAttribute : Attribute + { + public DiagnosticAnalyzerAttribute(string firstLanguage, params string[] additionalLanguages) {} + } + + public abstract class DiagnosticAnalyzer + { + public abstract System.Collections.Immutable.ImmutableArray SupportedDiagnostics { get; } + public abstract void Initialize(AnalysisContext context); + } + + public abstract class AnalysisContext + { + } +} + +namespace Microsoft.CodeAnalysis +{ + public sealed class DiagnosticDescriptor + { + } +} +"; + var minSystemCollectionsImmutableImage = CSharpCompilation.Create( + "System.Collections.Immutable", + new[] { SyntaxFactory.ParseSyntaxTree(minSystemCollectionsImmutableSource) }, + new[] { MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Runtime) }, + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, cryptoPublicKey: TestResources.TestKeys.PublicKey_b03f5f7f11d50a3a)).EmitToArray(); + + var minSystemCollectionsImmutableRef = MetadataReference.CreateFromImage(minSystemCollectionsImmutableImage); + + var minCodeAnalysisImage = CSharpCompilation.Create( + "Microsoft.CodeAnalysis", + new[] { SyntaxFactory.ParseSyntaxTree(minCodeAnalysisSource) }, + new[] + { + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Runtime), + minSystemCollectionsImmutableRef + }, + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, cryptoPublicKey: TestResources.TestKeys.PublicKey_31bf3856ad364e35)).EmitToArray(); + + var minCodeAnalysisRef = MetadataReference.CreateFromImage(minCodeAnalysisImage); + + var analyzerSource = @" +using System; +using System.Collections.ObjectModel; +using System.Collections.Immutable; +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.IO.Compression; +using System.Net.Http; +using System.Net.Security; +using System.Net.Sockets; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Runtime.Serialization; +using System.Security.AccessControl; +using System.Security.Cryptography; +using System.Security.Principal; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Xml; +using System.Xml.Serialization; +using System.Xml.XPath; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.Win32.SafeHandles; + +[DiagnosticAnalyzer(""C#"")] +public class TestAnalyzer : DiagnosticAnalyzer +{ + public override ImmutableArray SupportedDiagnostics => throw new NotImplementedException(new[] + { + typeof(Win32Exception), // Microsoft.Win32.Primitives + typeof(AppContext), // System.AppContext + typeof(Console), // System.Console + typeof(ValueTuple), // System.ValueTuple + typeof(FileVersionInfo), // System.Diagnostics.FileVersionInfo + typeof(Process), // System.Diagnostics.Process + typeof(ChineseLunisolarCalendar), // System.Globalization.Calendars + typeof(ZipArchive), // System.IO.Compression + typeof(ZipFile), // System.IO.Compression.ZipFile + typeof(FileOptions), // System.IO.FileSystem + typeof(FileAttributes), // System.IO.FileSystem.Primitives + typeof(HttpClient), // System.Net.Http + typeof(AuthenticatedStream), // System.Net.Security + typeof(IOControlCode), // System.Net.Sockets + typeof(RuntimeInformation), // System.Runtime.InteropServices.RuntimeInformation + typeof(SerializationException), // System.Runtime.Serialization.Primitives + typeof(GenericIdentity), // System.Security.Claims + typeof(Aes), // System.Security.Cryptography.Algorithms + typeof(CspParameters), // System.Security.Cryptography.Csp + typeof(AsnEncodedData), // System.Security.Cryptography.Encoding + typeof(AsymmetricAlgorithm), // System.Security.Cryptography.Primitives + typeof(SafeX509ChainHandle), // System.Security.Cryptography.X509Certificates + typeof(IXmlLineInfo), // System.Xml.ReaderWriter + typeof(XmlNode), // System.Xml.XmlDocument + typeof(XPathDocument), // System.Xml.XPath + typeof(XDocumentExtensions), // System.Xml.XPath.XDocument + typeof(CodePagesEncodingProvider),// System.Text.Encoding.CodePages + typeof(ValueTask<>), // System.Threading.Tasks.Extensions + + // csc doesn't ship with facades for the following assemblies. + // Analyzers can't use them unless they carry the facade with them. + + // typeof(SafePipeHandle), // System.IO.Pipes + // typeof(StackFrame), // System.Diagnostics.StackTrace + // typeof(BindingFlags), // System.Reflection.TypeExtensions + // typeof(AccessControlActions), // System.Security.AccessControl + // typeof(SafeAccessTokenHandle), // System.Security.Principal.Windows + // typeof(Thread), // System.Threading.Thread + }.Length.ToString()); + + public override void Initialize(AnalysisContext context) + { + } +}"; + + var analyzerImage = CSharpCompilation.Create( + analyzerAssemblyName, + new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree(analyzerSource) }, + new MetadataReference[] + { + minCodeAnalysisRef, + minSystemCollectionsImmutableRef, + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.Microsoft_Win32_Primitives), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_AppContext), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Console), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard10.System_ValueTuple), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Diagnostics_FileVersionInfo), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Diagnostics_Process), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Diagnostics_StackTrace), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Globalization_Calendars), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_IO_Compression), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_IO_Compression_ZipFile), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_IO_FileSystem), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_IO_FileSystem_Primitives), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_IO_Pipes), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Net_Http), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Net_Security), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Net_Sockets), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Reflection_TypeExtensions), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Runtime), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard11.System_Runtime_InteropServices_RuntimeInformation), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Runtime_Serialization_Primitives), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Security_AccessControl), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Security_Claims), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Security_Cryptography_Algorithms), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Security_Cryptography_Csp), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Security_Cryptography_Encoding), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Security_Cryptography_Primitives), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Security_Cryptography_X509Certificates), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Security_Principal_Windows), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Threading_Thread), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard10.System_Threading_Tasks_Extensions), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Xml_ReaderWriter), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Xml_XmlDocument), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Xml_XPath), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Xml_XPath_XDocument), + MetadataReference.CreateFromImage(TestResources.NetFX.netstandard13.System_Text_Encoding_CodePages) + }, + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)).EmitToArray(); + + return analyzerImage; + } public static string GetMSBuildDirectory() { diff --git a/src/Test/Utilities/Portable/Roslyn.Test.Utilities.csproj b/src/Test/Utilities/Portable/Roslyn.Test.Utilities.csproj index ff0ea37b57238..9f2f8b13d9bc0 100644 --- a/src/Test/Utilities/Portable/Roslyn.Test.Utilities.csproj +++ b/src/Test/Utilities/Portable/Roslyn.Test.Utilities.csproj @@ -2,18 +2,12 @@ - AnyCPU - AnyCPU Library true - netstandard1.3;$(RoslynPortableTargetFrameworks);net46 - $(DefineConstants);DNX - true - - false + netstandard2.0;$(RoslynPortableTargetFrameworks);net472 false - + @@ -94,6 +88,7 @@ PublicResXFileCodeGenerator TestResource.Designer.cs Roslyn.Test.Utilities + TestResource.resources @@ -106,15 +101,6 @@ - - - - - - - - - \ No newline at end of file diff --git a/src/Test/Utilities/Portable/Traits/Traits.cs b/src/Test/Utilities/Portable/Traits/Traits.cs index c2ba5fca80aed..1e9959d184514 100644 --- a/src/Test/Utilities/Portable/Traits/Traits.cs +++ b/src/Test/Utilities/Portable/Traits/Traits.cs @@ -45,6 +45,7 @@ public static class Features public const string CodeActionsAddOverload = "CodeActions.AddOverloads"; public const string CodeActionsAddParameter = "CodeActions.AddParameter"; public const string CodeActionsAddParenthesesAroundConditionalExpressionInInterpolatedString = "CodeActions.AddParenthesesAroundConditionalExpressionInInterpolatedString"; + public const string CodeActionsAddShadows = "CodeActions.AddShadows"; public const string CodeActionsAliasAmbiguousType = "CodeActions.AliasAmbiguousType"; public const string CodeActionsChangeToAsync = "CodeActions.ChangeToAsync"; public const string CodeActionsChangeToIEnumerable = "CodeActions.ChangeToIEnumerable"; @@ -90,6 +91,7 @@ public static class Features public const string CodeActionsInsertBraces = "CodeActions.InsertBraces"; public const string CodeActionsInsertMissingCast = "CodeActions.InsertMissingCast"; public const string CodeActionsInsertMissingTokens = "CodeActions.InsertMissingTokens"; + public const string CodeActionsIntroduceUsingStatement = "CodeActions.IntroduceUsingStatement"; public const string CodeActionsIntroduceVariable = "CodeActions.IntroduceVariable"; public const string CodeActionsInvertConditional = "CodeActions.InvertConditional"; public const string CodeActionsInvertIf = "CodeActions.InvertIf"; @@ -105,6 +107,7 @@ public static class Features public const string CodeActionsOrderModifiers = "CodeActions.OrderModifiers"; public const string CodeActionsPopulateSwitch = "CodeActions.PopulateSwitch"; public const string CodeActionsQualifyMemberAccess = "CodeActions.QualifyMemberAccess"; + public const string CodeActionsReplaceDefaultLiteral = "CodeActions.ReplaceDefaultLiteral"; public const string CodeActionsReplaceDocCommentTextWithTag = "CodeActions.ReplaceDocCommentTextWithTag"; public const string CodeActionsReplaceMethodWithProperty = "CodeActions.ReplaceMethodWithProperty"; public const string CodeActionsReplacePropertyWithMethods = "CodeActions.ReplacePropertyWithMethods"; @@ -178,6 +181,7 @@ public static class Features public const string F1Help = nameof(F1Help); public const string FindReferences = nameof(FindReferences); public const string FixIncorrectTokens = nameof(FixIncorrectTokens); + public const string FixInterpolatedVerbatimString = nameof(FixInterpolatedVerbatimString); public const string Formatting = nameof(Formatting); public const string GoToDefinition = nameof(GoToDefinition); public const string GoToImplementation = nameof(GoToImplementation); diff --git a/src/Tools/AnalyzerRunner/AnalyzerRunner.csproj b/src/Tools/AnalyzerRunner/AnalyzerRunner.csproj index af0d84ead3388..e6b3e7f89bbab 100644 --- a/src/Tools/AnalyzerRunner/AnalyzerRunner.csproj +++ b/src/Tools/AnalyzerRunner/AnalyzerRunner.csproj @@ -6,7 +6,7 @@ AnyCPU AnyCPU Exe - net46 + net472 $(RoslynDesktopRuntimeIdentifier) true @@ -19,7 +19,6 @@ - diff --git a/src/Tools/BuildBoss/App.config b/src/Tools/BuildBoss/App.config index 2d2a12d81be15..ecdcf8a54da31 100644 --- a/src/Tools/BuildBoss/App.config +++ b/src/Tools/BuildBoss/App.config @@ -1,6 +1,6 @@ - + diff --git a/src/Tools/BuildBoss/BuildBoss.csproj b/src/Tools/BuildBoss/BuildBoss.csproj index b6f0715f9a581..a48c304533cba 100644 --- a/src/Tools/BuildBoss/BuildBoss.csproj +++ b/src/Tools/BuildBoss/BuildBoss.csproj @@ -5,7 +5,7 @@ AnyCPU AnyCPU Exe - net46 + net472 false $(RoslynDesktopRuntimeIdentifier) false @@ -21,7 +21,6 @@ - diff --git a/src/Tools/BuildBoss/CompilerNuGetCheckerUtil.cs b/src/Tools/BuildBoss/CompilerNuGetCheckerUtil.cs index 940202856aadf..e0db01592eb25 100644 --- a/src/Tools/BuildBoss/CompilerNuGetCheckerUtil.cs +++ b/src/Tools/BuildBoss/CompilerNuGetCheckerUtil.cs @@ -60,11 +60,11 @@ private bool CheckDesktop(TextWriter textWriter) { var (allGood, dllRelativeNames) = GetDllRelativeNames( textWriter, - @"Exes\Csc\net46", - @"Exes\Vbc\net46", - @"Exes\Csi\net46", - @"Exes\VBCSCompiler\net46", - @"Dlls\Microsoft.Build.Tasks.CodeAnalysis\net46"); + @"Exes\Csc\net472", + @"Exes\Vbc\net472", + @"Exes\Csi\net472", + @"Exes\VBCSCompiler\net472", + @"Dlls\Microsoft.Build.Tasks.CodeAnalysis\net472"); if (!allGood) { return false; diff --git a/src/Tools/BuildBoss/ProjectCheckerUtil.cs b/src/Tools/BuildBoss/ProjectCheckerUtil.cs index 143c261cacae7..0160919b1c769 100644 --- a/src/Tools/BuildBoss/ProjectCheckerUtil.cs +++ b/src/Tools/BuildBoss/ProjectCheckerUtil.cs @@ -439,21 +439,33 @@ private bool CheckTargetFrameworks(TextWriter textWriter, RoslynProjectData data var allGood = true; foreach (var targetFramework in _projectUtil.GetAllTargetFrameworks()) { - switch (targetFramework) + // TODO: Code Style projects need to be moved over to 4.7.2 and netstandard2.0 + // https://devdiv.visualstudio.com/DevDiv/_workitems/edit/712825 + if (ProjectFilePath.Contains("CodeStyle")) { - case "net20": - case "net46": - case "netstandard1.3": - case "netcoreapp1.1": - case "netcoreapp2.1": - case "$(RoslynPortableTargetFrameworks)": - break; - default: - textWriter.WriteLine($"TargetFramework {targetFramework} is not supported in this build"); - allGood = false; - break; + + switch (targetFramework) + { + case "net46": + case "netstandard1.3": + continue; + } + } + else + { + switch (targetFramework) + { + case "net20": + case "net472": + case "netcoreapp1.1": + case "netcoreapp2.1": + case "$(RoslynPortableTargetFrameworks)": + continue; + } } + textWriter.WriteLine($"TargetFramework {targetFramework} is not supported in this build"); + allGood = false; } return allGood; diff --git a/src/Tools/BuildUtil/Roslyn.MSBuild.Util.csproj b/src/Tools/BuildUtil/Roslyn.MSBuild.Util.csproj index 5a928f7fc591c..f5a3b223c97cc 100644 --- a/src/Tools/BuildUtil/Roslyn.MSBuild.Util.csproj +++ b/src/Tools/BuildUtil/Roslyn.MSBuild.Util.csproj @@ -6,7 +6,7 @@ AnyCPU Library Roslyn.MSBuild.Util - net46 + net472 Key.snk diff --git a/src/Tools/GenerateSdkPackages/base.nuspec b/src/Tools/GenerateSdkPackages/base.nuspec index 9845a2031defa..58b895ea8a4a6 100644 --- a/src/Tools/GenerateSdkPackages/base.nuspec +++ b/src/Tools/GenerateSdkPackages/base.nuspec @@ -17,6 +17,6 @@ VSSDK - + diff --git a/src/Tools/Github/GitMergeBot/GitMergeBot.csproj b/src/Tools/Github/GitMergeBot/GitMergeBot.csproj index 32e7412bf6910..c61829ee00a82 100644 --- a/src/Tools/Github/GitMergeBot/GitMergeBot.csproj +++ b/src/Tools/Github/GitMergeBot/GitMergeBot.csproj @@ -11,7 +11,7 @@ Properties GitMergeBot GitMergeBot - v4.6 + v4.7.2 true diff --git a/src/Tools/Github/GithubMergeTool/GithubMergeTool.csproj b/src/Tools/Github/GithubMergeTool/GithubMergeTool.csproj index 2e5c5cda79a09..4803ce83eb35e 100644 --- a/src/Tools/Github/GithubMergeTool/GithubMergeTool.csproj +++ b/src/Tools/Github/GithubMergeTool/GithubMergeTool.csproj @@ -1,7 +1,7 @@  - net46 + net472 diff --git a/src/Tools/RepoUtil/App.config b/src/Tools/RepoUtil/App.config index 2d2a12d81be15..ecdcf8a54da31 100644 --- a/src/Tools/RepoUtil/App.config +++ b/src/Tools/RepoUtil/App.config @@ -1,6 +1,6 @@ - + diff --git a/src/Tools/RepoUtil/RepoUtil.csproj b/src/Tools/RepoUtil/RepoUtil.csproj index fbe7c070be59b..da15d4671f4ea 100644 --- a/src/Tools/RepoUtil/RepoUtil.csproj +++ b/src/Tools/RepoUtil/RepoUtil.csproj @@ -5,7 +5,7 @@ AnyCPU AnyCPU Exe - net46 + net472 $(RoslynDesktopRuntimeIdentifier) false publish\ @@ -39,16 +39,4 @@ - - - False - Microsoft .NET Framework 4.6 %28x86 and x64%29 - true - - - False - .NET Framework 3.5 SP1 - false - - \ No newline at end of file diff --git a/src/Tools/RoslynPublish/App.config b/src/Tools/RoslynPublish/App.config index 3668b7aba3ff3..4407175194375 100644 --- a/src/Tools/RoslynPublish/App.config +++ b/src/Tools/RoslynPublish/App.config @@ -1,7 +1,7 @@ - + diff --git a/src/Tools/RoslynPublish/RoslynPublish.csproj b/src/Tools/RoslynPublish/RoslynPublish.csproj index 5c297eb7b200d..40134051e7866 100644 --- a/src/Tools/RoslynPublish/RoslynPublish.csproj +++ b/src/Tools/RoslynPublish/RoslynPublish.csproj @@ -6,7 +6,7 @@ AnyCPU Exe RoslynPublish - net462 + net472 $(RoslynDesktopRuntimeIdentifier) false true @@ -23,7 +23,6 @@ - diff --git a/src/Tools/Source/DebuggerVisualizers/Roslyn.DebuggerVisualizers.csproj b/src/Tools/Source/DebuggerVisualizers/Roslyn.DebuggerVisualizers.csproj index 8fbc33645123d..864e6d56faa20 100644 --- a/src/Tools/Source/DebuggerVisualizers/Roslyn.DebuggerVisualizers.csproj +++ b/src/Tools/Source/DebuggerVisualizers/Roslyn.DebuggerVisualizers.csproj @@ -9,7 +9,7 @@ Library Roslyn.DebuggerVisualizers Roslyn.DebuggerVisualizers - v4.6 + v4.7.2 true false diff --git a/src/Tools/Source/MetadataVisualizer/MetadataVisualizer.csproj b/src/Tools/Source/MetadataVisualizer/MetadataVisualizer.csproj index 696d2334a9699..3e9bce92e3dfd 100644 --- a/src/Tools/Source/MetadataVisualizer/MetadataVisualizer.csproj +++ b/src/Tools/Source/MetadataVisualizer/MetadataVisualizer.csproj @@ -10,7 +10,7 @@ MetadataVisualizer mdv true - v4.6 + v4.7.2 true false diff --git a/src/Tools/Source/RunTests/RunTests.csproj b/src/Tools/Source/RunTests/RunTests.csproj index 0f839cad02fe3..fcf64800907c4 100644 --- a/src/Tools/Source/RunTests/RunTests.csproj +++ b/src/Tools/Source/RunTests/RunTests.csproj @@ -5,7 +5,7 @@ AnyCPU AnyCPU Exe - net46 + net472 $(RoslynDesktopRuntimeIdentifier) true false @@ -23,6 +23,5 @@ - \ No newline at end of file diff --git a/src/VisualStudio/CSharp/Impl/Microsoft.VisualStudio.LanguageServices.CSharp.csproj b/src/VisualStudio/CSharp/Impl/Microsoft.VisualStudio.LanguageServices.CSharp.csproj index 4b3a5542e846b..f918ca9814514 100644 --- a/src/VisualStudio/CSharp/Impl/Microsoft.VisualStudio.LanguageServices.CSharp.csproj +++ b/src/VisualStudio/CSharp/Impl/Microsoft.VisualStudio.LanguageServices.CSharp.csproj @@ -4,7 +4,6 @@ - @@ -23,7 +22,7 @@ false true false - net46 + net472 true diff --git a/src/VisualStudio/CSharp/Repl/CSharpInteractive.rsp b/src/VisualStudio/CSharp/Repl/CSharpInteractive.rsp index 2ec6fc9b4069b..96e81d8fec43b 100644 --- a/src/VisualStudio/CSharp/Repl/CSharpInteractive.rsp +++ b/src/VisualStudio/CSharp/Repl/CSharpInteractive.rsp @@ -1,7 +1,6 @@ /r:System /r:System.Core /r:Microsoft.CSharp -/r:System.ValueTuple.dll /u:System /u:System.IO /u:System.Collections.Generic diff --git a/src/VisualStudio/CSharp/Repl/Microsoft.VisualStudio.CSharp.Repl.csproj b/src/VisualStudio/CSharp/Repl/Microsoft.VisualStudio.CSharp.Repl.csproj index 5d38d09088224..3ff340e842d19 100644 --- a/src/VisualStudio/CSharp/Repl/Microsoft.VisualStudio.CSharp.Repl.csproj +++ b/src/VisualStudio/CSharp/Repl/Microsoft.VisualStudio.CSharp.Repl.csproj @@ -9,7 +9,7 @@ false true false - net46 + net472 diff --git a/src/VisualStudio/CSharp/Test/Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.csproj b/src/VisualStudio/CSharp/Test/Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.csproj index 3e739cf3ab48e..e9d323932fe8d 100644 --- a/src/VisualStudio/CSharp/Test/Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.csproj +++ b/src/VisualStudio/CSharp/Test/Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.csproj @@ -6,7 +6,7 @@ AnyCPU Library Roslyn.VisualStudio.CSharp.UnitTests - net46 + net472 $(RoslynDesktopRuntimeIdentifier) UnitTest true @@ -29,7 +29,6 @@ - diff --git a/src/VisualStudio/Core/Def/Implementation/GenerateType/GenerateTypeDialogViewModel.cs b/src/VisualStudio/Core/Def/Implementation/GenerateType/GenerateTypeDialogViewModel.cs index ce3a6a02efe8d..0a7087132b230 100644 --- a/src/VisualStudio/Core/Def/Implementation/GenerateType/GenerateTypeDialogViewModel.cs +++ b/src/VisualStudio/Core/Def/Implementation/GenerateType/GenerateTypeDialogViewModel.cs @@ -288,27 +288,7 @@ internal bool TrySubmit() { this.FullFilePath = Path.GetFullPath(this.FullFilePath); } - catch (ArgumentNullException e) - { - SendFailureNotification(e.Message); - return false; - } - catch (ArgumentException e) - { - SendFailureNotification(e.Message); - return false; - } - catch (SecurityException e) - { - SendFailureNotification(e.Message); - return false; - } - catch (NotSupportedException e) - { - SendFailureNotification(e.Message); - return false; - } - catch (PathTooLongException e) + catch (Exception e) { SendFailureNotification(e.Message); return false; @@ -319,7 +299,11 @@ internal bool TrySubmit() if (lastIndexOfSeparatorInFullPath != -1) { var fileNameInFullPathInContainers = this.FullFilePath.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries); - this.FullFilePath = string.Join("\\", fileNameInFullPathInContainers.Select(str => str.TrimStart())); + + // Trim spaces of each component of the file name. + // Note that path normalization changed between 4.6.1 and 4.6.2 and GetFullPath no longer trims trailing spaces. + // See https://blogs.msdn.microsoft.com/jeremykuhne/2016/06/21/more-on-new-net-path-handling/ + this.FullFilePath = string.Join("\\", fileNameInFullPathInContainers.Select(str => str.Trim())); } string projectRootPath = null; diff --git a/src/VisualStudio/Core/Def/Implementation/ProjectSystem/Legacy/AbstractLegacyProject.cs b/src/VisualStudio/Core/Def/Implementation/ProjectSystem/Legacy/AbstractLegacyProject.cs index 4357a46d36ef2..4eaaf06ed7a19 100644 --- a/src/VisualStudio/Core/Def/Implementation/ProjectSystem/Legacy/AbstractLegacyProject.cs +++ b/src/VisualStudio/Core/Def/Implementation/ProjectSystem/Legacy/AbstractLegacyProject.cs @@ -74,6 +74,7 @@ public AbstractLegacyProject( FilePath = projectFilePath, Hierarchy = hierarchy, ProjectGuid = GetProjectIDGuid(hierarchy), + DefaultNamespace = GetDefaultNamespace(hierarchy, language) }); Hierarchy = hierarchy; @@ -302,5 +303,50 @@ private static void ComputeFolderNames(uint folderItemID, List names, IV } } } + + /// + /// Get the default namespace of the project ("" if not defined, which means global namespace), + /// or null if it is unknown or not applicable. + /// + /// + /// This only has meaning in C# and is explicitly set to null in VB. + /// > + private static string GetDefaultNamespace(IVsHierarchy hierarchy, string language) + { + // While both csproj and vbproj might define property in the project file, + // they are very different things. + // + // In C#, it's called default namespace (even though we got the value from rootnamespace property), + // and it doesn't affect the semantic of the code in anyway, just something used by VS. + // For example, when you create a new class, the namespace for the new class is based on it. + // Therefore, we can't get this info from compiler. + // + // However, in VB, it's actually called root namespace, and that info is part of the VB compilation + // (parsed from arguments), because VB compiler needs it to determine the root of all the namespace + // declared in the compilation. + // + // Unfortunately, although being different concepts, default namespace and root namespace are almost + // used interchangebly in VS. For example, (1) the value is define in "rootnamespace" property in project + // files and, (2) the property name we use to call into DTE project below to retrieve the value is + // called "DefaultNamespace". + + if (hierarchy != null && language == LanguageNames.CSharp) + { + if (hierarchy.TryGetProject(out var dteProject)) + { + try + { + return (string)dteProject.Properties.Item("DefaultNamespace").Value; + } + catch (ArgumentException) + { + // DefaultNamespace does not exist for this project. + return string.Empty; + } + } + } + + return null; + } } } diff --git a/src/VisualStudio/Core/Def/Implementation/ProjectSystem/MetadataReferences/VisualStudioMetadataReferenceManager.cs b/src/VisualStudio/Core/Def/Implementation/ProjectSystem/MetadataReferences/VisualStudioMetadataReferenceManager.cs index f8cd5b278eb98..ae99bdf61f939 100644 --- a/src/VisualStudio/Core/Def/Implementation/ProjectSystem/MetadataReferences/VisualStudioMetadataReferenceManager.cs +++ b/src/VisualStudio/Core/Def/Implementation/ProjectSystem/MetadataReferences/VisualStudioMetadataReferenceManager.cs @@ -101,9 +101,17 @@ private bool VsSmartScopeCandidate(string fullPath) return _runtimeDirectories.Any(d => fullPath.StartsWith(d, StringComparison.OrdinalIgnoreCase)); } + internal static IEnumerable GetReferencePaths() + { + // TODO: + // WORKAROUND: properly enumerate them + yield return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), @"Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5"); + yield return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), @"Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0"); + } + private static ImmutableArray GetRuntimeDirectories() { - return ReferencePathUtilities.GetReferencePaths().Concat( + return GetReferencePaths().Concat( new string[] { Environment.GetFolderPath(Environment.SpecialFolder.Windows), diff --git a/src/VisualStudio/Core/Def/Implementation/ProjectSystem/MiscellaneousFilesWorkspace.cs b/src/VisualStudio/Core/Def/Implementation/ProjectSystem/MiscellaneousFilesWorkspace.cs index 85c7d265d80fc..edf49ec14955e 100644 --- a/src/VisualStudio/Core/Def/Implementation/ProjectSystem/MiscellaneousFilesWorkspace.cs +++ b/src/VisualStudio/Core/Def/Implementation/ProjectSystem/MiscellaneousFilesWorkspace.cs @@ -105,7 +105,7 @@ private LanguageInformation TryGetLanguageInformation(string filename) private IEnumerable CreateMetadataReferences() { var manager = this.Services.GetService(); - var searchPaths = ReferencePathUtilities.GetReferencePaths(); + var searchPaths = VisualStudioMetadataReferenceManager.GetReferencePaths(); return from fileName in new[] { "mscorlib.dll", "System.dll", "System.Core.dll" } let fullPath = FileUtilities.ResolveRelativePath(fileName, basePath: null, baseDirectory: null, searchPaths: searchPaths, fileExists: File.Exists) diff --git a/src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioMefHostServices.cs b/src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioMefHostServices.cs new file mode 100644 index 0000000000000..6c78769b7335c --- /dev/null +++ b/src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioMefHostServices.cs @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Host; +using Microsoft.CodeAnalysis.Host.Mef; +using Microsoft.VisualStudio.Composition; +using Roslyn.Utilities; + +namespace Microsoft.VisualStudio.LanguageServices +{ + /// + /// Provides host services imported via VS MEF. + /// + internal sealed class VisualStudioMefHostServices : HostServices, IMefHostExportProvider + { + // the export provider for the MEF composition + private readonly ExportProvider _exportProvider; + + // accumulated cache for exports + private ImmutableDictionary _exportsMap + = ImmutableDictionary.Empty; + + private VisualStudioMefHostServices(ExportProvider exportProvider) + { + Contract.ThrowIfNull(exportProvider); + _exportProvider = exportProvider; + } + + public static VisualStudioMefHostServices Create(ExportProvider exportProvider) + => new VisualStudioMefHostServices(exportProvider); + + /// + /// Creates a new associated with the specified workspace. + /// + protected internal override HostWorkspaceServices CreateWorkspaceServices(Workspace workspace) + => new MefWorkspaceServices(this, workspace); + + /// + /// Gets all the MEF exports of the specified type with the specified metadata. + /// + public IEnumerable> GetExports() + { + var key = new ExportKey(typeof(TExtension).AssemblyQualifiedName, typeof(TMetadata).AssemblyQualifiedName); + if (!_exportsMap.TryGetValue(key, out var exports)) + { + exports = ImmutableInterlocked.GetOrAdd(ref _exportsMap, key, _ => + { + return _exportProvider.GetExports().ToImmutableArray(); + }); + } + + return (IEnumerable>)exports; + } + + /// + /// Gets all the MEF exports of the specified type. + /// + public IEnumerable> GetExports() + { + var key = new ExportKey(typeof(TExtension).AssemblyQualifiedName, ""); + if (!_exportsMap.TryGetValue(key, out var exports)) + { + exports = ImmutableInterlocked.GetOrAdd(ref _exportsMap, key, _ => + _exportProvider.GetExports().ToImmutableArray()); + } + + return (IEnumerable>)exports; + } + + private struct ExportKey : IEquatable + { + internal readonly string ExtensionTypeName; + internal readonly string MetadataTypeName; + private readonly int _hash; + + public ExportKey(string extensionTypeName, string metadataTypeName) + { + ExtensionTypeName = extensionTypeName; + MetadataTypeName = metadataTypeName; + _hash = Hash.Combine(metadataTypeName.GetHashCode(), extensionTypeName.GetHashCode()); + } + + public bool Equals(ExportKey other) + => string.Compare(ExtensionTypeName, other.ExtensionTypeName, StringComparison.OrdinalIgnoreCase) == 0 && + string.Compare(MetadataTypeName, other.MetadataTypeName, StringComparison.OrdinalIgnoreCase) == 0; + + public override bool Equals(object obj) + => obj is ExportKey key && Equals(key); + + public override int GetHashCode() + => Hash.Combine(MetadataTypeName.GetHashCode(), ExtensionTypeName.GetHashCode()); + } + } +} diff --git a/src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioProjectCreationInfo.cs b/src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioProjectCreationInfo.cs index 85a260b732686..54d27e6986fb0 100644 --- a/src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioProjectCreationInfo.cs +++ b/src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioProjectCreationInfo.cs @@ -13,5 +13,7 @@ internal sealed class VisualStudioProjectCreationInfo public IVsHierarchy Hierarchy { get; set; } public Guid ProjectGuid { get; set; } + + public string DefaultNamespace { get; set; } } } diff --git a/src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioProjectFactory.cs b/src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioProjectFactory.cs index 84716648363f3..45604aca2821d 100644 --- a/src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioProjectFactory.cs +++ b/src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioProjectFactory.cs @@ -51,7 +51,8 @@ public VisualStudioProject CreateAndAddToWorkspace(string projectUniqueName, str language: language, filePath: creationInfo.FilePath, compilationOptions: creationInfo.CompilationOptions, - parseOptions: creationInfo.ParseOptions); + parseOptions: creationInfo.ParseOptions) + .WithDefaultNamespace(creationInfo.DefaultNamespace); // HACK: update this since we're still on the UI thread. Note we can only update this if we don't have projects -- the workspace // only lets us really do this with OnSolutionAdded for now. diff --git a/src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioWorkspaceImpl.cs b/src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioWorkspaceImpl.cs index 45bc437660551..2a7080db823eb 100644 --- a/src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioWorkspaceImpl.cs +++ b/src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioWorkspaceImpl.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; -using System.ComponentModel.Composition.Hosting; using System.IO; using System.Linq; using System.Text; @@ -18,6 +17,7 @@ using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.ComponentModelHost; +using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Venus; @@ -75,7 +75,7 @@ internal abstract partial class VisualStudioWorkspaceImpl : VisualStudioWorkspac internal FileChangeWatcher FileChangeWatcher { get; } public VisualStudioWorkspaceImpl(ExportProvider exportProvider, IAsyncServiceProvider asyncServiceProvider) - : base(MefV1HostServices.Create(exportProvider)) + : base(VisualStudioMefHostServices.Create(exportProvider)) { _threadingContext = exportProvider.GetExportedValue(); _textBufferCloneService = exportProvider.GetExportedValue(); diff --git a/src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioSymbolNavigationService.cs b/src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioSymbolNavigationService.cs index fcbff4445b340..d0038e47ec15b 100644 --- a/src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioSymbolNavigationService.cs +++ b/src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioSymbolNavigationService.cs @@ -114,14 +114,20 @@ public bool TryNavigateToSymbol(ISymbol symbol, Project project, OptionSet optio } // Generate new source or retrieve existing source for the symbol in question - var allowDecompilation = project.Solution.Workspace.Options.GetOption(FeatureOnOffOptions.NavigateToDecompiledSources) && !symbol.IsFromSource(); - if (allowDecompilation && !project.Solution.Workspace.Options.GetOption(FeatureOnOffOptions.AcceptedDecompilerDisclaimer)) + var allowDecompilation = false; + + // Check whether decompilation is supported for the project. We currently only support this for C# projects. + if (project.LanguageServices.GetService() != null) { - var notificationService = project.Solution.Workspace.Services.GetService(); - allowDecompilation = notificationService.ConfirmMessageBox(ServicesVSResources.Decompiler_Legal_Notice_Message, ServicesVSResources.Decompiler_Legal_Notice_Title, NotificationSeverity.Warning); - if (allowDecompilation) + allowDecompilation = project.Solution.Workspace.Options.GetOption(FeatureOnOffOptions.NavigateToDecompiledSources) && !symbol.IsFromSource(); + if (allowDecompilation && !project.Solution.Workspace.Options.GetOption(FeatureOnOffOptions.AcceptedDecompilerDisclaimer)) { - project.Solution.Workspace.Options = project.Solution.Workspace.Options.WithChangedOption(FeatureOnOffOptions.AcceptedDecompilerDisclaimer, true); + var notificationService = project.Solution.Workspace.Services.GetService(); + allowDecompilation = notificationService.ConfirmMessageBox(ServicesVSResources.Decompiler_Legal_Notice_Message, ServicesVSResources.Decompiler_Legal_Notice_Title, NotificationSeverity.Warning); + if (allowDecompilation) + { + project.Solution.Workspace.Options = project.Solution.Workspace.Options.WithChangedOption(FeatureOnOffOptions.AcceptedDecompilerDisclaimer, true); + } } } diff --git a/src/VisualStudio/Core/Def/Microsoft.VisualStudio.LanguageServices.csproj b/src/VisualStudio/Core/Def/Microsoft.VisualStudio.LanguageServices.csproj index 3d3869eeb52f1..6656596109930 100644 --- a/src/VisualStudio/Core/Def/Microsoft.VisualStudio.LanguageServices.csproj +++ b/src/VisualStudio/Core/Def/Microsoft.VisualStudio.LanguageServices.csproj @@ -7,7 +7,7 @@ Library Microsoft.VisualStudio.LanguageServices true - net46 + net472 false true false @@ -22,6 +22,12 @@ + + InternalUtilities\GlobalAssemblyCache.cs + + + InternalUtilities\FileKey.cs + Shared\ConcurrentLruCache.cs @@ -67,7 +73,6 @@ - @@ -173,6 +178,7 @@ + diff --git a/src/VisualStudio/Core/Impl/Microsoft.VisualStudio.LanguageServices.Implementation.csproj b/src/VisualStudio/Core/Impl/Microsoft.VisualStudio.LanguageServices.Implementation.csproj index 4078e46defbd3..68158ce182c7f 100644 --- a/src/VisualStudio/Core/Impl/Microsoft.VisualStudio.LanguageServices.Implementation.csproj +++ b/src/VisualStudio/Core/Impl/Microsoft.VisualStudio.LanguageServices.Implementation.csproj @@ -3,7 +3,6 @@ - @@ -16,7 +15,7 @@ Library Microsoft.VisualStudio.LanguageServices.Implementation true - net46 + net472 diff --git a/src/VisualStudio/Core/Impl/Options/AbstractOptionPreviewViewModel.cs b/src/VisualStudio/Core/Impl/Options/AbstractOptionPreviewViewModel.cs index 364e922d0d81b..e73ff6765d7d6 100644 --- a/src/VisualStudio/Core/Impl/Options/AbstractOptionPreviewViewModel.cs +++ b/src/VisualStudio/Core/Impl/Options/AbstractOptionPreviewViewModel.cs @@ -18,6 +18,7 @@ using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.ComponentModelHost; +using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; @@ -127,9 +128,9 @@ private set public void UpdatePreview(string text) { - var service = MefV1HostServices.Create(_componentModel.DefaultExportProvider); + var service = VisualStudioMefHostServices.Create(_componentModel.GetService()); var workspace = new PreviewWorkspace(service); - var fileName = string.Format("project.{0}", Language == "C#" ? "csproj" : "vbproj"); + var fileName = "project." + (Language == "C#" ? "csproj" : "vbproj"); var project = workspace.CurrentSolution.AddProject(fileName, "assembly.dll", Language); // use the mscorlib, system, and system.core that are loaded in the current process. diff --git a/src/VisualStudio/Core/Impl/RoslynVisualStudioWorkspace.cs b/src/VisualStudio/Core/Impl/RoslynVisualStudioWorkspace.cs index 0b63ff288c167..886f3d1c830cb 100644 --- a/src/VisualStudio/Core/Impl/RoslynVisualStudioWorkspace.cs +++ b/src/VisualStudio/Core/Impl/RoslynVisualStudioWorkspace.cs @@ -35,7 +35,7 @@ private RoslynVisualStudioWorkspace( ExportProvider exportProvider, [ImportMany] IEnumerable> streamingPresenters, [ImportMany] IEnumerable documentOptionsProviderFactories) - : base(exportProvider.AsExportProvider(), AsyncServiceProvider.GlobalProvider) // TODO: switch to the cleaner MEF import + : base(exportProvider, AsyncServiceProvider.GlobalProvider) // TODO: switch to the cleaner MEF import { _streamingPresenters = streamingPresenters; diff --git a/src/VisualStudio/Core/SolutionExplorerShim/Microsoft.VisualStudio.LanguageServices.SolutionExplorer.csproj b/src/VisualStudio/Core/SolutionExplorerShim/Microsoft.VisualStudio.LanguageServices.SolutionExplorer.csproj index bec9cd61c9d67..bb1103996a1b7 100644 --- a/src/VisualStudio/Core/SolutionExplorerShim/Microsoft.VisualStudio.LanguageServices.SolutionExplorer.csproj +++ b/src/VisualStudio/Core/SolutionExplorerShim/Microsoft.VisualStudio.LanguageServices.SolutionExplorer.csproj @@ -6,11 +6,10 @@ AnyCPU Library Microsoft.VisualStudio.LanguageServices.SolutionExplorer - net46 + net472 - diff --git a/src/VisualStudio/Core/Test.Next/Mocks/TestHostServices.cs b/src/VisualStudio/Core/Test.Next/Mocks/TestHostServices.cs index 4ef13e9e93250..b7457c734a4da 100644 --- a/src/VisualStudio/Core/Test.Next/Mocks/TestHostServices.cs +++ b/src/VisualStudio/Core/Test.Next/Mocks/TestHostServices.cs @@ -2,9 +2,9 @@ using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Host; -using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Composition; +using Microsoft.VisualStudio.LanguageServices; namespace Roslyn.VisualStudio.Next.UnitTests.Mocks { @@ -12,8 +12,7 @@ public static class TestHostServices { public static HostServices CreateHostServices(ExportProvider exportProvider = null) { - exportProvider = exportProvider ?? CreateMinimalExportProvider(); - return MefV1HostServices.Create(exportProvider.AsExportProvider()); + return VisualStudioMefHostServices.Create(exportProvider ?? CreateMinimalExportProvider()); } public static ExportProvider CreateMinimalExportProvider() diff --git a/src/VisualStudio/Core/Test.Next/Roslyn.VisualStudio.Next.UnitTests.csproj b/src/VisualStudio/Core/Test.Next/Roslyn.VisualStudio.Next.UnitTests.csproj index 1fb29103c1faa..28ec372d80ea9 100644 --- a/src/VisualStudio/Core/Test.Next/Roslyn.VisualStudio.Next.UnitTests.csproj +++ b/src/VisualStudio/Core/Test.Next/Roslyn.VisualStudio.Next.UnitTests.csproj @@ -6,7 +6,7 @@ AnyCPU Library Roslyn.VisualStudio.Next.UnitTests - net46 + net472 $(RoslynDesktopRuntimeIdentifier) true UnitTest @@ -22,7 +22,6 @@ - diff --git a/src/VisualStudio/Core/Test.Next/Services/SolutionServiceTests.cs b/src/VisualStudio/Core/Test.Next/Services/SolutionServiceTests.cs index 11776412ffcf4..1e382615e8c01 100644 --- a/src/VisualStudio/Core/Test.Next/Services/SolutionServiceTests.cs +++ b/src/VisualStudio/Core/Test.Next/Services/SolutionServiceTests.cs @@ -177,6 +177,14 @@ public async Task TestUpdateOutputRefFilePath() await VerifySolutionUpdate(code, s => s.WithProjectOutputRefFilePath(s.ProjectIds[0], "test.dll")); } + [Fact, Trait(Traits.Feature, Traits.Features.RemoteHost)] + public async Task TestUpdateDefaultNamespace() + { + var code = @"class Test { void Method() { } }"; + + await VerifySolutionUpdate(code, s => s.WithProjectDefaultNamespace(s.ProjectIds[0], "TestClassLibrary")); + } + [Fact, Trait(Traits.Feature, Traits.Features.RemoteHost)] public async Task TestUpdateDocumentInfo() { diff --git a/src/VisualStudio/Core/Test/Microsoft.VisualStudio.LanguageServices.UnitTests.vbproj b/src/VisualStudio/Core/Test/Microsoft.VisualStudio.LanguageServices.UnitTests.vbproj index f1032faf91e94..fb18b814f0d6f 100644 --- a/src/VisualStudio/Core/Test/Microsoft.VisualStudio.LanguageServices.UnitTests.vbproj +++ b/src/VisualStudio/Core/Test/Microsoft.VisualStudio.LanguageServices.UnitTests.vbproj @@ -5,7 +5,7 @@ AnyCPU AnyCPU Library - net46 + net472 $(RoslynDesktopRuntimeIdentifier) UnitTest true @@ -19,7 +19,6 @@ - diff --git a/src/VisualStudio/IntegrationTest/IntegrationService/Microsoft.VisualStudio.IntegrationTest.IntegrationService.csproj b/src/VisualStudio/IntegrationTest/IntegrationService/Microsoft.VisualStudio.IntegrationTest.IntegrationService.csproj index 31bbb03b19421..ded7ea1dea475 100644 --- a/src/VisualStudio/IntegrationTest/IntegrationService/Microsoft.VisualStudio.IntegrationTest.IntegrationService.csproj +++ b/src/VisualStudio/IntegrationTest/IntegrationService/Microsoft.VisualStudio.IntegrationTest.IntegrationService.csproj @@ -6,7 +6,7 @@ AnyCPU Library Microsoft.VisualStudio.IntegrationTest.IntegrationService - net46 + net472 false diff --git a/src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpAutomaticBraceCompletion.cs b/src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpAutomaticBraceCompletion.cs index f34f93d5e6554..634c1699ff7d8 100644 --- a/src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpAutomaticBraceCompletion.cs +++ b/src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpAutomaticBraceCompletion.cs @@ -200,6 +200,38 @@ class C { VisualStudio.Editor.Verify.CurrentLineText("string str = \"Hi Roslyn!\"$$", assertCaretPosition: true); } + [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] + public void DoubleQuote_FixedInterpolatedVerbatimString() + { + SetUpEditor(@" +class C +{ + void M() + { + $$ + } +}"); + + VisualStudio.Editor.SendKeys("var v = @$\""); + VisualStudio.Editor.Verify.CurrentLineText("var v = $@\"$$\"", assertCaretPosition: true); + + // Backspace removes quotes + VisualStudio.Editor.SendKeys(VirtualKey.Backspace); + VisualStudio.Editor.Verify.CurrentLineText("var v = $@$$", assertCaretPosition: true); + + // Undo puts them back + VisualStudio.Editor.Undo(); + VisualStudio.Editor.Verify.CurrentLineText("var v = $@\"$$\"", assertCaretPosition: true); + + // First, the FixInterpolatedVerbatimString action is undone (@$ reordering) + VisualStudio.Editor.Undo(); + VisualStudio.Editor.Verify.CurrentLineText("var v = @$\"$$\"", assertCaretPosition: true); + + // Then the automatic quote completion is undone + VisualStudio.Editor.Undo(); + VisualStudio.Editor.Verify.CurrentLineText("var v = @$\"$$", assertCaretPosition: true); + } + [WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)] public void AngleBracket_PossibleGenerics_InsertionAndCompletion() { diff --git a/src/VisualStudio/IntegrationTest/IntegrationTests/Microsoft.VisualStudio.LanguageServices.IntegrationTests.csproj b/src/VisualStudio/IntegrationTest/IntegrationTests/Microsoft.VisualStudio.LanguageServices.IntegrationTests.csproj index 232f927c18635..353eb6f4c415f 100644 --- a/src/VisualStudio/IntegrationTest/IntegrationTests/Microsoft.VisualStudio.LanguageServices.IntegrationTests.csproj +++ b/src/VisualStudio/IntegrationTest/IntegrationTests/Microsoft.VisualStudio.LanguageServices.IntegrationTests.csproj @@ -6,7 +6,7 @@ AnyCPU Library Roslyn.VisualStudio.IntegrationTests - net46 + net472 UnitTest @@ -37,7 +37,6 @@ - diff --git a/src/VisualStudio/IntegrationTest/TestSetup/Microsoft.VisualStudio.IntegrationTest.Setup.csproj b/src/VisualStudio/IntegrationTest/TestSetup/Microsoft.VisualStudio.IntegrationTest.Setup.csproj index e77fe2437c894..3674f449bcb50 100644 --- a/src/VisualStudio/IntegrationTest/TestSetup/Microsoft.VisualStudio.IntegrationTest.Setup.csproj +++ b/src/VisualStudio/IntegrationTest/TestSetup/Microsoft.VisualStudio.IntegrationTest.Setup.csproj @@ -6,7 +6,7 @@ AnyCPU Library Microsoft.VisualStudio.IntegrationTest.Setup - net46 + net472 Vsix false diff --git a/src/VisualStudio/IntegrationTest/TestUtilities/Microsoft.VisualStudio.IntegrationTest.Utilities.csproj b/src/VisualStudio/IntegrationTest/TestUtilities/Microsoft.VisualStudio.IntegrationTest.Utilities.csproj index fac11140f12bf..15ee83fbede90 100644 --- a/src/VisualStudio/IntegrationTest/TestUtilities/Microsoft.VisualStudio.IntegrationTest.Utilities.csproj +++ b/src/VisualStudio/IntegrationTest/TestUtilities/Microsoft.VisualStudio.IntegrationTest.Utilities.csproj @@ -6,7 +6,7 @@ AnyCPU Library Microsoft.VisualStudio.IntegrationTest.Utilities - net46 + net472 false diff --git a/src/VisualStudio/InteractiveServices/Microsoft.VisualStudio.InteractiveServices.csproj b/src/VisualStudio/InteractiveServices/Microsoft.VisualStudio.InteractiveServices.csproj index b2e884e43ccc8..5885cfb1faea2 100644 --- a/src/VisualStudio/InteractiveServices/Microsoft.VisualStudio.InteractiveServices.csproj +++ b/src/VisualStudio/InteractiveServices/Microsoft.VisualStudio.InteractiveServices.csproj @@ -7,14 +7,13 @@ Library Roslyn.VisualStudio.Services true - net46 + net472 - @@ -59,7 +58,6 @@ - diff --git a/src/VisualStudio/Razor/Microsoft.VisualStudio.LanguageServices.Razor.RemoteClient.csproj b/src/VisualStudio/Razor/Microsoft.VisualStudio.LanguageServices.Razor.RemoteClient.csproj index e859dd441d811..2a387c06a8a81 100644 --- a/src/VisualStudio/Razor/Microsoft.VisualStudio.LanguageServices.Razor.RemoteClient.csproj +++ b/src/VisualStudio/Razor/Microsoft.VisualStudio.LanguageServices.Razor.RemoteClient.csproj @@ -6,7 +6,7 @@ AnyCPU Library Microsoft.VisualStudio.LanguageServices.Razor.RemoteClient - net46 + net472 true diff --git a/src/VisualStudio/RemoteHostClientMock/Roslyn.VisualStudio.RemoteHostClientMock.csproj b/src/VisualStudio/RemoteHostClientMock/Roslyn.VisualStudio.RemoteHostClientMock.csproj index da67ce75f58f8..b8c06c85e5743 100644 --- a/src/VisualStudio/RemoteHostClientMock/Roslyn.VisualStudio.RemoteHostClientMock.csproj +++ b/src/VisualStudio/RemoteHostClientMock/Roslyn.VisualStudio.RemoteHostClientMock.csproj @@ -6,7 +6,7 @@ AnyCPU Library Roslyn.VisualStudio.RemoteHostClientMock - net46 + net472 Vsix false @@ -23,9 +23,6 @@ BuiltProjectOutputGroup%3b false - - BuiltProjectOutputGroup%3b - BuiltProjectOutputGroup%3b diff --git a/src/VisualStudio/RemoteHostClientMock/source.extension.vsixmanifest b/src/VisualStudio/RemoteHostClientMock/source.extension.vsixmanifest index 61743fc29bc86..102b04b60540e 100644 --- a/src/VisualStudio/RemoteHostClientMock/source.extension.vsixmanifest +++ b/src/VisualStudio/RemoteHostClientMock/source.extension.vsixmanifest @@ -12,7 +12,7 @@ - + diff --git a/src/VisualStudio/Setup.Dependencies/AssemblyRedirects.cs b/src/VisualStudio/Setup.Dependencies/AssemblyRedirects.cs index 71e4bf87bf4de..4363f3f954e8c 100644 --- a/src/VisualStudio/Setup.Dependencies/AssemblyRedirects.cs +++ b/src/VisualStudio/Setup.Dependencies/AssemblyRedirects.cs @@ -1,37 +1,12 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +using Microsoft.VisualStudio.Shell; using Roslyn.VisualStudio.Setup; [assembly: ProvideDependencyBindingRedirection("Microsoft.DiaSymReader.dll")] [assembly: ProvideDependencyBindingRedirection("Microsoft.DiaSymReader.PortablePdb.dll")] [assembly: ProvideDependencyBindingRedirection("System.Collections.Immutable.dll")] -//[assembly: ProvideDependencyBindingRedirection("System.Collections.dll")] // no implementation assembly for net46 -//[assembly: ProvideDependencyBindingRedirection("System.Collections.Concurrent.dll")] // no implementation assembly for net46 -//[assembly: ProvideDependencyBindingRedirection("System.Diagnostics.Contracts.dll")] // no implementation assembly for net46 -//[assembly: ProvideDependencyBindingRedirection("System.Diagnostics.Tools.dll")] // no implementation assembly for net46 -[assembly: ProvideDependencyBindingRedirection("System.Diagnostics.FileVersionInfo.dll")] -//[assembly: ProvideDependencyBindingRedirection("System.IO.dll")] // no implementation assembly for net46 -[assembly: ProvideDependencyBindingRedirection("System.IO.Compression.dll")] -[assembly: ProvideDependencyBindingRedirection("System.IO.FileSystem.dll")] -[assembly: ProvideDependencyBindingRedirection("System.IO.FileSystem.Primitives.dll")] -//[assembly: ProvideDependencyBindingRedirection("System.Linq.Expressions.dll")] // no implementation assembly for net46 -//[assembly: ProvideDependencyBindingRedirection("System.Linq.Parallel.dll")] // no implementation assembly for net46 -//[assembly: ProvideDependencyBindingRedirection("System.ObjectModel.dll")] // no implementation assembly for net46 [assembly: ProvideDependencyBindingRedirection("System.Reflection.Metadata.dll")] -[assembly: ProvideDependencyBindingRedirection("System.Runtime.InteropServices.RuntimeInformation.dll")] -//[assembly: ProvideDependencyBindingRedirection("System.Runtime.Numerics.dll")] // no implementation assembly for net46 -[assembly: ProvideDependencyBindingRedirection("System.Security.Cryptography.Algorithms.dll")] -[assembly: ProvideDependencyBindingRedirection("System.Security.Cryptography.Encoding.dll")] -[assembly: ProvideDependencyBindingRedirection("System.Security.Cryptography.Primitives.dll")] -[assembly: ProvideDependencyBindingRedirection("System.Security.Cryptography.X509Certificates.dll")] -//[assembly: ProvideDependencyBindingRedirection("System.Text.Encoding.dll")] // no implementation assembly for net46 -//[assembly: ProvideDependencyBindingRedirection("System.Text.Encoding.Extensions.dll")] // no implementation assembly for net46 -//[assembly: ProvideDependencyBindingRedirection("System.Text.RegularExpressions.dll")] // no implementation assembly for net46 -[assembly: ProvideDependencyBindingRedirection("System.Threading.Tasks.Extensions.dll")] -//[assembly: ProvideDependencyBindingRedirection("System.Threading.Tasks.Parallel.dll")] // no implementation assembly for net46 +[assembly: ProvideDependencyBindingRedirection("System.Runtime.CompilerServices.Unsafe.dll")] [assembly: ProvideDependencyBindingRedirection("System.Text.Encoding.CodePages.dll")] -[assembly: ProvideDependencyBindingRedirection("System.ValueTuple.dll")] -[assembly: ProvideDependencyBindingRedirection("System.Xml.ReaderWriter.dll")] -//[assembly: ProvideDependencyBindingRedirection("System.Xml.XDocument.dll")] // no implementation assembly for net46 -//[assembly: ProvideDependencyBindingRedirection("System.Xml.XmlDocument.dll")] // no implementation assembly for net46 -[assembly: ProvideDependencyBindingRedirection("System.Xml.XPath.XDocument.dll")] +[assembly: ProvideDependencyBindingRedirection("System.Threading.Tasks.Extensions.dll")] diff --git a/src/VisualStudio/Setup.Dependencies/Roslyn.VisualStudio.Setup.Dependencies.ValueTuple.pkgdef b/src/VisualStudio/Setup.Dependencies/Roslyn.VisualStudio.Setup.Dependencies.ValueTuple.pkgdef new file mode 100644 index 0000000000000..04b745ed4be38 Binary files /dev/null and b/src/VisualStudio/Setup.Dependencies/Roslyn.VisualStudio.Setup.Dependencies.ValueTuple.pkgdef differ diff --git a/src/VisualStudio/Setup.Dependencies/Roslyn.VisualStudio.Setup.Dependencies.csproj b/src/VisualStudio/Setup.Dependencies/Roslyn.VisualStudio.Setup.Dependencies.csproj index 4eec5befecaa4..9c1e04547ecc2 100644 --- a/src/VisualStudio/Setup.Dependencies/Roslyn.VisualStudio.Setup.Dependencies.csproj +++ b/src/VisualStudio/Setup.Dependencies/Roslyn.VisualStudio.Setup.Dependencies.csproj @@ -6,7 +6,7 @@ AnyCPU Library Roslyn.VisualStudio.Setup.Dependencies - net46 + net472 $(RoslynDesktopRuntimeIdentifier) Vsix true @@ -29,40 +29,11 @@ --> - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - @@ -75,51 +46,34 @@ - + - - - - - - - - - - - - - - - - - - - - - - - - - - - + - - - - - - - - - + + + - + + + \ No newline at end of file diff --git a/src/VisualStudio/Setup.Dependencies/source.extension.vsixmanifest b/src/VisualStudio/Setup.Dependencies/source.extension.vsixmanifest index 72926e50b8de5..519d21dbadd97 100644 --- a/src/VisualStudio/Setup.Dependencies/source.extension.vsixmanifest +++ b/src/VisualStudio/Setup.Dependencies/source.extension.vsixmanifest @@ -13,7 +13,7 @@ - + diff --git a/src/VisualStudio/Setup/AssemblyRedirects.cs b/src/VisualStudio/Setup/AssemblyRedirects.cs index 02f7fc3c634f5..5352ef6397868 100644 --- a/src/VisualStudio/Setup/AssemblyRedirects.cs +++ b/src/VisualStudio/Setup/AssemblyRedirects.cs @@ -41,7 +41,6 @@ [assembly: ProvideCodeBase(CodeBase = @"$PackageFolder$\System.Composition.Convention.dll")] [assembly: ProvideCodeBase(CodeBase = @"$PackageFolder$\System.Composition.Hosting.dll")] [assembly: ProvideCodeBase(CodeBase = @"$PackageFolder$\System.Composition.TypedParts.dll")] -[assembly: ProvideCodeBase(CodeBase = @"$PackageFolder$\System.Threading.Tasks.Extensions.dll")] [assembly: ProvideCodeBase(CodeBase = @"$PackageFolder$\Humanizer.dll")] [assembly: ProvideCodeBase(CodeBase = @"$PackageFolder$\ICSharpCode.Decompiler.dll")] diff --git a/src/VisualStudio/Setup/Roslyn.VisualStudio.Setup.csproj b/src/VisualStudio/Setup/Roslyn.VisualStudio.Setup.csproj index 0f92cddb6fdfb..61c4d2884c296 100644 --- a/src/VisualStudio/Setup/Roslyn.VisualStudio.Setup.csproj +++ b/src/VisualStudio/Setup/Roslyn.VisualStudio.Setup.csproj @@ -6,7 +6,7 @@ AnyCPU Library Roslyn.VisualStudio.Setup - net46 + net472 Vsix @@ -90,7 +90,7 @@ Workspaces.MSBuild BuiltProjectOutputGroup true - TargetFramework=net46 + TargetFramework=net472 CSharpWorkspace @@ -167,7 +167,6 @@ - diff --git a/src/VisualStudio/Setup/source.extension.vsixmanifest b/src/VisualStudio/Setup/source.extension.vsixmanifest index 21d459ca38c31..fa14449c855ba 100644 --- a/src/VisualStudio/Setup/source.extension.vsixmanifest +++ b/src/VisualStudio/Setup/source.extension.vsixmanifest @@ -13,11 +13,10 @@ - + - diff --git a/src/VisualStudio/TestUtilities2/Microsoft.VisualStudio.LanguageServices.Test.Utilities2.vbproj b/src/VisualStudio/TestUtilities2/Microsoft.VisualStudio.LanguageServices.Test.Utilities2.vbproj index ccb4a8e672991..e6ccfae915735 100644 --- a/src/VisualStudio/TestUtilities2/Microsoft.VisualStudio.LanguageServices.Test.Utilities2.vbproj +++ b/src/VisualStudio/TestUtilities2/Microsoft.VisualStudio.LanguageServices.Test.Utilities2.vbproj @@ -5,7 +5,7 @@ AnyCPU AnyCPU Library - net46 + net472 $(RoslynDesktopRuntimeIdentifier) true @@ -18,7 +18,6 @@ - diff --git a/src/VisualStudio/TestUtilities2/ProjectSystemShim/Framework/TestEnvironment.vb b/src/VisualStudio/TestUtilities2/ProjectSystemShim/Framework/TestEnvironment.vb index ceea191e6e1e5..47a9d512c58ae 100644 --- a/src/VisualStudio/TestUtilities2/ProjectSystemShim/Framework/TestEnvironment.vb +++ b/src/VisualStudio/TestUtilities2/ProjectSystemShim/Framework/TestEnvironment.vb @@ -79,7 +79,7 @@ Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Fr Public Sub New(exportProvider As Composition.ExportProvider) - MyBase.New(exportProvider.AsExportProvider(), exportProvider.GetExportedValue(Of MockServiceProvider)) + MyBase.New(exportProvider, exportProvider.GetExportedValue(Of MockServiceProvider)) End Sub Public Overrides Sub DisplayReferencedSymbols(solution As Microsoft.CodeAnalysis.Solution, referencedSymbols As IEnumerable(Of ReferencedSymbol)) diff --git a/src/VisualStudio/VisualBasic/Impl/Microsoft.VisualStudio.LanguageServices.VisualBasic.vbproj b/src/VisualStudio/VisualBasic/Impl/Microsoft.VisualStudio.LanguageServices.VisualBasic.vbproj index 6ea174bcf600b..dc12499457f05 100644 --- a/src/VisualStudio/VisualBasic/Impl/Microsoft.VisualStudio.LanguageServices.VisualBasic.vbproj +++ b/src/VisualStudio/VisualBasic/Impl/Microsoft.VisualStudio.LanguageServices.VisualBasic.vbproj @@ -8,13 +8,12 @@ false true false - net46 + net472 - diff --git a/src/VisualStudio/VisualBasic/Repl/Microsoft.VisualStudio.VisualBasic.Repl.vbproj b/src/VisualStudio/VisualBasic/Repl/Microsoft.VisualStudio.VisualBasic.Repl.vbproj index 764805f5ff5d7..ea931dd0dc7d6 100644 --- a/src/VisualStudio/VisualBasic/Repl/Microsoft.VisualStudio.VisualBasic.Repl.vbproj +++ b/src/VisualStudio/VisualBasic/Repl/Microsoft.VisualStudio.VisualBasic.Repl.vbproj @@ -8,7 +8,7 @@ false true false - net46 + net472 diff --git a/src/VisualStudio/VisualStudioDiagnosticsToolWindow/Roslyn.VisualStudio.DiagnosticsWindow.csproj b/src/VisualStudio/VisualStudioDiagnosticsToolWindow/Roslyn.VisualStudio.DiagnosticsWindow.csproj index 8df04b3c232c1..080b4887c49a9 100644 --- a/src/VisualStudio/VisualStudioDiagnosticsToolWindow/Roslyn.VisualStudio.DiagnosticsWindow.csproj +++ b/src/VisualStudio/VisualStudioDiagnosticsToolWindow/Roslyn.VisualStudio.DiagnosticsWindow.csproj @@ -4,7 +4,7 @@ AnyCPU AnyCPU - net46 + net472 Vsix Library Roslyn.VisualStudio.DiagnosticsWindow @@ -27,9 +27,6 @@ false - - false - false diff --git a/src/VisualStudio/VisualStudioInteractiveComponents/Roslyn.VisualStudio.InteractiveComponents.csproj b/src/VisualStudio/VisualStudioInteractiveComponents/Roslyn.VisualStudio.InteractiveComponents.csproj index 87089b3b31363..2b5b77f21660d 100644 --- a/src/VisualStudio/VisualStudioInteractiveComponents/Roslyn.VisualStudio.InteractiveComponents.csproj +++ b/src/VisualStudio/VisualStudioInteractiveComponents/Roslyn.VisualStudio.InteractiveComponents.csproj @@ -7,7 +7,7 @@ Library Roslyn.VisualStudio.InteractiveComponents Vsix - net46 + net472 true @@ -88,12 +88,6 @@ DebugSymbolsProjectOutputGroup true - - Workspaces.Desktop - BuiltProjectOutputGroup - DebugSymbolsProjectOutputGroup - true - Workspaces BuiltProjectOutputGroup @@ -109,7 +103,6 @@ - @@ -118,45 +111,7 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/VisualStudio/VisualStudioInteractiveComponents/source.extension.vsixmanifest b/src/VisualStudio/VisualStudioInteractiveComponents/source.extension.vsixmanifest index 005827653a796..3f4e4e09346a6 100644 --- a/src/VisualStudio/VisualStudioInteractiveComponents/source.extension.vsixmanifest +++ b/src/VisualStudio/VisualStudioInteractiveComponents/source.extension.vsixmanifest @@ -13,7 +13,7 @@ - + diff --git a/src/VisualStudio/Xaml/Impl/Microsoft.VisualStudio.LanguageServices.Xaml.csproj b/src/VisualStudio/Xaml/Impl/Microsoft.VisualStudio.LanguageServices.Xaml.csproj index 6e5bac4872b60..d7847b9d4e245 100644 --- a/src/VisualStudio/Xaml/Impl/Microsoft.VisualStudio.LanguageServices.Xaml.csproj +++ b/src/VisualStudio/Xaml/Impl/Microsoft.VisualStudio.LanguageServices.Xaml.csproj @@ -7,7 +7,7 @@ Library Microsoft.VisualStudio.LanguageServices.Xaml false - net46 + net472 None true diff --git a/src/Workspaces/CSharp/Portable/Microsoft.CodeAnalysis.CSharp.Workspaces.csproj b/src/Workspaces/CSharp/Portable/Microsoft.CodeAnalysis.CSharp.Workspaces.csproj index 3b2bc62a69a8e..3eb9bada1c1ea 100644 --- a/src/Workspaces/CSharp/Portable/Microsoft.CodeAnalysis.CSharp.Workspaces.csproj +++ b/src/Workspaces/CSharp/Portable/Microsoft.CodeAnalysis.CSharp.Workspaces.csproj @@ -7,7 +7,7 @@ Library Microsoft.CodeAnalysis.CSharp true - netstandard1.3 + netstandard2.0 true diff --git a/src/Workspaces/CSharpTest/Microsoft.CodeAnalysis.CSharp.Workspaces.UnitTests.csproj b/src/Workspaces/CSharpTest/Microsoft.CodeAnalysis.CSharp.Workspaces.UnitTests.csproj index de280d10292c4..f013b33f14ca2 100644 --- a/src/Workspaces/CSharpTest/Microsoft.CodeAnalysis.CSharp.Workspaces.UnitTests.csproj +++ b/src/Workspaces/CSharpTest/Microsoft.CodeAnalysis.CSharp.Workspaces.UnitTests.csproj @@ -6,7 +6,7 @@ AnyCPU Library Microsoft.CodeAnalysis.CSharp.UnitTests - net46 + net472 $(RoslynDesktopRuntimeIdentifier) UnitTest @@ -23,7 +23,6 @@ - diff --git a/src/Workspaces/Core/Desktop/Microsoft.CodeAnalysis.Workspaces.Common.nuspec b/src/Workspaces/Core/Desktop/Microsoft.CodeAnalysis.Workspaces.Common.nuspec deleted file mode 100644 index 7900281cb4718..0000000000000 --- a/src/Workspaces/Core/Desktop/Microsoft.CodeAnalysis.Workspaces.Common.nuspec +++ /dev/null @@ -1,52 +0,0 @@ - - - - $PackageId$ - $PackageDescription$ - $Version$ - $Authors$ - $RequireLicenseAcceptance$ - $PackageLicenseUrl$ - $PackageProjectUrl$ - $Copyright$ - $DevelopmentDependency$ - $PackageTags$ - $Serviceable$ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Workspaces/Core/Desktop/Microsoft.CodeAnalysis.Workspaces.Desktop.csproj b/src/Workspaces/Core/Desktop/Microsoft.CodeAnalysis.Workspaces.Desktop.csproj index 102b9fefb826c..954e718cc4fad 100644 --- a/src/Workspaces/Core/Desktop/Microsoft.CodeAnalysis.Workspaces.Desktop.csproj +++ b/src/Workspaces/Core/Desktop/Microsoft.CodeAnalysis.Workspaces.Desktop.csproj @@ -2,76 +2,18 @@ - AnyCPU - AnyCPU Library Microsoft.CodeAnalysis - true - net46 - $(DefineConstants);WORKSPACE_DESKTOP - - - true - - A shared package used by the .NET Compiler Platform ("Roslyn") including support for analyzing projects and solutions. - Do not install this package manually, it will be added as a prerequisite by other packages that require it. - - - - Microsoft.CodeAnalysis.Workspaces.Common - $(NuspecPackageId).nuspec - $(ArtifactsConfigurationDir) - - - false + net472 - - - - - - - - - - - - - - - - - InternalUtilities\DesktopAnalyzerAssemblyLoader.cs - - - InternalUtilities\GlobalAssemblyCache.cs - - - InternalUtilities\FileKey.cs - - - True - True - WorkspaceDesktopResources.resx - + + @@ -108,6 +50,7 @@ + @@ -116,20 +59,8 @@ - - - - - - - - - ResXFileCodeGenerator - WorkspaceDesktopResources.Designer.cs - - \ No newline at end of file diff --git a/src/Workspaces/Core/Desktop/Utilities/ReferencePathUtilities_Desktop.cs b/src/Workspaces/Core/Desktop/Utilities/ReferencePathUtilities_Desktop.cs deleted file mode 100644 index c4af81f58c1f2..0000000000000 --- a/src/Workspaces/Core/Desktop/Utilities/ReferencePathUtilities_Desktop.cs +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices; -using Microsoft.CodeAnalysis; - -namespace Roslyn.Utilities -{ - internal static class ReferencePathUtilities - { - public static bool TryGetReferenceFilePath(string filePath, out string referenceFilePath) - { - // TODO(DustinCa): This is a workaround and we'll need to update this to handle getting the - // correct reference assembly for different framework versions and profiles. We can use - // the handy ToolLocationHelper from Microsoft.Build.Utilities.v4.5.dll - - var assemblyName = Path.GetFileName(filePath); - - // NOTE: Don't use the Path.HasExtension() and Path.ChangeExtension() helpers because - // an assembly might have a dotted name like 'System.Core'. - var extension = Path.GetExtension(assemblyName); - if (!string.Equals(extension, ".dll", StringComparison.OrdinalIgnoreCase) && - !string.Equals(extension, ".exe", StringComparison.OrdinalIgnoreCase)) - { - assemblyName += ".dll"; - } - - foreach (var referenceAssemblyPath in GetReferencePaths()) - { - var referenceAssembly = Path.Combine(referenceAssemblyPath, assemblyName); - if (File.Exists(referenceAssembly)) - { - referenceFilePath = referenceAssembly; - return true; - } - } - - referenceFilePath = null; - return false; - } - - private static IEnumerable GetFrameworkPaths() - { - //// Concat(Path.GetDirectoryName(typeof(Microsoft.CSharp.RuntimeHelpers.SessionHelpers).Assembly.Location)). - return GlobalAssemblyCacheLocation.RootLocations.Concat(RuntimeEnvironment.GetRuntimeDirectory()); - } - - public static IEnumerable GetReferencePaths() - { - // TODO: - // WORKAROUND: properly enumerate them - yield return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), @"Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5"); - yield return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), @"Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0"); - } - - public static bool PartOfFrameworkOrReferencePaths(string filePath) - { - if (!PathUtilities.IsAbsolute(filePath)) - { - return false; - } - - var directory = Path.GetDirectoryName(filePath); - - var frameworkOrReferencePaths = GetReferencePaths().Concat(GetFrameworkPaths()).Select(FileUtilities.NormalizeDirectoryPath); - return frameworkOrReferencePaths.Any(dir => directory.StartsWith(dir, StringComparison.OrdinalIgnoreCase)); - } - } -} diff --git a/src/Workspaces/Core/Desktop/Workspace/CommandLineProject.cs b/src/Workspaces/Core/Desktop/Workspace/CommandLineProject.cs index 94005ce8716ff..164b799333613 100644 --- a/src/Workspaces/Core/Desktop/Workspace/CommandLineProject.cs +++ b/src/Workspaces/Core/Desktop/Workspace/CommandLineProject.cs @@ -1,5 +1,4 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - using System; using System.Collections.Generic; using System.Collections.Immutable; diff --git a/src/Workspaces/Core/Desktop/Workspace/Host/Mef/DesktopMefHostServices.cs b/src/Workspaces/Core/Desktop/Workspace/Host/Mef/DesktopMefHostServices.cs index cd8107d42a73f..f8ce18f36ce35 100644 --- a/src/Workspaces/Core/Desktop/Workspace/Host/Mef/DesktopMefHostServices.cs +++ b/src/Workspaces/Core/Desktop/Workspace/Host/Mef/DesktopMefHostServices.cs @@ -1,5 +1,4 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - using System.Collections.Immutable; using System.Reflection; using System.Threading; @@ -27,28 +26,6 @@ internal static void ResetHostServicesTestOnly() s_defaultServices = null; } - private static ImmutableArray s_defaultAssemblies; - public static ImmutableArray DefaultAssemblies - { - get - { - if (s_defaultAssemblies == null) - { - ImmutableInterlocked.InterlockedCompareExchange(ref s_defaultAssemblies, CreateDefaultAssemblies(), default); - } - - return s_defaultAssemblies; - } - } - - private static ImmutableArray CreateDefaultAssemblies() - { - var assemblyNames = new string[] - { - "Microsoft.CodeAnalysis.Workspaces.Desktop", - }; - - return MefHostServices.DefaultAssemblies.Concat(MefHostServices.LoadNearbyAssemblies(assemblyNames)); - } + public static ImmutableArray DefaultAssemblies => MefHostServices.DefaultAssemblies; } } diff --git a/src/Workspaces/Core/Desktop/Workspace/Host/Mef/MefV1HostServices.cs b/src/Workspaces/Core/Desktop/Workspace/Host/Mef/MefV1HostServices.cs index 5afd530e88958..3c425869e89ee 100644 --- a/src/Workspaces/Core/Desktop/Workspace/Host/Mef/MefV1HostServices.cs +++ b/src/Workspaces/Core/Desktop/Workspace/Host/Mef/MefV1HostServices.cs @@ -1,5 +1,4 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - using System; using System.Collections; using System.Collections.Generic; diff --git a/src/Workspaces/Core/Desktop/WorkspaceDesktopResources.Designer.cs b/src/Workspaces/Core/Desktop/WorkspaceDesktopResources.Designer.cs deleted file mode 100644 index a6011bfed0445..0000000000000 --- a/src/Workspaces/Core/Desktop/WorkspaceDesktopResources.Designer.cs +++ /dev/null @@ -1,81 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Microsoft.CodeAnalysis { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class WorkspaceDesktopResources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal WorkspaceDesktopResources() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.CodeAnalysis.WorkspaceDesktopResources", typeof(WorkspaceDesktopResources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to Invalid assembly name. - /// - internal static string Invalid_assembly_name { - get { - return ResourceManager.GetString("Invalid_assembly_name", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid characters in assembly name. - /// - internal static string Invalid_characters_in_assembly_name { - get { - return ResourceManager.GetString("Invalid_characters_in_assembly_name", resourceCulture); - } - } - } -} diff --git a/src/Workspaces/Core/Desktop/WorkspaceDesktopResources.resx b/src/Workspaces/Core/Desktop/WorkspaceDesktopResources.resx deleted file mode 100644 index 760a67017ce2f..0000000000000 --- a/src/Workspaces/Core/Desktop/WorkspaceDesktopResources.resx +++ /dev/null @@ -1,126 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Invalid assembly name - - - Invalid characters in assembly name - - \ No newline at end of file diff --git a/src/Workspaces/Core/MSBuild/Host/SimpleAnalyzerAssemblyLoaderService.cs b/src/Workspaces/Core/MSBuild/Host/SimpleAnalyzerAssemblyLoaderService.cs index 94d52e9c08a0c..e3c6be07792e9 100644 --- a/src/Workspaces/Core/MSBuild/Host/SimpleAnalyzerAssemblyLoaderService.cs +++ b/src/Workspaces/Core/MSBuild/Host/SimpleAnalyzerAssemblyLoaderService.cs @@ -8,7 +8,7 @@ namespace Microsoft.CodeAnalysis.Host [ExportWorkspaceService(typeof(IAnalyzerService), WorkspaceKind.MSBuild), Shared] internal sealed class SimpleAnalyzerAssemblyLoaderService : IAnalyzerService { -#if NET46 +#if NET472 private readonly DesktopAnalyzerAssemblyLoader _loader = new DesktopAnalyzerAssemblyLoader(); #elif NETCOREAPP1_1 || NETCOREAPP2_1 private readonly CoreClrAnalyzerAssemblyLoader _loader = new CoreClrAnalyzerAssemblyLoader(); diff --git a/src/Workspaces/Core/MSBuild/MSBuild/MSBuildProjectLoader.Worker.cs b/src/Workspaces/Core/MSBuild/MSBuild/MSBuildProjectLoader.Worker.cs index 4ecbb64d3a4ce..2cc3ee4715780 100644 --- a/src/Workspaces/Core/MSBuild/MSBuild/MSBuildProjectLoader.Worker.cs +++ b/src/Workspaces/Core/MSBuild/MSBuild/MSBuildProjectLoader.Worker.cs @@ -384,7 +384,8 @@ private Task CreateProjectInfoAsync(ProjectFileInfo projectFileInfo analyzerReferences: analyzerReferences, additionalDocuments: additionalDocuments, isSubmission: false, - hostObjectType: null); + hostObjectType: null) + .WithDefaultNamespace(projectFileInfo.DefaultNamespace); }); } diff --git a/src/Workspaces/Core/MSBuild/MSBuild/ProjectFile/ProjectFile.cs b/src/Workspaces/Core/MSBuild/MSBuild/ProjectFile/ProjectFile.cs index 19cef2ac2fb90..f8514061c3d6a 100644 --- a/src/Workspaces/Core/MSBuild/MSBuild/ProjectFile/ProjectFile.cs +++ b/src/Workspaces/Core/MSBuild/MSBuild/ProjectFile/ProjectFile.cs @@ -119,6 +119,19 @@ private ProjectFileInfo CreateProjectFileInfo(MSB.Execution.ProjectInstance proj outputRefFilePath = GetAbsolutePathRelativeToProject(outputRefFilePath); } + // Get the default namespace for C# project, which is a C# only concept at the moment. + // We need the language check because "rootnamespace" property is also used in VB for + // completely different purpose. + string defaultNamespace = null; + if (Language == LanguageNames.CSharp) + { + defaultNamespace = project.ReadPropertyString(PropertyNames.RootNamespace); + if (string.IsNullOrWhiteSpace(defaultNamespace)) + { + defaultNamespace = string.Empty; + } + } + var targetFramework = project.ReadPropertyString(PropertyNames.TargetFramework); if (string.IsNullOrWhiteSpace(targetFramework)) { @@ -139,6 +152,7 @@ private ProjectFileInfo CreateProjectFileInfo(MSB.Execution.ProjectInstance proj project.FullPath, outputFilePath, outputRefFilePath, + defaultNamespace, targetFramework, commandLineArgs, docs, diff --git a/src/Workspaces/Core/MSBuild/MSBuild/ProjectFile/ProjectFileInfo.cs b/src/Workspaces/Core/MSBuild/MSBuild/ProjectFile/ProjectFileInfo.cs index a2f7cb858094a..4b06d289621c0 100644 --- a/src/Workspaces/Core/MSBuild/MSBuild/ProjectFile/ProjectFileInfo.cs +++ b/src/Workspaces/Core/MSBuild/MSBuild/ProjectFile/ProjectFileInfo.cs @@ -35,6 +35,15 @@ internal sealed class ProjectFileInfo /// public string OutputRefFilePath { get; } + /// + /// The default namespace of the project ("" if not defined, which means global namespace), + /// or null if it is unknown or not applicable. + /// + /// + /// This only has meaning in C# and is explicitly set to null in VB. + /// > + public string DefaultNamespace { get; } + /// /// The target framework of this project. /// This takes the form of the 'short name' form used by NuGet (e.g. net46, netcoreapp2.0, etc.) @@ -78,6 +87,7 @@ private ProjectFileInfo( string filePath, string outputFilePath, string outputRefFilePath, + string defaultNamespace, string targetFramework, ImmutableArray commandLineArgs, ImmutableArray documents, @@ -92,6 +102,7 @@ private ProjectFileInfo( this.FilePath = filePath; this.OutputFilePath = outputFilePath; this.OutputRefFilePath = outputRefFilePath; + this.DefaultNamespace = defaultNamespace; this.TargetFramework = targetFramework; this.CommandLineArgs = commandLineArgs; this.Documents = documents; @@ -105,6 +116,7 @@ public static ProjectFileInfo Create( string filePath, string outputFilePath, string outputRefFilePath, + string defaultNamespace, string targetFramework, ImmutableArray commandLineArgs, ImmutableArray documents, @@ -117,6 +129,7 @@ public static ProjectFileInfo Create( filePath, outputFilePath, outputRefFilePath, + defaultNamespace, targetFramework, commandLineArgs, documents, @@ -131,6 +144,7 @@ public static ProjectFileInfo CreateEmpty(string language, string filePath, Diag filePath, outputFilePath: null, outputRefFilePath: null, + defaultNamespace: null, targetFramework: null, commandLineArgs: ImmutableArray.Empty, documents: ImmutableArray.Empty, diff --git a/src/Workspaces/Core/MSBuild/Microsoft.CodeAnalysis.Workspaces.MSBuild.csproj b/src/Workspaces/Core/MSBuild/Microsoft.CodeAnalysis.Workspaces.MSBuild.csproj index 2a96c6edf6277..bb88e5981cbbe 100644 --- a/src/Workspaces/Core/MSBuild/Microsoft.CodeAnalysis.Workspaces.MSBuild.csproj +++ b/src/Workspaces/Core/MSBuild/Microsoft.CodeAnalysis.Workspaces.MSBuild.csproj @@ -23,9 +23,6 @@ InternalUtilities\CoreClrAnalyzerAssemblyLoader.cs - - InternalUtilities\DesktopAnalyzerAssemblyLoader.cs - InternalUtilities\GlobalAssemblyCache.cs diff --git a/src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationFieldSymbol.cs b/src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationFieldSymbol.cs index a8b0cec18a17e..685b142d03268 100644 --- a/src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationFieldSymbol.cs +++ b/src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationFieldSymbol.cs @@ -75,6 +75,8 @@ public bool IsReadOnly public bool IsVolatile => false; + public bool IsFixedSizeBuffer => false; + public ImmutableArray CustomModifiers { get diff --git a/src/Workspaces/Core/Desktop/Execution/DesktopReferenceSerializationServiceFactory.cs b/src/Workspaces/Core/Portable/Execution/Desktop/DesktopReferenceSerializationServiceFactory.cs similarity index 100% rename from src/Workspaces/Core/Desktop/Execution/DesktopReferenceSerializationServiceFactory.cs rename to src/Workspaces/Core/Portable/Execution/Desktop/DesktopReferenceSerializationServiceFactory.cs diff --git a/src/Workspaces/Core/Desktop/Execution/SerializationAnalyzerAssemblyLoader.cs b/src/Workspaces/Core/Portable/Execution/Desktop/SerializationAnalyzerAssemblyLoader.cs similarity index 100% rename from src/Workspaces/Core/Desktop/Execution/SerializationAnalyzerAssemblyLoader.cs rename to src/Workspaces/Core/Portable/Execution/Desktop/SerializationAnalyzerAssemblyLoader.cs diff --git a/src/Workspaces/Core/Desktop/Workspace/Host/SimpleAnalyzerAssemblyLoaderService.cs b/src/Workspaces/Core/Portable/Execution/Desktop/SimpleAnalyzerAssemblyLoaderService.cs similarity index 100% rename from src/Workspaces/Core/Desktop/Workspace/Host/SimpleAnalyzerAssemblyLoaderService.cs rename to src/Workspaces/Core/Portable/Execution/Desktop/SimpleAnalyzerAssemblyLoaderService.cs diff --git a/src/Workspaces/Core/Portable/Formatting/Engine/TokenData.cs b/src/Workspaces/Core/Portable/Formatting/Engine/TokenData.cs index 8c791f5f98ff3..c6c62d3e5b5ba 100644 --- a/src/Workspaces/Core/Portable/Formatting/Engine/TokenData.cs +++ b/src/Workspaces/Core/Portable/Formatting/Engine/TokenData.cs @@ -17,9 +17,9 @@ namespace Microsoft.CodeAnalysis.Formatting /// this object is supposed to be live very short but created a lot of time. that is why it is struct. /// (same reason why SyntaxToken is struct - to reduce heap allocation) /// - internal struct TokenData : IEqualityComparer, IEquatable, IComparable, IComparer + internal readonly struct TokenData : IEqualityComparer, IEquatable, IComparable, IComparer { - public TokenData(TokenStream tokenStream, int indexInStream, SyntaxToken token) : this() + public TokenData(TokenStream tokenStream, int indexInStream, SyntaxToken token) { Contract.ThrowIfNull(tokenStream); Contract.ThrowIfFalse((indexInStream == -1) || (0 <= indexInStream && indexInStream < tokenStream.TokenCount)); diff --git a/src/Workspaces/Core/Portable/Formatting/Engine/TokenStream.cs b/src/Workspaces/Core/Portable/Formatting/Engine/TokenStream.cs index 7b62933a855d6..d19ba3cf9594b 100644 --- a/src/Workspaces/Core/Portable/Formatting/Engine/TokenStream.cs +++ b/src/Workspaces/Core/Portable/Formatting/Engine/TokenStream.cs @@ -25,7 +25,6 @@ internal partial class TokenStream // caches token information within given formatting span to improve perf private readonly List _tokens; - private readonly Dictionary _tokenToIndexMap; // caches original trivia info to improve perf private readonly TriviaData[] _cachedOriginalTriviaInfo; @@ -65,12 +64,6 @@ public TokenStream(TreeData treeData, OptionSet optionSet, TextSpan spanToFormat // initialize trivia related info _cachedOriginalTriviaInfo = new TriviaData[this.TokenCount - 1]; - _tokenToIndexMap = new Dictionary(this.TokenCount); - for (int i = 0; i < this.TokenCount; i++) - { - _tokenToIndexMap.Add(_tokens[i], i); - } - // Func Cache _getTriviaData = this.GetTriviaData; _getOriginalTriviaData = this.GetOriginalTriviaData; @@ -510,9 +503,51 @@ private bool IsFirstTokenOnLine(TokenData tokenData1, TokenData tokenData2) private int GetTokenIndexInStream(SyntaxToken token) { - if (_tokenToIndexMap.TryGetValue(token, out var value)) + var tokenIndex = _tokens.BinarySearch(token, TokenOrderComparer.Instance); + if (tokenIndex < 0) + { + return -1; + } + + // Source characters cannot be assigned to multiple tokens. If the token has non-zero width, it will be an + // exact match for at most one token. + if (!token.FullSpan.IsEmpty) { - return value; + return _tokens[tokenIndex] == token ? tokenIndex : -1; + } + + // Multiple tokens can have empty spans. The binary search operation will return one of them; look forward + // and then backward to locate the desired token within the set of one or more zero-width tokens located at + // the same position. + Debug.Assert(token.FullSpan.IsEmpty); + for (var i = tokenIndex; i < _tokens.Count; i++) + { + if (!_tokens[i].FullSpan.IsEmpty) + { + // Current token can't match because the span is different, and future tokens won't match because + // they are lexicographically after the token we are interested in. + break; + } + + if (_tokens[i] == token) + { + return i; + } + } + + for (var i = tokenIndex - 1; i >= 0; i--) + { + if (!_tokens[i].FullSpan.IsEmpty) + { + // Current token can't match because the span is different, and future tokens won't match because + // they are lexicographically before the token we are interested in. + break; + } + + if (_tokens[i] == token) + { + return i; + } } return -1; @@ -525,5 +560,17 @@ public IEnumerable> TokenIterator return new Iterator(_tokens); } } + + private sealed class TokenOrderComparer : IComparer + { + public static readonly TokenOrderComparer Instance = new TokenOrderComparer(); + + private TokenOrderComparer() { } + + public int Compare(SyntaxToken x, SyntaxToken y) + { + return x.FullSpan.CompareTo(y.FullSpan); + } + } } } diff --git a/src/Workspaces/Core/Desktop/Log/EtwLogger.cs b/src/Workspaces/Core/Portable/Log/EtwLogger.cs similarity index 100% rename from src/Workspaces/Core/Desktop/Log/EtwLogger.cs rename to src/Workspaces/Core/Portable/Log/EtwLogger.cs diff --git a/src/Workspaces/Core/Desktop/Log/RoslynEventSource.cs b/src/Workspaces/Core/Portable/Log/RoslynEventSource.cs similarity index 100% rename from src/Workspaces/Core/Desktop/Log/RoslynEventSource.cs rename to src/Workspaces/Core/Portable/Log/RoslynEventSource.cs diff --git a/src/Workspaces/Core/Desktop/Log/TraceLogger.cs b/src/Workspaces/Core/Portable/Log/TraceLogger.cs similarity index 100% rename from src/Workspaces/Core/Desktop/Log/TraceLogger.cs rename to src/Workspaces/Core/Portable/Log/TraceLogger.cs diff --git a/src/Workspaces/Core/Portable/Microsoft.CodeAnalysis.Workspaces.csproj b/src/Workspaces/Core/Portable/Microsoft.CodeAnalysis.Workspaces.csproj index 2db5781219185..b3e29f3fcbd2b 100644 --- a/src/Workspaces/Core/Portable/Microsoft.CodeAnalysis.Workspaces.csproj +++ b/src/Workspaces/Core/Portable/Microsoft.CodeAnalysis.Workspaces.csproj @@ -7,28 +7,34 @@ Library Microsoft.CodeAnalysis true - netstandard1.3 + netstandard2.0 $(DefineConstants);WORKSPACE - + + true Microsoft.CodeAnalysis.Workspaces.Common + + A shared package used by the .NET Compiler Platform ("Roslyn") including support for analyzing projects and solutions. + Do not install this package manually, it will be added as a prerequisite by other packages that require it. + + + + false - + + + + + + + Execution\Desktop\DesktopAnalyzerAssemblyLoader.cs + Collections\ArrayBuilderExtensions.cs @@ -339,13 +345,5 @@ - - - - - - - - \ No newline at end of file diff --git a/src/Workspaces/Core/Portable/Options/OptionServiceFactory.cs b/src/Workspaces/Core/Portable/Options/OptionServiceFactory.cs index d40b271d3cb48..c198124ca2e1e 100644 --- a/src/Workspaces/Core/Portable/Options/OptionServiceFactory.cs +++ b/src/Workspaces/Core/Portable/Options/OptionServiceFactory.cs @@ -8,6 +8,7 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Options { @@ -161,7 +162,6 @@ private class DocumentSpecificOptionSet : OptionSet { private readonly OptionSet _underlyingOptions; private readonly List _documentOptions; - private readonly object _gate = new object(); private ImmutableDictionary _values; public DocumentSpecificOptionSet(List documentOptions, OptionSet underlyingOptions) @@ -176,6 +176,7 @@ public DocumentSpecificOptionSet(List documentOptions, OptionS _values = values; } + [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/30819", AllowLocks = false)] public override object GetOption(OptionKey optionKey) { // If we already know the document specific value, we're done @@ -189,12 +190,7 @@ public override object GetOption(OptionKey optionKey) if (documentOptionSource.TryGetDocumentOption(optionKey, _underlyingOptions, out value)) { // Cache and return - lock (_gate) - { - _values = _values.Add(optionKey, value); - } - - return value; + return ImmutableInterlocked.GetOrAdd(ref _values, optionKey, value); } } diff --git a/src/Workspaces/Core/Portable/Options/WorkspaceOptionSet.cs b/src/Workspaces/Core/Portable/Options/WorkspaceOptionSet.cs index ecc46616a6b0f..4f437f02e00ae 100644 --- a/src/Workspaces/Core/Portable/Options/WorkspaceOptionSet.cs +++ b/src/Workspaces/Core/Portable/Options/WorkspaceOptionSet.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Collections.Immutable; +using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Options { @@ -13,7 +14,6 @@ internal sealed class WorkspaceOptionSet : OptionSet { private readonly IOptionService _service; - private readonly object _gate = new object(); private ImmutableDictionary _values; internal WorkspaceOptionSet(IOptionService service) @@ -28,18 +28,16 @@ private WorkspaceOptionSet(IOptionService service, ImmutableDictionary(this IReadOnlyList list) return list[list.Count - 1]; } + public static int IndexOf(this IReadOnlyList list, T value, int startIndex) + { + for (var index = startIndex; index < list.Count; index++) + { + if (EqualityComparer.Default.Equals(list[index], value)) + { + return index; + } + } + + return -1; + } + private class ReadOnlyList : IReadOnlyList { private readonly IList _list; diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/Project.cs b/src/Workspaces/Core/Portable/Workspace/Solution/Project.cs index 1eb9b8790597f..7344b3c57a1ed 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/Project.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/Project.cs @@ -62,6 +62,15 @@ internal Project(Solution solution, ProjectState projectState) /// public string OutputRefFilePath => _projectState.OutputRefFilePath; + /// + /// The default namespace of the project ("" if not defined, which means global namespace), + /// or null if it is unknown or not applicable. + /// + /// + /// This only has meaning in C# and is explicitly set to null in VB. + /// > + internal string DefaultNamespace => _projectState.DefaultNamespace; + /// /// if this supports providing data through the /// method. @@ -342,6 +351,14 @@ public Project WithAssemblyName(string assemblyName) return this.Solution.WithProjectAssemblyName(this.Id, assemblyName).GetProject(this.Id); } + /// + /// Creates a new instance of this project updated to have the new default namespace. + /// + internal Project WithDefaultNamespace(string defaultNamespace) + { + return this.Solution.WithProjectDefaultNamespace(this.Id, defaultNamespace).GetProject(this.Id); + } + /// /// Creates a new instance of this project updated to have the specified compilation options. /// diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/ProjectInfo.cs b/src/Workspaces/Core/Portable/Workspace/Solution/ProjectInfo.cs index 4a25189c67e7a..6a02eebdb7b7e 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/ProjectInfo.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/ProjectInfo.cs @@ -58,6 +58,15 @@ public sealed class ProjectInfo /// public string OutputRefFilePath => Attributes.OutputRefFilePath; + /// + /// The default namespace of the project ("" if not defined, which means global namespace), + /// or null if it is unknown or not applicable. + /// + /// + /// This only has meaning in C# and is explicitly set to null in VB. + /// > + internal string DefaultNamespace => Attributes.DefaultNamespace; + /// /// True if this is a submission project for interactive sessions. /// @@ -144,6 +153,7 @@ internal static ProjectInfo Create( string filePath, string outputFilePath, string outputRefFilePath, + string defaultNamespace, CompilationOptions compilationOptions, ParseOptions parseOptions, IEnumerable documents, @@ -165,6 +175,7 @@ internal static ProjectInfo Create( filePath, outputFilePath, outputRefFilePath, + defaultNamespace, isSubmission, hasAllInformation), compilationOptions, @@ -201,7 +212,7 @@ public static ProjectInfo Create( { return Create( id, version, name, assemblyName, language, - filePath, outputFilePath, outputRefFilePath: null, compilationOptions, parseOptions, + filePath, outputFilePath, outputRefFilePath: null, defaultNamespace: null, compilationOptions, parseOptions, documents, projectReferences, metadataReferences, analyzerReferences, additionalDocuments, isSubmission, hostObjectType, hasAllInformation: true); } @@ -230,7 +241,7 @@ public static ProjectInfo Create( { return Create( id, version, name, assemblyName, language, - filePath, outputFilePath, outputRefFilePath, compilationOptions, parseOptions, + filePath, outputFilePath, outputRefFilePath, defaultNamespace: null, compilationOptions, parseOptions, documents, projectReferences, metadataReferences, analyzerReferences, additionalDocuments, isSubmission, hostObjectType, hasAllInformation: true); } @@ -321,6 +332,11 @@ public ProjectInfo WithOutputRefFilePath(string outputRefFilePath) return With(attributes: Attributes.With(outputRefPath: outputRefFilePath)); } + internal ProjectInfo WithDefaultNamespace(string defaultNamespace) + { + return With(attributes: Attributes.With(defaultNamespace: defaultNamespace)); + } + public ProjectInfo WithCompilationOptions(CompilationOptions compilationOptions) { return With(compilationOptions: compilationOptions); @@ -402,6 +418,11 @@ internal class ProjectAttributes : IChecksummedObject, IObjectWritable /// public string OutputRefFilePath { get; } + /// + /// The default namespace of the project. + /// + public string DefaultNamespace { get; } + /// /// True if this is a submission project for interactive sessions. /// @@ -423,6 +444,7 @@ public ProjectAttributes( string filePath, string outputFilePath, string outputRefFilePath, + string defaultNamespace, bool isSubmission, bool hasAllInformation) { @@ -435,6 +457,7 @@ public ProjectAttributes( FilePath = filePath; OutputFilePath = outputFilePath; OutputRefFilePath = outputRefFilePath; + DefaultNamespace = defaultNamespace; IsSubmission = isSubmission; HasAllInformation = hasAllInformation; } @@ -447,6 +470,7 @@ public ProjectAttributes With( Optional filePath = default, Optional outputPath = default, Optional outputRefPath = default, + Optional defaultNamespace = default, Optional isSubmission = default, Optional hasAllInformation = default) { @@ -457,6 +481,7 @@ public ProjectAttributes With( var newFilepath = filePath.HasValue ? filePath.Value : FilePath; var newOutputPath = outputPath.HasValue ? outputPath.Value : OutputFilePath; var newOutputRefPath = outputRefPath.HasValue ? outputRefPath.Value : OutputRefFilePath; + var newDefaultNamespace = defaultNamespace.HasValue ? defaultNamespace.Value : DefaultNamespace; var newIsSubmission = isSubmission.HasValue ? isSubmission.Value : IsSubmission; var newHasAllInformation = hasAllInformation.HasValue ? hasAllInformation.Value : HasAllInformation; @@ -467,6 +492,7 @@ public ProjectAttributes With( newFilepath == FilePath && newOutputPath == OutputFilePath && newOutputRefPath == OutputRefFilePath && + newDefaultNamespace == DefaultNamespace && newIsSubmission == IsSubmission && newHasAllInformation == HasAllInformation) { @@ -482,6 +508,7 @@ public ProjectAttributes With( newFilepath, newOutputPath, newOutputRefPath, + newDefaultNamespace, newIsSubmission, newHasAllInformation); } @@ -501,6 +528,7 @@ public void WriteTo(ObjectWriter writer) writer.WriteString(FilePath); writer.WriteString(OutputFilePath); writer.WriteString(OutputRefFilePath); + writer.WriteString(DefaultNamespace); writer.WriteBoolean(IsSubmission); writer.WriteBoolean(HasAllInformation); @@ -519,10 +547,11 @@ public static ProjectAttributes ReadFrom(ObjectReader reader) var filePath = reader.ReadString(); var outputFilePath = reader.ReadString(); var outputRefFilePath = reader.ReadString(); + var defaultNamespace = reader.ReadString(); var isSubmission = reader.ReadBoolean(); var hasAllInformation = reader.ReadBoolean(); - return new ProjectAttributes(projectId, VersionStamp.Create(), name, assemblyName, language, filePath, outputFilePath, outputRefFilePath, isSubmission, hasAllInformation); + return new ProjectAttributes(projectId, VersionStamp.Create(), name, assemblyName, language, filePath, outputFilePath, outputRefFilePath, defaultNamespace, isSubmission, hasAllInformation); } private Checksum _lazyChecksum; diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/ProjectState.cs b/src/Workspaces/Core/Portable/Workspace/Solution/ProjectState.cs index eba1ea4435720..e53a4c5bc9e9c 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/ProjectState.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/ProjectState.cs @@ -268,6 +268,9 @@ public async Task GetSemanticVersionAsync(CancellationToken cancel [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public string OutputRefFilePath => this.ProjectInfo.OutputRefFilePath; + [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] + public string DefaultNamespace => this.ProjectInfo.DefaultNamespace; + [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public HostLanguageServices LanguageServices => _languageServices; @@ -424,6 +427,16 @@ public ProjectState UpdateOutputRefFilePath(string outputRefFilePath) return this.With(projectInfo: this.ProjectInfo.WithOutputRefFilePath(outputRefFilePath).WithVersion(this.Version.GetNewerVersion())); } + public ProjectState UpdateDefaultNamespace(string defaultNamespace) + { + if (defaultNamespace == this.DefaultNamespace) + { + return this; + } + + return this.With(projectInfo: this.ProjectInfo.WithDefaultNamespace(defaultNamespace).WithVersion(this.Version.GetNewerVersion())); + } + public ProjectState UpdateCompilationOptions(CompilationOptions options) { if (options == this.CompilationOptions) diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs b/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs index 00f43bf3afdce..fcad999e18d04 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/Solution.cs @@ -304,6 +304,20 @@ public Solution WithProjectOutputRefFilePath(ProjectId projectId, string outputR return new Solution(newState); } + /// + /// Creates a new solution instance with the project specified updated to have the default namespace. + /// + internal Solution WithProjectDefaultNamespace(ProjectId projectId, string defaultNamespace) + { + var newState = _state.WithProjectDefaultNamespace(projectId, defaultNamespace); + if (newState == _state) + { + return this; + } + + return new Solution(newState); + } + /// /// Creates a new solution instance with the project specified updated to have the name. /// diff --git a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.cs b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.cs index 09714b0b43b57..a22e9ca506022 100644 --- a/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.cs +++ b/src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.cs @@ -656,6 +656,29 @@ public SolutionState WithProjectOutputRefFilePath(ProjectId projectId, string ou return this.ForkProject(newProjectState); } + /// + /// Creates a new solution instance with the project specified updated to have the default namespace. + /// + public SolutionState WithProjectDefaultNamespace(ProjectId projectId, string defaultNamespace) + { + if (projectId == null) + { + throw new ArgumentNullException(nameof(projectId)); + } + + CheckContainsProject(projectId); + + var oldProjectState = this.GetProjectState(projectId); + var newProjectState = oldProjectState.UpdateDefaultNamespace(defaultNamespace); + + if (oldProjectState == newProjectState) + { + return this; + } + + return this.ForkProject(newProjectState); + } + /// /// Creates a new solution instance with the project specified updated to have the name. /// diff --git a/src/Workspaces/Core/Portable/Workspace/Workspace.cs b/src/Workspaces/Core/Portable/Workspace/Workspace.cs index 7f025665bc253..b4fa9c0a0671e 100644 --- a/src/Workspaces/Core/Portable/Workspace/Workspace.cs +++ b/src/Workspaces/Core/Portable/Workspace/Workspace.cs @@ -1445,7 +1445,8 @@ private ProjectInfo CreateProjectInfo(Project project) project.AdditionalDocuments.Select(d => CreateDocumentInfoWithText(d)), project.IsSubmission, project.State.HostObjectType, - project.OutputRefFilePath); + project.OutputRefFilePath) + .WithDefaultNamespace(project.DefaultNamespace); } private DocumentInfo CreateDocumentInfoWithText(TextDocument doc) diff --git a/src/Workspaces/CoreTest/Microsoft.CodeAnalysis.Workspaces.UnitTests.csproj b/src/Workspaces/CoreTest/Microsoft.CodeAnalysis.Workspaces.UnitTests.csproj index 00a3904511e78..273951dcc9df2 100644 --- a/src/Workspaces/CoreTest/Microsoft.CodeAnalysis.Workspaces.UnitTests.csproj +++ b/src/Workspaces/CoreTest/Microsoft.CodeAnalysis.Workspaces.UnitTests.csproj @@ -6,7 +6,7 @@ AnyCPU Library Microsoft.CodeAnalysis.UnitTests - net46 + net472 $(RoslynDesktopRuntimeIdentifier) UnitTest @@ -24,7 +24,6 @@ - diff --git a/src/Workspaces/CoreTest/SolutionTests/SolutionTests.cs b/src/Workspaces/CoreTest/SolutionTests/SolutionTests.cs index 3da91dbf31d54..7061ca269bc55 100644 --- a/src/Workspaces/CoreTest/SolutionTests/SolutionTests.cs +++ b/src/Workspaces/CoreTest/SolutionTests/SolutionTests.cs @@ -1152,42 +1152,6 @@ private ObjectReference GetObservedCompilation(Solution solution, P return new ObjectReference(observed); } - [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] - public void TestLoadProjectFromCommandLine() - { - string commandLine = @"goo.cs subdir\bar.cs /out:goo.dll /target:library"; - var info = CommandLineProject.CreateProjectInfo("TestProject", LanguageNames.CSharp, commandLine, @"C:\ProjectDirectory"); - var ws = new AdhocWorkspace(); - ws.AddProject(info); - var project = ws.CurrentSolution.GetProject(info.Id); - - Assert.Equal("TestProject", project.Name); - Assert.Equal("goo", project.AssemblyName); - Assert.Equal(OutputKind.DynamicallyLinkedLibrary, project.CompilationOptions.OutputKind); - - Assert.Equal(2, project.Documents.Count()); - - var gooDoc = project.Documents.First(d => d.Name == "goo.cs"); - Assert.Equal(0, gooDoc.Folders.Count); - Assert.Equal(@"C:\ProjectDirectory\goo.cs", gooDoc.FilePath); - - var barDoc = project.Documents.First(d => d.Name == "bar.cs"); - Assert.Equal(1, barDoc.Folders.Count); - Assert.Equal("subdir", barDoc.Folders[0]); - Assert.Equal(@"C:\ProjectDirectory\subdir\bar.cs", barDoc.FilePath); - } - - [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] - public void TestCommandLineProjectWithRelativePathOutsideProjectCone() - { - string commandLine = @"..\goo.cs"; - var info = CommandLineProject.CreateProjectInfo("TestProject", LanguageNames.CSharp, commandLine, @"C:\ProjectDirectory"); - - var docInfo = info.Documents.First(); - Assert.Equal(0, docInfo.Folders.Count); - Assert.Equal("goo.cs", docInfo.Name); - } - [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestWorkspaceLanguageServiceOverride() { diff --git a/src/Workspaces/CoreTest/WorkspaceTests/AdhocWorkspaceTests.cs b/src/Workspaces/CoreTest/WorkspaceTests/AdhocWorkspaceTests.cs index 3efa64426f3fd..4932f1ca40c04 100644 --- a/src/Workspaces/CoreTest/WorkspaceTests/AdhocWorkspaceTests.cs +++ b/src/Workspaces/CoreTest/WorkspaceTests/AdhocWorkspaceTests.cs @@ -152,41 +152,6 @@ public void TestAddProjects() } } - [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] - public async Task TestAddProject_CommandLineProjectAsync() - { - CreateFiles(GetSimpleCSharpSolutionFiles()); - - string commandLine = @"CSharpClass.cs /out:goo.dll /target:library"; - var baseDirectory = Path.Combine(this.SolutionDirectory.Path, "CSharpProject"); - - using (var ws = new AdhocWorkspace(DesktopMefHostServices.DefaultServices)) - { - var info = CommandLineProject.CreateProjectInfo("TestProject", LanguageNames.CSharp, commandLine, baseDirectory, ws); - ws.AddProject(info); - var project = ws.CurrentSolution.GetProject(info.Id); - - Assert.Equal("TestProject", project.Name); - Assert.Equal("goo", project.AssemblyName); - Assert.Equal(OutputKind.DynamicallyLinkedLibrary, project.CompilationOptions.OutputKind); - - Assert.Equal(1, project.Documents.Count()); - - var gooDoc = project.Documents.First(d => d.Name == "CSharpClass.cs"); - Assert.Equal(0, gooDoc.Folders.Count); - var expectedPath = Path.Combine(baseDirectory, "CSharpClass.cs"); - Assert.Equal(expectedPath, gooDoc.FilePath); - - var text = (await gooDoc.GetTextAsync()).ToString(); - Assert.NotEqual("", text); - - var tree = await gooDoc.GetSyntaxRootAsync(); - Assert.Equal(false, tree.ContainsDiagnostics); - - var compilation = await project.GetCompilationAsync(); - } - } - [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestAddProject_TryApplyChanges() { diff --git a/src/Workspaces/CoreTestUtilities/ExportProviderCache.cs b/src/Workspaces/CoreTestUtilities/MEF/ExportProviderCache.cs similarity index 94% rename from src/Workspaces/CoreTestUtilities/ExportProviderCache.cs rename to src/Workspaces/CoreTestUtilities/MEF/ExportProviderCache.cs index a0f082c45e673..bf1ac688e8ffa 100644 --- a/src/Workspaces/CoreTestUtilities/ExportProviderCache.cs +++ b/src/Workspaces/CoreTestUtilities/MEF/ExportProviderCache.cs @@ -25,13 +25,6 @@ public static class ExportProviderCache private static readonly IExportProviderFactory s_defaultHostExportProviderFactory = CreateExportProviderFactory(s_defaultHostCatalog); - // Cache the catalog and export provider factory for DesktopMefHostServices.DefaultAssemblies - private static readonly ComposableCatalog s_desktopHostCatalog = - CreateAssemblyCatalog(DesktopMefHostServices.DefaultAssemblies); - - private static readonly IExportProviderFactory s_desktopHostExportProviderFactory = - CreateExportProviderFactory(s_desktopHostCatalog); - // Cache the catalog and export provider factory for RoslynServices.RemoteHostAssemblies private static readonly ComposableCatalog s_remoteHostCatalog = CreateAssemblyCatalog(RoslynServices.RemoteHostAssemblies); @@ -73,10 +66,6 @@ public static ComposableCatalog GetOrCreateAssemblyCatalog(IEnumerable { return s_defaultHostCatalog; } - else if (assembliesArray == DesktopMefHostServices.DefaultAssemblies) - { - return s_desktopHostCatalog; - } else if (assembliesArray == RoslynServices.RemoteHostAssemblies) { return s_remoteHostCatalog; @@ -169,10 +158,6 @@ public static IExportProviderFactory GetOrCreateExportProviderFactory(Composable { return s_defaultHostExportProviderFactory; } - else if (catalog == s_desktopHostCatalog) - { - return s_desktopHostExportProviderFactory; - } else if (catalog == s_remoteHostCatalog) { return s_remoteHostExportProviderFactory; diff --git a/src/Workspaces/CoreTestUtilities/UseExportProviderAttribute.cs b/src/Workspaces/CoreTestUtilities/MEF/UseExportProviderAttribute.cs similarity index 95% rename from src/Workspaces/CoreTestUtilities/UseExportProviderAttribute.cs rename to src/Workspaces/CoreTestUtilities/MEF/UseExportProviderAttribute.cs index 80f21e41ec2f4..4d7275ed51cc0 100644 --- a/src/Workspaces/CoreTestUtilities/UseExportProviderAttribute.cs +++ b/src/Workspaces/CoreTestUtilities/MEF/UseExportProviderAttribute.cs @@ -15,6 +15,7 @@ using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Composition; +using Microsoft.VisualStudio.LanguageServices; using Roslyn.Test.Utilities; using Xunit.Sdk; @@ -41,7 +42,7 @@ namespace Microsoft.CodeAnalysis.Test.Utilities /// /// [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] - public sealed class UseExportProviderAttribute : BeforeAfterTestAttribute + public class UseExportProviderAttribute : BeforeAfterTestAttribute { /// /// Asynchronous operations are expected to be cancelled at the end of the test that started them. Operations @@ -66,7 +67,6 @@ public override void Before(MethodInfo methodUnderTest) { MefHostServices.HookServiceCreation(CreateMefHostServices); RoslynServices.HookHostServices(() => _remoteHostServices.Value); - DesktopMefHostServices.ResetHostServicesTestOnly(); // make sure we enable this for all unit tests AsynchronousOperationListenerProvider.Enable(enable: true, diagnostics: true); @@ -144,7 +144,6 @@ public override void After(MethodInfo methodUnderTest) RoslynServices.HookHostServices(() => throw new InvalidOperationException("Cannot create host services after test tear down.")); // Reset static state variables. - DesktopMefHostServices.ResetHostServicesTestOnly(); _hostServices = null; ExportProviderCache.SetEnabled_OnlyUseExportProviderAttributeCanCall(false); } @@ -199,27 +198,27 @@ private static MefHostServices CreateRemoteHostServices() private class ExportProviderMefHostServices : MefHostServices, IMefHostExportProvider { - private readonly MefV1HostServices _mefV1HostServices; + private readonly VisualStudioMefHostServices _vsHostServices; public ExportProviderMefHostServices(ExportProvider exportProvider) : base(new ContainerConfiguration().CreateContainer()) { - _mefV1HostServices = MefV1HostServices.Create(exportProvider.AsExportProvider()); + _vsHostServices = VisualStudioMefHostServices.Create(exportProvider); } protected internal override HostWorkspaceServices CreateWorkspaceServices(Workspace workspace) { - return _mefV1HostServices.CreateWorkspaceServices(workspace); + return _vsHostServices.CreateWorkspaceServices(workspace); } IEnumerable> IMefHostExportProvider.GetExports() { - return _mefV1HostServices.GetExports(); + return _vsHostServices.GetExports(); } IEnumerable> IMefHostExportProvider.GetExports() { - return _mefV1HostServices.GetExports(); + return _vsHostServices.GetExports(); } } } diff --git a/src/Workspaces/CoreTestUtilities/Resources/ProjectFiles/CSharp/ReferencesPortableProject.csproj b/src/Workspaces/CoreTestUtilities/Resources/ProjectFiles/CSharp/ReferencesPortableProject.csproj index 77f73e32de1a7..5f51b775bc400 100644 --- a/src/Workspaces/CoreTestUtilities/Resources/ProjectFiles/CSharp/ReferencesPortableProject.csproj +++ b/src/Workspaces/CoreTestUtilities/Resources/ProjectFiles/CSharp/ReferencesPortableProject.csproj @@ -11,7 +11,7 @@ Properties Bug2824 Bug2824 - v4.6 + v4.6.1 512 true diff --git a/src/Workspaces/CoreTestUtilities/Roslyn.Services.UnitTests.Utilities.csproj b/src/Workspaces/CoreTestUtilities/Roslyn.Services.UnitTests.Utilities.csproj index b666f054570bb..d45cdd5167f18 100644 --- a/src/Workspaces/CoreTestUtilities/Roslyn.Services.UnitTests.Utilities.csproj +++ b/src/Workspaces/CoreTestUtilities/Roslyn.Services.UnitTests.Utilities.csproj @@ -6,7 +6,7 @@ AnyCPU Library Microsoft.CodeAnalysis.UnitTests - net46 + net472 $(RoslynDesktopRuntimeIdentifier) false @@ -19,7 +19,6 @@ - @@ -55,5 +54,6 @@ + \ No newline at end of file diff --git a/src/Workspaces/CoreTest/WorkspaceTests/CommandLineProjectTests.cs b/src/Workspaces/DesktopTest/CommandLineProjectTests.cs similarity index 87% rename from src/Workspaces/CoreTest/WorkspaceTests/CommandLineProjectTests.cs rename to src/Workspaces/DesktopTest/CommandLineProjectTests.cs index 49df0f5a1d835..6a6b36d6a3d7c 100644 --- a/src/Workspaces/CoreTest/WorkspaceTests/CommandLineProjectTests.cs +++ b/src/Workspaces/DesktopTest/CommandLineProjectTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; +using System.Composition; +using System.Composition.Hosting; using System.IO; using System.Linq; using Microsoft.CodeAnalysis.Host.Mef; @@ -11,8 +13,19 @@ namespace Microsoft.CodeAnalysis.UnitTests { [UseExportProvider] - public partial class CommandLineProjectTests : TestBase + public class CommandLineProjectTests : TestBase { + [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] + public void TestCommandLineProjectWithRelativePathOutsideProjectCone() + { + string commandLine = @"..\goo.cs"; + var info = CommandLineProject.CreateProjectInfo("TestProject", LanguageNames.CSharp, commandLine, @"C:\ProjectDirectory"); + + var docInfo = info.Documents.First(); + Assert.Equal(0, docInfo.Folders.Count); + Assert.Equal("goo.cs", docInfo.Name); + } + [Fact] public void TestCreateWithoutRequiredServices() { @@ -20,7 +33,7 @@ public void TestCreateWithoutRequiredServices() Assert.Throws(delegate { - var ws = new AdhocWorkspace(); // only includes portable services + var ws = new AdhocWorkspace(new MefHostServices(new ContainerConfiguration().CreateContainer())); // no services var info = CommandLineProject.CreateProjectInfo("TestProject", LanguageNames.CSharp, commandLine, @"C:\ProjectDirectory", ws); }); } diff --git a/src/Workspaces/DesktopTest/CommandLineProjectWorkspaceTests.cs b/src/Workspaces/DesktopTest/CommandLineProjectWorkspaceTests.cs new file mode 100644 index 0000000000000..0239d8203cd67 --- /dev/null +++ b/src/Workspaces/DesktopTest/CommandLineProjectWorkspaceTests.cs @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Host.Mef; +using Microsoft.CodeAnalysis.Test.Utilities; +using Roslyn.Utilities; +using Xunit; + +namespace Microsoft.CodeAnalysis.UnitTests +{ + [UseExportProvider] + public class CommandLineProjectWorkspaceTests : WorkspaceTestBase + { + [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] + public async Task TestAddProject_CommandLineProjectAsync() + { + CreateFiles(GetSimpleCSharpSolutionFiles()); + + string commandLine = @"CSharpClass.cs /out:goo.dll /target:library"; + var baseDirectory = Path.Combine(SolutionDirectory.Path, "CSharpProject"); + + using (var ws = new AdhocWorkspace(DesktopMefHostServices.DefaultServices)) + { + var info = CommandLineProject.CreateProjectInfo("TestProject", LanguageNames.CSharp, commandLine, baseDirectory, ws); + ws.AddProject(info); + var project = ws.CurrentSolution.GetProject(info.Id); + + Assert.Equal("TestProject", project.Name); + Assert.Equal("goo", project.AssemblyName); + Assert.Equal(OutputKind.DynamicallyLinkedLibrary, project.CompilationOptions.OutputKind); + + Assert.Equal(1, project.Documents.Count()); + + var gooDoc = project.Documents.First(d => d.Name == "CSharpClass.cs"); + Assert.Equal(0, gooDoc.Folders.Count); + var expectedPath = Path.Combine(baseDirectory, "CSharpClass.cs"); + Assert.Equal(expectedPath, gooDoc.FilePath); + + var text = (await gooDoc.GetTextAsync()).ToString(); + Assert.NotEqual("", text); + + var tree = await gooDoc.GetSyntaxRootAsync(); + Assert.Equal(false, tree.ContainsDiagnostics); + + var compilation = await project.GetCompilationAsync(); + } + } + + [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] + public void TestLoadProjectFromCommandLine() + { + string commandLine = @"goo.cs subdir\bar.cs /out:goo.dll /target:library"; + var info = CommandLineProject.CreateProjectInfo("TestProject", LanguageNames.CSharp, commandLine, @"C:\ProjectDirectory"); + var ws = new AdhocWorkspace(); + ws.AddProject(info); + var project = ws.CurrentSolution.GetProject(info.Id); + + Assert.Equal("TestProject", project.Name); + Assert.Equal("goo", project.AssemblyName); + Assert.Equal(OutputKind.DynamicallyLinkedLibrary, project.CompilationOptions.OutputKind); + + Assert.Equal(2, project.Documents.Count()); + + var gooDoc = project.Documents.First(d => d.Name == "goo.cs"); + Assert.Equal(0, gooDoc.Folders.Count); + Assert.Equal(@"C:\ProjectDirectory\goo.cs", gooDoc.FilePath); + + var barDoc = project.Documents.First(d => d.Name == "bar.cs"); + Assert.Equal(1, barDoc.Folders.Count); + Assert.Equal("subdir", barDoc.Folders[0]); + Assert.Equal(@"C:\ProjectDirectory\subdir\bar.cs", barDoc.FilePath); + } + } +} diff --git a/src/Workspaces/DesktopTest/Microsoft.CodeAnalysis.Workspaces.Desktop.UnitTests.csproj b/src/Workspaces/DesktopTest/Microsoft.CodeAnalysis.Workspaces.Desktop.UnitTests.csproj new file mode 100644 index 0000000000000..cc9ccddc5e115 --- /dev/null +++ b/src/Workspaces/DesktopTest/Microsoft.CodeAnalysis.Workspaces.Desktop.UnitTests.csproj @@ -0,0 +1,47 @@ + + + + + AnyCPU + AnyCPU + Library + Microsoft.CodeAnalysis.UnitTests + net472 + $(RoslynDesktopRuntimeIdentifier) + UnitTest + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Workspaces/DesktopTest/UseMefV1ExportProviderAttribute.cs b/src/Workspaces/DesktopTest/UseMefV1ExportProviderAttribute.cs new file mode 100644 index 0000000000000..22af8daa1c4da --- /dev/null +++ b/src/Workspaces/DesktopTest/UseMefV1ExportProviderAttribute.cs @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System; +using System.Reflection; +using Microsoft.CodeAnalysis.Host.Mef; +using Microsoft.CodeAnalysis.Test.Utilities; + +namespace Microsoft.CodeAnalysis.UnitTests +{ + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] + internal class UseMefV1ExportProviderAttribute : UseExportProviderAttribute + { + public override void Before(MethodInfo methodUnderTest) + { + DesktopMefHostServices.ResetHostServicesTestOnly(); + base.Before(methodUnderTest); + } + + public override void After(MethodInfo methodUnderTest) + { + base.After(methodUnderTest); + DesktopMefHostServices.ResetHostServicesTestOnly(); + } + } +} diff --git a/src/Workspaces/MSBuildTest/MSBuildWorkspaceTestBase.cs b/src/Workspaces/MSBuildTest/MSBuildWorkspaceTestBase.cs index eff911d4f85ae..63348a5de010e 100644 --- a/src/Workspaces/MSBuildTest/MSBuildWorkspaceTestBase.cs +++ b/src/Workspaces/MSBuildTest/MSBuildWorkspaceTestBase.cs @@ -8,6 +8,7 @@ using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.CodeAnalysis.UnitTests.TestFiles; +using Roslyn.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.MSBuild.UnitTests.SolutionGeneration; using CS = Microsoft.CodeAnalysis.CSharp; @@ -19,6 +20,11 @@ public class MSBuildWorkspaceTestBase : WorkspaceTestBase { protected const string MSBuildNamespace = "http://schemas.microsoft.com/developer/msbuild/2003"; + protected void AssertFailures(MSBuildWorkspace workspace, params string[] expectedFailures) + { + AssertEx.Equal(expectedFailures, workspace.Diagnostics.Where(d => d.Kind == WorkspaceDiagnosticKind.Failure).Select(d => d.Message)); + } + protected async Task AssertCSCompilationOptionsAsync(T expected, Func actual) { var options = await LoadCSharpCompilationOptionsAsync(); diff --git a/src/Workspaces/MSBuildTest/MSBuildWorkspaceTests.cs b/src/Workspaces/MSBuildTest/MSBuildWorkspaceTests.cs index 0fecbde3919e4..3c8143f2badf3 100644 --- a/src/Workspaces/MSBuildTest/MSBuildWorkspaceTests.cs +++ b/src/Workspaces/MSBuildTest/MSBuildWorkspaceTests.cs @@ -107,8 +107,11 @@ public async Task Test_OpenProjectReferencingPortableProject() using (var workspace = CreateMSBuildWorkspace()) { var project = await workspace.OpenProjectAsync(projectFilePath); + AssertFailures(workspace); + var hasFacades = project.MetadataReferences.OfType().Any(r => r.FilePath.Contains("Facade")); - Assert.True(hasFacades); + Assert.True(hasFacades, userMessage: "Expected to find facades in the project references:" + Environment.NewLine + + string.Join(Environment.NewLine, project.MetadataReferences.OfType().Select(r => r.FilePath))); } } diff --git a/src/Workspaces/MSBuildTest/Microsoft.CodeAnalysis.Workspaces.MSBuild.UnitTests.csproj b/src/Workspaces/MSBuildTest/Microsoft.CodeAnalysis.Workspaces.MSBuild.UnitTests.csproj index 172f8d42df745..4da0a5beb4bd2 100644 --- a/src/Workspaces/MSBuildTest/Microsoft.CodeAnalysis.Workspaces.MSBuild.UnitTests.csproj +++ b/src/Workspaces/MSBuildTest/Microsoft.CodeAnalysis.Workspaces.MSBuild.UnitTests.csproj @@ -6,7 +6,7 @@ AnyCPU Library Microsoft.CodeAnalysis.MSBuild.UnitTests - net46 + net472 $(RoslynDesktopRuntimeIdentifier) UnitTest @@ -21,7 +21,6 @@ - diff --git a/src/Workspaces/Remote/Core/Microsoft.CodeAnalysis.Remote.Workspaces.csproj b/src/Workspaces/Remote/Core/Microsoft.CodeAnalysis.Remote.Workspaces.csproj index 516ac99ff8138..2a1ae75ad50f0 100644 --- a/src/Workspaces/Remote/Core/Microsoft.CodeAnalysis.Remote.Workspaces.csproj +++ b/src/Workspaces/Remote/Core/Microsoft.CodeAnalysis.Remote.Workspaces.csproj @@ -6,7 +6,7 @@ AnyCPU Library Microsoft.CodeAnalysis.Remote - net46 + net472 true @@ -27,8 +27,6 @@ - - diff --git a/src/Workspaces/Remote/Core/Services/SolutionCreator.cs b/src/Workspaces/Remote/Core/Services/SolutionCreator.cs index b03f46ceff40f..3a05c8406e3a4 100644 --- a/src/Workspaces/Remote/Core/Services/SolutionCreator.cs +++ b/src/Workspaces/Remote/Core/Services/SolutionCreator.cs @@ -267,6 +267,11 @@ private async Task UpdateProjectInfoAsync(Project project, Checksum inf project = project.Solution.WithProjectOutputRefFilePath(project.Id, newProjectInfo.OutputRefFilePath).GetProject(project.Id); } + if (project.State.ProjectInfo.Attributes.DefaultNamespace != newProjectInfo.DefaultNamespace) + { + project = project.Solution.WithProjectDefaultNamespace(project.Id, newProjectInfo.DefaultNamespace).GetProject(project.Id); + } + if (project.State.ProjectInfo.Attributes.HasAllInformation != newProjectInfo.HasAllInformation) { project = project.Solution.WithHasAllInformation(project.Id, newProjectInfo.HasAllInformation).GetProject(project.Id); @@ -516,7 +521,9 @@ await _assetService.GetAssetAsync( projectInfo.Id, projectInfo.Version, projectInfo.Name, projectInfo.AssemblyName, projectInfo.Language, projectInfo.FilePath, projectInfo.OutputFilePath, compilationOptions, parseOptions, - documents, p2p, metadata, analyzers, additionals, projectInfo.IsSubmission).WithHasAllInformation(projectInfo.HasAllInformation); + documents, p2p, metadata, analyzers, additionals, projectInfo.IsSubmission) + .WithHasAllInformation(projectInfo.HasAllInformation) + .WithDefaultNamespace(projectInfo.DefaultNamespace); } private async Task> CreateCollectionAsync(ChecksumCollection collections) diff --git a/src/Workspaces/Remote/Razor/Microsoft.CodeAnalysis.Remote.Razor.ServiceHub.csproj b/src/Workspaces/Remote/Razor/Microsoft.CodeAnalysis.Remote.Razor.ServiceHub.csproj index c677676363373..dc2a08c1ce580 100644 --- a/src/Workspaces/Remote/Razor/Microsoft.CodeAnalysis.Remote.Razor.ServiceHub.csproj +++ b/src/Workspaces/Remote/Razor/Microsoft.CodeAnalysis.Remote.Razor.ServiceHub.csproj @@ -6,7 +6,7 @@ AnyCPU Library Microsoft.CodeAnalysis.Remote.Razor.ServiceHub - net46 + net472 true diff --git a/src/Workspaces/Remote/ServiceHub/Microsoft.CodeAnalysis.Remote.ServiceHub.csproj b/src/Workspaces/Remote/ServiceHub/Microsoft.CodeAnalysis.Remote.ServiceHub.csproj index 914b1ccb0646c..0bfe03a8e4f3a 100644 --- a/src/Workspaces/Remote/ServiceHub/Microsoft.CodeAnalysis.Remote.ServiceHub.csproj +++ b/src/Workspaces/Remote/ServiceHub/Microsoft.CodeAnalysis.Remote.ServiceHub.csproj @@ -6,7 +6,7 @@ AnyCPU Library Microsoft.CodeAnalysis.Remote - net46 + net472 true @@ -21,8 +21,6 @@ - - diff --git a/src/Workspaces/VisualBasic/Portable/Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj b/src/Workspaces/VisualBasic/Portable/Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj index 29f0c9d97309d..0d3aa16597d49 100644 --- a/src/Workspaces/VisualBasic/Portable/Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj +++ b/src/Workspaces/VisualBasic/Portable/Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj @@ -5,7 +5,7 @@ AnyCPU AnyCPU Library - netstandard1.3 + netstandard2.0 diff --git a/src/Workspaces/VisualBasicTest/Microsoft.CodeAnalysis.VisualBasic.Workspaces.UnitTests.vbproj b/src/Workspaces/VisualBasicTest/Microsoft.CodeAnalysis.VisualBasic.Workspaces.UnitTests.vbproj index b3ff4470f6d2a..0172fb4f263a5 100644 --- a/src/Workspaces/VisualBasicTest/Microsoft.CodeAnalysis.VisualBasic.Workspaces.UnitTests.vbproj +++ b/src/Workspaces/VisualBasicTest/Microsoft.CodeAnalysis.VisualBasic.Workspaces.UnitTests.vbproj @@ -7,7 +7,7 @@ Library Off Default - net46 + net472 $(RoslynDesktopRuntimeIdentifier) UnitTest @@ -23,7 +23,6 @@ -